x402 micropayment rail
Why this matters
Monthly subscriptions and manual API-key signups break one-off automated requests, while charging per chunk on streaming responses runs straight into HTTP header ordering because response headers flush before the final chunk count is established. Implementing the x402 v2 HTTP 402 Payment Required flow with real WebCrypto ECDSA P-256 signatures and a single-writer Cloudflare Durable Object SQLite ledger tests both fixed-price single-shot billing and partial streaming settlement.
What this opens up
Pay-per-request HTTP 402 access for articles ($0.001) and metered Server-Sent Events (SSE) streams ($0.0005/chunk) without subscriptions or long-lived bearer keys, with single-debit Idempotency-Key retries and exact partial charges when a stream stops early.
How the tests work
- Click Run 1-Click exact Flow ($0.001) to trigger an unpaid
402challenge on/api/paid/article, sign aPAYMENT-SIGNATUREheader with your browser P-256 key, and receive200 OKplus aPAYMENT-RESPONSEreceipt. - In Pay-Per-Chunk SSE Stream (
uptoScheme), toggle Abort Mid-Stream (or click Abort Active Stream Now mid-flight) to verify that authorizing a$0.010ceiling and stopping after 3 chunks debits strictly$0.0015and releases$0.0085. - Run the 4 Failure & Latency Tests to verify single-debit idempotent retries,
409 NONCE_ALREADY_SETTLEDdouble-spend blocks, low-balance402rejections, and warm Durable Object vs. 80 ms external RPC verification latency. - Switch tabs in Decoded x402 Headers & Wire Trace and watch the SQLite Settlement Ledger update live with every committed nonce.
Hypothesis
Pairing HTTP
402price challenges (PAYMENT-REQUIRED) with WebCrypto ECDSA P-256 client authorizations (PAYMENT-SIGNATURE) and an atomic SQLite Durable Object ledger (PaymentLedger) handles both idempotent single-shotexactcharges and partial streaming metereduptoSSE settlement cleanly.
What confirms it: GET /api/paid/article settles $0.001 (1,000 atomic micro-units) once across network retries with matching (Idempotency-Key, wallet, resource, scheme); GET /api/paid/stream bills strictly for delivered chunks (500 micro-units each up to $0.010), emits a closing SSE settlement frame, and persists receipts at GET /api/receipt/:nonce; conflicting nonce reuse fails closed with 409 NONCE_ALREADY_SETTLED.
What bounds or disproves it: Under streaming upto SSE, HTTP headers flush before chunk 1 while total delivered units are still undetermined—requiring terminal SSE settlement events rather than response headers—and an uncached 80 ms external facilitator RPC round-trip dominates fast edge latency compared with a warm Durable Object SQLite check.
Under the hood
x402 Micropayment Rail (source on GitHub) runs a Cloudflare Worker (src/router.ts) backed by a single-writer SQLite Durable Object (PaymentLedger in src/ledger-core.ts) with shared browser/server header encoding and P-256 signing in public/lib/x402-protocol.js:
exactfixed-price settlement (GET /api/paid/article): Returns HTTP402with a Base64-encoded JSONPAYMENT-REQUIREDheader (1,000atomic micro-units /$0.001), verifies the client’s WebCrypto ECDSA P-256PAYMENT-SIGNATURE, commits the debit insidetransactionSync()keyed bynonce PRIMARY KEY, and returns cached200 PAYMENT-RESPONSEreceipts on matchingIdempotency-Keyretries while rejecting conflicting nonce reuse with409 NONCE_ALREADY_SETTLED.uptostreaming metered SSE (GET /api/paid/stream): Verifies the signed spend ceiling before flushing SSE headers, streams chunks at500micro-units ($0.0005) each, settles strictly delivered units on normal completion, ceiling cap, or mid-stream abort, emits a terminalevent: settlementframe, and persists the receipt atGET /api/receipt/:nonce.- Direct facilitator endpoints & latency probe: Exposes
/facilitator/supported,/facilitator/verify(with optionalsimulateRpcMsdelay), and/facilitator/settleto measure warm local Durable Object settlement against an 80 ms external RPC round-trip.
Key terms & further reading
- x402 v2 Protocol ↗
- An open HTTP micropayment protocol that passes machine-readable payment challenges, signed authorizations, and receipts in HTTP headers.
- HTTP 402 Payment Required (RFC 9110 §15.5.3) ↗
- The standard HTTP status code reserved for resources that require payment before returning a response.
- ECDSA P-256 (Web Crypto API) ↗
- A browser-native elliptic-curve signature algorithm used to bind each payment approval to a route, amount or ceiling, expiry, and unique nonce.
- Server-Sent Events (SSE) ↗
- An HTTP streaming format (
text/event-stream) used here to deliver metered response chunks followed by a closingsettlementreceipt frame. - Idempotency-Key Header ↗
- A client-supplied header letting servers return a cached settlement receipt on retried requests instead of debiting twice.
- Cloudflare Durable Objects ↗
- Single-writer edge compute objects with embedded SQLite transactions that enforce nonce uniqueness and atomic balance debits.
Open questions
- Can HTTP/2 & HTTP/3 response trailers carry standard
PAYMENT-RESPONSEreceipts reliably through browserfetch()and reverse proxies? - How should automated clients bound cumulative spend across dozens of
402micro-charges without popping a confirmation prompt on every$0.001fetch?
Iteration log
- — Deployed Cloudflare Worker + SQLite Durable Object (
PaymentLedger) implementing x402 v2PAYMENT-REQUIRED/ ECDSA P-256PAYMENT-SIGNATURE/PAYMENT-RESPONSEacrossexact(GET /api/paid/article), streaming metereduptoSSE (GET /api/paid/stream),/facilitator/supported,/facilitator/verify,/facilitator/settle,409 NONCE_ALREADY_SETTLEDreplay checks, and warm DO vs. 80 ms external RPC latency comparisons.
Primitives tested: HTTP 402 Payment Required (x402 v2), WebCrypto ECDSA P-256 (PAYMENT-SIGNATURE), Streaming SSE Metered Settlement (upto), Idempotency-Key & Nonce Replay Ledger, Durable Object SQLite (PaymentLedger).
This is an active lab under /labs/ and stays off the main RSS feed until graduated into a full essay.