Skip to content

x402 on Cloudflare Workers: AI Agents Pay Per Call in USDC

• Updated
14 min read
Markdown Share this post: Share on X Share this post on X Share on LinkedIn Share this post on LinkedIn

Agents can now pay per call on this site with zero account infrastructure: three live endpoints, POST /v1/resume-eval scoring a resume at a flat $0.005, POST /v1/agent-readiness auditing a domain’s agent readiness at $0.05, and GET /v1/btc-regime gating a Bitcoin trend signal at $0.003, settled in USDC (USD Coin, a dollar-pegged stablecoin) on Base mainnet. Deterministic checks and a System One judge model split the scoring; judge outputs are probabilistic and degrade to explicit warnings on judge failure, never silent scores. Payment is the authentication: no accounts, no API keys, no OAuth flows. The proof is a confirmed settlement transaction on chain, with a PAYMENT-RESPONSE header carrying the payer, the transaction hash, and the network; Table 1 reproduces the full receipt.

Machine-payable APIs are real, small, and shippable. This post documents the shipped stack, the settlement state machine, two barely-documented replay-protection findings, and what a week of live traffic does not yet prove. The site’s agent surface was already machine-readable (Agent-Ready Websites); HTTP 402 adds the incentive layer on top of that addressability.

Table 1: Mainnet settlement receipt for POST /v1/resume-eval.
FieldObserved value
Challenge statusHTTP 402 with Base64-encoded PAYMENT-REQUIRED header
Price5000 base units ($0.005; USDC uses 6 decimals)
AssetUSDC at 0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913
Networkeip155:8453 (Base mainnet)
Settlement transaction0xddc212d834162a7642341310de13d573e99796a22ae390042e3dca4f7b57bf39
PAYMENT-RESPONSE{ success: true, payer, transaction, network }

What Is x402?

x402 is an open protocol that turns HTTP status code 402 into a machine-negotiable payment request, in its version 2 specification from December 2025. Historically, 402 sat unused in the HTTP standard; x402 activates it for agents: a server answers an unauthenticated request with 402 plus a structured challenge, and the client pays and retries.

Three Headers, One Payment

The protocol runs on three headers. PAYMENT-REQUIRED carries the challenge: a Base64-encoded JSON document declaring the price, the asset, and the network. PAYMENT-SIGNATURE carries the client’s signed payment on the retry. PAYMENT-RESPONSE returns the settlement receipt on the successful response.

Version 2 renamed the v1 X-PAYMENT headers to these scheme-neutral names and adopted CAIP-2 chain identifiers such as eip155:84532 (Base Sepolia) and eip155:8453 (Base mainnet). The scoped @x402/hono package implements v2; the unscoped legacy package implements v1.

The Challenge Is Self-Describing

The decoded challenge from production shows how self-describing the contract is. The agent learns the exact amount, the token contract, and the chain identifier without any out-of-band configuration.

Code Snippet 1: The 402 challenge returned by production, Base64-decoded and abridged. Values are as observed; amount is in the token’s base units. Once the X402_PAY_TO secret is set, the challenge also carries a payTo receiving address, elided here.
{
  "resource": {
    "url": "https://clouatre.ca/v1/resume-eval",
    "description": "Resume rubric evaluation",
    "mimeType": "application/json"
  },
  "accepts": [
    {
      "scheme": "exact",
      "network": "eip155:8453",
      "amount": "5000",
      "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
      "maxTimeoutSeconds": 60
    }
  ]
}PAYMENT-REQUIRED

How Does the Settlement State Machine Work?

Figure 1 shows the machine as its four actors see it; this section walks it gate by gate, because each gate exists to keep a specific failure from reaching settlement.

The Ordering Is the Security Property

The route verifies the payment signature first via the facilitator (a public service that checks payment proofs on behalf of resource servers; the verify call is free), then checks for replays, then validates input, then executes, and settles only after a 2xx response exists. The verify-first order is deliberate: because verify is free, unauthenticated garbage never writes to Durable Object storage, and duplicate detection costs only the free call.

Client Worker ReplayGuard Facilitator 1. POST + signature 2. verify (free) 3. reject: 402 4. check sig hash 5. duplicate: 409 8. settle (1-3s tail) 9. receipt 10. 200 + PAYMENT-RESPONSE 6. validate input, 7. evaluate on-chain wait
Figure 1: One paid request across the four actors, inside the premium Worker; the diagram’s Worker column spans the content and payment services, joined by a service binding. The two facilitator hops draw on that column’s outbound subrequest budget; the synchronous wait during step 8 is where the one-to-three-second chain tail lands, ahead of the step-10 response. Dotted arrows are rejections and receipts.

The load-bearing detail is the final step. Settlement, the on-chain transfer of the listed price, fires strictly on 2xx, and nothing else reaches the chain: a 400 never settles, a 409 never runs, and a handler-level 424 probe failure has been observed to leave the wallet balance unchanged across three paid calls whose signatures had already verified. The route costs the operator nothing unless the caller receives a valid response, a property worth calling fail-closed commerce, verified beyond input-level failures.

One consequence matters to client implementers: the replay guard records the signature before input validation, so a payment signature is single-attempt per HTTP transaction regardless of status code. A client whose first attempt died with a 400 cannot retry the same signature; the retry gets a 409 even though nothing settled.

Latency and Subrequest Budget

The ordering also bounds the latency and subrequest budget. Each paid call makes two outbound facilitator subrequests from the payment Worker, one for verify and one for settle, plus the evaluation compute. Settlement is an on-chain operation and adds a one to three second tail; because the response releases only after settle, client-facing timeout expectations must account for that tail. The maxTimeoutSeconds value of 60 in the challenge exists for exactly this reason. The unpaid path waits on nothing: after a facilitator outage turned the 402 challenge into a 20-40-second way of saying no, the challenge is now built entirely from local route state; only the paid path contacts a facilitator, bounded at five seconds, with a second keyless facilitator as failover.

A Deliberately Small Stack

The shipped stack is deliberately small: Hono v4 (a lightweight router framework) dispatched only for the /v1/* prefix, @x402/hono 2.29.0, a Durable Object (a single-threaded Cloudflare stateful actor) named ReplayGuard, and the hosted Coinbase Developer Platform facilitator at https://api.cdp.coinbase.com/platform/v2/x402, which answers live requests. The demonstration originally ran on the testnet-only public facilitator at https://x402.org/facilitator. The payment stack lives in a dedicated premium Worker that the content Worker forwards to over a service binding, so the 600-line production handler is untouched and replay state stays isolated from preview deployments; the dispatch is a three-line prefix check.

What Does Replay Protection Look Like in Practice?

Replay protection, the defense against one payment being reused for many requests, turned out to have two independent layers, and the interaction between them produced the most interesting findings of the project. Neither layer relies on application logic staying correct; one is enforced by chain semantics, the other by execution isolation.

Layer One: Execution Isolation

The first layer is the ReplayGuard Durable Object. Its check() method performs an atomic check-and-record of a payment signature’s hash; Durable Object execution is single-threaded, so no two requests can interleave inside it. Entries expire after 120 seconds, swept lazily on access and by a single rolling alarm that purges every expired entry and rearms to the earliest remaining expiry. A newer signature can move the alarm earlier, which is safe: the alarm only sweeps expired entries, so firing sooner merely purges them sooner. The 120-second window is not arbitrary: the @x402 SDK (2.28.0) derives the validBefore deadline of the EIP-3009 authorization (Ethereum’s transferWithAuthorization standard for payments) from the challenge’s maxTimeoutSeconds (60), so a signature older than 60 seconds is permanently unspendable on chain, and the guard’s memory outlives the signature’s cryptographic validity by design (Figure 2).

EIP-3009 validity (validBefore) ReplayGuard DO memory (TTL) Chain nonce (permanent) 0s 60s 120s signature expires DO memory ends
Figure 2: Coverage overlap over one signature’s life. The Durable Object’s memory ends 60 seconds after the signature itself expires, so no gap exists between the application guard and the chain guard.
Code Snippet 2: The core of check() in the ReplayGuard Durable Object. The check and the record happen in one call, which makes the duplicate window impossible to interleave.
async check(sigHash: string): Promise<"ok" | "duplicate"> {
  const now = Date.now();
  const existing =
    await this.ctx.storage.get<number>(`nonce:${sigHash}`);
  if (existing !== undefined) {
    if (existing > now) return "duplicate"; 
    await this.ctx.storage.delete(`nonce:${sigHash}`);
  }
  const expiresAt = now + TTL_MS;
  await this.ctx.storage.put(`nonce:${sigHash}`, expiresAt);
  const alarm = await this.ctx.storage.getAlarm();
  if (alarm === null || expiresAt < alarm) {
    await this.ctx.storage.setAlarm(expiresAt);
  }
  return "ok";
}workers/premium/src/replay-guard.ts

Layer Two: Chain-Enforced Nonces, and Two Field Findings

Which layer catches a replay depends on when it arrives, and the answer changes twice over one signature’s life; Table 2 walks the windows.

Table 2: The three defense windows against payment replay, over one signature’s lifetime.
WindowElapsed timeCatching layerReturned status
Same-signature retry, recorded but unsettled0 to ~3 seconds, or any time after a 400ReplayGuard Durable Object, atomic check-and-record409 replay_blocked
Post-settlement~3 to 60 secondsFacilitator, spent EIP-3009 nonce on chain402
Post-expiryOver 60 secondsEIP-3009 validBefore deadline passed402

Finding one is about test environments. Under wrangler dev, Cloudflare’s local development server, the Worker’s configured custom domain rewrites the request host, so the SDK derives the resource URL as the production domain even on localhost. The public facilitator accepts verify and settle calls for that dev-origin resource without complaint. It validates the signed payment against the requirements that the resource server itself submits, resource URL included, and never probes the origin. The same verbatim derivation surfaced in production, where plain-http requests on custom domains yielded challenges advertising an http:// resource URL; the content Worker now answers those requests with a 308 https redirect before the premium Worker ever sees them. Teams reproducing x402 handshakes locally should expect test runs to reference production URLs and to settle anyway.

The intuitive expectation for a post-settlement replay is a conflict error; the field result is HTTP 402. That mismatch is the finding: verify-first ordering means the facilitator adjudicates every request carrying a still-valid signature, and it rejects the spent EIP-3009 nonce (EIP-3009 is the Ethereum standard that lets USDC transfers carry a single-use nonce, so the chain itself enforces one-use payments) before the Durable Object is ever consulted. The DO’s 409 therefore covers only signatures it has recorded but that never settled, whether a concurrent in-flight duplicate or a retry after a 400; entries persist for the full 120-second TTL (time to live) regardless of settlement outcome. The two layers are independent and both fail closed; across four settled test runs, no double-settlements occurred. The mainnet funded runs reproduced the full handshake end to end; the immediate same-signature retry drew 409 replay_blocked exactly as the recorded-but-unsettled window predicts. The receipt below is the corresponding settlement from the testnet demonstration, where the same window was first observed.

Code Snippet 3: The testnet-phase settlement’s PAYMENT-RESPONSE header, Base64-decoded; the transaction hash verifies on Base Sepolia via Blockscout.
{
  "success": true,
  "payer": "0x3930d60b71Ca88040157cca6298e6e5F29172cAB",
  "transaction": "0xc4d698451550e459a4fb5f738a23fc5e3789240e2ca0f1bd5af7b63fc701c20d",
  "network": "eip155:84532"
}PAYMENT-RESPONSE

What Did the KISS Re-Scope Cut?

The initial architecture plan sequenced the full Hono re-route of the production Worker, a dedicated custom domain, Coinbase Developer Platform (CDP) secrets, and telemetry before verifying a single transaction. The implementation re-scope inverted that: it cut everything not strictly security-bearing, validated the full handshake under wrangler dev before any deploy, and shipped in three incremental changesets within a single session.

Table 3: Planned architecture, KISS re-scope in the testnet phase, and the mainnet end-state.
Original planKISS decision (testnet phase)Mainnet end-state
Full Hono re-route of the 600-line handlerHono dispatched only for /v1/*; default branch untouchedPrefix dispatch proved durable; unchanged
api.clouatre.ca custom domain plus CORSExisting production routes; no DNS changesStill existing production routes; never needed
CDP facilitator with JWT secretsPublic facilitator; no secrets issuedCDP facilitator live with Ed25519 JWT secrets
Analytics Engine telemetry and KV audit layerDeferred to a later graduation stageAnalytics Engine telemetry live (premium_events); KV audit deferred
Playwright suite and worker typecheck gateOne client smoke test as the merge gateUnit tests plus a deploy-time secret guard added; no Playwright suite

The Lesson for Live Payment APIs

Minimal means not touching the default branch of the fetch handler; a prefix dispatch preserves existing production behavior exactly. The dedicated premium Worker was the one addition beyond the original plan, made for replay-state isolation from preview deployments. Because the full handshake passed locally before any deployment, the merge became a non-event. The remaining deferred features stay the production end-state; the authenticated facilitator landed ahead of its secrets, and the initial release proved the payment primitive first.

What Doesn’t This Prove Yet?

Volume is a handful of payments, which is evidence of correctness, not evidence of demand. What the testnet phase proved ended where testnet’s jurisdiction ended; the mainnet cutover closed that gap. The endpoint settled in value-bearing USDC on Base behind the hosted CDP facilitator, paying into a dedicated receive-only wallet. The first funded runs settled exactly: two payments moved on chain, a same-signature replay drew 409 replay_blocked, and an unpaid request still drew the 402 challenge. Replay protection covers a 120-second window, after which expiry removes the guard’s memory; the chain’s single-use nonce is what protects late replays.

One caveat belongs on the record: settlement requires the X402_PAY_TO receiving-address secret, and the challenge omits payTo until it is set, which blocks any funded run against the deployed URL. The receipt in Table 1 was captured only after that step completed; a deploy-time guard now fails any deployment where the secret is absent.

Where Agents Find This Endpoint

The x402 ecosystem indexes paid resources through the 402 challenge itself: once a payment settles through the CDP facilitator, the challenge’s enriched metadata (service name, tags, icon, request and response shapes) is picked up automatically by the CDP Bazaar, which downstream directories index from; listing in aggregators follows over days, not at deploy time. The first settled payment is the submission.

Table 4: Discovery surfaces that list the paid endpoints, by indexing mechanism.
SurfaceWhat it provides
CDP BazaarAutomatic indexing after the first settled payment; no submission step
x402scanPublic explorer of x402 resources, indexed from facilitator traffic and submissions
x402-listCommunity directory of x402 endpoints
This sitellms.txt, /v1/openapi.json, and /.well-known/x402

For agents that crawl rather than query a bazaar, the site advertises the endpoints directly: llms.txt and llms-full.txt list them under Agent Discovery, a free OpenAPI 3.1 document at /v1/openapi.json describes the request and response contract, and /.well-known/x402 declares every resource, price, network, and asset in one machine-readable file, generated from the same resource list the bazaar metadata uses, so adding the third endpoint was, again, a one-line change. Each is linked from the others, so one fetch lands an agent on all three.

What Comes Next?

The stack covers production use: telemetry, a production facilitator behind a dedicated receiving wallet, a value-bearing USDC asset on Base, judge-scored evaluations, and a paid MCP (Model Context Protocol) transport at /mcp exposing all three endpoints as tools under the same USDC settlement. Conversion is measurable: most challenge traffic is scanners, and paid conversion sits near 0.4 percent. The payment infrastructure performs as designed; whether buyers arrive at scale is not something the protocol can answer.

The browser-side tools in Does WebMCP Pay Off for Content Sites? remain free and client-side; the paid /mcp transport is the network-facing counterpart.

For technical executives, the takeaway is concrete: machine-payable APIs require no billing vendor and no identity system, just a Worker, a payment middleware mount, a facilitator, and a receiving address. The economics are similarly small: the hosted facilitator includes the first 1,000 settlements a month, then charges $0.001 per settlement and covers the settlement gas. Payment is also the abuse control; every caller either pays or consumes only a free verify. The open questions, demand and treasury operations, are business decisions that the protocol deliberately leaves untouched; their P&L consequences are analyzed in Pay-Per-Call APIs: $0.005 Calls, Measured Treasury Costs. On the other side of the table, buyers can verify an endpoint before signing anything; the checks are laid out in Verifying x402 Endpoints: The 5-Check Buyer Recipe.


Previous Post
When Should an AI Agent Enumerate, and When Delegate?
Next Post
Pay-Per-Call APIs: $0.005 Calls, Measured Treasury Costs

Related Posts