Wallet: Initializing… Ledger: DO SQLite

Track 9 · Agent Discovery, Auth & Protocol Bridges · HTTP 402 + SQLite Durable Object

x402 Micropayment Rail

Subscriptions and manual API-key signups break one-off automated requests, while billing per chunk on streaming responses hits HTTP header timing because headers flush before the final chunk count is established. This lab runs the x402 v2 HTTP 402 Payment Required flow end to end with browser ECDSA P-256 signatures, Idempotency-Key retries, SSE chunk metering, and an atomic Durable Objects SQLite ledger.

Why this matters

Paid web APIs usually force monthly plans or long-lived bearer keys, while naive per-call billing either double-charges on network retries or fails when a streaming response stops early.

What this opens up

Pay-per-request HTTP 402 access for articles ($0.001) and metered streaming responses ($0.0005/chunk) without accounts or subscriptions, with single-debit retries and exact partial settlement on stream abort.

How the tests work

Run the 1-Click exact Flow to see a full 402 → sign → 200 receipt, toggle Abort Mid-Stream on the upto SSE panel to verify partial charges, then run the 4 Failure & Latency Tests below.

Demo Payer Wallet & Browser P-256 Key

Your private signing key stays in browser WebCrypto memory while your test balance and spent nonces are enforced in the server's PaymentLedger SQLite Durable Object.

Balance $0.050000 50,000 µUSDC
Total Settled $0.000000 0 µUSDC
Wallet ID initializing… Next nonce: #1
ECDSA P-256 Thumbprint generating… RFC 7638 SHA-256 JWK

1. Fixed-Price Request (exact Scheme)

Fetches /api/paid/article for $0.001 (1,000 µUSDC): receives HTTP 402, signs a P-256 header, and settles once.

Idle
1. 402 Challenge 2. P-256 Sign 3. 200 + Receipt
Verify —
Settle —
Round-Trip —
Overhead Share —
Click "Run 1-Click exact Flow ($0.001)" to trigger HTTP 402, decode PAYMENT-REQUIRED, sign PAYMENT-SIGNATURE with WebCrypto P-256, and receive 200 + PAYMENT-RESPONSE.

2. Pay-Per-Chunk SSE Stream (upto Scheme)

Authorizes a spend ceiling on /api/paid/stream ($0.0005/chunk) and charges strictly for chunks delivered before completion or abort.

Idle
After chunk:
Authorized ceiling vs. settled usage appears here. Released: —
Toggle "Abort Mid-Stream" to verify partial settlement: authorizing a $0.010 ceiling and aborting after 3 chunks debits strictly $0.0015 (1,500 µUSDC) and releases $0.0085.

4 Failure & Latency Tests (Live Worker Checks)

Each button sends real HTTP requests to the Worker and Durable Object ledger to verify retries, replay blocks, balance limits, and verification overhead.

1. Safe Network Retry (Single Debit)

Not Run

Sends a signed exact request with an Idempotency-Key and replays it verbatim, confirming a cached 200 receipt with idempotentReplay: true and only 1 debit.

2. Blocked Double-Spend Replay

Not Run

Reuses an already-spent txNonce with a different route or key, verifying the ledger fails closed with 409 NONCE_ALREADY_SETTLED and 0 extra debit.

3. Low Balance & Under-Signed Amount

Not Run

Tests signing 500 µUSDC for a 1,000 µUSDC route (402 UNDER_AUTHORIZED_AMOUNT) and requesting a ceiling above wallet balance (402 INSUFFICIENT_BALANCE).

4. Latency: Local DO vs. 80 ms External RPC

Not Run

Times 3 live exact calls on a warm Durable Object (0 ms RPC) against 3 calls with an 80 ms external facilitator delay to show how uncached verification affects edge latency.

Run any of the 4 tests above to inspect exact HTTP status codes, balance before/after assertions, and latency distributions.

Decoded x402 Headers & Wire Trace

Switch tabs to read the Base64-decoded JSON headers from your latest paid request.

{
  "hint": "Execute an exact or upto flow above to inspect decoded x402 v2 headers here."
}

SQLite Settlement Ledger (Durable Object)

Every settled charge is committed atomically in the settlements table keyed by unique nonce.

0 settled
Tx / Nonce Scheme Resource Authorized Settled Status

Recent Edge Wire Events

Architecture How an HTTP 402 price challenge, P-256 signature, and SQLite Durable Object settle a request
Live Request Path · Browser ECDSA P-256 Wallet + Cloudflare SQLite Durable Object
1. Payer Client

Browser P-256 Wallet

PAYMENT-SIGNATURE: base64(JSON)
  • Gets HTTP 402 and decodes the PAYMENT-REQUIRED price challenge
  • Signs the route, price or ceiling, expiry, and unique nonce
  • Sends an Idempotency-Key so retries never double-charge
2. Resource Server

Cloudflare Worker src/router.ts

  1. /api/paid/article (exact): verifies and settles $0.001 before returning 200 + PAYMENT-RESPONSE
  2. /api/paid/stream (upto): checks ceiling before streaming SSE chunks at $0.0005 each, then settles delivered count
  3. Exposes /facilitator/verify and /facilitator/settle directly

Enforces strict CSP, no-cache, nosniff, and frame-ancestors on every response.

200 SETTLED

PaymentLedger SQLite DO

Atomic debit + nonce commit
nonce PRIMARY KEY Idempotency-Key cache Partial upto release
402 / 409 REJECT

Fail-Closed Guards

NONCE_ALREADY_SETTLED · INSUFFICIENT_BALANCE

Blocks cross-route replays, wrong keys, expired signatures, and under-funded ceilings with zero balance change.

Why Streaming Receipts Cannot Travel in Initial HTTP Headers

Protocol Constraint

On single-shot exact requests, settlement finishes before response headers flush, so PAYMENT-RESPONSE travels in an HTTP header. On streaming upto SSE, headers must flush before chunk 1 while total delivered chunks are still undetermined—so the final receipt is sent in the closing event: settlement SSE frame and stored at GET /api/receipt/<nonce> for dropped connections.

All signature verification and SQLite ledger updates run inside this Cloudflare Worker and its PaymentLedger Durable Object—no mocked balances or client-side settlement math.
How This Is Set Up

x402 v2 Challenge, P-256 Authorization & Atomic SQLite Settlement

Replacing static API-key walls with HTTP 402 Payment Required headers, WebCrypto P-256 authorizations, and single-writer Durable Object SQLite transactions.

Static API key + subscription wall
// Out-of-band signup, long-lived secret, opaque billing:
const res = await fetch("https://api.example/brief", {
  headers: { Authorization: "Bearer sk_live_long_lived_key" },
});
// No machine-readable price on 402; no per-call ceiling;
// network retries risk double-billing unless custom logic exists.
x402 HTTP 402 + scoped P-256 authorization
// 1. Unpaid probe returns 402 + base64 PAYMENT-REQUIRED challenge
const probe = await fetch("/api/paid/article");
const challenge = decodeX402Header(probe.headers.get("PAYMENT-REQUIRED"));

// 2. Sign exact price or upto ceiling with unique nonce + Idempotency-Key
const sig = await signPaymentAuthorization({
  privateKey, publicKeyJwk, scheme: "exact",
  payer: walletId, resource: "/api/paid/article",
  maxAmount: challenge.accepts[0].amount, nonce,
});
const paid = await fetch("/api/paid/article", {
  headers: {
    "PAYMENT-SIGNATURE": encodeX402Header(sig),
    "Idempotency-Key": idemKey,
  },
});
const receipt = decodeX402Header(paid.headers.get("PAYMENT-RESPONSE"));
Atomic Durable Object SQLite Settlement Core (src/ledger-core.ts)
// WebCrypto ECDSA P-256 verification runs async before entering transactionSync;
// Nonce uniqueness, idempotency cache, balance check, and debit commit atomically:
return this.storage.transactionSync(() => {
  const existing = this.getSettlementByNonce(auth.nonce);
  if (existing) {
    if (idemKey && existing.idempotency_key === idemKey &&
        existing.wallet_id === auth.payer &&
        existing.resource === input.expectedResource) {
      return { ok: true, idempotentReplay: true, receipt: cachedReceipt };
    }
    return { ok: false, status: 409, code: "NONCE_ALREADY_SETTLED" };
  }
  if (wallet.balance < settleAmount) {
    return { ok: false, status: 402, code: "INSUFFICIENT_BALANCE" };
  }
  // Debit strictly settleAmount (exact price or delivered upto chunks)
  this.storage.exec("UPDATE wallets SET balance = balance - ? WHERE wallet_id = ?", settleAmount, auth.payer);
  this.storage.exec("INSERT INTO settlements (nonce, ...) VALUES (?, ...)", auth.nonce, ...);
});
What disappears

Manual developer account signups, monthly subscription minimums, and long-lived bearer API keys copied into agent configurations.

What becomes explicit

Per-resource price or ceiling in PAYMENT-REQUIRED, cryptographic payer authorization bound to route and nonce, idempotent retry semantics, and exact delivered-unit billing.

Platform gaps remaining

Browsers lack native HTTP 402 wallet mediation and trailer-header access in fetch() streams, so upto final receipts rely on terminal SSE events; off-edge blockchain RPC verification adds latency that requires warm facilitator caching or batched clearing.

Key terms & further reading
x402 v2 Protocol
An open HTTP micropayment protocol that exchanges machine-readable payment challenges, signed authorizations, and receipts in HTTP headers.
HTTP 402 Payment Required
The HTTP status code reserved in RFC 9110 for responses that require payment before returning the requested resource.
ECDSA P-256 (Web Crypto API)
A browser-native elliptic-curve digital signature algorithm used here to bind each payment approval to a route, amount, and unique nonce.
Server-Sent Events (SSE)
A unidirectional HTTP streaming format (text/event-stream) that sends incremental data chunks and a closing settlement event.
Idempotency-Key Header
A client-supplied token letting a server recognize retried payment requests and return the original receipt without charging twice.
Cloudflare Durable Objects
Single-writer edge objects with embedded SQLite transactions that prevent double-spends and race conditions during settlement.