# x402 micropayment rail

- Status: `experiment`
- Track: [agent discovery, auth & protocol bridges](https://aifoc.us/labs/agent-bridges-and-discovery/)
- Layer: 9. Agent Discovery, Auth & Protocol Bridges
- Updated: 2 December 2026
- Live demo: https://x402-micropayment-rail.kinlan-test.workers.dev
- Source: https://github.com/PaulKinlan/x402-micropayment-rail

## Inspired by

- [A link is all you need](https://aifoc.us/a-link-is-all-you-need/)
- [the token salary](https://aifoc.us/the-token-salary/)
- [what token slinging taught me about ai costs](https://aifoc.us/token-slinging/)

## 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](https://www.x402.org/) [HTTP 402 Payment Required](https://www.rfc-editor.org/rfc/rfc9110#section-15.5.3) flow with real [WebCrypto ECDSA P-256](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/sign) signatures and a single-writer [Cloudflare Durable Object](https://developers.cloudflare.com/durable-objects/) 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)](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) streams (`$0.0005`/chunk) without subscriptions or long-lived bearer keys, with single-debit [`Idempotency-Key`](https://datatracker.ietf.org/doc/draft-ietf-httpapi-idempotency-key-header/) retries and exact partial charges when a stream stops early.

## How the tests work

1. Click **Run 1-Click exact Flow ($0.001)** to trigger an unpaid `402` challenge on `/api/paid/article`, sign a `PAYMENT-SIGNATURE` header with your browser P-256 key, and receive `200 OK` plus a `PAYMENT-RESPONSE` receipt.
2. In **Pay-Per-Chunk SSE Stream (`upto` Scheme)**, toggle **Abort Mid-Stream** (or click **Abort Active Stream Now** mid-flight) to verify that authorizing a `$0.010` ceiling and stopping after 3 chunks debits strictly `$0.0015` and releases `$0.0085`.
3. Run the **4 Failure & Latency Tests** to verify single-debit idempotent retries, `409 NONCE_ALREADY_SETTLED` double-spend blocks, low-balance `402` rejections, and warm Durable Object vs. 80 ms external RPC verification latency.
4. Switch tabs in **Decoded x402 Headers & Wire Trace** and watch the **SQLite Settlement Ledger** update live with every committed nonce.


## Hypothesis

- **Claim:** Pairing HTTP `402` price challenges (`PAYMENT-REQUIRED`) with WebCrypto ECDSA P-256 client authorizations (`PAYMENT-SIGNATURE`) and an atomic SQLite Durable Object ledger (`PaymentLedger`) handles both idempotent single-shot `exact` charges and partial streaming metered `upto` SSE settlement cleanly.
- **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`.
- **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](https://x402-micropayment-rail.kinlan-test.workers.dev) ([source on GitHub](https://github.com/PaulKinlan/x402-micropayment-rail)) 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`:

- **`exact` fixed-price settlement (`GET /api/paid/article`):** Returns HTTP `402` with a Base64-encoded JSON `PAYMENT-REQUIRED` header (`1,000` atomic micro-units / `$0.001`), verifies the client's WebCrypto ECDSA P-256 `PAYMENT-SIGNATURE`, commits the debit inside `transactionSync()` keyed by `nonce PRIMARY KEY`, and returns cached `200 PAYMENT-RESPONSE` receipts on matching `Idempotency-Key` retries while rejecting conflicting nonce reuse with `409 NONCE_ALREADY_SETTLED`.
- **`upto` streaming metered SSE (`GET /api/paid/stream`):** Verifies the signed spend ceiling before flushing SSE headers, streams chunks at `500` micro-units (`$0.0005`) each, settles strictly delivered units on normal completion, ceiling cap, or mid-stream abort, emits a terminal `event: settlement` frame, and persists the receipt at `GET /api/receipt/:nonce`.
- **Direct facilitator endpoints & latency probe:** Exposes `/facilitator/supported`, `/facilitator/verify` (with optional `simulateRpcMs` delay), and `/facilitator/settle` to measure warm local Durable Object settlement against an 80 ms external RPC round-trip.


## Key terms & further reading

- [x402 v2 Protocol](https://www.x402.org/) — 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)](https://www.rfc-editor.org/rfc/rfc9110#section-15.5.3) — The standard HTTP status code reserved for resources that require payment before returning a response.
- [ECDSA P-256 (Web Crypto API)](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/sign) — 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)](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) — An HTTP streaming format (`text/event-stream`) used here to deliver metered response chunks followed by a closing `settlement` receipt frame.
- [Idempotency-Key Header](https://datatracker.ietf.org/doc/draft-ietf-httpapi-idempotency-key-header/) — A client-supplied header letting servers return a cached settlement receipt on retried requests instead of debiting twice.
- [Cloudflare Durable Objects](https://developers.cloudflare.com/durable-objects/) — Single-writer edge compute objects with embedded SQLite transactions that enforce nonce uniqueness and atomic balance debits.

## Open questions to iterate on

- Can HTTP/2 & HTTP/3 response trailers carry standard `PAYMENT-RESPONSE` receipts reliably through browser `fetch()` and reverse proxies?
- How should automated clients bound cumulative spend across dozens of `402` micro-charges without popping a confirmation prompt on every `$0.001` fetch?

## Iteration log

- **2026-12-02:** Deployed Cloudflare Worker + SQLite Durable Object (`PaymentLedger`) implementing x402 v2 `PAYMENT-REQUIRED` / ECDSA P-256 `PAYMENT-SIGNATURE` / `PAYMENT-RESPONSE` across `exact` (`GET /api/paid/article`), streaming metered `upto` SSE (`GET /api/paid/stream`), `/facilitator/supported`, `/facilitator/verify`, `/facilitator/settle`, `409 NONCE_ALREADY_SETTLED` replay 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)`

## Connected labs in other tracks

- [attribution & metering protocol lab](https://aifoc.us/labs/web-protocols/attribution-metering-lab/) — Compares HTTP 402 per-request settlement against signed referral attribution receipts.
- [passkey attenuated capabilities](https://aifoc.us/labs/delegated-authority/passkey-agent-caps/) — Enforces hardware-backed dollar spend caps inside a Durable Object ledger.
- [web bot auth & aipref gate](https://aifoc.us/labs/web-protocols/web-bot-auth-aipref-gate/) — Combines crawler authentication with RSL 1.0 licensing and `Content-Usage` preference headers.

---
Canonical: https://aifoc.us/labs/agent-bridges-and-discovery/x402-micropayment-rail/
