Skip to content
Open
Show file tree
Hide file tree
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 Jun 8, 2026
d7eb6f5
fix(python): harden session watermark and commit-receipt handling
EfeDurmaz16 Jun 8, 2026
5cf2722
fix(python): advance request nonce when reconciling a replayed settle…
EfeDurmaz16 Jun 8, 2026
23d4028
style(python): ruff-format session modules and make test transports p…
EfeDurmaz16 Jun 9, 2026
0361b69
fix(python): clamp replayed-receipt reconcile + strict u64 parsing
EfeDurmaz16 Jun 9, 2026
c68b94b
refactor(python): delegate VoucherData.message_bytes to the canonical…
EfeDurmaz16 Jun 10, 2026
aa7b7db
feat(python): generate the payment-channels client with codama-py
EfeDurmaz16 Jun 11, 2026
e062fad
refactor(python): delegate payment-channels glue to the generated client
EfeDurmaz16 Jun 11, 2026
49ab0f9
fix(python): record replayed commits like the rust spine
EfeDurmaz16 Jun 12, 2026
1ad73ff
fix(python): reject unknown modes and receipt statuses at decode
EfeDurmaz16 Jun 12, 2026
cec4a43
feat(python): add the challenge-driven payment-channel open layer
EfeDurmaz16 Jun 12, 2026
894b384
feat(python): add metered SSE stream consumption
EfeDurmaz16 Jun 12, 2026
8f4f779
chore(python): regenerate uv.lock for anchorpy and borsh-construct
EfeDurmaz16 Jun 12, 2026
e45ddaa
docs(python): mark session as client-only in the scheme matrix
EfeDurmaz16 Jun 12, 2026
c894dab
style(python): drop em-dashes from session docstrings
EfeDurmaz16 Jun 12, 2026
6337ff0
feat(python): mpp/session server + routes (port of Go #160)
EfeDurmaz16 Jun 13, 2026
843b99d
feat(python): playground-api example (FastAPI port of Go #160)
EfeDurmaz16 Jun 13, 2026
7a87f2d
refactor(python): align playground-api with the TS reference (review)
EfeDurmaz16 Jun 15, 2026
1185326
docs(python): self-standing docstrings; playground uses yfinance
EfeDurmaz16 Jun 15, 2026
ac03f87
feat(python/fastapi): add pay_kit.fastapi.install() one-call server s…
EfeDurmaz16 Jun 16, 2026
e22694d
refactor(python/playground): cut to the advertised endpoints
EfeDurmaz16 Jun 16, 2026
e2410f1
docs(python): per-field docs for session intents; trim playground README
EfeDurmaz16 Jun 16, 2026
cd09887
fix(python/playground): truthful docs + lean charges (review)
EfeDurmaz16 Jun 17, 2026
c54564d
refactor(python/playground): gate session routes via a FastAPI depend…
EfeDurmaz16 Jun 17, 2026
c8aecc3
test(python/playground): add playground-api smoke tests
EfeDurmaz16 Jun 17, 2026
ee548c0
refactor(python/playground): rewrite to the idiomatic pay_kit example…
EfeDurmaz16 Jun 18, 2026
4416db6
feat(python/mpp): on-chain settle-at-close + idle-close settlement
EfeDurmaz16 Jun 19, 2026
780f9a9
fix(python/mpp): clamp + reconcile replayed commit watermark
EfeDurmaz16 Jun 19, 2026
c7ef1bb
feat(python/mpp): server-broadcast open path (openTxSubmitter=server)
EfeDurmaz16 Jun 19, 2026
e3d633e
fix(python/mpp): co-sign client-built open instead of building from f…
EfeDurmaz16 Jun 19, 2026
196e025
test(python/mpp): surfnet on-chain session lifecycle e2e
EfeDurmaz16 Jun 19, 2026
8f857c2
feat(python/playground): align playground-api with the TypeScript sur…
EfeDurmaz16 Jun 19, 2026
88b7949
fix(python/playground): close TS-alignment gaps found by cross-check
EfeDurmaz16 Jun 19, 2026
41805ab
fix(python/mpp): encode charge payment-receipt as the canonical receipt
EfeDurmaz16 Jun 19, 2026
52a59a2
feat(python/playground): settle the session on-chain + voucher route
EfeDurmaz16 Jun 19, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions justfile
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,14 @@ payment-channels-generate-rs: codegen-install
cd {{codegen_dir}} && pnpm run payment-channels:rust
cd rust && cargo fmt -p payment-channels-client

# Full refresh: pull IDL + regenerate Rust client.
payment-channels-sync: payment-channels-pull-idl payment-channels-generate-rs
# Render the Python client from the vendored IDL. Wipes
# `python/src/pay_kit/protocols/programs/paymentchannels/` and rewrites
# it in place — see {{codegen_dir}}/generate-payment-channels-client-py.ts.
payment-channels-generate-py: codegen-install
cd {{codegen_dir}} && pnpm run payment-channels:python

Copy link
Copy Markdown
Collaborator

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?


# Full refresh: pull IDL + regenerate Rust and Python clients.
payment-channels-sync: payment-channels-pull-idl payment-channels-generate-rs payment-channels-generate-py

# ── TypeScript ──

Expand Down
14 changes: 13 additions & 1 deletion python/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,19 @@ Use MPP when:
|---------------|--------|
| `charge/pull` | ✅ |
| `charge/push` | ✅ |
| `session` | — |
| `session` | ✅ (on-chain settle-at-close pending) |

`session` ships both sides. Client: `ActiveSession` voucher signing, the
challenge-driven pull/clientVoucher payment-channel openers (fee payer =
challenge operator, pending-server-signature placeholder), the metered
`SessionConsumer`, and the SSE streaming helpers (`MeteredSseSession`,
`MeteredSseStream`, `HttpCommitTransport`). Server: the session method
(`new_session`) issuing challenges and verifying credentials/vouchers, the
reserve/commit metering side channel (`session_routes`), the shared channel
store, and the idle-close watchdog. Not yet ported: the server-broadcast open
path (`openTxSubmitter=server`), pull/operatedVoucher (multi-delegate) opens,
and on-chain settle-at-close, so a closed channel's `settledSignature` stays
`null` until that lands.

The MPP server owns the full lifecycle: it issues signed challenges with a
fresh `recentBlockhash`, parses and validates the `Authorization: Payment`
Expand Down
41 changes: 41 additions & 0 deletions python/examples/playground_api/README.md
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.
202 changes: 202 additions & 0 deletions python/examples/playground_api/app.py
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
Loading
Loading