-
Notifications
You must be signed in to change notification settings - Fork 18
feat(python): MPP sessions (client + server + playground) #161
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
EfeDurmaz16
wants to merge
35
commits into
solana-foundation:main
Choose a base branch
from
EfeDurmaz16:feat/python-mpp-session
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
35 commits
Select commit
Hold shift + click to select a range
278b574
feat(python): add MPP client session intent
EfeDurmaz16 d7eb6f5
fix(python): harden session watermark and commit-receipt handling
EfeDurmaz16 5cf2722
fix(python): advance request nonce when reconciling a replayed settle…
EfeDurmaz16 23d4028
style(python): ruff-format session modules and make test transports p…
EfeDurmaz16 0361b69
fix(python): clamp replayed-receipt reconcile + strict u64 parsing
EfeDurmaz16 c68b94b
refactor(python): delegate VoucherData.message_bytes to the canonical…
EfeDurmaz16 aa7b7db
feat(python): generate the payment-channels client with codama-py
EfeDurmaz16 e062fad
refactor(python): delegate payment-channels glue to the generated client
EfeDurmaz16 49ab0f9
fix(python): record replayed commits like the rust spine
EfeDurmaz16 1ad73ff
fix(python): reject unknown modes and receipt statuses at decode
EfeDurmaz16 cec4a43
feat(python): add the challenge-driven payment-channel open layer
EfeDurmaz16 894b384
feat(python): add metered SSE stream consumption
EfeDurmaz16 8f4f779
chore(python): regenerate uv.lock for anchorpy and borsh-construct
EfeDurmaz16 e45ddaa
docs(python): mark session as client-only in the scheme matrix
EfeDurmaz16 c894dab
style(python): drop em-dashes from session docstrings
EfeDurmaz16 6337ff0
feat(python): mpp/session server + routes (port of Go #160)
EfeDurmaz16 843b99d
feat(python): playground-api example (FastAPI port of Go #160)
EfeDurmaz16 7a87f2d
refactor(python): align playground-api with the TS reference (review)
EfeDurmaz16 1185326
docs(python): self-standing docstrings; playground uses yfinance
EfeDurmaz16 ac03f87
feat(python/fastapi): add pay_kit.fastapi.install() one-call server s…
EfeDurmaz16 e22694d
refactor(python/playground): cut to the advertised endpoints
EfeDurmaz16 e2410f1
docs(python): per-field docs for session intents; trim playground README
EfeDurmaz16 cd09887
fix(python/playground): truthful docs + lean charges (review)
EfeDurmaz16 c54564d
refactor(python/playground): gate session routes via a FastAPI depend…
EfeDurmaz16 c8aecc3
test(python/playground): add playground-api smoke tests
EfeDurmaz16 ee548c0
refactor(python/playground): rewrite to the idiomatic pay_kit example…
EfeDurmaz16 4416db6
feat(python/mpp): on-chain settle-at-close + idle-close settlement
EfeDurmaz16 780f9a9
fix(python/mpp): clamp + reconcile replayed commit watermark
EfeDurmaz16 c7ef1bb
feat(python/mpp): server-broadcast open path (openTxSubmitter=server)
EfeDurmaz16 e3d633e
fix(python/mpp): co-sign client-built open instead of building from f…
EfeDurmaz16 196e025
test(python/mpp): surfnet on-chain session lifecycle e2e
EfeDurmaz16 8f857c2
feat(python/playground): align playground-api with the TypeScript sur…
EfeDurmaz16 88b7949
fix(python/playground): close TS-alignment gaps found by cross-check
EfeDurmaz16 41805ab
fix(python/mpp): encode charge payment-receipt as the canonical receipt
EfeDurmaz16 52a59a2
feat(python/playground): settle the session on-chain + voucher route
EfeDurmaz16 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| # Playground API (Python) | ||
|
|
||
| A FastAPI server gated with the unified `pay_kit` surface, aligned with the | ||
| TypeScript playground (`typescript/examples/playground-api`). Zero-config: | ||
| `pay_kit.configure(network="solana_localnet")` boots against the hosted Surfpool | ||
| sandbox with the shipped demo signer. | ||
|
|
||
| Routes: | ||
|
|
||
| - `GET /api/v1/fortune` fixed charge, settled over MPP or x402 (client's choice). | ||
| - `GET /api/v1/quote/{symbol}` fixed charge, MPP or x402; `via` reports the rail used. | ||
| - `GET /api/v1/joke` MPP charge with a platform split (x402 auto-disabled). | ||
| - `GET /api/v1/stream` MPP session: open a channel, stream metered SSE deliveries. | ||
| - `GET /sessions/receipt/{id}` poll a session channel's settle status (out-of-band settlement). | ||
| - `GET /api/v1/docs[...]` unpaid SDK reference markdown (when generated). | ||
| - `POST /api/v1/faucet/airdrop` localnet-only USDC faucet for client wallets. | ||
| - `GET /openapi.json` OpenAPI 3.1 discovery with `x-payment-info` offers per route. | ||
| - `GET /api/v1/health` free liveness probe + operator / network info. | ||
|
|
||
| The session side-channel (`POST /__402/session/deliveries` and `/commit`) is | ||
| mounted for the metered-voucher flow. | ||
|
|
||
| The x402 `upto` (usage) and MPP `subscription` gates the TS playground also | ||
| shows are intentionally left out: the Python SDK does not ship those gate kinds | ||
| yet (a follow-up), so they are not hand-rolled here. | ||
|
|
||
| Run: | ||
|
|
||
| ```sh | ||
| cd python | ||
| uvicorn examples.playground_api.app:app --port 3000 | ||
| # Optional: seed operator/recipient/platform on the local sandbox at boot. | ||
| PAY_KIT_PLAYGROUND_FUND=1 uvicorn examples.playground_api.app:app --port 3000 | ||
| ``` | ||
|
|
||
| Drive it: | ||
|
|
||
| ```sh | ||
| curl -i http://127.0.0.1:3000/api/v1/fortune # 402 payment required | ||
| pay curl http://127.0.0.1:3000/api/v1/fortune # pays and succeeds | ||
| ``` |
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,202 @@ | ||
| # examples/playground_api/app.py | ||
| """The pay-kit playground API (FastAPI), gated with the unified pay_kit surface. | ||
|
|
||
| Aligned with the TypeScript playground (`typescript/examples/playground-api`): | ||
| one config boots the server and a small route catalogue exercises every gate the | ||
| Python SDK ships today. | ||
|
|
||
| GET /api/v1/fortune fixed charge, MPP or x402 (client's choice) | ||
| GET /api/v1/quote/{symbol} fixed charge, MPP or x402 | ||
| GET /api/v1/joke MPP charge with a platform split (x402 auto-off) | ||
| GET /api/v1/stream MPP session: open a channel, stream metered SSE | ||
| GET /api/v1/docs[...] unpaid SDK reference (docs.py) | ||
| POST /api/v1/faucet/airdrop localnet-only USDC faucet (sandbox.py) | ||
| GET /openapi.json OpenAPI 3.1 discovery (x-payment-info offers) | ||
| GET /api/v1/health free liveness probe + operator/network info | ||
|
|
||
| The x402 `upto` (usage) and MPP `subscription` gates the TS playground also shows | ||
| are intentionally absent: the Python SDK does not ship those gate kinds yet, so | ||
| they are left for a follow-up rather than hand-rolled here. | ||
|
|
||
| Run: | ||
|
|
||
| cd python | ||
| uvicorn examples.playground_api.app:app --port 3000 | ||
|
|
||
| Drive it: | ||
|
|
||
| curl -i http://127.0.0.1:3000/api/v1/fortune # 402 payment required | ||
| pay curl http://127.0.0.1:3000/api/v1/fortune # pays and succeeds | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import os | ||
| import random | ||
|
|
||
| from fastapi import Depends, FastAPI, Request | ||
|
|
||
| import pay_kit | ||
| from pay_kit import Gate, Pricing, usd | ||
| from pay_kit._paycore.protocol import Protocol | ||
| from pay_kit.fastapi import Payment, RequirePayment, install | ||
|
|
||
| from . import discovery | ||
| from .docs import register_docs | ||
| from .sandbox import fund_sandbox, fund_usdc, register_faucet | ||
|
|
||
| pay_kit.configure(network=os.getenv("PAY_KIT_NETWORK", "solana_localnet")) | ||
|
|
||
| # Imported after configure() so the session method builds from the resolved | ||
| # operator / recipient / challenge-binding secret. | ||
| from . import sessions # noqa: E402 | ||
|
|
||
| _cfg = pay_kit.config() | ||
| _RECIPIENT = _cfg.effective_recipient() | ||
| # A second recipient for the split demo (the platform's cut). A fixed, valid | ||
| # base58 pubkey distinct from the operator/recipient. | ||
| PLATFORM = "9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin" | ||
|
|
||
|
|
||
| class Catalog(Pricing): | ||
| """The route catalogue: every charge-gated route declares its gate here.""" | ||
|
|
||
| def __init__(self) -> None: | ||
| defaults = {"default_pay_to": _RECIPIENT, "accept_default": _cfg.accept} | ||
| # Fixed charges, settled over whichever protocol the client picks. | ||
| self.fortune = Gate.build(name="fortune", amount=usd("0.01"), description="A fortune cookie", **defaults) | ||
| self.quote = Gate.build(name="quote", amount=usd("0.01"), description="Stock quote", **defaults) | ||
| # MPP charge with a split: the platform takes 0.003 of the 0.01, the | ||
| # seller (operator) nets 0.007. Multi-recipient splits are not expressible | ||
| # in x402 `exact`, so this gate names MPP explicitly (a fee gate that | ||
| # inherited the default accept would be rejected for still listing x402). | ||
| self.joke = Gate.build( | ||
| name="joke", | ||
| amount=usd("0.01"), | ||
| description="A programmer joke", | ||
| external_id="paykit/joke: seller payout", | ||
| fee_within={PLATFORM: usd("0.003")}, | ||
| accept=(Protocol.MPP,), | ||
| default_pay_to=_RECIPIENT, | ||
| ) | ||
|
|
||
|
|
||
| catalog = Catalog() | ||
|
|
||
| # Module-level dependency singletons (FastAPI resolves them per request). | ||
| require_fortune = Depends(RequirePayment("fortune", pricing=catalog)) | ||
| require_quote = Depends(RequirePayment("quote", pricing=catalog)) | ||
| require_joke = Depends(RequirePayment("joke", pricing=catalog)) | ||
|
|
||
| JOKES = ( | ||
| "Why do programmers prefer dark mode? Because light attracts bugs.", | ||
| 'A SQL query walks into a bar, sees two tables, and asks: "Can I JOIN you?"', | ||
| "There are 10 kinds of people: those who understand binary and those who don't.", | ||
| ) | ||
| FORTUNES = ( | ||
| "A smooth long journey! Great expectations.", | ||
| "Your code will compile on the first try today.", | ||
| "A thrilling time is in your immediate future.", | ||
| "The settlement you await will confirm on-chain.", | ||
| ) | ||
|
|
||
| # `openapi_url=None` frees /openapi.json for our discovery document (below); | ||
| # FastAPI's auto-generated schema would otherwise own that path. | ||
| app = FastAPI(title="PayKit Playground (Python)", openapi_url=None) | ||
| # One-call setup: payment-header CORS + the PayKitError -> 402 challenge mapping. | ||
| install(app) | ||
| app.include_router(sessions.router) | ||
|
|
||
|
|
||
| # ── Priced routes ── | ||
| # Paths are generic (/api/v1/<name>); the protocol + scheme each route accepts is | ||
| # carried by the discovery offers (method/scheme), not the URL. | ||
|
|
||
|
|
||
| @app.get("/api/v1/fortune") | ||
| async def fortune(_payment: Payment = require_fortune) -> dict[str, str]: | ||
| """Fixed charge, settled over whichever protocol the client picks.""" | ||
| return {"fortune": random.choice(FORTUNES)} | ||
|
|
||
|
|
||
| @app.get("/api/v1/quote/{symbol}") | ||
| async def quote(symbol: str, payment: Payment = require_quote) -> dict[str, object]: | ||
| """Fixed charge. ``via`` reports which protocol settled the request.""" | ||
| sym = symbol.upper() | ||
| return {"price": 100 + (ord(sym[0]) % 50) if sym else 100, "symbol": sym, "via": payment.protocol.value} | ||
|
|
||
|
|
||
| @app.get("/api/v1/joke") | ||
| async def joke(_payment: Payment = require_joke) -> dict[str, str]: | ||
| """MPP charge with a platform split (seller nets 0.007, platform 0.003).""" | ||
| return {"joke": random.choice(JOKES)} | ||
|
|
||
|
|
||
| @app.get("/api/v1/health") | ||
| async def health_info() -> dict[str, object]: | ||
| """Free liveness probe + operator/recipient/network info (no balance RPC).""" | ||
| return { | ||
| "feePayer": _cfg.operator.signer.pubkey(), | ||
| "network": _cfg.network.value, | ||
| "ok": True, | ||
| "recipient": _RECIPIENT, | ||
| } | ||
|
|
||
|
|
||
| # ── Docs + sandbox faucet ── | ||
| register_docs(app) | ||
| if _cfg.network.value == "solana_localnet": | ||
| register_faucet(app, _cfg.effective_rpc_url()) | ||
| # Optional zero-config funding for a live localnet run. Off by default so the | ||
| # smoke test (which boots the app) never touches the network. | ||
| if os.getenv("PAY_KIT_PLAYGROUND_FUND") == "1": | ||
| fund_sandbox(_cfg.effective_rpc_url(), _cfg.operator.signer.pubkey(), _RECIPIENT) | ||
| # The split recipient only needs a USDC account to receive its cut (no SOL). | ||
| fund_usdc(_cfg.effective_rpc_url(), PLATFORM) | ||
|
|
||
|
|
||
| # ── Discovery ── | ||
| # OpenAPI 3.1 with an `x-payment-info.offers` list per gated route, byte-aligned | ||
| # with the TS playground's /openapi.json (see discovery.py). | ||
| _OPENAPI = discovery.build_openapi_document( | ||
| info={"title": "PayKit Playground", "version": "1.0.0"}, | ||
| routes=[ | ||
| { | ||
| "method": "GET", | ||
| "path": "/api/v1/fortune", | ||
| "summary": catalog.fortune.description, | ||
| "offers": discovery.charge_offers(catalog.fortune, _cfg), | ||
| }, | ||
| { | ||
| "method": "GET", | ||
| "path": "/api/v1/quote/{symbol}", | ||
| "summary": catalog.quote.description, | ||
| "offers": discovery.charge_offers(catalog.quote, _cfg), | ||
| }, | ||
| { | ||
| "method": "GET", | ||
| "path": "/api/v1/joke", | ||
| "summary": catalog.joke.description, | ||
| "offers": discovery.charge_offers(catalog.joke, _cfg), | ||
| }, | ||
| { | ||
| "method": "GET", | ||
| "path": "/api/v1/stream", | ||
| "summary": "Metered token stream", | ||
| "offers": [ | ||
| discovery.session_offer( | ||
| _cfg, | ||
| cap_base_units="1000000", | ||
| unit_price_base_units="100", | ||
| pay_to=_RECIPIENT, | ||
| ) | ||
| ], | ||
| }, | ||
| ], | ||
| ) | ||
|
|
||
|
|
||
| @app.get("/openapi.json") | ||
| async def openapi_discovery(_request: Request) -> dict[str, object]: | ||
| """OpenAPI 3.1 discovery document (advisory; the 402 challenge is authoritative).""" | ||
| return _OPENAPI |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think we also have some codama commands in the main justfile, can we consolidate?