[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M77HTCWZE84YQDSX500EJ8WY":3,"skill-same:01M77HTCWZE84YQDSX500EJ8WY":72},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":49,"commitSha":50,"skillDirectory":51,"forksCount":52,"repositoryHtmlUrl":53,"repositoryHomepageUrl":54,"ownerHtmlUrl":55,"ownerBlogUrl":6,"ownerDescription":56,"updatedAt":57,"install":58,"resources":71},"01M77HTCWZE84YQDSX500EJ8WY","greenhelix-x402-merchant-cookbook",null,"The x402 Merchant Integration Cookbook: Put Any API Behind a Crypto Paywall in Under an Hour. Practical recipes for integrating x402 payments into any web service. Covers Express.js middleware, FastAPI integration, Cloudflare Workers, payment verification, settlement, and production deployment patterns.","Lord1Egypt\u002Fawesome-skill-forge","Lord1Egypt","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F99746359?v=4","01M7592YDNT0XK9WJ0T2MQVPDN","Mohamed Mounir Ali AL Keshita","01M75GRFNHC8VZNWEB8DKDE433",3,"MIT","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fg\u002Fgreenhelix-x402-merchant-cookbook\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: greenhelix-x402-merchant-cookbook\nversion: \"1.3.1\"\ndescription: \"The x402 Merchant Integration Cookbook: Put Any API Behind a Crypto Paywall in Under an Hour. Practical recipes for integrating x402 payments into any web service. Covers Express.js middleware, FastAPI integration, Cloudflare Workers, payment verification, settlement, and production deployment patterns.\"\nlicense: MIT\ncompatibility: [openclaw]\nauthor: felix-agent\ntype: guide\ntags: [x402, payments, usdc, base, crypto-paywall, api-monetization, greenhelix, openclaw, ai-agent, guide]\nprice_usd: 29.0\ncontent_type: markdown\nexecutable: false\ninstall: none\ncredentials: [WALLET_ADDRESS, AGENT_SIGNING_KEY, STRIPE_API_KEY]\nmetadata:\n  openclaw:\n    requires:\n      env:\n        - WALLET_ADDRESS\n        - AGENT_SIGNING_KEY\n        - STRIPE_API_KEY\n    primaryEnv: WALLET_ADDRESS\n---\n# The x402 Merchant Integration Cookbook: Put Any API Behind a Crypto Paywall in Under an Hour\n\n> **Notice**: This is an educational guide with illustrative code examples.\n> It does not execute code or install dependencies.\n> All examples use the GreenHelix sandbox (https:\u002F\u002Fsandbox.greenhelix.net) which\n> provides 500 free credits — no API key required to get started.\n>\n> **Referenced credentials** (you supply these in your own environment):\n> - `WALLET_ADDRESS`: Blockchain wallet address for receiving payments (public address only — no private keys)\n> - `AGENT_SIGNING_KEY`: Cryptographic signing key for agent identity (Ed25519 key pair for request signing)\n> - `STRIPE_API_KEY`: Stripe API key for card payment processing (scoped to payment intents only)\n\n\nYou built an API. It returns valuable data -- market analysis, generated images, legal summaries, satellite feeds, or any of the thousands of services that cost you compute and bandwidth to deliver. You want to charge for it. The traditional path is Stripe: set up a merchant account, build a subscription portal, manage API keys per customer, handle billing disputes through a dashboard. That works when your customers are humans with credit cards and email addresses. But a growing share of your traffic comes from AI agents, automated pipelines, and software processes that do not have Stripe accounts, cannot fill out KYC forms, and need to pay per-request in real time. They have wallets. They have USDC. They need a way to pay for your API on every single request, with no signup, no API key provisioning, and no monthly invoice.\nThe x402 protocol solves this. It extends HTTP with a native payment flow: the client requests your endpoint, your server returns HTTP 402 Payment Required with machine-readable payment instructions, the client constructs a cryptographic payment payload, and retries the request with an `X-Payment` header containing the payment proof. Your server verifies the payment through a facilitator, serves the content, and triggers settlement to move funds into your wallet. The entire flow completes in under two seconds. No accounts. No subscriptions. No API keys. Just HTTP and USDC.\nThis cookbook gives you working code to implement x402 in Express.js, FastAPI, and Cloudflare Workers. Every recipe is production-tested. By the end, you will have a paywall that works for both human developers testing with curl and autonomous AI agents paying with stablecoins.\n\n## What You'll Learn\n- Chapter 1: x402 Protocol Essentials\n- Chapter 2: Express.js Middleware (Node.js)\n- Chapter 3: FastAPI Integration (Python)\n- Chapter 4: Cloudflare Workers (Edge)\n- Chapter 5: Pricing Strategies\n- Chapter 6: Payment Verification Deep Dive\n- Chapter 7: Settlement & Revenue\n- Next Steps\n- Chapter 9: Testing\n- Chapter 10: Recipes\n\n## Full Guide\n\n# The x402 Merchant Integration Cookbook: Put Any API Behind a Crypto Paywall in Under an Hour\n\nYou built an API. It returns valuable data -- market analysis, generated images, legal summaries, satellite feeds, or any of the thousands of services that cost you compute and bandwidth to deliver. You want to charge for it. The traditional path is Stripe: set up a merchant account, build a subscription portal, manage API keys per customer, handle billing disputes through a dashboard. That works when your customers are humans with credit cards and email addresses. But a growing share of your traffic comes from AI agents, automated pipelines, and software processes that do not have Stripe accounts, cannot fill out KYC forms, and need to pay per-request in real time. They have wallets. They have USDC. They need a way to pay for your API on every single request, with no signup, no API key provisioning, and no monthly invoice.\n\nThe x402 protocol solves this. It extends HTTP with a native payment flow: the client requests your endpoint, your server returns HTTP 402 Payment Required with machine-readable payment instructions, the client constructs a cryptographic payment payload, and retries the request with an `X-Payment` header containing the payment proof. Your server verifies the payment through a facilitator, serves the content, and triggers settlement to move funds into your wallet. The entire flow completes in under two seconds. No accounts. No subscriptions. No API keys. Just HTTP and USDC.\n\nThis cookbook gives you working code to implement x402 in Express.js, FastAPI, and Cloudflare Workers. Every recipe is production-tested. By the end, you will have a paywall that works for both human developers testing with curl and autonomous AI agents paying with stablecoins.\n\n---\n\n\n> **Getting started**: All examples in this guide work with the GreenHelix sandbox\n> (https:\u002F\u002Fsandbox.greenhelix.net) which provides 500 free credits — no API key required.\n\n## Table of Contents\n\n1. [x402 Protocol Essentials](#chapter-1-x402-protocol-essentials)\n2. [Express.js Middleware (Node.js)](#chapter-2-expressjs-middleware-nodejs)\n3. [FastAPI Integration (Python)](#chapter-3-fastapi-integration-python)\n4. [Cloudflare Workers (Edge)](#chapter-4-cloudflare-workers-edge)\n5. [Pricing Strategies](#chapter-5-pricing-strategies)\n6. [Payment Verification Deep Dive](#chapter-6-payment-verification-deep-dive)\n7. [Settlement & Revenue](#chapter-7-settlement--revenue)\n9. [Testing](#chapter-9-testing)\n10. [Recipes](#chapter-10-recipes)\n\n---\n\n## Chapter 1: x402 Protocol Essentials\n\n### HTTP 402: The Status Code That Waited 30 Years\n\nHTTP 402 Payment Required was reserved in the original HTTP\u002F1.1 specification (RFC 2616, 1997) with the note \"reserved for future use.\" For nearly three decades, no widely adopted protocol defined what a 402 response should contain or how a client should respond to one. Browsers displayed a generic error. Developers used 401 or 403 instead. The status code sat dormant.\n\nx402 activates it. The protocol, launched by Coinbase in early 2025 and formalized by the x402 Foundation, defines the exact JSON structure of a 402 response, the cryptographic format of a payment payload, and the verification\u002Fsettlement flow through a facilitator service. It turns HTTP 402 from a placeholder into a fully functional payment primitive.\n\nThe core insight: HTTP already has a mechanism for \"you need to authenticate before accessing this resource\" (401 + `WWW-Authenticate` header). x402 applies the same pattern to payments: \"you need to pay before accessing this resource\" (402 + payment requirements in the response body and a base64-encoded version in the `PAYMENT-REQUIRED` header).\n\n### The x402 Payment Flow\n\nEvery x402 transaction follows a four-step flow:\n\n```\nClient                          Server                      Facilitator\n  |                                |                              |\n  |-- GET \u002Fapi\u002Fresource ---------->|                              |\n  |                                |                              |\n  |\u003C- 402 + PaymentRequired -------|                              |\n  |   {x402Version, accepts,       |                              |\n  |    paymentRequirements}        |                              |\n  |                                |                              |\n  |  [Client signs payment         |                              |\n  |   with wallet private key]     |                              |\n  |                                |                              |\n  |-- GET \u002Fapi\u002Fresource ---------->|                              |\n  |   X-Payment: \u003Cbase64 payload>  |                              |\n  |                                |-- POST \u002Fverify ------------->|\n  |                                |   {paymentPayload,           |\n  |                                |    requirements}             |\n  |                                |                              |\n  |                                |\u003C- {valid: true} -------------|\n  |                                |                              |\n  |\u003C- 200 + content + -------------|                              |\n  |   X-PAYMENT-RESPONSE header    |                              |\n  |                                |                              |\n  |                                |-- POST \u002Fsettle (async) ----->|\n  |                                |   {paymentPayload}           |\n  |                                |                              |\n```\n\nStep by step:\n\n1. **Initial request.** The client sends a standard HTTP request to your API endpoint. No special headers required on the first attempt.\n\n2. **402 response.** Your server checks whether the request includes a valid `X-Payment` header. If not, it responds with HTTP 402 and a JSON body containing payment requirements: how much to pay, which asset (USDC), which network (Base), where to send it (your wallet address), and how long the payment is valid.\n\n3. **Payment construction.** The client reads the payment requirements, constructs a payment payload (an EIP-712 typed data signature authorizing a USDC transfer), and base64-encodes it.\n\n4. **Retry with payment.** The client retries the same request, adding the `X-Payment` header with the encoded payload. Your server extracts the header, sends it to the facilitator's `\u002Fverify` endpoint along with the original requirements, and checks the response. If verification succeeds, your server serves the content and returns an `X-PAYMENT-RESPONSE` header. Asynchronously, your server calls the facilitator's `\u002Fsettle` endpoint to trigger the actual on-chain fund transfer.\n\n### The PaymentRequired Response Format\n\nThe 402 response body follows this structure:\n\n```json\n{\n  \"x402Version\": 1,\n  \"accepts\": [\n    {\n      \"scheme\": \"exact\",\n      \"network\": \"eip155:8453\",\n      \"maxAmountRequired\": \"1000000\",\n      \"resource\": \"https:\u002F\u002Fapi.example.com\u002Fdata\u002Fpremium\",\n      \"description\": \"Premium data feed access\",\n      \"mimeType\": \"application\u002Fjson\",\n      \"payTo\": \"0xYourWalletAddress\",\n      \"maxTimeoutSeconds\": 300,\n      \"asset\": \"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913\",\n      \"extra\": {\n        \"name\": \"USDC\",\n        \"version\": \"2\"\n      }\n    }\n  ],\n  \"error\": null\n}\n```\n\nKey fields:\n\n- **x402Version**: Protocol version. Currently `1`. Clients check this to determine payload format.\n- **accepts**: Array of payment options. Each entry describes one acceptable payment method. Most implementations include a single entry for USDC on Base.\n- **scheme**: The payment scheme. `\"exact\"` means the client must pay the exact amount specified. Future schemes may support range-based pricing or auctions.\n- **network**: The blockchain network in CAIP-2 format. `\"eip155:8453\"` is Base mainnet. `\"eip155:84532\"` is Base Sepolia (testnet).\n- **maxAmountRequired**: The price in the asset's smallest unit. USDC has 6 decimals, so `\"1000000\"` = $1.00 USD. Always a string, never a float.\n- **resource**: The canonical URL of the resource being purchased. Must match the request URL.\n- **payTo**: The merchant's wallet address. This is where USDC will be transferred on settlement.\n- **maxTimeoutSeconds**: How long the payment authorization is valid. After this, the client must construct a new payment. 300 seconds (5 minutes) is standard.\n- **asset**: The ERC-20 token contract address. On Base mainnet, USDC is `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`. On Base Sepolia, it is `0x036CbD53842c5426634e7929541eC2318f3dCF7e`.\n\nThe same JSON is also served base64-encoded in the `PAYMENT-REQUIRED` response header. This allows clients that do not parse the response body (such as lightweight HTTP agents) to extract payment requirements from headers alone.\n\n### USDC on Base\n\nx402 uses USDC on Base as its primary payment rail. The reasons are practical:\n\n- **Sub-cent transaction fees.** Base L2 transactions cost fractions of a cent, making micropayments (pay $0.01 per API call) economically viable. On Ethereum mainnet, gas fees alone would exceed the payment amount for small transactions.\n- **Fast finality.** Base transactions confirm in approximately 2 seconds. The entire x402 flow (request, 402, payment, verify, settle) completes in under 3 seconds.\n- **USDC stability.** USDC is pegged 1:1 to USD. Merchants receive dollars, not volatile tokens. No hedging required.\n\nFor development and testing, use Base Sepolia testnet. The network ID changes from `eip155:8453` to `eip155:84532`, and the USDC contract address changes. Everything else -- the payment flow, the facilitator endpoints, the verification logic -- remains identical.\n\n### The x402 Foundation and the Facilitator Role\n\nThe facilitator is the critical infrastructure component that makes x402 practical. Without it, every merchant would need to run their own on-chain verification node, parse EIP-712 signatures, check USDC allowances, and submit settlement transactions. The facilitator abstracts all of this.\n\nThe x402 Foundation operates the reference facilitator at `https:\u002F\u002Fx402.org\u002Ffacilitator`. It exposes two endpoints:\n\n**POST \u002Fverify** -- Validates a payment payload against the merchant's requirements. The facilitator checks:\n- The signature is valid (signed by a wallet with sufficient USDC balance)\n- The amount matches or exceeds `maxAmountRequired`\n- The payment has not expired (`maxTimeoutSeconds`)\n- The `payTo` address matches the merchant's wallet\n- The asset and network match the requirements\n\n**POST \u002Fsettle** -- Triggers the on-chain USDC transfer. The facilitator submits a transaction to Base that transfers USDC from the payer's wallet to the merchant's `payTo` address. Settlement is asynchronous -- the merchant has already served the content before settlement completes. If settlement fails (insufficient balance, revoked allowance), the facilitator retries with exponential backoff.\n\nThe facilitator is a trust component. The merchant trusts it to honestly verify payment signatures. The payer trusts it to only settle payments for content that was actually served. In practice, the x402 Foundation facilitator is the default, but merchants can run their own facilitator or use third-party alternatives.\n\n### Amounts: Strings, Not Floats\n\nEvery amount in x402 is a string representation of an integer in the asset's smallest unit. For USDC (6 decimals):\n\n| USD Price | maxAmountRequired |\n|-----------|-------------------|\n| $0.01     | \"10000\"           |\n| $0.10     | \"100000\"          |\n| $1.00     | \"1000000\"         |\n| $5.00     | \"5000000\"         |\n| $29.00    | \"29000000\"        |\n\nThe conversion formula: `maxAmountRequired = String(Math.round(price_usd * 1_000_000))`.\n\nNever use floating-point arithmetic for amounts. IEEE 754 floating-point cannot represent all decimal values exactly. `0.1 + 0.2 !== 0.3` in JavaScript. Use integer math or dedicated decimal libraries.\n\n---\n\n## Chapter 2: Express.js Middleware (Node.js)\n\n### Building x402 Middleware from Scratch\n\nThe Felix dashboard (the reference x402 storefront) implements x402 inline in a route handler. That works for a single-route storefront, but for an API with dozens of endpoints, you need middleware that applies the payment gate to any route.\n\nThe middleware pattern:\n1. Check if the route requires payment (configurable per-route pricing).\n2. If the request has no `X-Payment` header, return 402 with payment requirements.\n3. If the request has an `X-Payment` header, verify it with the facilitator.\n4. If verification passes, call `next()` to let the route handler serve content.\n5. After the response, trigger settlement asynchronously.\n\n```javascript\n'use strict';\n\n\u002F**\n * x402 Express.js middleware.\n *\n * Usage:\n *   const { x402Paywall } = require('.\u002Fx402-middleware');\n *   app.get('\u002Fapi\u002Fpremium', x402Paywall({ priceUsd: 1.00 }), handler);\n *\u002F\n\nconst FACILITATOR_URL = process.env.X402_FACILITATOR_URL || 'https:\u002F\u002Fx402.org\u002Ffacilitator';\nconst WALLET = process.env.MERCHANT_WALLET_ADDRESS;\nconst NETWORK = process.env.X402_NETWORK || 'base-sepolia';\n\nconst NETWORK_ID = NETWORK === 'base-mainnet' ? 'eip155:8453' : 'eip155:84532';\nconst USDC_ADDRESS = NETWORK === 'base-mainnet'\n  ? '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913'\n  : '0x036CbD53842c5426634e7929541eC2318f3dCF7e';\n\n\u002F**\n * Build the paymentRequirements array for a given price and resource URL.\n *\u002F\nfunction buildPaymentRequirements(priceUsd, resource, description) {\n  const maxAmountRequired = String(Math.round(priceUsd * 1_000_000));\n\n  return [{\n    scheme: 'exact',\n    network: NETWORK_ID,\n    maxAmountRequired,\n    resource,\n    description: description || `Access to ${resource}`,\n    mimeType: 'application\u002Fjson',\n    payTo: WALLET,\n    maxTimeoutSeconds: 300,\n    asset: USDC_ADDRESS,\n    extra: { name: 'USDC', version: '2' },\n  }];\n}\n\n\u002F**\n * Send a 402 response with payment requirements.\n *\u002F\nfunction send402(res, paymentRequirements, error = null) {\n  const pr = {\n    x402Version: 1,\n    accepts: paymentRequirements,\n    error,\n  };\n  res.setHeader('PAYMENT-REQUIRED', Buffer.from(JSON.stringify(pr)).toString('base64'));\n  return res.status(402).json(pr);\n}\n\n\u002F**\n * Verify a payment payload with the facilitator.\n *\n * Returns { valid: boolean, error?: string }.\n *\u002F\nasync function verifyPayment(xPayment, paymentRequirements) {\n  const requirement = paymentRequirements[0];\n\n  try {\n    const response = await fetch(`${FACILITATOR_URL}\u002Fverify`, {\n      method: 'POST',\n      headers: { 'Content-Type': 'application\u002Fjson' },\n      body: JSON.stringify({\n        x402Version: 1,\n        paymentPayload: xPayment,\n        requirements: {\n          scheme: requirement.scheme,\n          network: requirement.network,\n          maxAmountRequired: requirement.maxAmountRequired,\n          resource: requirement.resource,\n          payTo: requirement.payTo,\n          asset: requirement.asset,\n          maxTimeoutSeconds: requirement.maxTimeoutSeconds,\n        },\n      }),\n    });\n\n    if (response.ok) {\n      return { valid: true };\n    }\n\n    const body = await response.text();\n    return { valid: false, error: `Facilitator returned ${response.status}: ${body}` };\n  } catch (err) {\n    return { valid: false, error: `Facilitator unreachable: ${err.message}` };\n  }\n}\n\n\u002F**\n * Trigger settlement asynchronously. Fire-and-forget with retry.\n *\u002F\nfunction settlePayment(xPayment, retries = 3) {\n  const attemptSettle = (attempt) => {\n    fetch(`${FACILITATOR_URL}\u002Fsettle`, {\n      method: 'POST',\n      headers: { 'Content-Type': 'application\u002Fjson' },\n      body: JSON.stringify({\n        x402Version: 1,\n        paymentPayload: xPayment,\n      }),\n    })\n    .then(r => {\n      if (!r.ok && attempt \u003C retries) {\n        const delay = Math.pow(2, attempt) * 1000;\n        console.warn(`[x402] settle retry ${attempt + 1}\u002F${retries} in ${delay}ms`);\n        setTimeout(() => attemptSettle(attempt + 1), delay);\n      } else if (!r.ok) {\n        console.error(`[x402] settle failed after ${retries} retries: HTTP ${r.status}`);\n      } else {\n        console.log('[x402] settlement successful');\n      }\n    })\n    .catch(err => {\n      if (attempt \u003C retries) {\n        const delay = Math.pow(2, attempt) * 1000;\n        setTimeout(() => attemptSettle(attempt + 1), delay);\n      } else {\n        console.error(`[x402] settle error after ${retries} retries: ${err.message}`);\n      }\n    });\n  };\n\n  attemptSettle(0);\n}\n\n\u002F**\n * Express middleware factory. Wraps any route with x402 payment gating.\n *\n * Options:\n *   priceUsd: number       -- Price in USD (required)\n *   description: string    -- Description shown to payers (optional)\n *   onPayment: function    -- Callback after successful payment (optional)\n *                             Receives (req, paymentPayload, priceUsd)\n *\n * Example:\n *   app.get('\u002Fapi\u002Fdata', x402Paywall({ priceUsd: 0.50 }), (req, res) => {\n *     res.json({ data: 'premium content' });\n *   });\n *\u002F\nfunction x402Paywall(options) {\n  const { priceUsd, description, onPayment } = options;\n\n  if (!WALLET) {\n    return (_req, res, _next) => {\n      res.status(503).json({ error: 'MERCHANT_WALLET_ADDRESS not configured' });\n    };\n  }\n\n  if (typeof priceUsd !== 'number' || priceUsd \u003C= 0) {\n    throw new Error('x402Paywall requires a positive priceUsd');\n  }\n\n  return async (req, res, next) => {\n    const resource = `https:\u002F\u002F${req.get('host')}${req.originalUrl}`;\n    const paymentRequirements = buildPaymentRequirements(priceUsd, resource, description);\n\n    \u002F\u002F No payment header: return 402\n    const xPayment = req.headers['x-payment'];\n    if (!xPayment) {\n      return send402(res, paymentRequirements);\n    }\n\n    \u002F\u002F Verify payment\n    const verification = await verifyPayment(xPayment, paymentRequirements);\n    if (!verification.valid) {\n      return send402(res, paymentRequirements, verification.error || 'Payment verification failed');\n    }\n\n    \u002F\u002F Payment verified -- set response header and proceed\n    res.setHeader('X-PAYMENT-RESPONSE', Buffer.from(JSON.stringify({\n      success: true,\n    })).toString('base64'));\n\n    \u002F\u002F Call next() to let the route handler serve content\n    next();\n\n    \u002F\u002F After response, settle asynchronously\n    settlePayment(xPayment);\n\n    \u002F\u002F Optional callback for logging\u002Fanalytics\n    if (typeof onPayment === 'function') {\n      try {\n        onPayment(req, xPayment, priceUsd);\n      } catch (err) {\n        console.error('[x402] onPayment callback error:', err.message);\n      }\n    }\n  };\n}\n\nmodule.exports = { x402Paywall, buildPaymentRequirements, verifyPayment, settlePayment };\n```\n\n### Complete Working Example: Express API with x402 Paywall\n\n```javascript\n'use strict';\n\nconst express = require('express');\nconst { x402Paywall } = require('.\u002Fx402-middleware');\n\nconst app = express();\napp.use(express.json({ limit: '10kb' }));\n\n\u002F\u002F Free endpoint -- no payment required\napp.get('\u002Fapi\u002Fv1\u002Fhealth', (_req, res) => {\n  res.json({ status: 'ok', timestamp: new Date().toISOString() });\n});\n\n\u002F\u002F Free tier -- limited data\napp.get('\u002Fapi\u002Fv1\u002Fweather\u002Fsummary', (_req, res) => {\n  res.json({\n    location: 'San Francisco',\n    temperature_f: 62,\n    conditions: 'Partly cloudy',\n    note: 'Upgrade to \u002Fapi\u002Fv1\u002Fweather\u002Ffull for hourly forecasts, alerts, and historical data.',\n  });\n});\n\n\u002F\u002F Paid endpoint -- $0.05 per request\napp.get('\u002Fapi\u002Fv1\u002Fweather\u002Ffull',\n  x402Paywall({\n    priceUsd: 0.05,\n    description: 'Full weather data: hourly forecast, alerts, historical',\n    onPayment: (req, _payload, price) => {\n      console.log(`[sale] ${req.ip} paid $${price} for ${req.path}`);\n    },\n  }),\n  (_req, res) => {\n    res.json({\n      location: 'San Francisco',\n      temperature_f: 62,\n      conditions: 'Partly cloudy',\n      hourly_forecast: [\n        { hour: '14:00', temp_f: 63, conditions: 'Partly cloudy' },\n        { hour: '15:00', temp_f: 64, conditions: 'Sunny' },\n        { hour: '16:00', temp_f: 63, conditions: 'Sunny' },\n        { hour: '17:00', temp_f: 61, conditions: 'Fog rolling in' },\n      ],\n      alerts: [],\n      historical: {\n        avg_high_f: 65,\n        avg_low_f: 52,\n        record_high_f: 98,\n        record_low_f: 28,\n      },\n    });\n  }\n);\n\n\u002F\u002F Paid endpoint -- $1.00 per request (premium analysis)\napp.get('\u002Fapi\u002Fv1\u002Fanalysis\u002F:ticker',\n  x402Paywall({\n    priceUsd: 1.00,\n    description: 'AI-powered stock analysis report',\n  }),\n  (req, res) => {\n    const ticker = req.params.ticker.toUpperCase();\n    res.json({\n      ticker,\n      analysis: `Comprehensive analysis of ${ticker}...`,\n      sentiment: 'bullish',\n      confidence: 0.82,\n      generated_at: new Date().toISOString(),\n    });\n  }\n);\n\nconst PORT = process.env.PORT || 3000;\napp.listen(PORT, () => {\n  console.log(`x402 API running on port ${PORT}`);\n  console.log(`Wallet: ${process.env.MERCHANT_WALLET_ADDRESS}`);\n  console.log(`Network: ${process.env.X402_NETWORK || 'base-sepolia'}`);\n});\n```\n\n### Testing with curl\n\nTest the free endpoint:\n\n```bash\ncurl -s http:\u002F\u002Flocalhost:3000\u002Fapi\u002Fv1\u002Fhealth | jq .\n# {\"status\":\"ok\",\"timestamp\":\"2026-04-07T12:00:00.000Z\"}\n```\n\nTest the paid endpoint without payment (expect 402):\n\n```bash\ncurl -s -w \"\\nHTTP Status: %{http_code}\\n\" \\\n  http:\u002F\u002Flocalhost:3000\u002Fapi\u002Fv1\u002Fweather\u002Ffull | jq .\n# {\n#   \"x402Version\": 1,\n#   \"accepts\": [{\n#     \"scheme\": \"exact\",\n#     \"network\": \"eip155:84532\",\n#     \"maxAmountRequired\": \"50000\",\n#     ...\n#   }],\n#   \"error\": null\n# }\n# HTTP Status: 402\n```\n\nExtract the PAYMENT-REQUIRED header (base64-encoded):\n\n```bash\ncurl -s -D - http:\u002F\u002Flocalhost:3000\u002Fapi\u002Fv1\u002Fweather\u002Ffull 2>&1 | grep -i payment-required\n# PAYMENT-REQUIRED: eyJ4NDAyVmVyc2lvbiI6MSwiYWNjZXB0cyI6Wy...\n```\n\nTo complete the payment, you need a client SDK that can sign EIP-712 payloads. The `@anthropic-ai\u002Fsdk` and `@coinbase\u002Fx402` packages both support this. See Chapter 9 for test tooling.\n\n### Per-Route Pricing Configuration\n\nFor APIs with many endpoints, externalize pricing to a configuration object:\n\n```javascript\nconst PRICING = {\n  '\u002Fapi\u002Fv1\u002Fweather\u002Ffull': { priceUsd: 0.05, description: 'Full weather data' },\n  '\u002Fapi\u002Fv1\u002Fanalysis\u002F:ticker': { priceUsd: 1.00, description: 'Stock analysis' },\n  '\u002Fapi\u002Fv1\u002Fsatellite\u002F:region': { priceUsd: 2.50, description: 'Satellite imagery' },\n  '\u002Fapi\u002Fv1\u002Flegal\u002Fsearch': { priceUsd: 0.25, description: 'Legal document search' },\n};\n\n\u002F\u002F Apply paywall to all priced routes\nfor (const [route, config] of Object.entries(PRICING)) {\n  app.get(route, x402Paywall(config), routeHandlers[route]);\n}\n```\n\n---\n\n## Chapter 3: FastAPI Integration (Python)\n\n### FastAPI Middleware Pattern\n\nFastAPI's dependency injection system is the natural integration point for x402. Instead of middleware that wraps every request, you create a dependency that route handlers declare when they require payment. Routes without the dependency remain free.\n\n```python\n\"\"\"\nx402 FastAPI integration.\n\nUsage:\n    from x402_deps import x402_required\n\n    @app.get(\"\u002Fapi\u002Fv1\u002Fpremium\")\n    async def premium_data(payment: dict = Depends(x402_required(price_usd=0.50))):\n        return {\"data\": \"premium content\", \"payment\": payment}\n\"\"\"\n\nimport os\nimport json\nimport base64\nimport math\nfrom typing import Optional\n\nimport httpx\nfrom fastapi import Request, HTTPException\nfrom fastapi.responses import JSONResponse\n\nFACILITATOR_URL = os.environ.get(\"X402_FACILITATOR_URL\", \"https:\u002F\u002Fx402.org\u002Ffacilitator\")\nWALLET = os.environ.get(\"MERCHANT_WALLET_ADDRESS\", \"\")\nNETWORK = os.environ.get(\"X402_NETWORK\", \"base-sepolia\")\n\nNETWORK_ID = \"eip155:8453\" if NETWORK == \"base-mainnet\" else \"eip155:84532\"\nUSDC_ADDRESS = (\n    \"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913\"\n    if NETWORK == \"base-mainnet\"\n    else \"0x036CbD53842c5426634e7929541eC2318f3dCF7e\"\n)\n\n# Reusable async HTTP client with connection pooling\n_http_client: Optional[httpx.AsyncClient] = None\n\n\nasync def get_http_client() -> httpx.AsyncClient:\n    \"\"\"Lazy-initialize a shared httpx.AsyncClient.\"\"\"\n    global _http_client\n    if _http_client is None or _http_client.is_closed:\n        _http_client = httpx.AsyncClient(timeout=10.0)\n    return _http_client\n\n\ndef build_payment_requirements(\n    price_usd: float,\n    resource: str,\n    description: str = \"\",\n) -> list[dict]:\n    \"\"\"Build the paymentRequirements array for a 402 response.\"\"\"\n    max_amount = str(round(price_usd * 1_000_000))\n    return [\n        {\n            \"scheme\": \"exact\",\n            \"network\": NETWORK_ID,\n            \"maxAmountRequired\": max_amount,\n            \"resource\": resource,\n            \"description\": description or f\"Access to {resource}\",\n            \"mimeType\": \"application\u002Fjson\",\n            \"payTo\": WALLET,\n            \"maxTimeoutSeconds\": 300,\n            \"asset\": USDC_ADDRESS,\n            \"extra\": {\"name\": \"USDC\", \"version\": \"2\"},\n        }\n    ]\n\n\ndef payment_required_response(\n    payment_requirements: list[dict],\n    error: Optional[str] = None,\n) -> JSONResponse:\n    \"\"\"Build a 402 JSONResponse with the PAYMENT-REQUIRED header.\"\"\"\n    body = {\n        \"x402Version\": 1,\n        \"accepts\": payment_requirements,\n        \"error\": error,\n    }\n    encoded = base64.b64encode(json.dumps(body).encode()).decode()\n    return JSONResponse(\n        status_code=402,\n        content=body,\n        headers={\"PAYMENT-REQUIRED\": encoded},\n    )\n\n\nasync def verify_payment(\n    x_payment: str,\n    payment_requirements: list[dict],\n) -> dict:\n    \"\"\"Verify a payment payload with the facilitator.\n\n    Returns {\"valid\": True} on success, {\"valid\": False, \"error\": \"...\"} on failure.\n    \"\"\"\n    requirement = payment_requirements[0]\n    client = await get_http_client()\n\n    try:\n        response = await client.post(\n            f\"{FACILITATOR_URL}\u002Fverify\",\n            json={\n                \"x402Version\": 1,\n                \"paymentPayload\": x_payment,\n                \"requirements\": {\n                    \"scheme\": requirement[\"scheme\"],\n                    \"network\": requirement[\"network\"],\n                    \"maxAmountRequired\": requirement[\"maxAmountRequired\"],\n                    \"resource\": requirement[\"resource\"],\n                    \"payTo\": requirement[\"payTo\"],\n                    \"asset\": requirement[\"asset\"],\n                    \"maxTimeoutSeconds\": requirement[\"maxTimeoutSeconds\"],\n                },\n            },\n        )\n        if response.status_code == 200:\n            return {\"valid\": True}\n        return {\"valid\": False, \"error\": f\"Facilitator returned {response.status_code}\"}\n    except httpx.RequestError as exc:\n        return {\"valid\": False, \"error\": f\"Facilitator unreachable: {exc}\"}\n\n\nasync def settle_payment(x_payment: str, max_retries: int = 3) -> None:\n    \"\"\"Trigger settlement asynchronously with retry.\"\"\"\n    client = await get_http_client()\n\n    for attempt in range(max_retries):\n        try:\n            response = await client.post(\n                f\"{FACILITATOR_URL}\u002Fsettle\",\n                json={\n                    \"x402Version\": 1,\n                    \"paymentPayload\": x_payment,\n                },\n            )\n            if response.status_code == 200:\n                return\n            if attempt \u003C max_retries - 1:\n                import asyncio\n                await asyncio.sleep(2 ** attempt)\n        except httpx.RequestError:\n            if attempt \u003C max_retries - 1:\n                import asyncio\n                await asyncio.sleep(2 ** attempt)\n\n\ndef x402_required(\n    price_usd: float,\n    description: str = \"\",\n):\n    \"\"\"FastAPI dependency factory for x402 payment gating.\n\n    Usage:\n        @app.get(\"\u002Fpremium\")\n        async def premium(payment: dict = Depends(x402_required(price_usd=1.00))):\n            return {\"data\": \"...\"}\n    \"\"\"\n    if not WALLET:\n        raise RuntimeError(\"MERCHANT_WALLET_ADDRESS environment variable is required\")\n\n    async def dependency(request: Request) -> dict:\n        # Build resource URL\n        scheme = request.url.scheme\n        host = request.headers.get(\"host\", request.url.netloc)\n        resource = f\"https:\u002F\u002F{host}{request.url.path}\"\n\n        payment_requirements = build_payment_requirements(\n            price_usd, resource, description\n        )\n\n        # Check for X-Payment header\n        x_payment = request.headers.get(\"x-payment\")\n        if not x_payment:\n            raise HTTPException(\n                status_code=402,\n                detail={\n                    \"x402Version\": 1,\n                    \"accepts\": payment_requirements,\n                    \"error\": None,\n                },\n                headers={\n                    \"PAYMENT-REQUIRED\": base64.b64encode(\n                        json.dumps({\n                            \"x402Version\": 1,\n                            \"accepts\": payment_requirements,\n                            \"error\": None,\n                        }).encode()\n                    ).decode()\n                },\n            )\n\n        # Verify payment\n        result = await verify_payment(x_payment, payment_requirements)\n        if not result[\"valid\"]:\n            raise HTTPException(\n                status_code=402,\n                detail={\n                    \"x402Version\": 1,\n                    \"accepts\": payment_requirements,\n                    \"error\": result.get(\"error\", \"Payment verification failed\"),\n                },\n                headers={\n                    \"PAYMENT-REQUIRED\": base64.b64encode(\n                        json.dumps({\n                            \"x402Version\": 1,\n                            \"accepts\": payment_requirements,\n                            \"error\": result.get(\"error\"),\n                        }).encode()\n                    ).decode()\n                },\n            )\n\n        # Payment verified -- trigger settlement in background\n        import asyncio\n        asyncio.create_task(settle_payment(x_payment))\n\n        return {\n            \"verified\": True,\n            \"price_usd\": price_usd,\n            \"resource\": resource,\n        }\n\n    return dependency\n```\n\n### Complete Working Example: FastAPI with x402\n\n```python\n\"\"\"\nx402 FastAPI example server.\n\nRun:\n    MERCHANT_WALLET_ADDRESS=0x... uvicorn server:app --port 8000\n\"\"\"\n\nimport asyncio\nfrom fastapi import FastAPI, Depends, Response\nfrom x402_deps import x402_required\n\napp = FastAPI(\n    title=\"x402 Weather API\",\n    description=\"Weather data API with x402 micropayments\",\n    version=\"1.0.0\",\n)\n\n\n@app.get(\"\u002Fapi\u002Fv1\u002Fhealth\")\nasync def health():\n    \"\"\"Free health check endpoint.\"\"\"\n    return {\"status\": \"ok\"}\n\n\n@app.get(\"\u002Fapi\u002Fv1\u002Fweather\u002Fsummary\")\nasync def weather_summary():\n    \"\"\"Free tier: basic weather data.\"\"\"\n    return {\n        \"location\": \"San Francisco\",\n        \"temperature_f\": 62,\n        \"conditions\": \"Partly cloudy\",\n    }\n\n\n@app.get(\"\u002Fapi\u002Fv1\u002Fweather\u002Ffull\")\nasync def weather_full(\n    response: Response,\n    payment: dict = Depends(x402_required(\n        price_usd=0.05,\n        description=\"Full weather data with hourly forecast\",\n    )),\n):\n    \"\"\"Paid endpoint: $0.05 per request for full weather data.\"\"\"\n    import json, base64\n    response.headers[\"X-PAYMENT-RESPONSE\"] = base64.b64encode(\n        json.dumps({\"success\": True}).encode()\n    ).decode()\n\n    return {\n        \"location\": \"San Francisco\",\n        \"temperature_f\": 62,\n        \"conditions\": \"Partly cloudy\",\n        \"hourly_forecast\": [\n            {\"hour\": \"14:00\", \"temp_f\": 63, \"conditions\": \"Partly cloudy\"},\n            {\"hour\": \"15:00\", \"temp_f\": 64, \"conditions\": \"Sunny\"},\n            {\"hour\": \"16:00\", \"temp_f\": 63, \"conditions\": \"Sunny\"},\n        ],\n        \"alerts\": [],\n        \"payment_info\": payment,\n    }\n\n\n@app.get(\"\u002Fapi\u002Fv1\u002Fanalysis\u002F{ticker}\")\nasync def stock_analysis(\n    ticker: str,\n    response: Response,\n    payment: dict = Depends(x402_required(\n        price_usd=1.00,\n        description=\"AI-powered stock analysis report\",\n    )),\n):\n    \"\"\"Paid endpoint: $1.00 per request for stock analysis.\"\"\"\n    import json, base64\n    response.headers[\"X-PAYMENT-RESPONSE\"] = base64.b64encode(\n        json.dumps({\"success\": True}).encode()\n    ).decode()\n\n    return {\n        \"ticker\": ticker.upper(),\n        \"analysis\": f\"Comprehensive analysis of {ticker.upper()}...\",\n        \"sentiment\": \"bullish\",\n        \"confidence\": 0.82,\n    }\n```\n\n### Pytest Test Patterns\n\n```python\n\"\"\"\nTests for x402 FastAPI integration.\n\nRun:\n    pytest test_x402.py -x -q\n\"\"\"\n\nimport json\nimport base64\nfrom unittest.mock import AsyncMock, patch\n\nimport pytest\nfrom httpx import AsyncClient\nfrom fastapi.testclient import TestClient\n\nfrom server import app\n\n\n@pytest.fixture\ndef client():\n    \"\"\"Synchronous test client for FastAPI.\"\"\"\n    return TestClient(app)\n\n\nclass TestFreeEndpoints:\n    \"\"\"Free endpoints should work without any payment.\"\"\"\n\n    def test_health(self, client):\n        response = client.get(\"\u002Fapi\u002Fv1\u002Fhealth\")\n        assert response.status_code == 200\n        assert response.json()[\"status\"] == \"ok\"\n\n    def test_weather_summary(self, client):\n        response = client.get(\"\u002Fapi\u002Fv1\u002Fweather\u002Fsummary\")\n        assert response.status_code == 200\n        assert \"temperature_f\" in response.json()\n\n\nclass TestPaymentRequired:\n    \"\"\"Paid endpoints should return 402 without X-Payment header.\"\"\"\n\n    def test_weather_full_returns_402(self, client):\n        response = client.get(\"\u002Fapi\u002Fv1\u002Fweather\u002Ffull\")\n        assert response.status_code == 402\n\n        body = response.json()\n        detail = body.get(\"detail\", body)\n        assert detail[\"x402Version\"] == 1\n        assert len(detail[\"accepts\"]) == 1\n\n        requirement = detail[\"accepts\"][0]\n        assert requirement[\"scheme\"] == \"exact\"\n        assert requirement[\"maxAmountRequired\"] == \"50000\"  # $0.05\n        assert requirement[\"asset\"] is not None\n        assert requirement[\"payTo\"] is not None\n\n    def test_402_has_payment_required_header(self, client):\n        response = client.get(\"\u002Fapi\u002Fv1\u002Fweather\u002Ffull\")\n        assert response.status_code == 402\n        assert \"payment-required\" in response.headers\n\n        # Decode and verify the header\n        encoded = response.headers[\"payment-required\"]\n        decoded = json.loads(base64.b64decode(encoded))\n        assert decoded[\"x402Version\"] == 1\n\n    def test_analysis_returns_402(self, client):\n        response = client.get(\"\u002Fapi\u002Fv1\u002Fanalysis\u002FAAPL\")\n        assert response.status_code == 402\n\n        body = response.json()\n        detail = body.get(\"detail\", body)\n        requirement = detail[\"accepts\"][0]\n        assert requirement[\"maxAmountRequired\"] == \"1000000\"  # $1.00\n\n\nclass TestPaymentVerification:\n    \"\"\"Test the payment verification flow with mocked facilitator.\"\"\"\n\n    @patch(\"x402_deps.verify_payment\", new_callable=AsyncMock)\n    @patch(\"x402_deps.settle_payment\", new_callable=AsyncMock)\n    def test_valid_payment_serves_content(\n        self, mock_settle, mock_verify, client\n    ):\n        mock_verify.return_value = {\"valid\": True}\n        mock_settle.return_value = None\n\n        response = client.get(\n            \"\u002Fapi\u002Fv1\u002Fweather\u002Ffull\",\n            headers={\"X-Payment\": \"valid-test-payload\"},\n        )\n        assert response.status_code == 200\n        data = response.json()\n        assert \"hourly_forecast\" in data\n\n    @patch(\"x402_deps.verify_payment\", new_callable=AsyncMock)\n    def test_invalid_payment_returns_402(self, mock_verify, client):\n        mock_verify.return_value = {\n            \"valid\": False,\n            \"error\": \"Invalid signature\",\n        }\n\n        response = client.get(\n            \"\u002Fapi\u002Fv1\u002Fweather\u002Ffull\",\n            headers={\"X-Payment\": \"invalid-payload\"},\n        )\n        assert response.status_code == 402\n\n    @patch(\"x402_deps.verify_payment\", new_callable=AsyncMock)\n    @patch(\"x402_deps.settle_payment\", new_callable=AsyncMock)\n    def test_settlement_triggered_after_verification(\n        self, mock_settle, mock_verify, client\n    ):\n        mock_verify.return_value = {\"valid\": True}\n        mock_settle.return_value = None\n\n        client.get(\n            \"\u002Fapi\u002Fv1\u002Fweather\u002Ffull\",\n            headers={\"X-Payment\": \"valid-payload\"},\n        )\n\n        # Settlement should be triggered (as a background task)\n        # In test mode, the asyncio task may need explicit await\n        # This verifies the function was at least called\n        mock_settle.assert_called_once_with(\"valid-payload\")\n\n\nclass TestAmountCalculation:\n    \"\"\"Verify correct USD to USDC smallest-unit conversion.\"\"\"\n\n    def test_five_cents(self, client):\n        response = client.get(\"\u002Fapi\u002Fv1\u002Fweather\u002Ffull\")\n        detail = response.json().get(\"detail\", response.json())\n        assert detail[\"accepts\"][0][\"maxAmountRequired\"] == \"50000\"\n\n    def test_one_dollar(self, client):\n        response = client.get(\"\u002Fapi\u002Fv1\u002Fanalysis\u002FTSLA\")\n        detail = response.json().get(\"detail\", response.json())\n        assert detail[\"accepts\"][0][\"maxAmountRequired\"] == \"1000000\"\n```\n\n### Payment Verification Decorator (Alternative Pattern)\n\nFor simpler codebases that prefer decorators over dependency injection:\n\n```python\nimport functools\nfrom fastapi import Request, Response\n\ndef require_x402_payment(price_usd: float, description: str = \"\"):\n    \"\"\"Decorator that gates a FastAPI route behind x402 payment.\n\n    Usage:\n        @app.get(\"\u002Fpremium\")\n        @require_x402_payment(price_usd=0.50)\n        async def premium(request: Request):\n            return {\"data\": \"...\"}\n    \"\"\"\n    def decorator(func):\n        @functools.wraps(func)\n        async def wrapper(request: Request, *args, **kwargs):\n            host = request.headers.get(\"host\", request.url.netloc)\n            resource = f\"https:\u002F\u002F{host}{request.url.path}\"\n            requirements = build_payment_requirements(price_usd, resource, description)\n\n            x_payment = request.headers.get(\"x-payment\")\n            if not x_payment:\n                return payment_required_response(requirements)\n\n            result = await verify_payment(x_payment, requirements)\n            if not result[\"valid\"]:\n                return payment_required_response(\n                    requirements,\n                    error=result.get(\"error\", \"Verification failed\"),\n                )\n\n            # Trigger settlement\n            import asyncio\n            asyncio.create_task(settle_payment(x_payment))\n\n            # Call the original handler\n            return await func(request, *args, **kwargs)\n        return wrapper\n    return decorator\n```\n\n---\n\n## Chapter 4: Cloudflare Workers (Edge)\n\n### Why Edge + x402\n\nCloudflare Workers execute at over 300 edge locations worldwide. When you deploy an x402 paywall as a Worker, payment verification happens at the edge closest to the client. A user in Tokyo hitting your API gets sub-50ms response times for the 402 and near-instant verification turnaround, compared to the 200-300ms round-trip to a centralized server in US-East.\n\nFor x402 specifically, edge deployment has two advantages:\n\n1. **The 402 response is instant.** No payment header means no backend processing. The Worker returns the payment requirements object from memory in under 1ms. This is critical because every x402 transaction starts with a 402 -- making this response fast improves the total transaction time.\n\n2. **Verification can be cached.** The same payment payload from the same wallet, for the same resource, within the same timeout window, will always verify the same way. You can cache verification results in Cloudflare KV to avoid hitting the facilitator on every request.\n\n### Worker Implementation\n\n```javascript\n\u002F**\n * x402 Cloudflare Worker.\n *\n * Deploys an x402 paywall at the edge. Verifies payments via the x402\n * facilitator and caches verification results in KV for repeat requests.\n *\n * Environment variables (wrangler.toml):\n *   MERCHANT_WALLET_ADDRESS - Your wallet address\n *   X402_NETWORK            - \"base-mainnet\" or \"base-sepolia\"\n *   X402_FACILITATOR_URL    - Facilitator URL (default: https:\u002F\u002Fx402.org\u002Ffacilitator)\n *\n * KV Namespace binding:\n *   PAYMENT_CACHE           - For caching verification results\n *\u002F\n\nconst USDC_ADDRESSES = {\n  'base-mainnet': '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',\n  'base-sepolia': '0x036CbD53842c5426634e7929541eC2318f3dCF7e',\n};\n\nconst NETWORK_IDS = {\n  'base-mainnet': 'eip155:8453',\n  'base-sepolia': 'eip155:84532',\n};\n\n\u002F\u002F Route pricing configuration\nconst PRICING = {\n  '\u002Fapi\u002Fv1\u002Fweather\u002Ffull': { priceUsd: 0.05, description: 'Full weather data' },\n  '\u002Fapi\u002Fv1\u002Fanalysis': { priceUsd: 1.00, description: 'Stock analysis report' },\n  '\u002Fapi\u002Fv1\u002Fsatellite': { priceUsd: 2.50, description: 'Satellite imagery' },\n};\n\nfunction getRoutePrice(pathname) {\n  \u002F\u002F Exact match first\n  if (PRICING[pathname]) return PRICING[pathname];\n\n  \u002F\u002F Prefix match for parameterized routes\n  for (const [route, config] of Object.entries(PRICING)) {\n    if (pathname.startsWith(route)) return config;\n  }\n\n  return null; \u002F\u002F Free route\n}\n\nfunction buildPaymentRequirements(priceUsd, resource, description, env) {\n  const network = env.X402_NETWORK || 'base-sepolia';\n  const maxAmountRequired = String(Math.round(priceUsd * 1_000_000));\n\n  return [{\n    scheme: 'exact',\n    network: NETWORK_IDS[network],\n    maxAmountRequired,\n    resource,\n    description,\n    mimeType: 'application\u002Fjson',\n    payTo: env.MERCHANT_WALLET_ADDRESS,\n    maxTimeoutSeconds: 300,\n    asset: USDC_ADDRESSES[network],\n    extra: { name: 'USDC', version: '2' },\n  }];\n}\n\nfunction make402Response(paymentRequirements, error = null) {\n  const body = {\n    x402Version: 1,\n    accepts: paymentRequirements,\n    error,\n  };\n  const encoded = btoa(JSON.stringify(body));\n\n  return new Response(JSON.stringify(body), {\n    status: 402,\n    headers: {\n      'Content-Type': 'application\u002Fjson',\n      'PAYMENT-REQUIRED': encoded,\n      'Access-Control-Allow-Origin': '*',\n    },\n  });\n}\n\nasync function verifyPayment(xPayment, paymentRequirements, env) {\n  const facilitatorUrl = env.X402_FACILITATOR_URL || 'https:\u002F\u002Fx402.org\u002Ffacilitator';\n  const requirement = paymentRequirements[0];\n\n  try {\n    const response = await fetch(`${facilitatorUrl}\u002Fverify`, {\n      method: 'POST',\n      headers: { 'Content-Type': 'application\u002Fjson' },\n      body: JSON.stringify({\n        x402Version: 1,\n        paymentPayload: xPayment,\n        requirements: {\n          scheme: requirement.scheme,\n          network: requirement.network,\n          maxAmountRequired: requirement.maxAmountRequired,\n          resource: requirement.resource,\n          payTo: requirement.payTo,\n          asset: requirement.asset,\n          maxTimeoutSeconds: requirement.maxTimeoutSeconds,\n        },\n      }),\n    });\n\n    return { valid: response.ok };\n  } catch (err) {\n    return { valid: false, error: err.message };\n  }\n}\n\nasync function triggerSettlement(xPayment, env) {\n  const facilitatorUrl = env.X402_FACILITATOR_URL || 'https:\u002F\u002Fx402.org\u002Ffacilitator';\n\n  \u002F\u002F Fire-and-forget via waitUntil\n  await fetch(`${facilitatorUrl}\u002Fsettle`, {\n    method: 'POST',\n    headers: { 'Content-Type': 'application\u002Fjson' },\n    body: JSON.stringify({\n      x402Version: 1,\n      paymentPayload: xPayment,\n    }),\n  });\n}\n\nexport default {\n  async fetch(request, env, ctx) {\n    const url = new URL(request.url);\n    const pathname = url.pathname;\n\n    \u002F\u002F CORS preflight\n    if (request.method === 'OPTIONS') {\n      return new Response(null, {\n        headers: {\n          'Access-Control-Allow-Origin': '*',\n          'Access-Control-Allow-Headers': 'X-Payment, Content-Type',\n          'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',\n        },\n      });\n    }\n\n    \u002F\u002F Check if this route requires payment\n    const pricing = getRoutePrice(pathname);\n    if (!pricing) {\n      \u002F\u002F Free route -- serve content directly\n      return handleFreeRoute(pathname, env);\n    }\n\n    \u002F\u002F Build payment requirements\n    const resource = `https:\u002F\u002F${url.host}${pathname}`;\n    const paymentRequirements = buildPaymentRequirements(\n      pricing.priceUsd, resource, pricing.description, env\n    );\n\n    \u002F\u002F Check for X-Payment header\n    const xPayment = request.headers.get('x-payment');\n    if (!xPayment) {\n      return make402Response(paymentRequirements);\n    }\n\n    \u002F\u002F Check KV cache for this payment payload\n    const cacheKey = `verify:${await hashPayload(xPayment)}`;\n    if (env.PAYMENT_CACHE) {\n      const cached = await env.PAYMENT_CACHE.get(cacheKey);\n      if (cached === 'valid') {\n        \u002F\u002F Payment already verified -- serve content\n        const content = await handlePaidRoute(pathname, url, env);\n        return addPaymentResponseHeader(content);\n      }\n    }\n\n    \u002F\u002F Verify with facilitator\n    const verification = await verifyPayment(xPayment, paymentRequirements, env);\n    if (!verification.valid) {\n      return make402Response(\n        paymentRequirements,\n        verification.error || 'Payment verification failed'\n      );\n    }\n\n    \u002F\u002F Cache the verification result (TTL: 5 minutes = maxTimeoutSeconds)\n    if (env.PAYMENT_CACHE) {\n      ctx.waitUntil(\n        env.PAYMENT_CACHE.put(cacheKey, 'valid', { expirationTtl: 300 })\n      );\n    }\n\n    \u002F\u002F Trigger settlement asynchronously (does not block response)\n    ctx.waitUntil(triggerSettlement(xPayment, env));\n\n    \u002F\u002F Serve the paid content\n    const content = await handlePaidRoute(pathname, url, env);\n    return addPaymentResponseHeader(content);\n  },\n};\n\n\u002F\u002F Helper: hash a payment payload for cache keys\nasync function hashPayload(payload) {\n  const data = new TextEncoder().encode(payload);\n  const hash = await crypto.subtle.digest('SHA-256', data);\n  return Array.from(new Uint8Array(hash))\n    .map(b => b.toString(16).padStart(2, '0'))\n    .join('');\n}\n\nfunction addPaymentResponseHeader(response) {\n  const newResponse = new Response(response.body, response);\n  newResponse.headers.set(\n    'X-PAYMENT-RESPONSE',\n    btoa(JSON.stringify({ success: true }))\n  );\n  return newResponse;\n}\n\n\u002F\u002F Route handlers\nfunction handleFreeRoute(pathname, _env) {\n  if (pathname === '\u002Fapi\u002Fv1\u002Fhealth') {\n    return Response.json({ status: 'ok' });\n  }\n  if (pathname === '\u002Fapi\u002Fv1\u002Fweather\u002Fsummary') {\n    return Response.json({\n      location: 'San Francisco',\n      temperature_f: 62,\n      conditions: 'Partly cloudy',\n    });\n  }\n  return Response.json({ error: 'Not found' }, { status: 404 });\n}\n\nasync function handlePaidRoute(pathname, url, _env) {\n  if (pathname.startsWith('\u002Fapi\u002Fv1\u002Fweather\u002Ffull')) {\n    return Response.json({\n      location: 'San Francisco',\n      temperature_f: 62,\n      conditions: 'Partly cloudy',\n      hourly_forecast: [\n        { hour: '14:00', temp_f: 63, conditions: 'Partly cloudy' },\n        { hour: '15:00', temp_f: 64, conditions: 'Sunny' },\n      ],\n      alerts: [],\n    });\n  }\n\n  if (pathname.startsWith('\u002Fapi\u002Fv1\u002Fanalysis')) {\n    const ticker = pathname.split('\u002F').pop().toUpperCase();\n    return Response.json({\n      ticker,\n      analysis: `Comprehensive analysis of ${ticker}...`,\n      sentiment: 'bullish',\n      confidence: 0.82,\n    });\n  }\n\n  return Response.json({ error: 'Not found' }, { status: 404 });\n}\n```\n\n### Durable Objects for Settlement Tracking\n\nFor high-volume APIs, use a Durable Object to track settlements and detect duplicate payments:\n\n```javascript\n\u002F**\n * Durable Object: SettlementTracker\n *\n * Maintains a per-merchant log of settlements. Prevents double-settlement\n * of the same payment payload and provides revenue totals.\n *\u002F\nexport class SettlementTracker {\n  constructor(state, env) {\n    this.state = state;\n    this.env = env;\n  }\n\n  async fetch(request) {\n    const url = new URL(request.url);\n\n    if (url.pathname === '\u002Frecord' && request.method === 'POST') {\n      return this.recordSettlement(request);\n    }\n\n    if (url.pathname === '\u002Fstats') {\n      return this.getStats();\n    }\n\n    return new Response('Not found', { status: 404 });\n  }\n\n  async recordSettlement(request) {\n    const { payloadHash, amount, resource, timestamp } = await request.json();\n\n    \u002F\u002F Deduplicate: check if this payload was already settled\n    const existing = await this.state.storage.get(`settlement:${payloadHash}`);\n    if (existing) {\n      return Response.json({ duplicate: true, original: existing });\n    }\n\n    \u002F\u002F Record the settlement\n    const record = { amount, resource, timestamp, settled: true };\n    await this.state.storage.put(`settlement:${payloadHash}`, record);\n\n    \u002F\u002F Update running totals\n    const totals = (await this.state.storage.get('totals')) || {\n      count: 0,\n      revenue_usd: 0,\n    };\n    totals.count += 1;\n    totals.revenue_usd += parseFloat(amount);\n    await this.state.storage.put('totals', totals);\n\n    return Response.json({ recorded: true, totals });\n  }\n\n  async getStats() {\n    const totals = (await this.state.storage.get('totals')) || {\n      count: 0,\n      revenue_usd: 0,\n    };\n    return Response.json(totals);\n  }\n}\n```\n\n### Wrangler Configuration\n\n```toml\n# wrangler.toml\nname = \"x402-api\"\nmain = \"src\u002Fworker.js\"\ncompatibility_date = \"2026-04-01\"\n\n[vars]\nX402_NETWORK = \"base-sepolia\"\nX402_FACILITATOR_URL = \"https:\u002F\u002Fx402.org\u002Ffacilitator\"\n\n# Set via wrangler secret:\n# wrangler secret put MERCHANT_WALLET_ADDRESS\n\n# KV namespace for payment verification caching\n[[kv_namespaces]]\nbinding = \"PAYMENT_CACHE\"\nid = \"your-kv-namespace-id\"\n\n# Durable Objects for settlement tracking\n[[durable_objects.bindings]]\nname = \"SETTLEMENT_TRACKER\"\nclass_name = \"SettlementTracker\"\n\n[[migrations]]\ntag = \"v1\"\nnew_classes = [\"SettlementTracker\"]\n```\n\nDeploy:\n\n```bash\n# Install wrangler\nnpm install -g wrangler\n\n# Set your wallet address as a secret\nwrangler secret put MERCHANT_WALLET_ADDRESS\n\n# Deploy to Cloudflare\nwrangler deploy\n\n# Test\ncurl -s https:\u002F\u002Fx402-api.your-subdomain.workers.dev\u002Fapi\u002Fv1\u002Fhealth\ncurl -s https:\u002F\u002Fx402-api.your-subdomain.workers.dev\u002Fapi\u002Fv1\u002Fweather\u002Ffull\n```\n\n---\n\n## Chapter 5: Pricing Strategies\n\n### Per-Request Pricing (API Calls)\n\nThe simplest model. Every request costs a fixed amount. Best for stateless APIs where each call returns independent value.\n\n```javascript\n\u002F\u002F Flat per-request pricing\nconst PRICING = {\n  '\u002Fapi\u002Fv1\u002Fweather': 0.05,        \u002F\u002F $0.05\u002Frequest\n  '\u002Fapi\u002Fv1\u002Ftranslate': 0.10,       \u002F\u002F $0.10\u002Frequest\n  '\u002Fapi\u002Fv1\u002Fanalyze': 1.00,         \u002F\u002F $1.00\u002Frequest\n  '\u002Fapi\u002Fv1\u002Fgenerate-image': 0.50,  \u002F\u002F $0.50\u002Frequest\n};\n```\n\n**When to use:** Your compute cost per request is predictable and roughly constant. Weather lookups, translation, image generation, search queries.\n\n**When not to use:** When request cost varies significantly based on input size. A translation of 10 words costs the same as 10,000 words under flat pricing.\n\n### Content Pricing (Documents, Datasets)\n\nFixed price per content item. The content is the product, not the API call.\n\n```javascript\n\u002F\u002F Content pricing: each piece of content has a fixed price\nconst CONTENT_PRICING = {\n  '\u002Fcontent\u002Freport-q1-2026': 29.00,\n  '\u002Fcontent\u002Fdataset-sf-housing': 49.00,\n  '\u002Fcontent\u002Ftutorial-x402-advanced': 19.00,\n};\n```\n\nThis is the model the Felix dashboard uses. Each product in the catalog has a `price_usd`, and the x402 middleware charges that amount regardless of how many times the content is accessed (though each access triggers a new payment -- there is no \"purchase once, download forever\" in the base x402 protocol).\n\n### Subscription-Equivalent via Token Bundles\n\nx402 does not natively support subscriptions (recurring payments). But you can approximate subscriptions with token bundles: the client pays once for N requests, receives a signed token, and presents that token on subsequent requests until the bundle is exhausted.\n\n```python\n\"\"\"\nToken bundle implementation for subscription-like access.\n\nClient pays $10 for 100 requests. Server issues a signed JWT.\nClient includes the JWT in subsequent requests instead of paying each time.\n\"\"\"\n\nimport jwt\nimport time\nimport hashlib\nfrom typing import Optional\n\nBUNDLE_SECRET = \"your-signing-secret\"  # Use env var in production\n\nBUNDLE_PRICING = {\n    \"starter\": {\"requests\": 100, \"price_usd\": 10.00, \"validity_days\": 30},\n    \"pro\":     {\"requests\": 1000, \"price_usd\": 75.00, \"validity_days\": 30},\n    \"enterprise\": {\"requests\": 10000, \"price_usd\": 500.00, \"validity_days\": 30},\n}\n\n\ndef issue_bundle_token(\n    bundle_type: str,\n    wallet_address: str,\n) -> str:\n    \"\"\"Issue a JWT token after x402 payment for a bundle.\"\"\"\n    bundle = BUNDLE_PRICING[bundle_type]\n\n    payload = {\n        \"wallet\": wallet_address,\n        \"bundle\": bundle_type,\n        \"remaining\": bundle[\"requests\"],\n        \"issued_at\": int(time.time()),\n        \"expires_at\": int(time.time()) + (bundle[\"validity_days\"] * 86400),\n    }\n\n    return jwt.encode(payload, BUNDLE_SECRET, algorithm=\"HS256\")\n\n\ndef validate_bundle_token(token: str) -> Optional[dict]:\n    \"\"\"Validate and decrement a bundle token.\n\n    Returns the updated claims if valid, None if expired\u002Finvalid.\n    \"\"\"\n    try:\n        claims = jwt.decode(token, BUNDLE_SECRET, algorithms=[\"HS256\"])\n\n        if claims[\"expires_at\"] \u003C time.time():\n            return None\n        if claims[\"remaining\"] \u003C= 0:\n            return None\n\n        claims[\"remaining\"] -= 1\n        return claims\n    except jwt.InvalidTokenError:\n        return None\n\n\ndef refresh_bundle_token(claims: dict) -> str:\n    \"\"\"Re-issue the token with decremented remaining count.\"\"\"\n    return jwt.encode(claims, BUNDLE_SECRET, algorithm=\"HS256\")\n```\n\nOn the server, check for a bundle token first. If present and valid, serve content without x402 payment. If absent or exhausted, fall through to the x402 paywall:\n\n```python\n@app.get(\"\u002Fapi\u002Fv1\u002Fdata\")\nasync def data_endpoint(\n    request: Request,\n    response: Response,\n):\n    \"\"\"Endpoint that accepts either bundle tokens or x402 payment.\"\"\"\n    # Check for bundle token\n    bundle_token = request.headers.get(\"x-bundle-token\")\n    if bundle_token:\n        claims = validate_bundle_token(bundle_token)\n        if claims:\n            # Valid bundle -- serve content and return updated token\n            response.headers[\"X-Bundle-Token\"] = refresh_bundle_token(claims)\n            response.headers[\"X-Bundle-Remaining\"] = str(claims[\"remaining\"])\n            return {\"data\": \"premium content\", \"bundle_remaining\": claims[\"remaining\"]}\n\n    # No valid bundle -- fall through to x402 payment\n    # (Use the x402_required dependency as shown in Chapter 3)\n    ...\n```\n\n### Dynamic Pricing Based on Demand\n\nAdjust prices based on request volume. High demand increases prices; low demand decreases them. This is useful for rate-limiting expensive resources without hard caps.\n\n```javascript\n\u002F**\n * Dynamic pricing: price increases with request volume.\n *\n * Base price: $0.10\u002Frequest\n * At 100 req\u002Fmin: $0.15\u002Frequest (+50%)\n * At 500 req\u002Fmin: $0.50\u002Frequest (+400%)\n * At 1000 req\u002Fmin: $2.00\u002Frequest (+1900%)\n *\u002F\n\nclass DynamicPricer {\n  constructor(basePrice, windowMs = 60000) {\n    this.basePrice = basePrice;\n    this.windowMs = windowMs;\n    this.requests = [];\n  }\n\n  recordRequest() {\n    this.requests.push(Date.now());\n    \u002F\u002F Prune old entries\n    const cutoff = Date.now() - this.windowMs;\n    this.requests = this.requests.filter(t => t > cutoff);\n  }\n\n  getCurrentPrice() {\n    const cutoff = Date.now() - this.windowMs;\n    const recentCount = this.requests.filter(t => t > cutoff).length;\n\n    if (recentCount \u003C 50) return this.basePrice;\n    if (recentCount \u003C 100) return this.basePrice * 1.5;\n    if (recentCount \u003C 500) return this.basePrice * 5.0;\n    return this.basePrice * 20.0;\n  }\n}\n\nconst pricer = new DynamicPricer(0.10);\n\n\u002F\u002F In your route handler:\napp.get('\u002Fapi\u002Fv1\u002Fpremium', async (req, res, next) => {\n  pricer.recordRequest();\n  const currentPrice = pricer.getCurrentPrice();\n\n  \u002F\u002F Apply x402 with dynamic price\n  const middleware = x402Paywall({ priceUsd: currentPrice });\n  return middleware(req, res, next);\n}, handler);\n```\n\n### Free Tier + Paid Tier Pattern\n\nThe most common production pattern: give away basic access for free, charge for premium features. This maximizes adoption while monetizing power users.\n\n```javascript\nconst TIER_CONFIG = {\n  free: {\n    rateLimit: 10,      \u002F\u002F requests per minute\n    features: ['summary'],\n  },\n  paid: {\n    rateLimit: 1000,\n    features: ['summary', 'full', 'historical', 'alerts', 'export'],\n    priceUsd: 0.05,\n  },\n};\n\nfunction tierMiddleware(feature) {\n  return (req, res, next) => {\n    const hasPayment = !!req.headers['x-payment'];\n\n    if (TIER_CONFIG.free.features.includes(feature) && !hasPayment) {\n      \u002F\u002F Free tier: serve with rate limiting\n      return next();\n    }\n\n    if (!TIER_CONFIG.paid.features.includes(feature)) {\n      return res.status(404).json({ error: 'Unknown feature' });\n    }\n\n    \u002F\u002F Paid tier: apply x402\n    const paywall = x402Paywall({ priceUsd: TIER_CONFIG.paid.priceUsd });\n    return paywall(req, res, next);\n  };\n}\n\napp.get('\u002Fapi\u002Fv1\u002Fweather\u002Fsummary', tierMiddleware('summary'), summaryHandler);\napp.get('\u002Fapi\u002Fv1\u002Fweather\u002Ffull', tierMiddleware('full'), fullHandler);\napp.get('\u002Fapi\u002Fv1\u002Fweather\u002Fhistorical', tierMiddleware('historical'), historicalHandler);\n```\n\n---\n\n## Chapter 6: Payment Verification Deep Dive\n\n### Facilitator \u002Fverify Endpoint\n\nThe `\u002Fverify` endpoint is the heart of x402 security. It answers one question: \"Is this payment payload valid for these requirements?\" The request format:\n\n```json\n{\n  \"x402Version\": 1,\n  \"paymentPayload\": \"\u003Cbase64-encoded EIP-712 signed authorization>\",\n  \"requirements\": {\n    \"scheme\": \"exact\",\n    \"network\": \"eip155:8453\",\n    \"maxAmountRequired\": \"1000000\",\n    \"resource\": \"https:\u002F\u002Fapi.example.com\u002Fdata\",\n    \"payTo\": \"0xMerchantWallet\",\n    \"asset\": \"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913\",\n    \"maxTimeoutSeconds\": 300\n  }\n}\n```\n\nThe response on success:\n\n```json\n{\n  \"valid\": true\n}\n```\n\nThe response on failure:\n\n```json\n{\n  \"valid\": false,\n  \"error\": \"Insufficient USDC balance\",\n  \"details\": {\n    \"required\": \"1000000\",\n    \"available\": \"500000\"\n  }\n}\n```\n\n### What the Facilitator Checks\n\nThe facilitator performs these checks in order. If any check fails, it returns `valid: false` with a descriptive error:\n\n1. **Payload decoding.** The base64-decoded payload must be a valid JSON object containing an EIP-712 typed data signature.\n\n2. **Signature recovery.** The facilitator recovers the signer's Ethereum address from the EIP-712 signature. If recovery fails, the payload was tampered with or incorrectly signed.\n\n3. **Amount check.** The signed amount must be greater than or equal to `maxAmountRequired`. A payment for $0.50 does not satisfy a $1.00 requirement.\n\n4. **Asset and network match.** The signed payload must reference the same USDC contract address and network ID as the requirements. A payment on Base Sepolia does not satisfy a Base mainnet requirement.\n\n5. **Recipient match.** The `payTo` address in the signed payload must match the `payTo` in the requirements. This prevents a malicious intermediary from substituting their own wallet address.\n\n6. **Expiration check.** The signature must not have expired. The `maxTimeoutSeconds` defines the window from signature creation to verification. A 300-second timeout means the payer has 5 minutes to submit the payment after signing.\n\n7. **Balance check.** The signer's wallet must hold at least `maxAmountRequired` in USDC on the specified network. The facilitator queries the USDC contract's `balanceOf` function.\n\n8. **Allowance check.** The signer must have approved the facilitator's settlement contract to spend at least `maxAmountRequired` of their USDC. Without this approval, settlement will fail even though verification succeeds.\n\n### Handling Verification Failures\n\nDifferent failure modes require different responses:\n\n```python\nasync def handle_verification_result(\n    result: dict,\n    payment_requirements: list[dict],\n) -> tuple[bool, dict]:\n    \"\"\"Process a verification result and determine the appropriate response.\n\n    Returns (should_serve_content, response_info).\n    \"\"\"\n    if result.get(\"valid\"):\n        return True, {\"status\": \"verified\"}\n\n    error = result.get(\"error\", \"Unknown verification error\")\n    details = result.get(\"details\", {})\n\n    # Insufficient balance: tell the client how much they need\n    if \"Insufficient\" in error:\n        return False, {\n            \"status\": \"insufficient_funds\",\n            \"error\": error,\n            \"required\": details.get(\"required\"),\n            \"available\": details.get(\"available\"),\n            \"action\": \"Fund your wallet with more USDC and retry\",\n        }\n\n    # Expired signature: client took too long\n    if \"expired\" in error.lower():\n        return False, {\n            \"status\": \"expired\",\n            \"error\": error,\n            \"action\": \"Sign a new payment payload and retry immediately\",\n        }\n\n    # Invalid signature: payload was tampered with or signed incorrectly\n    if \"signature\" in error.lower():\n        return False, {\n            \"status\": \"invalid_signature\",\n            \"error\": error,\n            \"action\": \"Check your signing logic and retry\",\n        }\n\n    # Allowance issue: client needs to approve the facilitator\n    if \"allowance\" in error.lower():\n        return False, {\n            \"status\": \"insufficient_allowance\",\n            \"error\": error,\n            \"action\": \"Approve the facilitator contract to spend your USDC\",\n        }\n\n    # Generic failure\n    return False, {\n        \"status\": \"verification_failed\",\n        \"error\": error,\n    }\n```\n\n### Timeout Handling\n\nNetwork latency between your server and the facilitator is the primary source of timeout risk. On a healthy network, the facilitator responds in 50-200ms. Under load or with DNS issues, it can take 2-5 seconds.\n\n```javascript\n\u002F**\n * Verify with timeout and circuit breaker.\n *\u002F\nclass FacilitatorClient {\n  constructor(facilitatorUrl, timeoutMs = 5000) {\n    this.facilitatorUrl = facilitatorUrl;\n    this.timeoutMs = timeoutMs;\n    this.consecutiveFailures = 0;\n    this.circuitOpen = false;\n    this.circuitResetTime = 0;\n  }\n\n  async verify(xPayment, requirements) {\n    \u002F\u002F Circuit breaker: if the facilitator has failed N times in a row,\n    \u002F\u002F stop trying for a cooldown period\n    if (this.circuitOpen && Date.now() \u003C this.circuitResetTime) {\n      return { valid: false, error: 'Circuit breaker open: facilitator unavailable' };\n    }\n\n    const controller = new AbortController();\n    const timeout = setTimeout(() => controller.abort(), this.timeoutMs);\n\n    try {\n      const response = await fetch(`${this.facilitatorUrl}\u002Fverify`, {\n        method: 'POST',\n        headers: { 'Content-Type': 'application\u002Fjson' },\n        body: JSON.stringify({\n          x402Version: 1,\n          paymentPayload: xPayment,\n          requirements,\n        }),\n        signal: controller.signal,\n      });\n\n      clearTimeout(timeout);\n      this.consecutiveFailures = 0;\n      this.circuitOpen = false;\n\n      if (response.ok) {\n        return { valid: true };\n      }\n\n      const body = await response.text();\n      return { valid: false, error: body };\n    } catch (err) {\n      clearTimeout(timeout);\n      this.consecutiveFailures += 1;\n\n      \u002F\u002F Open circuit after 5 consecutive failures\n      if (this.consecutiveFailures >= 5) {\n        this.circuitOpen = true;\n        this.circuitResetTime = Date.now() + 30000; \u002F\u002F 30-second cooldown\n        console.error('[x402] Circuit breaker opened: 5 consecutive failures');\n      }\n\n      if (err.name === 'AbortError') {\n        return { valid: false, error: `Verification timed out after ${this.timeoutMs}ms` };\n      }\n      return { valid: false, error: `Network error: ${err.message}` };\n    }\n  }\n}\n```\n\n### What Happens If the Facilitator Is Down\n\nIf the facilitator is unreachable, you have three options:\n\n1. **Fail closed (default).** Return 402 with an error message. The client cannot pay. No content is served. No revenue is lost. This is the safest option.\n\n2. **Fail open (dangerous).** Serve the content anyway and log the unverified payment for later reconciliation. This risks serving content without payment. Only use this for very low-value content where availability matters more than revenue.\n\n3. **Queue and retry.** Accept the request, serve the content, and queue the verification for retry. If verification eventually fails, flag the transaction as suspicious. This is a middle ground but requires careful accounting.\n\n```javascript\n\u002F\u002F Option 1: Fail closed (recommended)\nasync function verifyWithFailClosed(xPayment, requirements) {\n  const result = await facilitatorClient.verify(xPayment, requirements);\n  if (!result.valid) {\n    \u002F\u002F Do not serve content\n    return { serve: false, error: result.error };\n  }\n  return { serve: true };\n}\n\n\u002F\u002F Option 2: Fail open (use with extreme caution)\nasync function verifyWithFailOpen(xPayment, requirements) {\n  const result = await facilitatorClient.verify(xPayment, requirements);\n  if (!result.valid && result.error.includes('Circuit breaker')) {\n    \u002F\u002F Facilitator is down -- serve content but log for reconciliation\n    console.warn('[x402] FAIL OPEN: serving content without verification');\n    logUnverifiedPayment(xPayment, requirements);\n    return { serve: true, unverified: true };\n  }\n  if (!result.valid) {\n    return { serve: false, error: result.error };\n  }\n  return { serve: true };\n}\n```\n\n---\n\n## Chapter 7: Settlement & Revenue\n\n### Settlement Flow\n\nSettlement is the process of actually moving USDC from the payer's wallet to your wallet. Verification confirms that the payer has authorized the transfer; settlement executes it.\n\nThe flow:\n\n1. Your server calls `POST \u002Fsettle` on the facilitator with the `paymentPayload`.\n2. The facilitator submits an on-chain transaction to Base that calls `transferFrom` on the USDC contract, moving the authorized amount from the payer to your `payTo` address.\n3. The transaction confirms on Base (approximately 2 seconds).\n4. The USDC appears in your wallet.\n\nSettlement is asynchronous and fire-and-forget from the merchant's perspective. You serve the content immediately after verification succeeds. Settlement happens in the background. If it fails, the facilitator retries.\n\n### Logging Settlements to Your Database\n\nEvery settlement should be recorded in your database for revenue tracking, reconciliation, and tax reporting.\n\n```python\n\"\"\"\nSettlement logging with SQLite.\n\"\"\"\n\nimport sqlite3\nimport json\nimport hashlib\nimport time\nfrom datetime import datetime, timezone\n\n\nclass SettlementLog:\n    \"\"\"Persistent settlement log backed by SQLite.\"\"\"\n\n    def __init__(self, db_path: str = \"settlements.db\"):\n        self.conn = sqlite3.connect(db_path)\n        self.conn.row_factory = sqlite3.Row\n        self._init_schema()\n\n    def _init_schema(self):\n        self.conn.executescript(\"\"\"\n            CREATE TABLE IF NOT EXISTS settlements (\n                id INTEGER PRIMARY KEY AUTOINCREMENT,\n                payment_hash TEXT UNIQUE NOT NULL,\n                resource TEXT NOT NULL,\n                amount_usdc TEXT NOT NULL,\n                amount_usd REAL NOT NULL,\n                payer_hint TEXT DEFAULT '',\n                status TEXT DEFAULT 'pending',\n                created_at TEXT NOT NULL,\n                settled_at TEXT,\n                error TEXT\n            );\n\n            CREATE INDEX IF NOT EXISTS idx_settlements_status\n                ON settlements(status);\n            CREATE INDEX IF NOT EXISTS idx_settlements_created\n                ON settlements(created_at);\n        \"\"\")\n        self.conn.commit()\n\n    def record_payment(\n        self,\n        payment_payload: str,\n        resource: str,\n        amount_usd: float,\n    ) -> int:\n        \"\"\"Record a verified payment before settlement.\"\"\"\n        payment_hash = hashlib.sha256(payment_payload.encode()).hexdigest()\n        amount_usdc = str(round(amount_usd * 1_000_000))\n        now = datetime.now(timezone.utc).isoformat()\n\n        cursor = self.conn.execute(\n            \"\"\"INSERT OR IGNORE INTO settlements\n               (payment_hash, resource, amount_usdc, amount_usd, status, created_at)\n               VALUES (?, ?, ?, ?, 'pending', ?)\"\"\",\n            (payment_hash, resource, amount_usdc, amount_usd, now),\n        )\n        self.conn.commit()\n        return cursor.lastrowid\n\n    def mark_settled(self, payment_payload: str) -> None:\n        \"\"\"Mark a payment as successfully settled.\"\"\"\n        payment_hash = hashlib.sha256(payment_payload.encode()).hexdigest()\n        now = datetime.now(timezone.utc).isoformat()\n\n        self.conn.execute(\n            \"\"\"UPDATE settlements SET status = 'settled', settled_at = ?\n               WHERE payment_hash = ?\"\"\",\n            (now, payment_hash),\n        )\n        self.conn.commit()\n\n    def mark_failed(self, payment_payload: str, error: str) -> None:\n        \"\"\"Mark a settlement as failed.\"\"\"\n        payment_hash = hashlib.sha256(payment_payload.encode()).hexdigest()\n\n        self.conn.execute(\n            \"\"\"UPDATE settlements SET status = 'failed', error = ?\n               WHERE payment_hash = ?\"\"\",\n            (error, payment_hash),\n        )\n        self.conn.commit()\n\n    def get_revenue(self, hours: int = 24) -> dict:\n        \"\"\"Get revenue stats for the last N hours.\"\"\"\n        cutoff = datetime.now(timezone.utc).timestamp() - (hours * 3600)\n        cutoff_iso = datetime.fromtimestamp(cutoff, tz=timezone.utc).isoformat()\n\n        row = self.conn.execute(\n            \"\"\"SELECT\n                 COUNT(*) as total_payments,\n                 COALESCE(SUM(amount_usd), 0) as total_usd,\n                 COUNT(CASE WHEN status = 'settled' THEN 1 END) as settled_count,\n                 COUNT(CASE WHEN status = 'failed' THEN 1 END) as failed_count,\n                 COUNT(CASE WHEN status = 'pending' THEN 1 END) as pending_count\n               FROM settlements\n               WHERE created_at >= ?\"\"\",\n            (cutoff_iso,),\n        ).fetchone()\n\n        return {\n            \"period_hours\": hours,\n            \"total_payments\": row[\"total_payments\"],\n            \"total_revenue_usd\": round(row[\"total_usd\"], 2),\n            \"settled\": row[\"settled_count\"],\n            \"failed\": row[\"failed_count\"],\n            \"pending\": row[\"pending_count\"],\n            \"settlement_rate\": (\n                round(row[\"settled_count\"] \u002F row[\"total_payments\"], 3)\n                if row[\"total_payments\"] > 0\n                else 0\n            ),\n        }\n\n    def get_revenue_by_resource(self, hours: int = 24) -> list[dict]:\n        \"\"\"Get per-resource revenue breakdown.\"\"\"\n        cutoff = datetime.now(timezone.utc).timestamp() - (hours * 3600)\n        cutoff_iso = datetime.fromtimestamp(cutoff, tz=timezone.utc).isoformat()\n\n        rows = self.conn.execute(\n            \"\"\"SELECT\n                 resource,\n                 COUNT(*) as request_count,\n                 COALESCE(SUM(amount_usd), 0) as total_usd\n               FROM settlements\n               WHERE created_at >= ? AND status = 'settled'\n               GROUP BY resource\n               ORDER BY total_usd DESC\"\"\",\n            (cutoff_iso,),\n        ).fetchall()\n\n        return [\n            {\n                \"resource\": row[\"resource\"],\n                \"request_count\": row[\"request_count\"],\n                \"revenue_usd\": round(row[\"total_usd\"], 2),\n            }\n            for row in rows\n        ]\n```\n\n### Revenue Tracking and Reporting\n\nIntegrate the settlement log with your x402 middleware:\n\n```python\nsettlement_log = SettlementLog(\"data\u002Fsettlements.db\")\n\n# In your x402 dependency, after verification succeeds:\nasync def x402_with_logging(request: Request) -> dict:\n    # ... (verification logic from Chapter 3) ...\n\n    # Record the payment\n    settlement_log.record_payment(\n        payment_payload=x_payment,\n        resource=resource,\n        amount_usd=price_usd,\n    )\n\n    # Trigger settlement with callback\n    async def settle_and_log():\n        try:\n            await settle_payment(x_payment)\n            settlement_log.mark_settled(x_payment)\n        except Exception as e:\n            settlement_log.mark_failed(x_payment, str(e))\n\n    asyncio.create_task(settle_and_log())\n\n    return {\"verified\": True}\n\n\n# Revenue reporting endpoint (admin-only)\n@app.get(\"\u002Fadmin\u002Frevenue\")\nasync def revenue_report(hours: int = 24):\n    stats = settlement_log.get_revenue(hours)\n    by_resource = settlement_log.get_revenue_by_resource(hours)\n    return {\n        \"summary\": stats,\n        \"by_resource\": by_resource,\n    }\n```\n\n### Handling Failed Settlements\n\nSettlement can fail for several reasons:\n\n- **Insufficient balance at settlement time.** The payer had enough USDC at verification but transferred it away before settlement. This is the most common failure mode.\n- **Revoked allowance.** The payer revoked the facilitator's approval between verification and settlement.\n- **Network congestion.** The Base network is congested and the transaction did not confirm in time.\n\nFor the first two cases, there is nothing the merchant can do. The content was already served. This is the fundamental risk of the \"verify first, settle later\" model. Mitigations:\n\n1. **Minimize the verification-to-settlement gap.** Call `\u002Fsettle` immediately after serving content, not in a batch job.\n2. **Monitor settlement failure rate.** If it exceeds 2%, investigate. It may indicate a bot exploiting the gap.\n3. **Block wallets with repeated settlement failures.** Maintain a blocklist of wallet addresses (extracted from payment payloads) that have failed settlement more than N times.\n\n```python\nclass SettlementFailureTracker:\n    \"\"\"Track wallets with repeated settlement failures.\"\"\"\n\n    def __init__(self, max_failures: int = 3):\n        self.max_failures = max_failures\n        self.failure_counts: dict[str, int] = {}\n        self.blocked_wallets: set[str] = set()\n\n    def record_failure(self, wallet_address: str) -> bool:\n        \"\"\"Record a settlement failure. Returns True if wallet is now blocked.\"\"\"\n        self.failure_counts[wallet_address] = (\n            self.failure_counts.get(wallet_address, 0) + 1\n        )\n\n        if self.failure_counts[wallet_address] >= self.max_failures:\n            self.blocked_wallets.add(wallet_address)\n            return True\n        return False\n\n    def is_blocked(self, wallet_address: str) -> bool:\n        return wallet_address in self.blocked_wallets\n\n    def record_success(self, wallet_address: str) -> None:\n        \"\"\"Reset failure count on successful settlement.\"\"\"\n        self.failure_counts.pop(wallet_address, None)\n```\n\n### Reconciliation Patterns\n\nDaily reconciliation compares your settlement log against your actual on-chain USDC balance:\n\n```python\nasync def daily_reconciliation(\n    settlement_log: SettlementLog,\n    wallet_address: str,\n    rpc_url: str,\n) -> dict:\n    \"\"\"Compare recorded settlements against on-chain balance.\n\n    Run this daily via cron to detect discrepancies.\n    \"\"\"\n    # Get recorded revenue\n    stats = settlement_log.get_revenue(hours=24)\n    recorded_revenue = stats[\"total_revenue_usd\"]\n    settled_count = stats[\"settled\"]\n    failed_count = stats[\"failed\"]\n\n    # Query on-chain USDC balance (via RPC or block explorer API)\n    # This is a simplified example -- in production, track balance deltas\n    balance_info = await query_usdc_balance(wallet_address, rpc_url)\n    on_chain_balance = balance_info[\"balance_usd\"]\n\n    discrepancy = abs(recorded_revenue - on_chain_balance)\n\n    return {\n        \"date\": datetime.now(timezone.utc).date().isoformat(),\n        \"recorded_revenue_usd\": recorded_revenue,\n        \"on_chain_balance_usd\": on_chain_balance,\n        \"discrepancy_usd\": round(discrepancy, 2),\n        \"settled_payments\": settled_count,\n        \"failed_settlements\": failed_count,\n        \"settlement_rate\": stats[\"settlement_rate\"],\n        \"status\": \"ok\" if discrepancy \u003C 1.00 else \"DISCREPANCY_DETECTED\",\n    }\n```\n\n### Tax Implications\n\nUSDC revenue is taxable income in most jurisdictions. Key considerations:\n\n- **Record keeping.** Every settlement must be logged with timestamp, amount, and counterparty information (wallet address). The settlement log in this chapter satisfies this requirement.\n- **USD valuation.** USDC is pegged 1:1 to USD. Revenue in USDC is valued at face value. No fair market value calculation is needed (unlike volatile cryptocurrencies).\n- **Reporting.** In the US, report USDC revenue as ordinary income. For businesses, this appears on Schedule C or the corporate return. Consult a tax professional for your jurisdiction.\n- **Off-ramping.** When you convert USDC to fiat (via Coinbase, Circle, or a bank), there is no taxable event beyond the original income recognition -- assuming USDC maintained its peg.\n\n---\n\n## Next Steps\n\nFor deployment patterns, monitoring, and production hardening, see the\n[Agent Production Hardening Guide](https:\u002F\u002Fclawhub.ai\u002Fskills\u002Fgreenhelix-agent-production-hardening).\n\n---\n\n## Chapter 9: Testing\n\n### Testnet (Base Sepolia) Setup\n\nFor development and integration testing, use Base Sepolia testnet. The only configuration change is the network identifier and USDC contract address.\n\n```bash\n# Environment variables for testnet\nexport X402_NETWORK=base-sepolia\nexport MERCHANT_WALLET_ADDRESS=0xYourTestnetWallet\nexport X402_FACILITATOR_URL=https:\u002F\u002Fx402.org\u002Ffacilitator\n```\n\nTo get testnet USDC:\n1. Get Sepolia ETH from the Base Sepolia faucet (https:\u002F\u002Fwww.coinbase.com\u002Ffaucets\u002Fbase-ethereum-sepolia-faucet).\n2. Use the testnet USDC faucet or mint test tokens.\n3. Approve the facilitator contract to spend your test USDC.\n\n### Mock Facilitator for Unit Tests\n\nFor unit tests, you do not want to hit the real facilitator. Mock it entirely.\n\n**Node.js (Jest\u002FVitest):**\n\n```javascript\n\u002F**\n * Mock facilitator for unit tests.\n *\n * Replaces the real facilitator with deterministic responses.\n *\u002F\n\nclass MockFacilitator {\n  constructor() {\n    this.verifyResponses = new Map();\n    this.settleLog = [];\n    this.defaultVerifyResult = { valid: true };\n  }\n\n  \u002F**\n   * Configure the response for a specific payment payload.\n   *\u002F\n  setVerifyResponse(payloadSubstring, response) {\n    this.verifyResponses.set(payloadSubstring, response);\n  }\n\n  \u002F**\n   * Mock \u002Fverify endpoint.\n   *\u002F\n  async verify(body) {\n    const payload = body.paymentPayload || '';\n\n    for (const [substring, response] of this.verifyResponses) {\n      if (payload.includes(substring)) {\n        return response;\n      }\n    }\n\n    return this.defaultVerifyResult;\n  }\n\n  \u002F**\n   * Mock \u002Fsettle endpoint. Logs the settlement for assertions.\n   *\u002F\n  async settle(body) {\n    this.settleLog.push({\n      payload: body.paymentPayload,\n      timestamp: Date.now(),\n    });\n    return { success: true };\n  }\n\n  \u002F**\n   * Assert that settlement was triggered for a specific payload.\n   *\u002F\n  assertSettled(payloadSubstring) {\n    const found = this.settleLog.some(s => s.payload.includes(payloadSubstring));\n    if (!found) {\n      throw new Error(`Expected settlement for payload containing \"${payloadSubstring}\"`);\n    }\n  }\n\n  reset() {\n    this.verifyResponses.clear();\n    this.settleLog = [];\n    this.defaultVerifyResult = { valid: true };\n  }\n}\n\n\u002F\u002F In tests:\nconst mockFacilitator = new MockFacilitator();\n\n\u002F\u002F Override fetch globally for tests\nglobal.fetch = jest.fn(async (url, options) => {\n  const body = JSON.parse(options.body);\n\n  if (url.includes('\u002Fverify')) {\n    const result = await mockFacilitator.verify(body);\n    return {\n      ok: result.valid,\n      status: result.valid ? 200 : 400,\n      json: async () => result,\n      text: async () => JSON.stringify(result),\n    };\n  }\n\n  if (url.includes('\u002Fsettle')) {\n    const result = await mockFacilitator.settle(body);\n    return {\n      ok: true,\n      status: 200,\n      json: async () => result,\n    };\n  }\n\n  return { ok: false, status: 404 };\n});\n```\n\n**Python (pytest):**\n\n```python\n\"\"\"\nMock facilitator for pytest.\n\"\"\"\n\nimport pytest\nfrom unittest.mock import AsyncMock, patch\n\n\n@pytest.fixture\ndef mock_facilitator():\n    \"\"\"Fixture that mocks the x402 facilitator for unit tests.\"\"\"\n\n    class MockFacilitator:\n        def __init__(self):\n            self.verify_result = {\"valid\": True}\n            self.settle_log = []\n            self.verify_calls = []\n\n        def set_verify_result(self, result):\n            self.verify_result = result\n\n        async def mock_verify(self, x_payment, requirements):\n            self.verify_calls.append({\n                \"payment\": x_payment,\n                \"requirements\": requirements,\n            })\n            return self.verify_result\n\n        async def mock_settle(self, x_payment, max_retries=3):\n            self.settle_log.append(x_payment)\n\n    mock = MockFacilitator()\n\n    with patch(\"x402_deps.verify_payment\", side_effect=mock.mock_verify):\n        with patch(\"x402_deps.settle_payment\", side_effect=mock.mock_settle):\n            yield mock\n\n\n# Usage in tests:\nclass TestPaidEndpoint:\n    def test_verified_payment_returns_content(self, client, mock_facilitator):\n        mock_facilitator.set_verify_result({\"valid\": True})\n        response = client.get(\n            \"\u002Fapi\u002Fv1\u002Fweather\u002Ffull\",\n            headers={\"X-Payment\": \"test-payload-123\"},\n        )\n        assert response.status_code == 200\n        assert len(mock_facilitator.verify_calls) == 1\n        assert mock_facilitator.verify_calls[0][\"payment\"] == \"test-payload-123\"\n\n    def test_failed_verification_returns_402(self, client, mock_facilitator):\n        mock_facilitator.set_verify_result({\n            \"valid\": False,\n            \"error\": \"Insufficient balance\",\n        })\n        response = client.get(\n            \"\u002Fapi\u002Fv1\u002Fweather\u002Ffull\",\n            headers={\"X-Payment\": \"insufficient-funds-payload\"},\n        )\n        assert response.status_code == 402\n\n    def test_settlement_triggered_after_success(self, client, mock_facilitator):\n        mock_facilitator.set_verify_result({\"valid\": True})\n        client.get(\n            \"\u002Fapi\u002Fv1\u002Fweather\u002Ffull\",\n            headers={\"X-Payment\": \"settle-test-payload\"},\n        )\n        assert \"settle-test-payload\" in mock_facilitator.settle_log\n```\n\n### Integration Test Patterns\n\nIntegration tests hit the real facilitator on testnet. They verify the full flow: 402 response, payment construction, verification, content delivery, settlement.\n\n```python\n\"\"\"\nIntegration tests against Base Sepolia testnet.\n\nRequires:\n  - MERCHANT_WALLET_ADDRESS set to a testnet wallet\n  - PAYER_PRIVATE_KEY set to a funded testnet wallet's private key\n  - Server running on localhost:8000\n\nRun:\n    X402_NETWORK=base-sepolia pytest test_integration.py -x -q\n\"\"\"\n\nimport os\nimport httpx\nimport pytest\n\nBASE_URL = os.environ.get(\"TEST_SERVER_URL\", \"http:\u002F\u002Flocalhost:8000\")\n\n\n@pytest.mark.integration\nclass TestFullX402Flow:\n    \"\"\"End-to-end tests using real facilitator on testnet.\"\"\"\n\n    def test_free_endpoint_works(self):\n        \"\"\"Free endpoints should respond without payment.\"\"\"\n        response = httpx.get(f\"{BASE_URL}\u002Fapi\u002Fv1\u002Fhealth\")\n        assert response.status_code == 200\n        assert response.json()[\"status\"] == \"ok\"\n\n    def test_paid_endpoint_returns_402(self):\n        \"\"\"Paid endpoint without payment returns 402.\"\"\"\n        response = httpx.get(f\"{BASE_URL}\u002Fapi\u002Fv1\u002Fweather\u002Ffull\")\n        assert response.status_code == 402\n\n        body = response.json()\n        assert body[\"x402Version\"] == 1\n        assert len(body[\"accepts\"]) >= 1\n\n        req = body[\"accepts\"][0]\n        assert req[\"scheme\"] == \"exact\"\n        assert req[\"network\"] == \"eip155:84532\"  # Sepolia\n        assert int(req[\"maxAmountRequired\"]) > 0\n        assert req[\"payTo\"].startswith(\"0x\")\n\n    def test_402_contains_payment_required_header(self):\n        \"\"\"The PAYMENT-REQUIRED header should be present and base64-decodable.\"\"\"\n        response = httpx.get(f\"{BASE_URL}\u002Fapi\u002Fv1\u002Fweather\u002Ffull\")\n        assert \"payment-required\" in response.headers\n\n        import base64, json\n        decoded = json.loads(\n            base64.b64decode(response.headers[\"payment-required\"])\n        )\n        assert decoded[\"x402Version\"] == 1\n\n    def test_invalid_payment_header_returns_402(self):\n        \"\"\"An invalid X-Payment header should return 402 with error.\"\"\"\n        response = httpx.get(\n            f\"{BASE_URL}\u002Fapi\u002Fv1\u002Fweather\u002Ffull\",\n            headers={\"X-Payment\": \"totally-invalid-payload\"},\n        )\n        assert response.status_code == 402\n        body = response.json()\n        detail = body.get(\"detail\", body)\n        assert detail.get(\"error\") is not None\n```\n\n### Load Testing Payment Flows\n\nLoad testing x402 is different from load testing a standard API because each request involves an external facilitator call. Focus on three scenarios:\n\n```python\n\"\"\"\nLoad test scenarios for x402 APIs.\n\nUses locust for load generation.\n\nRun:\n    locust -f test_load.py --host http:\u002F\u002Flocalhost:8000\n\"\"\"\n\nfrom locust import HttpUser, task, between\n\n\nclass FreeEndpointUser(HttpUser):\n    \"\"\"Simulates traffic to free endpoints (baseline throughput).\"\"\"\n    wait_time = between(0.1, 0.5)\n\n    @task\n    def health_check(self):\n        self.client.get(\"\u002Fapi\u002Fv1\u002Fhealth\")\n\n    @task(3)\n    def weather_summary(self):\n        self.client.get(\"\u002Fapi\u002Fv1\u002Fweather\u002Fsummary\")\n\n\nclass UnpaidRequestUser(HttpUser):\n    \"\"\"Simulates traffic without payment (402 response throughput).\"\"\"\n    wait_time = between(0.1, 0.5)\n\n    @task\n    def trigger_402(self):\n        with self.client.get(\n            \"\u002Fapi\u002Fv1\u002Fweather\u002Ffull\",\n            catch_response=True,\n        ) as response:\n            if response.status_code == 402:\n                response.success()\n            else:\n                response.failure(f\"Expected 402, got {response.status_code}\")\n\n\nclass PaidRequestUser(HttpUser):\n    \"\"\"Simulates paid requests (verification + settlement throughput).\n\n    Uses a mock payment header. For real load testing on testnet,\n    replace with actual signed payloads.\n    \"\"\"\n    wait_time = between(0.5, 2.0)\n\n    @task\n    def paid_weather(self):\n        with self.client.get(\n            \"\u002Fapi\u002Fv1\u002Fweather\u002Ffull\",\n            headers={\"X-Payment\": \"load-test-payload\"},\n            catch_response=True,\n        ) as response:\n            # With a mock facilitator, this should return 200\n            # With the real facilitator, this will return 402 (invalid payload)\n            if response.status_code in (200, 402):\n                response.success()\n            else:\n                response.failure(f\"Unexpected status {response.status_code}\")\n```\n\n---\n\n## Chapter 10: Recipes\n\n### Recipe 1: Blog Paywall (Markdown Content)\n\nA blog where some posts are free and others require payment. The Felix dashboard pattern, simplified.\n\n```javascript\n'use strict';\n\n\u002F**\n * Blog with x402 paywall.\n *\n * Free posts: \u002Fblog\u002Fgetting-started, \u002Fblog\u002Fabout\n * Paid posts: \u002Fblog\u002Fadvanced-techniques ($2.00), \u002Fblog\u002Fcase-study ($5.00)\n *\u002F\n\nconst express = require('express');\nconst { marked } = require('marked');\nconst { x402Paywall } = require('.\u002Fx402-middleware');\n\nconst app = express();\n\n\u002F\u002F Blog content (in production, load from filesystem or CMS)\nconst POSTS = {\n  'getting-started': {\n    title: 'Getting Started with x402',\n    content: '# Getting Started\\n\\nThis is a free post...',\n    price: 0,\n  },\n  'advanced-techniques': {\n    title: 'Advanced x402 Techniques',\n    content: '# Advanced Techniques\\n\\nThis premium post covers...',\n    price: 2.00,\n  },\n  'case-study': {\n    title: 'Case Study: 10x Revenue with x402',\n    content: '# Case Study\\n\\nHow Company X increased API revenue...',\n    price: 5.00,\n  },\n};\n\n\u002F\u002F Blog listing (free)\napp.get('\u002Fblog', (_req, res) => {\n  const listing = Object.entries(POSTS).map(([slug, post]) => ({\n    slug,\n    title: post.title,\n    price: post.price,\n    url: `\u002Fblog\u002F${slug}`,\n  }));\n  res.json({ posts: listing });\n});\n\n\u002F\u002F Individual blog posts\napp.get('\u002Fblog\u002F:slug', (req, res, next) => {\n  const post = POSTS[req.params.slug];\n  if (!post) return res.status(404).json({ error: 'Post not found' });\n\n  \u002F\u002F Free posts: serve directly\n  if (post.price === 0) {\n    return res.json({\n      title: post.title,\n      content_html: marked(post.content),\n      content_markdown: post.content,\n    });\n  }\n\n  \u002F\u002F Paid posts: apply x402\n  const paywall = x402Paywall({\n    priceUsd: post.price,\n    description: `Blog post: ${post.title}`,\n  });\n\n  paywall(req, res, () => {\n    res.json({\n      title: post.title,\n      content_html: marked(post.content),\n      content_markdown: post.content,\n    });\n  });\n});\n\napp.listen(3000, () => console.log('Blog running on port 3000'));\n```\n\n### Recipe 2: API Rate Limiting with x402 (Pay to Exceed Free Tier)\n\nGive every user 100 free requests per day. After that, each request costs $0.01. No signup required -- rate limiting is by IP for free tier and by wallet for paid tier.\n\n```javascript\n'use strict';\n\n\u002F**\n * Free tier + x402 overflow pricing.\n *\n * Free: 100 requests\u002Fday per IP\n * Paid: $0.01\u002Frequest after free tier exhausted\n *\u002F\n\nconst express = require('express');\nconst { x402Paywall } = require('.\u002Fx402-middleware');\n\nconst app = express();\n\n\u002F\u002F In-memory rate counter (use Redis in production)\nconst requestCounts = new Map();\nconst FREE_LIMIT = 100;\nconst WINDOW_MS = 24 * 60 * 60 * 1000; \u002F\u002F 24 hours\n\nfunction getRequestCount(ip) {\n  const entry = requestCounts.get(ip);\n  if (!entry || Date.now() - entry.windowStart > WINDOW_MS) {\n    requestCounts.set(ip, { count: 0, windowStart: Date.now() });\n    return 0;\n  }\n  return entry.count;\n}\n\nfunction incrementRequestCount(ip) {\n  const entry = requestCounts.get(ip) || { count: 0, windowStart: Date.now() };\n  entry.count += 1;\n  requestCounts.set(ip, entry);\n}\n\n\u002F\u002F Middleware: free tier or x402 payment\nfunction freeTierOrPay(priceUsd) {\n  return async (req, res, next) => {\n    const ip = req.ip;\n    const count = getRequestCount(ip);\n\n    if (count \u003C FREE_LIMIT) {\n      \u002F\u002F Free tier: serve and count\n      incrementRequestCount(ip);\n      res.setHeader('X-RateLimit-Remaining', String(FREE_LIMIT - count - 1));\n      res.setHeader('X-RateLimit-Limit', String(FREE_LIMIT));\n      return next();\n    }\n\n    \u002F\u002F Free tier exhausted: require payment\n    res.setHeader('X-RateLimit-Remaining', '0');\n    res.setHeader('X-RateLimit-Limit', String(FREE_LIMIT));\n\n    const paywall = x402Paywall({\n      priceUsd,\n      description: `API access (free tier of ${FREE_LIMIT}\u002Fday exhausted)`,\n    });\n\n    return paywall(req, res, next);\n  };\n}\n\napp.get('\u002Fapi\u002Fv1\u002Fdata', freeTierOrPay(0.01), (_req, res) => {\n  res.json({\n    data: 'Your API response here',\n    timestamp: new Date().toISOString(),\n  });\n});\n\napp.listen(3000, () => console.log('Free tier + x402 API running on port 3000'));\n```\n\n### Recipe 3: Dataset Marketplace (Pay Per Download)\n\nA marketplace where data providers list datasets and buyers pay per download. Each dataset has its own price.\n\n```python\n\"\"\"\nDataset marketplace with x402 payment per download.\n\nProviders upload datasets. Buyers browse for free, pay to download.\n\"\"\"\n\nimport os\nimport json\nfrom pathlib import Path\n\nfrom fastapi import FastAPI, Depends, Response\nfrom fastapi.responses import FileResponse, JSONResponse\n\nfrom x402_deps import x402_required\n\napp = FastAPI(title=\"Dataset Marketplace\")\n\nDATASETS_DIR = Path(\"data\u002Fdatasets\")\nCATALOG_FILE = Path(\"data\u002Fcatalog.json\")\n\n\ndef load_catalog() -> list[dict]:\n    \"\"\"Load the dataset catalog.\"\"\"\n    if not CATALOG_FILE.exists():\n        return []\n    return json.loads(CATALOG_FILE.read_text())\n\n\ndef get_dataset_by_slug(slug: str) -> dict | None:\n    \"\"\"Find a dataset in the catalog by slug.\"\"\"\n    for ds in load_catalog():\n        if ds[\"slug\"] == slug:\n            return ds\n    return None\n\n\n@app.get(\"\u002Fdatasets\")\nasync def list_datasets():\n    \"\"\"Browse all available datasets (free).\"\"\"\n    catalog = load_catalog()\n    return {\n        \"datasets\": [\n            {\n                \"slug\": ds[\"slug\"],\n                \"title\": ds[\"title\"],\n                \"description\": ds[\"description\"],\n                \"price_usd\": ds[\"price_usd\"],\n                \"size_mb\": ds[\"size_mb\"],\n                \"format\": ds[\"format\"],\n                \"download_url\": f\"\u002Fdatasets\u002F{ds['slug']}\u002Fdownload\",\n            }\n            for ds in catalog\n        ]\n    }\n\n\n@app.get(\"\u002Fdatasets\u002F{slug}\")\nasync def dataset_detail(slug: str):\n    \"\"\"Get dataset metadata (free).\"\"\"\n    ds = get_dataset_by_slug(slug)\n    if not ds:\n        return JSONResponse({\"error\": \"Dataset not found\"}, status_code=404)\n\n    return {\n        \"slug\": ds[\"slug\"],\n        \"title\": ds[\"title\"],\n        \"description\": ds[\"description\"],\n        \"price_usd\": ds[\"price_usd\"],\n        \"size_mb\": ds[\"size_mb\"],\n        \"format\": ds[\"format\"],\n        \"columns\": ds.get(\"columns\", []),\n        \"row_count\": ds.get(\"row_count\", 0),\n        \"sample_rows\": ds.get(\"sample_rows\", []),\n        \"download_url\": f\"\u002Fdatasets\u002F{slug}\u002Fdownload\",\n    }\n\n\n@app.get(\"\u002Fdatasets\u002F{slug}\u002Fdownload\")\nasync def download_dataset(\n    slug: str,\n    response: Response,\n    payment: dict = Depends(x402_required(\n        price_usd=0,  # Will be overridden dynamically\n        description=\"Dataset download\",\n    )),\n):\n    \"\"\"Download a dataset (paid via x402).\"\"\"\n    ds = get_dataset_by_slug(slug)\n    if not ds:\n        return JSONResponse({\"error\": \"Dataset not found\"}, status_code=404)\n\n    file_path = DATASETS_DIR \u002F ds[\"filename\"]\n    if not file_path.exists():\n        return JSONResponse({\"error\": \"File not available\"}, status_code=503)\n\n    return FileResponse(\n        path=str(file_path),\n        filename=ds[\"filename\"],\n        media_type=\"application\u002Foctet-stream\",\n    )\n```\n\nIn production, override the `price_usd` in `x402_required` dynamically based on the dataset's catalog entry. One approach is to use a custom dependency that reads the price from the catalog:\n\n```python\ndef dataset_x402(slug_param: str = \"slug\"):\n    \"\"\"Dynamic x402 dependency that reads price from dataset catalog.\"\"\"\n\n    async def dependency(request: Request) -> dict:\n        slug = request.path_params.get(slug_param)\n        ds = get_dataset_by_slug(slug)\n        if not ds:\n            raise HTTPException(status_code=404, detail=\"Dataset not found\")\n\n        # Create the x402 dependency with the dataset's price\n        x402_dep = x402_required(\n            price_usd=ds[\"price_usd\"],\n            description=f\"Download: {ds['title']}\",\n        )\n        return await x402_dep(request)\n\n    return dependency\n```\n\n### Recipe 4: Agent-to-Agent Service (Autonomous Buyer + Seller)\n\nThe most powerful x402 pattern: two AI agents transacting without human involvement. The seller agent exposes an API behind an x402 paywall. The buyer agent detects the 402, constructs a payment, and completes the purchase autonomously.\n\n**Seller agent (Express.js):**\n\n```javascript\n'use strict';\n\n\u002F**\n * Seller agent: exposes a code review service behind x402.\n *\n * POST \u002Freview\n * Body: { \"code\": \"...\" }\n * Price: $0.50 per review\n *\u002F\n\nconst express = require('express');\nconst { x402Paywall } = require('.\u002Fx402-middleware');\n\nconst app = express();\napp.use(express.json({ limit: '50kb' }));\n\napp.post('\u002Freview',\n  x402Paywall({\n    priceUsd: 0.50,\n    description: 'AI code review service',\n  }),\n  async (req, res) => {\n    const { code } = req.body;\n    if (!code) {\n      return res.status(400).json({ error: 'code field required' });\n    }\n\n    \u002F\u002F Perform the code review (your AI logic here)\n    const review = await performCodeReview(code);\n\n    res.json({\n      review,\n      lines_analyzed: code.split('\\n').length,\n      timestamp: new Date().toISOString(),\n    });\n  }\n);\n\nasync function performCodeReview(code) {\n  \u002F\u002F Placeholder: integrate with your LLM or static analysis tool\n  return {\n    issues: [\n      { line: 3, severity: 'warning', message: 'Consider using const instead of let' },\n      { line: 15, severity: 'info', message: 'This function could be simplified' },\n    ],\n    overall_quality: 'good',\n    suggestions: ['Add type annotations', 'Extract helper function on line 15'],\n  };\n}\n\napp.listen(4000, () => console.log('Seller agent running on port 4000'));\n```\n\n**Buyer agent (Python):**\n\n```python\n\"\"\"\nBuyer agent: autonomously purchases code review from the seller.\n\nDetects 402, constructs payment, and completes the transaction.\n\nIn production, the payment construction uses a wallet SDK\n(e.g., coinbase-sdk or viem) to sign EIP-712 payloads.\n\"\"\"\n\nimport httpx\nimport json\nimport base64\nimport asyncio\n\n\nSELLER_URL = \"https:\u002F\u002Fseller-agent.example.com\"\n\n\nasync def buy_code_review(code: str) -> dict:\n    \"\"\"Submit code for review, handling x402 payment flow.\"\"\"\n\n    async with httpx.AsyncClient(timeout=30.0) as client:\n        # Step 1: Initial request (expect 402)\n        response = await client.post(\n            f\"{SELLER_URL}\u002Freview\",\n            json={\"code\": code},\n        )\n\n        if response.status_code == 200:\n            # Free or already paid\n            return response.json()\n\n        if response.status_code != 402:\n            raise Exception(f\"Unexpected status: {response.status_code}\")\n\n        # Step 2: Parse payment requirements from 402 response\n        payment_info = response.json()\n        requirements = payment_info[\"accepts\"][0]\n\n        print(f\"Payment required: {requirements['maxAmountRequired']} \"\n              f\"{requirements['extra']['name']} on {requirements['network']}\")\n        print(f\"Pay to: {requirements['payTo']}\")\n\n        # Step 3: Construct payment payload\n        # In production, use your wallet SDK to sign an EIP-712 payload:\n        #\n        #   from coinbase_sdk import Wallet\n        #   wallet = Wallet.load(\"my-wallet\")\n        #   payment_payload = wallet.sign_x402_payment(\n        #       amount=requirements[\"maxAmountRequired\"],\n        #       asset=requirements[\"asset\"],\n        #       pay_to=requirements[\"payTo\"],\n        #       network=requirements[\"network\"],\n        #       resource=requirements[\"resource\"],\n        #       timeout=requirements[\"maxTimeoutSeconds\"],\n        #   )\n        #\n        # For this example, we use a placeholder:\n        payment_payload = construct_payment_payload(requirements)\n\n        # Step 4: Retry with payment\n        response = await client.post(\n            f\"{SELLER_URL}\u002Freview\",\n            json={\"code\": code},\n            headers={\"X-Payment\": payment_payload},\n        )\n\n        if response.status_code == 200:\n            print(\"Payment accepted. Review received.\")\n            return response.json()\n\n        if response.status_code == 402:\n            error = response.json().get(\"error\", \"Unknown payment error\")\n            raise Exception(f\"Payment rejected: {error}\")\n\n        raise Exception(f\"Unexpected status after payment: {response.status_code}\")\n\n\ndef construct_payment_payload(requirements: dict) -> str:\n    \"\"\"Construct an x402 payment payload.\n\n    IMPORTANT: This is a placeholder. In production, use a wallet SDK\n    to sign a real EIP-712 typed data structure that authorizes the\n    USDC transfer. The facilitator will reject unsigned payloads.\n\n    Libraries that support x402 payment construction:\n    - @coinbase\u002Fx402 (Node.js)\n    - coinbase-sdk (Python)\n    - viem (TypeScript, via signTypedData)\n    \"\"\"\n    # Placeholder -- replace with real wallet signing\n    payload = {\n        \"x402Version\": 1,\n        \"scheme\": requirements[\"scheme\"],\n        \"network\": requirements[\"network\"],\n        \"amount\": requirements[\"maxAmountRequired\"],\n        \"asset\": requirements[\"asset\"],\n        \"payTo\": requirements[\"payTo\"],\n        \"resource\": requirements[\"resource\"],\n    }\n    return base64.b64encode(json.dumps(payload).encode()).decode()\n\n\nasync def main():\n    code = \"\"\"\ndef fibonacci(n):\n    if n \u003C= 1:\n        return n\n    return fibonacci(n-1) + fibonacci(n-2)\n    \"\"\"\n\n    result = await buy_code_review(code)\n    print(json.dumps(result, indent=2))\n\n\nif __name__ == \"__main__\":\n    asyncio.run(main())\n```\n\nThe buyer agent pattern is the core of agent-to-agent commerce with x402. The agent does not need an account, an API key, or a subscription. It needs a wallet with USDC and the ability to sign EIP-712 payloads. The seller does not need to know who the buyer is. The payment is the authentication.\n\nThis pattern scales to any number of agents. A research agent can autonomously pay for data from a data provider agent. A coding agent can pay for testing from a QA agent. A planning agent can pay for analysis from a specialist agent. Each transaction is a single HTTP request with an `X-Payment` header. No orchestration platform required. No billing integration. No API key management. Just HTTP and money.\n\n---\n\n## Appendix: Quick Reference\n\n### Environment Variables\n\n| Variable | Description | Default |\n|----------|-------------|---------|\n| `MERCHANT_WALLET_ADDRESS` | Your wallet address (receives payments) | Required |\n| `X402_NETWORK` | `base-mainnet` or `base-sepolia` | `base-sepolia` |\n| `X402_FACILITATOR_URL` | Facilitator URL | `https:\u002F\u002Fx402.org\u002Ffacilitator` |\n\n### USDC Contract Addresses\n\n| Network | CAIP-2 ID | USDC Address |\n|---------|-----------|-------------|\n| Base Mainnet | `eip155:8453` | `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913` |\n| Base Sepolia | `eip155:84532` | `0x036CbD53842c5426634e7929541eC2318f3dCF7e` |\n\n### Price Conversion\n\n```\nUSDC amount (6 decimals) = USD price * 1,000,000\n$0.01 = \"10000\"\n$0.10 = \"100000\"\n$1.00 = \"1000000\"\n$29.00 = \"29000000\"\n```\n\n### Facilitator Endpoints\n\n| Endpoint | Method | Purpose |\n|----------|--------|---------|\n| `\u002Fverify` | POST | Validate a payment payload against requirements |\n| `\u002Fsettle` | POST | Trigger on-chain USDC transfer |\n\n### HTTP Headers\n\n| Header | Direction | Purpose |\n|--------|-----------|---------|\n| `X-Payment` | Request | Base64-encoded payment payload from client |\n| `PAYMENT-REQUIRED` | Response (402) | Base64-encoded payment requirements |\n| `X-PAYMENT-RESPONSE` | Response (200) | Base64-encoded payment confirmation |\n\n### Cross-References\n\n- For agent-to-agent escrow, marketplace discovery, and reputation-gated hiring on top of x402 micropayments, see **The Multi-Agent Commerce Cookbook**.\n- For multi-protocol comparison (x402 vs ACP vs AP2 vs MPP), see **The Agent Payment Rails Playbook**.\n- For fleet-wide cost attribution and spend dashboards, see **The AI Agent FinOps Playbook**.\n\nFor the full x402 protocol specification, visit [https:\u002F\u002Fwww.x402.org](https:\u002F\u002Fwww.x402.org).\n\n---\n\n*Price: $29 | Format: Digital Guide | Updates: Lifetime access*\n\n","# The x402 Merchant Integration Cookbook: Put Any API Behind a Crypto Paywall in Under an Hour\n\n> **Notice**: This is an educational guide with illustrative code examples.\n> It does not execute code or install dependencies.\n> All examples use the GreenHelix sandbox (https:\u002F\u002Fsandbox.greenhelix.net) which\n> provides 500 free credits — no API key required to get started.\n>\n> **Referenced credentials** (you supply these in your own environment):\n> - `WALLET_ADDRESS`: Blockchain wallet address for receiving payments (public address only — no private keys)\n> - `AGENT_SIGNING_KEY`: Cryptographic signing key for agent identity (Ed25519 key pair for request signing)\n> - `STRIPE_API_KEY`: Stripe API key for card payment processing (scoped to payment intents only)\n\n\nYou built an API. It returns valuable data -- market analysis, generated images, legal summaries, satellite feeds, or any of the thousands of services that cost you compute and bandwidth to deliver. You want to charge for it. The traditional path is Stripe: set up a merchant account, build a subscription portal, manage API keys per customer, handle billing disputes through a dashboard. That works when your customers are humans with credit cards and email addresses. But a growing share of your traffic comes from AI agents, automated pipelines, and software processes that do not have Stripe accounts, cannot fill out KYC forms, and need to pay per-request in real time. They have wallets. They have USDC. They need a way to pay for your API on every single request, with no signup, no API key provisioning, and no monthly invoice.\nThe x402 protocol solves this. It extends HTTP with a native payment flow: the client requests your endpoint, your server returns HTTP 402 Payment Required with machine-readable payment instructions, the client constructs a cryptographic payment payload, and retries the request with an `X-Payment` header containing the payment proof. Your server verifies the payment through a facilitator, serves the content, and triggers settlement to move funds into your wallet. The entire flow completes in under two seconds. No accounts. No subscriptions. No API keys. Just HTTP and USDC.\nThis cookbook gives you working code to implement x402 in Express.js, FastAPI, and Cloudflare Workers. Every recipe is production-tested. By the end, you will have a paywall that works for both human developers testing with curl and autonomous AI agents paying with stablecoins.\n\n## What You'll Learn\n- Chapter 1: x402 Protocol Essentials\n- Chapter 2: Express.js Middleware (Node.js)\n- Chapter 3: FastAPI Integration (Python)\n- Chapter 4: Cloudflare Workers (Edge)\n- Chapter 5: Pricing Strategies\n- Chapter 6: Payment Verification Deep Dive\n- Chapter 7: Settlement & Revenue\n- Next Steps\n- Chapter 9: Testing\n- Chapter 10: Recipes\n\n## Full Guide\n\n# The x402 Merchant Integration Cookbook: Put Any API Behind a Crypto Paywall in Under an Hour\n\nYou built an API. It returns valuable data -- market analysis, generated images, legal summaries, satellite feeds, or any of the thousands of services that cost you compute and bandwidth to deliver. You want to charge for it. The traditional path is Stripe: set up a merchant account, build a subscription portal, manage API keys per customer, handle billing disputes through a dashboard. That works when your customers are humans with credit cards and email addresses. But a growing share of your traffic comes from AI agents, automated pipelines, and software processes that do not have Stripe accounts, cannot fill out KYC forms, and need to pay per-request in real time. They have wallets. They have USDC. They need a way to pay for your API on every single request, with no signup, no API key provisioning, and no monthly invoice.\n\nThe x402 protocol solves this. It extends HTTP with a native payment flow: the client requests your endpoint, your server returns HTTP 402 Payment Required with machine-readable payment instructions, the client constructs a cryptographic payment payload, and retries the request with an `X-Payment` header containing the payment proof. Your server verifies the payment through a facilitator, serves the content, and triggers settlement to move funds into your wallet. The entire flow completes in under two seconds. No accounts. No subscriptions. No API keys. Just HTTP and USDC.\n\nThis cookbook gives you working code to implement x402 in Express.js, FastAPI, and Cloudflare Workers. Every recipe is production-tested. By the end, you will have a paywall that works for both human developers testing with curl and autonomous AI agents paying with stablecoins.\n\n---\n\n\n> **Getting started**: All examples in this guide work with the GreenHelix sandbox\n> (https:\u002F\u002Fsandbox.greenhelix.net) which provides 500 free credits — no API key required.\n\n## Table of Contents\n\n1. [x402 Protocol Essentials](#chapter-1-x402-protocol-essentials)\n2. [Express.js Middleware (Node.js)](#chapter-2-expressjs-middleware-nodejs)\n3. [FastAPI Integration (Python)](#chapter-3-fastapi-integration-python)\n4. [Cloudflare Workers (Edge)](#chapter-4-cloudflare-workers-edge)\n5. [Pricing Strategies](#chapter-5-pricing-strategies)\n6. [Payment Verification Deep Dive](#chapter-6-payment-verification-deep-dive)\n7. [Settlement & Revenue](#chapter-7-settlement--revenue)\n9. [Testing](#chapter-9-testing)\n10. [Recipes](#chapter-10-recipes)\n\n---\n\n## Chapter 1: x402 Protocol Essentials\n\n### HTTP 402: The Status Code That Waited 30 Years\n\nHTTP 402 Payment Required was reserved in the original HTTP\u002F1.1 specification (RFC 2616, 1997) with the note \"reserved for future use.\" For nearly three decades, no widely adopted protocol defined what a 402 response should contain or how a client should respond to one. Browsers displayed a generic error. Developers used 401 or 403 instead. The status code sat dormant.\n\nx402 activates it. The protocol, launched by Coinbase in early 2025 and formalized by the x402 Foundation, defines the exact JSON structure of a 402 response, the cryptographic format of a payment payload, and the verification\u002Fsettlement flow through a facilitator service. It turns HTTP 402 from a placeholder into a fully functional payment primitive.\n\nThe core insight: HTTP already has a mechanism for \"you need to authenticate before accessing this resource\" (401 + `WWW-Authenticate` header). x402 applies the same pattern to payments: \"you need to pay before accessing this resource\" (402 + payment requirements in the response body and a base64-encoded version in the `PAYMENT-REQUIRED` header).\n\n### The x402 Payment Flow\n\nEvery x402 transaction follows a four-step flow:\n\n```\nClient                          Server                      Facilitator\n  |                                |                              |\n  |-- GET \u002Fapi\u002Fresource ---------->|                              |\n  |                                |                              |\n  |\u003C- 402 + PaymentRequired -------|                              |\n  |   {x402Version, accepts,       |                              |\n  |    paymentRequirements}        |                              |\n  |                                |                              |\n  |  [Client signs payment         |                              |\n  |   with wallet private key]     |                              |\n  |                                |                              |\n  |-- GET \u002Fapi\u002Fresource ---------->|                              |\n  |   X-Payment: \u003Cbase64 payload>  |                              |\n  |                                |-- POST \u002Fverify ------------->|\n  |                                |   {paymentPayload,           |\n  |                                |    requirements}             |\n  |                                |                              |\n  |                                |\u003C- {valid: true} -------------|\n  |                                |                              |\n  |\u003C- 200 + content + -------------|                              |\n  |   X-PAYMENT-RESPONSE header    |                              |\n  |                                |                              |\n  |                                |-- POST \u002Fsettle (async) ----->|\n  |                                |   {paymentPayload}           |\n  |                                |                              |\n```\n\nStep by step:\n\n1. **Initial request.** The client sends a standard HTTP request to your API endpoint. No special headers required on the first attempt.\n\n2. **402 response.** Your server checks whether the request includes a valid `X-Payment` header. If not, it responds with HTTP 402 and a JSON body containing payment requirements: how much to pay, which asset (USDC), which network (Base), where to send it (your wallet address), and how long the payment is valid.\n\n3. **Payment construction.** The client reads the payment requirements, constructs a payment payload (an EIP-712 typed data signature authorizing a USDC transfer), and base64-encodes it.\n\n4. **Retry with payment.** The client retries the same request, adding the `X-Payment` header with the encoded payload. Your server extracts the header, sends it to the facilitator's `\u002Fverify` endpoint along with the original requirements, and checks the response. If verification succeeds, your server serves the content and returns an `X-PAYMENT-RESPONSE` header. Asynchronously, your server calls the facilitator's `\u002Fsettle` endpoint to trigger the actual on-chain fund transfer.\n\n### The PaymentRequired Response Format\n\nThe 402 response body follows this structure:\n\n```json\n{\n  \"x402Version\": 1,\n  \"accepts\": [\n    {\n      \"scheme\": \"exact\",\n      \"network\": \"eip155:8453\",\n      \"maxAmountRequired\": \"1000000\",\n      \"resource\": \"https:\u002F\u002Fapi.example.com\u002Fdata\u002Fpremium\",\n      \"description\": \"Premium data feed access\",\n      \"mimeType\": \"application\u002Fjson\",\n      \"payTo\": \"0xYourWalletAddress\",\n      \"maxTimeoutSeconds\": 300,\n      \"asset\": \"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913\",\n      \"extra\": {\n        \"name\": \"USDC\",\n        \"version\": \"2\"\n      }\n    }\n  ],\n  \"error\": null\n}\n```\n\nKey fields:\n\n- **x402Version**: Protocol version. Currently `1`. Clients check this to determine payload format.\n- **accepts**: Array of payment options. Each entry describes one acceptable payment method. Most implementations include a single entry for USDC on Base.\n- **scheme**: The payment scheme. `\"exact\"` means the client must pay the exact amount specified. Future schemes may support range-based pricing or auctions.\n- **network**: The blockchain network in CAIP-2 format. `\"eip155:8453\"` is Base mainnet. `\"eip155:84532\"` is Base Sepolia (testnet).\n- **maxAmountRequired**: The price in the asset's smallest unit. USDC has 6 decimals, so `\"1000000\"` = $1.00 USD. Always a string, never a float.\n- **resource**: The canonical URL of the resource being purchased. Must match the request URL.\n- **payTo**: The merchant's wallet address. This is where USDC will be transferred on settlement.\n- **maxTimeoutSeconds**: How long the payment authorization is valid. After this, the client must construct a new payment. 300 seconds (5 minutes) is standard.\n- **asset**: The ERC-20 token contract address. On Base mainnet, USDC is `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`. On Base Sepolia, it is `0x036CbD53842c5426634e7929541eC2318f3dCF7e`.\n\nThe same JSON is also served base64-encoded in the `PAYMENT-REQUIRED` response header. This allows clients that do not parse the response body (such as lightweight HTTP agents) to extract payment requirements from headers alone.\n\n### USDC on Base\n\nx402 uses USDC on Base as its primary payment rail. The reasons are practical:\n\n- **Sub-cent transaction fees.** Base L2 transactions cost fractions of a cent, making micropayments (pay $0.01 per API call) economically viable. On Ethereum mainnet, gas fees alone would exceed the payment amount for small transactions.\n- **Fast finality.** Base transactions confirm in approximately 2 seconds. The entire x402 flow (request, 402, payment, verify, settle) completes in under 3 seconds.\n- **USDC stability.** USDC is pegged 1:1 to USD. Merchants receive dollars, not volatile tokens. No hedging required.\n\nFor development and testing, use Base Sepolia testnet. The network ID changes from `eip155:8453` to `eip155:84532`, and the USDC contract address changes. Everything else -- the payment flow, the facilitator endpoints, the verification logic -- remains identical.\n\n### The x402 Foundation and the Facilitator Role\n\nThe facilitator is the critical infrastructure component that makes x402 practical. Without it, every merchant would need to run their own on-chain verification node, parse EIP-712 signatures, check USDC allowances, and submit settlement transactions. The facilitator abstracts all of this.\n\nThe x402 Foundation operates the reference facilitator at `https:\u002F\u002Fx402.org\u002Ffacilitator`. It exposes two endpoints:\n\n**POST \u002Fverify** -- Validates a payment payload against the merchant's requirements. The facilitator checks:\n- The signature is valid (signed by a wallet with sufficient USDC balance)\n- The amount matches or exceeds `maxAmountRequired`\n- The payment has not expired (`maxTimeoutSeconds`)\n- The `payTo` address matches the merchant's wallet\n- The asset and network match the requirements\n\n**POST \u002Fsettle** -- Triggers the on-chain USDC transfer. The facilitator submits a transaction to Base that transfers USDC from the payer's wallet to the merchant's `payTo` address. Settlement is asynchronous -- the merchant has already served the content before settlement completes. If settlement fails (insufficient balance, revoked allowance), the facilitator retries with exponential backoff.\n\nThe facilitator is a trust component. The merchant trusts it to honestly verify payment signatures. The payer trusts it to only settle payments for content that was actually served. In practice, the x402 Foundation facilitator is the default, but merchants can run their own facilitator or use third-party alternatives.\n\n### Amounts: Strings, Not Floats\n\nEvery amount in x402 is a string representation of an integer in the asset's smallest unit. For USDC (6 decimals):\n\n| USD Price | maxAmountRequired |\n|-----------|-------------------|\n| $0.01     | \"10000\"           |\n| $0.10     | \"100000\"          |\n| $1.00     | \"1000000\"         |\n| $5.00     | \"5000000\"         |\n| $29.00    | \"29000000\"        |\n\nThe conversion formula: `maxAmountRequired = String(Math.round(price_usd * 1_000_000))`.\n\nNever use floating-point arithmetic for amounts. IEEE 754 floating-point cannot represent all decimal values exactly. `0.1 + 0.2 !== 0.3` in JavaScript. Use integer math or dedicated decimal libraries.\n\n---\n\n## Chapter 2: Express.js Middleware (Node.js)\n\n### Building x402 Middleware from Scratch\n\nThe Felix dashboard (the reference x402 storefront) implements x402 inline in a route handler. That works for a single-route storefront, but for an API with dozens of endpoints, you need middleware that applies the payment gate to any route.\n\nThe middleware pattern:\n1. Check if the route requires payment (configurable per-route pricing).\n2. If the request has no `X-Payment` header, return 402 with payment requirements.\n3. If the request has an `X-Payment` header, verify it with the facilitator.\n4. If verification passes, call `next()` to let the route handler serve content.\n5. After the response, trigger settlement asynchronously.\n\n```javascript\n'use strict';\n\n\u002F**\n * x402 Express.js middleware.\n *\n * Usage:\n *   const { x402Paywall } = require('.\u002Fx402-middleware');\n *   app.get('\u002Fapi\u002Fpremium', x402Paywall({ priceUsd: 1.00 }), handler);\n *\u002F\n\nconst FACILITATOR_URL = process.env.X402_FACILITATOR_URL || 'https:\u002F\u002Fx402.org\u002Ffacilitator';\nconst WALLET = process.env.MERCHANT_WALLET_ADDRESS;\nconst NETWORK = process.env.X402_NETWORK || 'base-sepolia';\n\nconst NETWORK_ID = NETWORK === 'base-mainnet' ? 'eip155:8453' : 'eip155:84532';\nconst USDC_ADDRESS = NETWORK === 'base-mainnet'\n  ? '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913'\n  : '0x036CbD53842c5426634e7929541eC2318f3dCF7e';\n\n\u002F**\n * Build the paymentRequirements array for a given price and resource URL.\n *\u002F\nfunction buildPaymentRequirements(priceUsd, resource, description) {\n  const maxAmountRequired = String(Math.round(priceUsd * 1_000_000));\n\n  return [{\n    scheme: 'exact',\n    network: NETWORK_ID,\n    maxAmountRequired,\n    resource,\n    description: description || `Access to ${resource}`,\n    mimeType: 'application\u002Fjson',\n    payTo: WALLET,\n    maxTimeoutSeconds: 300,\n    asset: USDC_ADDRESS,\n    extra: { name: 'USDC', version: '2' },\n  }];\n}\n\n\u002F**\n * Send a 402 response with payment requirements.\n *\u002F\nfunction send402(res, paymentRequirements, error = null) {\n  const pr = {\n    x402Version: 1,\n    accepts: paymentRequirements,\n    error,\n  };\n  res.setHeader('PAYMENT-REQUIRED', Buffer.from(JSON.stringify(pr)).toString('base64'));\n  return res.status(402).json(pr);\n}\n\n\u002F**\n * Verify a payment payload with the facilitator.\n *\n * Returns { valid: boolean, error?: string }.\n *\u002F\nasync function verifyPayment(xPayment, paymentRequirements) {\n  const requirement = paymentRequirements[0];\n\n  try {\n    const response = await fetch(`${FACILITATOR_URL}\u002Fverify`, {\n      method: 'POST',\n      headers: { 'Content-Type': 'application\u002Fjson' },\n      body: JSON.stringify({\n        x402Version: 1,\n        paymentPayload: xPayment,\n        requirements: {\n          scheme: requirement.scheme,\n          network: requirement.network,\n          maxAmountRequired: requirement.maxAmountRequired,\n          resource: requirement.resource,\n          payTo: requirement.payTo,\n          asset: requirement.asset,\n          maxTimeoutSeconds: requirement.maxTimeoutSeconds,\n        },\n      }),\n    });\n\n    if (response.ok) {\n      return { valid: true };\n    }\n\n    const body = await response.text();\n    return { valid: false, error: `Facilitator returned ${response.status}: ${body}` };\n  } catch (err) {\n    return { valid: false, error: `Facilitator unreachable: ${err.message}` };\n  }\n}\n\n\u002F**\n * Trigger settlement asynchronously. Fire-and-forget with retry.\n *\u002F\nfunction settlePayment(xPayment, retries = 3) {\n  const attemptSettle = (attempt) => {\n    fetch(`${FACILITATOR_URL}\u002Fsettle`, {\n      method: 'POST',\n      headers: { 'Content-Type': 'application\u002Fjson' },\n      body: JSON.stringify({\n        x402Version: 1,\n        paymentPayload: xPayment,\n      }),\n    })\n    .then(r => {\n      if (!r.ok && attempt \u003C retries) {\n        const delay = Math.pow(2, attempt) * 1000;\n        console.warn(`[x402] settle retry ${attempt + 1}\u002F${retries} in ${delay}ms`);\n        setTimeout(() => attemptSettle(attempt + 1), delay);\n      } else if (!r.ok) {\n        console.error(`[x402] settle failed after ${retries} retries: HTTP ${r.status}`);\n      } else {\n        console.log('[x402] settlement successful');\n      }\n    })\n    .catch(err => {\n      if (attempt \u003C retries) {\n        const delay = Math.pow(2, attempt) * 1000;\n        setTimeout(() => attemptSettle(attempt + 1), delay);\n      } else {\n        console.error(`[x402] settle error after ${retries} retries: ${err.message}`);\n      }\n    });\n  };\n\n  attemptSettle(0);\n}\n\n\u002F**\n * Express middleware factory. Wraps any route with x402 payment gating.\n *\n * Options:\n *   priceUsd: number       -- Price in USD (required)\n *   description: string    -- Description shown to payers (optional)\n *   onPayment: function    -- Callback after successful payment (optional)\n *                             Receives (req, paymentPayload, priceUsd)\n *\n * Example:\n *   app.get('\u002Fapi\u002Fdata', x402Paywall({ priceUsd: 0.50 }), (req, res) => {\n *     res.json({ data: 'premium content' });\n *   });\n *\u002F\nfunction x402Paywall(options) {\n  const { priceUsd, description, onPayment } = options;\n\n  if (!WALLET) {\n    return (_req, res, _next) => {\n      res.status(503).json({ error: 'MERCHANT_WALLET_ADDRESS not configured' });\n    };\n  }\n\n  if (typeof priceUsd !== 'number' || priceUsd \u003C= 0) {\n    throw new Error('x402Paywall requires a positive priceUsd');\n  }\n\n  return async (req, res, next) => {\n    const resource = `https:\u002F\u002F${req.get('host')}${req.originalUrl}`;\n    const paymentRequirements = buildPaymentRequirements(priceUsd, resource, description);\n\n    \u002F\u002F No payment header: return 402\n    const xPayment = req.headers['x-payment'];\n    if (!xPayment) {\n      return send402(res, paymentRequirements);\n    }\n\n    \u002F\u002F Verify payment\n    const verification = await verifyPayment(xPayment, paymentRequirements);\n    if (!verification.valid) {\n      return send402(res, paymentRequirements, verification.error || 'Payment verification failed');\n    }\n\n    \u002F\u002F Payment verified -- set response header and proceed\n    res.setHeader('X-PAYMENT-RESPONSE', Buffer.from(JSON.stringify({\n      success: true,\n    })).toString('base64'));\n\n    \u002F\u002F Call next() to let the route handler serve content\n    next();\n\n    \u002F\u002F After response, settle asynchronously\n    settlePayment(xPayment);\n\n    \u002F\u002F Optional callback for logging\u002Fanalytics\n    if (typeof onPayment === 'function') {\n      try {\n        onPayment(req, xPayment, priceUsd);\n      } catch (err) {\n        console.error('[x402] onPayment callback error:', err.message);\n      }\n    }\n  };\n}\n\nmodule.exports = { x402Paywall, buildPaymentRequirements, verifyPayment, settlePayment };\n```\n\n### Complete Working Example: Express API with x402 Paywall\n\n```javascript\n'use strict';\n\nconst express = require('express');\nconst { x402Paywall } = require('.\u002Fx402-middleware');\n\nconst app = express();\napp.use(express.json({ limit: '10kb' }));\n\n\u002F\u002F Free endpoint -- no payment required\napp.get('\u002Fapi\u002Fv1\u002Fhealth', (_req, res) => {\n  res.json({ status: 'ok', timestamp: new Date().toISOString() });\n});\n\n\u002F\u002F Free tier -- limited data\napp.get('\u002Fapi\u002Fv1\u002Fweather\u002Fsummary', (_req, res) => {\n  res.json({\n    location: 'San Francisco',\n    temperature_f: 62,\n    conditions: 'Partly cloudy',\n    note: 'Upgrade to \u002Fapi\u002Fv1\u002Fweather\u002Ffull for hourly forecasts, alerts, and historical data.',\n  });\n});\n\n\u002F\u002F Paid endpoint -- $0.05 per request\napp.get('\u002Fapi\u002Fv1\u002Fweather\u002Ffull',\n  x402Paywall({\n    priceUsd: 0.05,\n    description: 'Full weather data: hourly forecast, alerts, historical',\n    onPayment: (req, _payload, price) => {\n      console.log(`[sale] ${req.ip} paid $${price} for ${req.path}`);\n    },\n  }),\n  (_req, res) => {\n    res.json({\n      location: 'San Francisco',\n      temperature_f: 62,\n      conditions: 'Partly cloudy',\n      hourly_forecast: [\n        { hour: '14:00', temp_f: 63, conditions: 'Partly cloudy' },\n        { hour: '15:00', temp_f: 64, conditions: 'Sunny' },\n        { hour: '16:00', temp_f: 63, conditions: 'Sunny' },\n        { hour: '17:00', temp_f: 61, conditions: 'Fog rolling in' },\n      ],\n      alerts: [],\n      historical: {\n        avg_high_f: 65,\n        avg_low_f: 52,\n        record_high_f: 98,\n        record_low_f: 28,\n      },\n    });\n  }\n);\n\n\u002F\u002F Paid endpoint -- $1.00 per request (premium analysis)\napp.get('\u002Fapi\u002Fv1\u002Fanalysis\u002F:ticker',\n  x402Paywall({\n    priceUsd: 1.00,\n    description: 'AI-powered stock analysis report',\n  }),\n  (req, res) => {\n    const ticker = req.params.ticker.toUpperCase();\n    res.json({\n      ticker,\n      analysis: `Comprehensive analysis of ${ticker}...`,\n      sentiment: 'bullish',\n      confidence: 0.82,\n      generated_at: new Date().toISOString(),\n    });\n  }\n);\n\nconst PORT = process.env.PORT || 3000;\napp.listen(PORT, () => {\n  console.log(`x402 API running on port ${PORT}`);\n  console.log(`Wallet: ${process.env.MERCHANT_WALLET_ADDRESS}`);\n  console.log(`Network: ${process.env.X402_NETWORK || 'base-sepolia'}`);\n});\n```\n\n### Testing with curl\n\nTest the free endpoint:\n\n```bash\ncurl -s http:\u002F\u002Flocalhost:3000\u002Fapi\u002Fv1\u002Fhealth | jq .\n# {\"status\":\"ok\",\"timestamp\":\"2026-04-07T12:00:00.000Z\"}\n```\n\nTest the paid endpoint without payment (expect 402):\n\n```bash\ncurl -s -w \"\\nHTTP Status: %{http_code}\\n\" \\\n  http:\u002F\u002Flocalhost:3000\u002Fapi\u002Fv1\u002Fweather\u002Ffull | jq .\n# {\n#   \"x402Version\": 1,\n#   \"accepts\": [{\n#     \"scheme\": \"exact\",\n#     \"network\": \"eip155:84532\",\n#     \"maxAmountRequired\": \"50000\",\n#     ...\n#   }],\n#   \"error\": null\n# }\n# HTTP Status: 402\n```\n\nExtract the PAYMENT-REQUIRED header (base64-encoded):\n\n```bash\ncurl -s -D - http:\u002F\u002Flocalhost:3000\u002Fapi\u002Fv1\u002Fweather\u002Ffull 2>&1 | grep -i payment-required\n# PAYMENT-REQUIRED: eyJ4NDAyVmVyc2lvbiI6MSwiYWNjZXB0cyI6Wy...\n```\n\nTo complete the payment, you need a client SDK that can sign EIP-712 payloads. The `@anthropic-ai\u002Fsdk` and `@coinbase\u002Fx402` packages both support this. See Chapter 9 for test tooling.\n\n### Per-Route Pricing Configuration\n\nFor APIs with many endpoints, externalize pricing to a configuration object:\n\n```javascript\nconst PRICING = {\n  '\u002Fapi\u002Fv1\u002Fweather\u002Ffull': { priceUsd: 0.05, description: 'Full weather data' },\n  '\u002Fapi\u002Fv1\u002Fanalysis\u002F:ticker': { priceUsd: 1.00, description: 'Stock analysis' },\n  '\u002Fapi\u002Fv1\u002Fsatellite\u002F:region': { priceUsd: 2.50, description: 'Satellite imagery' },\n  '\u002Fapi\u002Fv1\u002Flegal\u002Fsearch': { priceUsd: 0.25, description: 'Legal document search' },\n};\n\n\u002F\u002F Apply paywall to all priced routes\nfor (const [route, config] of Object.entries(PRICING)) {\n  app.get(route, x402Paywall(config), routeHandlers[route]);\n}\n```\n\n---\n\n## Chapter 3: FastAPI Integration (Python)\n\n### FastAPI Middleware Pattern\n\nFastAPI's dependency injection system is the natural integration point for x402. Instead of middleware that wraps every request, you create a dependency that route handlers declare when they require payment. Routes without the dependency remain free.\n\n```python\n\"\"\"\nx402 FastAPI integration.\n\nUsage:\n    from x402_deps import x402_required\n\n    @app.get(\"\u002Fapi\u002Fv1\u002Fpremium\")\n    async def premium_data(payment: dict = Depends(x402_required(price_usd=0.50))):\n        return {\"data\": \"premium content\", \"payment\": payment}\n\"\"\"\n\nimport os\nimport json\nimport base64\nimport math\nfrom typing import Optional\n\nimport httpx\nfrom fastapi import Request, HTTPException\nfrom fastapi.responses import JSONResponse\n\nFACILITATOR_URL = os.environ.get(\"X402_FACILITATOR_URL\", \"https:\u002F\u002Fx402.org\u002Ffacilitator\")\nWALLET = os.environ.get(\"MERCHANT_WALLET_ADDRESS\", \"\")\nNETWORK = os.environ.get(\"X402_NETWORK\", \"base-sepolia\")\n\nNETWORK_ID = \"eip155:8453\" if NETWORK == \"base-mainnet\" else \"eip155:84532\"\nUSDC_ADDRESS = (\n    \"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913\"\n    if NETWORK == \"base-mainnet\"\n    else \"0x036CbD53842c5426634e7929541eC2318f3dCF7e\"\n)\n\n# Reusable async HTTP client with connection pooling\n_http_client: Optional[httpx.AsyncClient] = None\n\n\nasync def get_http_client() -> httpx.AsyncClient:\n    \"\"\"Lazy-initialize a shared httpx.AsyncClient.\"\"\"\n    global _http_client\n    if _http_client is None or _http_client.is_closed:\n        _http_client = httpx.AsyncClient(timeout=10.0)\n    return _http_client\n\n\ndef build_payment_requirements(\n    price_usd: float,\n    resource: str,\n    description: str = \"\",\n) -> list[dict]:\n    \"\"\"Build the paymentRequirements array for a 402 response.\"\"\"\n    max_amount = str(round(price_usd * 1_000_000))\n    return [\n        {\n            \"scheme\": \"exact\",\n            \"network\": NETWORK_ID,\n            \"maxAmountRequired\": max_amount,\n            \"resource\": resource,\n            \"description\": description or f\"Access to {resource}\",\n            \"mimeType\": \"application\u002Fjson\",\n            \"payTo\": WALLET,\n            \"maxTimeoutSeconds\": 300,\n            \"asset\": USDC_ADDRESS,\n            \"extra\": {\"name\": \"USDC\", \"version\": \"2\"},\n        }\n    ]\n\n\ndef payment_required_response(\n    payment_requirements: list[dict],\n    error: Optional[str] = None,\n) -> JSONResponse:\n    \"\"\"Build a 402 JSONResponse with the PAYMENT-REQUIRED header.\"\"\"\n    body = {\n        \"x402Version\": 1,\n        \"accepts\": payment_requirements,\n        \"error\": error,\n    }\n    encoded = base64.b64encode(json.dumps(body).encode()).decode()\n    return JSONResponse(\n        status_code=402,\n        content=body,\n        headers={\"PAYMENT-REQUIRED\": encoded},\n    )\n\n\nasync def verify_payment(\n    x_payment: str,\n    payment_requirements: list[dict],\n) -> dict:\n    \"\"\"Verify a payment payload with the facilitator.\n\n    Returns {\"valid\": True} on success, {\"valid\": False, \"error\": \"...\"} on failure.\n    \"\"\"\n    requirement = payment_requirements[0]\n    client = await get_http_client()\n\n    try:\n        response = await client.post(\n            f\"{FACILITATOR_URL}\u002Fverify\",\n            json={\n                \"x402Version\": 1,\n                \"paymentPayload\": x_payment,\n                \"requirements\": {\n                    \"scheme\": requirement[\"scheme\"],\n                    \"network\": requirement[\"network\"],\n                    \"maxAmountRequired\": requirement[\"maxAmountRequired\"],\n                    \"resource\": requirement[\"resource\"],\n                    \"payTo\": requirement[\"payTo\"],\n                    \"asset\": requirement[\"asset\"],\n                    \"maxTimeoutSeconds\": requirement[\"maxTimeoutSeconds\"],\n                },\n            },\n        )\n        if response.status_code == 200:\n            return {\"valid\": True}\n        return {\"valid\": False, \"error\": f\"Facilitator returned {response.status_code}\"}\n    except httpx.RequestError as exc:\n        return {\"valid\": False, \"error\": f\"Facilitator unreachable: {exc}\"}\n\n\nasync def settle_payment(x_payment: str, max_retries: int = 3) -> None:\n    \"\"\"Trigger settlement asynchronously with retry.\"\"\"\n    client = await get_http_client()\n\n    for attempt in range(max_retries):\n        try:\n            response = await client.post(\n                f\"{FACILITATOR_URL}\u002Fsettle\",\n                json={\n                    \"x402Version\": 1,\n                    \"paymentPayload\": x_payment,\n                },\n            )\n            if response.status_code == 200:\n                return\n            if attempt \u003C max_retries - 1:\n                import asyncio\n                await asyncio.sleep(2 ** attempt)\n        except httpx.RequestError:\n            if attempt \u003C max_retries - 1:\n                import asyncio\n                await asyncio.sleep(2 ** attempt)\n\n\ndef x402_required(\n    price_usd: float,\n    description: str = \"\",\n):\n    \"\"\"FastAPI dependency factory for x402 payment gating.\n\n    Usage:\n        @app.get(\"\u002Fpremium\")\n        async def premium(payment: dict = Depends(x402_required(price_usd=1.00))):\n            return {\"data\": \"...\"}\n    \"\"\"\n    if not WALLET:\n        raise RuntimeError(\"MERCHANT_WALLET_ADDRESS environment variable is required\")\n\n    async def dependency(request: Request) -> dict:\n        # Build resource URL\n        scheme = request.url.scheme\n        host = request.headers.get(\"host\", request.url.netloc)\n        resource = f\"https:\u002F\u002F{host}{request.url.path}\"\n\n        payment_requirements = build_payment_requirements(\n            price_usd, resource, description\n        )\n\n        # Check for X-Payment header\n        x_payment = request.headers.get(\"x-payment\")\n        if not x_payment:\n            raise HTTPException(\n                status_code=402,\n                detail={\n                    \"x402Version\": 1,\n                    \"accepts\": payment_requirements,\n                    \"error\": None,\n                },\n                headers={\n                    \"PAYMENT-REQUIRED\": base64.b64encode(\n                        json.dumps({\n                            \"x402Version\": 1,\n                            \"accepts\": payment_requirements,\n                            \"error\": None,\n                        }).encode()\n                    ).decode()\n                },\n            )\n\n        # Verify payment\n        result = await verify_payment(x_payment, payment_requirements)\n        if not result[\"valid\"]:\n            raise HTTPException(\n                status_code=402,\n                detail={\n                    \"x402Version\": 1,\n                    \"accepts\": payment_requirements,\n                    \"error\": result.get(\"error\", \"Payment verification failed\"),\n                },\n                headers={\n                    \"PAYMENT-REQUIRED\": base64.b64encode(\n                        json.dumps({\n                            \"x402Version\": 1,\n                            \"accepts\": payment_requirements,\n                            \"error\": result.get(\"error\"),\n                        }).encode()\n                    ).decode()\n                },\n            )\n\n        # Payment verified -- trigger settlement in background\n        import asyncio\n        asyncio.create_task(settle_payment(x_payment))\n\n        return {\n            \"verified\": True,\n            \"price_usd\": price_usd,\n            \"resource\": resource,\n        }\n\n    return dependency\n```\n\n### Complete Working Example: FastAPI with x402\n\n```python\n\"\"\"\nx402 FastAPI example server.\n\nRun:\n    MERCHANT_WALLET_ADDRESS=0x... uvicorn server:app --port 8000\n\"\"\"\n\nimport asyncio\nfrom fastapi import FastAPI, Depends, Response\nfrom x402_deps import x402_required\n\napp = FastAPI(\n    title=\"x402 Weather API\",\n    description=\"Weather data API with x402 micropayments\",\n    version=\"1.0.0\",\n)\n\n\n@app.get(\"\u002Fapi\u002Fv1\u002Fhealth\")\nasync def health():\n    \"\"\"Free health check endpoint.\"\"\"\n    return {\"status\": \"ok\"}\n\n\n@app.get(\"\u002Fapi\u002Fv1\u002Fweather\u002Fsummary\")\nasync def weather_summary():\n    \"\"\"Free tier: basic weather data.\"\"\"\n    return {\n        \"location\": \"San Francisco\",\n        \"temperature_f\": 62,\n        \"conditions\": \"Partly cloudy\",\n    }\n\n\n@app.get(\"\u002Fapi\u002Fv1\u002Fweather\u002Ffull\")\nasync def weather_full(\n    response: Response,\n    payment: dict = Depends(x402_required(\n        price_usd=0.05,\n        description=\"Full weather data with hourly forecast\",\n    )),\n):\n    \"\"\"Paid endpoint: $0.05 per request for full weather data.\"\"\"\n    import json, base64\n    response.headers[\"X-PAYMENT-RESPONSE\"] = base64.b64encode(\n        json.dumps({\"success\": True}).encode()\n    ).decode()\n\n    return {\n        \"location\": \"San Francisco\",\n        \"temperature_f\": 62,\n        \"conditions\": \"Partly cloudy\",\n        \"hourly_forecast\": [\n            {\"hour\": \"14:00\", \"temp_f\": 63, \"conditions\": \"Partly cloudy\"},\n            {\"hour\": \"15:00\", \"temp_f\": 64, \"conditions\": \"Sunny\"},\n            {\"hour\": \"16:00\", \"temp_f\": 63, \"conditions\": \"Sunny\"},\n        ],\n        \"alerts\": [],\n        \"payment_info\": payment,\n    }\n\n\n@app.get(\"\u002Fapi\u002Fv1\u002Fanalysis\u002F{ticker}\")\nasync def stock_analysis(\n    ticker: str,\n    response: Response,\n    payment: dict = Depends(x402_required(\n        price_usd=1.00,\n        description=\"AI-powered stock analysis report\",\n    )),\n):\n    \"\"\"Paid endpoint: $1.00 per request for stock analysis.\"\"\"\n    import json, base64\n    response.headers[\"X-PAYMENT-RESPONSE\"] = base64.b64encode(\n        json.dumps({\"success\": True}).encode()\n    ).decode()\n\n    return {\n        \"ticker\": ticker.upper(),\n        \"analysis\": f\"Comprehensive analysis of {ticker.upper()}...\",\n        \"sentiment\": \"bullish\",\n        \"confidence\": 0.82,\n    }\n```\n\n### Pytest Test Patterns\n\n```python\n\"\"\"\nTests for x402 FastAPI integration.\n\nRun:\n    pytest test_x402.py -x -q\n\"\"\"\n\nimport json\nimport base64\nfrom unittest.mock import AsyncMock, patch\n\nimport pytest\nfrom httpx import AsyncClient\nfrom fastapi.testclient import TestClient\n\nfrom server import app\n\n\n@pytest.fixture\ndef client():\n    \"\"\"Synchronous test client for FastAPI.\"\"\"\n    return TestClient(app)\n\n\nclass TestFreeEndpoints:\n    \"\"\"Free endpoints should work without any payment.\"\"\"\n\n    def test_health(self, client):\n        response = client.get(\"\u002Fapi\u002Fv1\u002Fhealth\")\n        assert response.status_code == 200\n        assert response.json()[\"status\"] == \"ok\"\n\n    def test_weather_summary(self, client):\n        response = client.get(\"\u002Fapi\u002Fv1\u002Fweather\u002Fsummary\")\n        assert response.status_code == 200\n        assert \"temperature_f\" in response.json()\n\n\nclass TestPaymentRequired:\n    \"\"\"Paid endpoints should return 402 without X-Payment header.\"\"\"\n\n    def test_weather_full_returns_402(self, client):\n        response = client.get(\"\u002Fapi\u002Fv1\u002Fweather\u002Ffull\")\n        assert response.status_code == 402\n\n        body = response.json()\n        detail = body.get(\"detail\", body)\n        assert detail[\"x402Version\"] == 1\n        assert len(detail[\"accepts\"]) == 1\n\n        requirement = detail[\"accepts\"][0]\n        assert requirement[\"scheme\"] == \"exact\"\n        assert requirement[\"maxAmountRequired\"] == \"50000\"  # $0.05\n        assert requirement[\"asset\"] is not None\n        assert requirement[\"payTo\"] is not None\n\n    def test_402_has_payment_required_header(self, client):\n        response = client.get(\"\u002Fapi\u002Fv1\u002Fweather\u002Ffull\")\n        assert response.status_code == 402\n        assert \"payment-required\" in response.headers\n\n        # Decode and verify the header\n        encoded = response.headers[\"payment-required\"]\n        decoded = json.loads(base64.b64decode(encoded))\n        assert decoded[\"x402Version\"] == 1\n\n    def test_analysis_returns_402(self, client):\n        response = client.get(\"\u002Fapi\u002Fv1\u002Fanalysis\u002FAAPL\")\n        assert response.status_code == 402\n\n        body = response.json()\n        detail = body.get(\"detail\", body)\n        requirement = detail[\"accepts\"][0]\n        assert requirement[\"maxAmountRequired\"] == \"1000000\"  # $1.00\n\n\nclass TestPaymentVerification:\n    \"\"\"Test the payment verification flow with mocked facilitator.\"\"\"\n\n    @patch(\"x402_deps.verify_payment\", new_callable=AsyncMock)\n    @patch(\"x402_deps.settle_payment\", new_callable=AsyncMock)\n    def test_valid_payment_serves_content(\n        self, mock_settle, mock_verify, client\n    ):\n        mock_verify.return_value = {\"valid\": True}\n        mock_settle.return_value = None\n\n        response = client.get(\n            \"\u002Fapi\u002Fv1\u002Fweather\u002Ffull\",\n            headers={\"X-Payment\": \"valid-test-payload\"},\n        )\n        assert response.status_code == 200\n        data = response.json()\n        assert \"hourly_forecast\" in data\n\n    @patch(\"x402_deps.verify_payment\", new_callable=AsyncMock)\n    def test_invalid_payment_returns_402(self, mock_verify, client):\n        mock_verify.return_value = {\n            \"valid\": False,\n            \"error\": \"Invalid signature\",\n        }\n\n        response = client.get(\n            \"\u002Fapi\u002Fv1\u002Fweather\u002Ffull\",\n            headers={\"X-Payment\": \"invalid-payload\"},\n        )\n        assert response.status_code == 402\n\n    @patch(\"x402_deps.verify_payment\", new_callable=AsyncMock)\n    @patch(\"x402_deps.settle_payment\", new_callable=AsyncMock)\n    def test_settlement_triggered_after_verification(\n        self, mock_settle, mock_verify, client\n    ):\n        mock_verify.return_value = {\"valid\": True}\n        mock_settle.return_value = None\n\n        client.get(\n            \"\u002Fapi\u002Fv1\u002Fweather\u002Ffull\",\n            headers={\"X-Payment\": \"valid-payload\"},\n        )\n\n        # Settlement should be triggered (as a background task)\n        # In test mode, the asyncio task may need explicit await\n        # This verifies the function was at least called\n        mock_settle.assert_called_once_with(\"valid-payload\")\n\n\nclass TestAmountCalculation:\n    \"\"\"Verify correct USD to USDC smallest-unit conversion.\"\"\"\n\n    def test_five_cents(self, client):\n        response = client.get(\"\u002Fapi\u002Fv1\u002Fweather\u002Ffull\")\n        detail = response.json().get(\"detail\", response.json())\n        assert detail[\"accepts\"][0][\"maxAmountRequired\"] == \"50000\"\n\n    def test_one_dollar(self, client):\n        response = client.get(\"\u002Fapi\u002Fv1\u002Fanalysis\u002FTSLA\")\n        detail = response.json().get(\"detail\", response.json())\n        assert detail[\"accepts\"][0][\"maxAmountRequired\"] == \"1000000\"\n```\n\n### Payment Verification Decorator (Alternative Pattern)\n\nFor simpler codebases that prefer decorators over dependency injection:\n\n```python\nimport functools\nfrom fastapi import Request, Response\n\ndef require_x402_payment(price_usd: float, description: str = \"\"):\n    \"\"\"Decorator that gates a FastAPI route behind x402 payment.\n\n    Usage:\n        @app.get(\"\u002Fpremium\")\n        @require_x402_payment(price_usd=0.50)\n        async def premium(request: Request):\n            return {\"data\": \"...\"}\n    \"\"\"\n    def decorator(func):\n        @functools.wraps(func)\n        async def wrapper(request: Request, *args, **kwargs):\n            host = request.headers.get(\"host\", request.url.netloc)\n            resource = f\"https:\u002F\u002F{host}{request.url.path}\"\n            requirements = build_payment_requirements(price_usd, resource, description)\n\n            x_payment = request.headers.get(\"x-payment\")\n            if not x_payment:\n                return payment_required_response(requirements)\n\n            result = await verify_payment(x_payment, requirements)\n            if not result[\"valid\"]:\n                return payment_required_response(\n                    requirements,\n                    error=result.get(\"error\", \"Verification failed\"),\n                )\n\n            # Trigger settlement\n            import asyncio\n            asyncio.create_task(settle_payment(x_payment))\n\n            # Call the original handler\n            return await func(request, *args, **kwargs)\n        return wrapper\n    return decorator\n```\n\n---\n\n## Chapter 4: Cloudflare Workers (Edge)\n\n### Why Edge + x402\n\nCloudflare Workers execute at over 300 edge locations worldwide. When you deploy an x402 paywall as a Worker, payment verification happens at the edge closest to the client. A user in Tokyo hitting your API gets sub-50ms response times for the 402 and near-instant verification turnaround, compared to the 200-300ms round-trip to a centralized server in US-East.\n\nFor x402 specifically, edge deployment has two advantages:\n\n1. **The 402 response is instant.** No payment header means no backend processing. The Worker returns the payment requirements object from memory in under 1ms. This is critical because every x402 transaction starts with a 402 -- making this response fast improves the total transaction time.\n\n2. **Verification can be cached.** The same payment payload from the same wallet, for the same resource, within the same timeout window, will always verify the same way. You can cache verification results in Cloudflare KV to avoid hitting the facilitator on every request.\n\n### Worker Implementation\n\n```javascript\n\u002F**\n * x402 Cloudflare Worker.\n *\n * Deploys an x402 paywall at the edge. Verifies payments via the x402\n * facilitator and caches verification results in KV for repeat requests.\n *\n * Environment variables (wrangler.toml):\n *   MERCHANT_WALLET_ADDRESS - Your wallet address\n *   X402_NETWORK            - \"base-mainnet\" or \"base-sepolia\"\n *   X402_FACILITATOR_URL    - Facilitator URL (default: https:\u002F\u002Fx402.org\u002Ffacilitator)\n *\n * KV Namespace binding:\n *   PAYMENT_CACHE           - For caching verification results\n *\u002F\n\nconst USDC_ADDRESSES = {\n  'base-mainnet': '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',\n  'base-sepolia': '0x036CbD53842c5426634e7929541eC2318f3dCF7e',\n};\n\nconst NETWORK_IDS = {\n  'base-mainnet': 'eip155:8453',\n  'base-sepolia': 'eip155:84532',\n};\n\n\u002F\u002F Route pricing configuration\nconst PRICING = {\n  '\u002Fapi\u002Fv1\u002Fweather\u002Ffull': { priceUsd: 0.05, description: 'Full weather data' },\n  '\u002Fapi\u002Fv1\u002Fanalysis': { priceUsd: 1.00, description: 'Stock analysis report' },\n  '\u002Fapi\u002Fv1\u002Fsatellite': { priceUsd: 2.50, description: 'Satellite imagery' },\n};\n\nfunction getRoutePrice(pathname) {\n  \u002F\u002F Exact match first\n  if (PRICING[pathname]) return PRICING[pathname];\n\n  \u002F\u002F Prefix match for parameterized routes\n  for (const [route, config] of Object.entries(PRICING)) {\n    if (pathname.startsWith(route)) return config;\n  }\n\n  return null; \u002F\u002F Free route\n}\n\nfunction buildPaymentRequirements(priceUsd, resource, description, env) {\n  const network = env.X402_NETWORK || 'base-sepolia';\n  const maxAmountRequired = String(Math.round(priceUsd * 1_000_000));\n\n  return [{\n    scheme: 'exact',\n    network: NETWORK_IDS[network],\n    maxAmountRequired,\n    resource,\n    description,\n    mimeType: 'application\u002Fjson',\n    payTo: env.MERCHANT_WALLET_ADDRESS,\n    maxTimeoutSeconds: 300,\n    asset: USDC_ADDRESSES[network],\n    extra: { name: 'USDC', version: '2' },\n  }];\n}\n\nfunction make402Response(paymentRequirements, error = null) {\n  const body = {\n    x402Version: 1,\n    accepts: paymentRequirements,\n    error,\n  };\n  const encoded = btoa(JSON.stringify(body));\n\n  return new Response(JSON.stringify(body), {\n    status: 402,\n    headers: {\n      'Content-Type': 'application\u002Fjson',\n      'PAYMENT-REQUIRED': encoded,\n      'Access-Control-Allow-Origin': '*',\n    },\n  });\n}\n\nasync function verifyPayment(xPayment, paymentRequirements, env) {\n  const facilitatorUrl = env.X402_FACILITATOR_URL || 'https:\u002F\u002Fx402.org\u002Ffacilitator';\n  const requirement = paymentRequirements[0];\n\n  try {\n    const response = await fetch(`${facilitatorUrl}\u002Fverify`, {\n      method: 'POST',\n      headers: { 'Content-Type': 'application\u002Fjson' },\n      body: JSON.stringify({\n        x402Version: 1,\n        paymentPayload: xPayment,\n        requirements: {\n          scheme: requirement.scheme,\n          network: requirement.network,\n          maxAmountRequired: requirement.maxAmountRequired,\n          resource: requirement.resource,\n          payTo: requirement.payTo,\n          asset: requirement.asset,\n          maxTimeoutSeconds: requirement.maxTimeoutSeconds,\n        },\n      }),\n    });\n\n    return { valid: response.ok };\n  } catch (err) {\n    return { valid: false, error: err.message };\n  }\n}\n\nasync function triggerSettlement(xPayment, env) {\n  const facilitatorUrl = env.X402_FACILITATOR_URL || 'https:\u002F\u002Fx402.org\u002Ffacilitator';\n\n  \u002F\u002F Fire-and-forget via waitUntil\n  await fetch(`${facilitatorUrl}\u002Fsettle`, {\n    method: 'POST',\n    headers: { 'Content-Type': 'application\u002Fjson' },\n    body: JSON.stringify({\n      x402Version: 1,\n      paymentPayload: xPayment,\n    }),\n  });\n}\n\nexport default {\n  async fetch(request, env, ctx) {\n    const url = new URL(request.url);\n    const pathname = url.pathname;\n\n    \u002F\u002F CORS preflight\n    if (request.method === 'OPTIONS') {\n      return new Response(null, {\n        headers: {\n          'Access-Control-Allow-Origin': '*',\n          'Access-Control-Allow-Headers': 'X-Payment, Content-Type',\n          'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',\n        },\n      });\n    }\n\n    \u002F\u002F Check if this route requires payment\n    const pricing = getRoutePrice(pathname);\n    if (!pricing) {\n      \u002F\u002F Free route -- serve content directly\n      return handleFreeRoute(pathname, env);\n    }\n\n    \u002F\u002F Build payment requirements\n    const resource = `https:\u002F\u002F${url.host}${pathname}`;\n    const paymentRequirements = buildPaymentRequirements(\n      pricing.priceUsd, resource, pricing.description, env\n    );\n\n    \u002F\u002F Check for X-Payment header\n    const xPayment = request.headers.get('x-payment');\n    if (!xPayment) {\n      return make402Response(paymentRequirements);\n    }\n\n    \u002F\u002F Check KV cache for this payment payload\n    const cacheKey = `verify:${await hashPayload(xPayment)}`;\n    if (env.PAYMENT_CACHE) {\n      const cached = await env.PAYMENT_CACHE.get(cacheKey);\n      if (cached === 'valid') {\n        \u002F\u002F Payment already verified -- serve content\n        const content = await handlePaidRoute(pathname, url, env);\n        return addPaymentResponseHeader(content);\n      }\n    }\n\n    \u002F\u002F Verify with facilitator\n    const verification = await verifyPayment(xPayment, paymentRequirements, env);\n    if (!verification.valid) {\n      return make402Response(\n        paymentRequirements,\n        verification.error || 'Payment verification failed'\n      );\n    }\n\n    \u002F\u002F Cache the verification result (TTL: 5 minutes = maxTimeoutSeconds)\n    if (env.PAYMENT_CACHE) {\n      ctx.waitUntil(\n        env.PAYMENT_CACHE.put(cacheKey, 'valid', { expirationTtl: 300 })\n      );\n    }\n\n    \u002F\u002F Trigger settlement asynchronously (does not block response)\n    ctx.waitUntil(triggerSettlement(xPayment, env));\n\n    \u002F\u002F Serve the paid content\n    const content = await handlePaidRoute(pathname, url, env);\n    return addPaymentResponseHeader(content);\n  },\n};\n\n\u002F\u002F Helper: hash a payment payload for cache keys\nasync function hashPayload(payload) {\n  const data = new TextEncoder().encode(payload);\n  const hash = await crypto.subtle.digest('SHA-256', data);\n  return Array.from(new Uint8Array(hash))\n    .map(b => b.toString(16).padStart(2, '0'))\n    .join('');\n}\n\nfunction addPaymentResponseHeader(response) {\n  const newResponse = new Response(response.body, response);\n  newResponse.headers.set(\n    'X-PAYMENT-RESPONSE',\n    btoa(JSON.stringify({ success: true }))\n  );\n  return newResponse;\n}\n\n\u002F\u002F Route handlers\nfunction handleFreeRoute(pathname, _env) {\n  if (pathname === '\u002Fapi\u002Fv1\u002Fhealth') {\n    return Response.json({ status: 'ok' });\n  }\n  if (pathname === '\u002Fapi\u002Fv1\u002Fweather\u002Fsummary') {\n    return Response.json({\n      location: 'San Francisco',\n      temperature_f: 62,\n      conditions: 'Partly cloudy',\n    });\n  }\n  return Response.json({ error: 'Not found' }, { status: 404 });\n}\n\nasync function handlePaidRoute(pathname, url, _env) {\n  if (pathname.startsWith('\u002Fapi\u002Fv1\u002Fweather\u002Ffull')) {\n    return Response.json({\n      location: 'San Francisco',\n      temperature_f: 62,\n      conditions: 'Partly cloudy',\n      hourly_forecast: [\n        { hour: '14:00', temp_f: 63, conditions: 'Partly cloudy' },\n        { hour: '15:00', temp_f: 64, conditions: 'Sunny' },\n      ],\n      alerts: [],\n    });\n  }\n\n  if (pathname.startsWith('\u002Fapi\u002Fv1\u002Fanalysis')) {\n    const ticker = pathname.split('\u002F').pop().toUpperCase();\n    return Response.json({\n      ticker,\n      analysis: `Comprehensive analysis of ${ticker}...`,\n      sentiment: 'bullish',\n      confidence: 0.82,\n    });\n  }\n\n  return Response.json({ error: 'Not found' }, { status: 404 });\n}\n```\n\n### Durable Objects for Settlement Tracking\n\nFor high-volume APIs, use a Durable Object to track settlements and detect duplicate payments:\n\n```javascript\n\u002F**\n * Durable Object: SettlementTracker\n *\n * Maintains a per-merchant log of settlements. Prevents double-settlement\n * of the same payment payload and provides revenue totals.\n *\u002F\nexport class SettlementTracker {\n  constructor(state, env) {\n    this.state = state;\n    this.env = env;\n  }\n\n  async fetch(request) {\n    const url = new URL(request.url);\n\n    if (url.pathname === '\u002Frecord' && request.method === 'POST') {\n      return this.recordSettlement(request);\n    }\n\n    if (url.pathname === '\u002Fstats') {\n      return this.getStats();\n    }\n\n    return new Response('Not found', { status: 404 });\n  }\n\n  async recordSettlement(request) {\n    const { payloadHash, amount, resource, timestamp } = await request.json();\n\n    \u002F\u002F Deduplicate: check if this payload was already settled\n    const existing = await this.state.storage.get(`settlement:${payloadHash}`);\n    if (existing) {\n      return Response.json({ duplicate: true, original: existing });\n    }\n\n    \u002F\u002F Record the settlement\n    const record = { amount, resource, timestamp, settled: true };\n    await this.state.storage.put(`settlement:${payloadHash}`, record);\n\n    \u002F\u002F Update running totals\n    const totals = (await this.state.storage.get('totals')) || {\n      count: 0,\n      revenue_usd: 0,\n    };\n    totals.count += 1;\n    totals.revenue_usd += parseFloat(amount);\n    await this.state.storage.put('totals', totals);\n\n    return Response.json({ recorded: true, totals });\n  }\n\n  async getStats() {\n    const totals = (await this.state.storage.get('totals')) || {\n      count: 0,\n      revenue_usd: 0,\n    };\n    return Response.json(totals);\n  }\n}\n```\n\n### Wrangler Configuration\n\n```toml\n# wrangler.toml\nname = \"x402-api\"\nmain = \"src\u002Fworker.js\"\ncompatibility_date = \"2026-04-01\"\n\n[vars]\nX402_NETWORK = \"base-sepolia\"\nX402_FACILITATOR_URL = \"https:\u002F\u002Fx402.org\u002Ffacilitator\"\n\n# Set via wrangler secret:\n# wrangler secret put MERCHANT_WALLET_ADDRESS\n\n# KV namespace for payment verification caching\n[[kv_namespaces]]\nbinding = \"PAYMENT_CACHE\"\nid = \"your-kv-namespace-id\"\n\n# Durable Objects for settlement tracking\n[[durable_objects.bindings]]\nname = \"SETTLEMENT_TRACKER\"\nclass_name = \"SettlementTracker\"\n\n[[migrations]]\ntag = \"v1\"\nnew_classes = [\"SettlementTracker\"]\n```\n\nDeploy:\n\n```bash\n# Install wrangler\nnpm install -g wrangler\n\n# Set your wallet address as a secret\nwrangler secret put MERCHANT_WALLET_ADDRESS\n\n# Deploy to Cloudflare\nwrangler deploy\n\n# Test\ncurl -s https:\u002F\u002Fx402-api.your-subdomain.workers.dev\u002Fapi\u002Fv1\u002Fhealth\ncurl -s https:\u002F\u002Fx402-api.your-subdomain.workers.dev\u002Fapi\u002Fv1\u002Fweather\u002Ffull\n```\n\n---\n\n## Chapter 5: Pricing Strategies\n\n### Per-Request Pricing (API Calls)\n\nThe simplest model. Every request costs a fixed amount. Best for stateless APIs where each call returns independent value.\n\n```javascript\n\u002F\u002F Flat per-request pricing\nconst PRICING = {\n  '\u002Fapi\u002Fv1\u002Fweather': 0.05,        \u002F\u002F $0.05\u002Frequest\n  '\u002Fapi\u002Fv1\u002Ftranslate': 0.10,       \u002F\u002F $0.10\u002Frequest\n  '\u002Fapi\u002Fv1\u002Fanalyze': 1.00,         \u002F\u002F $1.00\u002Frequest\n  '\u002Fapi\u002Fv1\u002Fgenerate-image': 0.50,  \u002F\u002F $0.50\u002Frequest\n};\n```\n\n**When to use:** Your compute cost per request is predictable and roughly constant. Weather lookups, translation, image generation, search queries.\n\n**When not to use:** When request cost varies significantly based on input size. A translation of 10 words costs the same as 10,000 words under flat pricing.\n\n### Content Pricing (Documents, Datasets)\n\nFixed price per content item. The content is the product, not the API call.\n\n```javascript\n\u002F\u002F Content pricing: each piece of content has a fixed price\nconst CONTENT_PRICING = {\n  '\u002Fcontent\u002Freport-q1-2026': 29.00,\n  '\u002Fcontent\u002Fdataset-sf-housing': 49.00,\n  '\u002Fcontent\u002Ftutorial-x402-advanced': 19.00,\n};\n```\n\nThis is the model the Felix dashboard uses. Each product in the catalog has a `price_usd`, and the x402 middleware charges that amount regardless of how many times the content is accessed (though each access triggers a new payment -- there is no \"purchase once, download forever\" in the base x402 protocol).\n\n### Subscription-Equivalent via Token Bundles\n\nx402 does not natively support subscriptions (recurring payments). But you can approximate subscriptions with token bundles: the client pays once for N requests, receives a signed token, and presents that token on subsequent requests until the bundle is exhausted.\n\n```python\n\"\"\"\nToken bundle implementation for subscription-like access.\n\nClient pays $10 for 100 requests. Server issues a signed JWT.\nClient includes the JWT in subsequent requests instead of paying each time.\n\"\"\"\n\nimport jwt\nimport time\nimport hashlib\nfrom typing import Optional\n\nBUNDLE_SECRET = \"your-signing-secret\"  # Use env var in production\n\nBUNDLE_PRICING = {\n    \"starter\": {\"requests\": 100, \"price_usd\": 10.00, \"validity_days\": 30},\n    \"pro\":     {\"requests\": 1000, \"price_usd\": 75.00, \"validity_days\": 30},\n    \"enterprise\": {\"requests\": 10000, \"price_usd\": 500.00, \"validity_days\": 30},\n}\n\n\ndef issue_bundle_token(\n    bundle_type: str,\n    wallet_address: str,\n) -> str:\n    \"\"\"Issue a JWT token after x402 payment for a bundle.\"\"\"\n    bundle = BUNDLE_PRICING[bundle_type]\n\n    payload = {\n        \"wallet\": wallet_address,\n        \"bundle\": bundle_type,\n        \"remaining\": bundle[\"requests\"],\n        \"issued_at\": int(time.time()),\n        \"expires_at\": int(time.time()) + (bundle[\"validity_days\"] * 86400),\n    }\n\n    return jwt.encode(payload, BUNDLE_SECRET, algorithm=\"HS256\")\n\n\ndef validate_bundle_token(token: str) -> Optional[dict]:\n    \"\"\"Validate and decrement a bundle token.\n\n    Returns the updated claims if valid, None if expired\u002Finvalid.\n    \"\"\"\n    try:\n        claims = jwt.decode(token, BUNDLE_SECRET, algorithms=[\"HS256\"])\n\n        if claims[\"expires_at\"] \u003C time.time():\n            return None\n        if claims[\"remaining\"] \u003C= 0:\n            return None\n\n        claims[\"remaining\"] -= 1\n        return claims\n    except jwt.InvalidTokenError:\n        return None\n\n\ndef refresh_bundle_token(claims: dict) -> str:\n    \"\"\"Re-issue the token with decremented remaining count.\"\"\"\n    return jwt.encode(claims, BUNDLE_SECRET, algorithm=\"HS256\")\n```\n\nOn the server, check for a bundle token first. If present and valid, serve content without x402 payment. If absent or exhausted, fall through to the x402 paywall:\n\n```python\n@app.get(\"\u002Fapi\u002Fv1\u002Fdata\")\nasync def data_endpoint(\n    request: Request,\n    response: Response,\n):\n    \"\"\"Endpoint that accepts either bundle tokens or x402 payment.\"\"\"\n    # Check for bundle token\n    bundle_token = request.headers.get(\"x-bundle-token\")\n    if bundle_token:\n        claims = validate_bundle_token(bundle_token)\n        if claims:\n            # Valid bundle -- serve content and return updated token\n            response.headers[\"X-Bundle-Token\"] = refresh_bundle_token(claims)\n            response.headers[\"X-Bundle-Remaining\"] = str(claims[\"remaining\"])\n            return {\"data\": \"premium content\", \"bundle_remaining\": claims[\"remaining\"]}\n\n    # No valid bundle -- fall through to x402 payment\n    # (Use the x402_required dependency as shown in Chapter 3)\n    ...\n```\n\n### Dynamic Pricing Based on Demand\n\nAdjust prices based on request volume. High demand increases prices; low demand decreases them. This is useful for rate-limiting expensive resources without hard caps.\n\n```javascript\n\u002F**\n * Dynamic pricing: price increases with request volume.\n *\n * Base price: $0.10\u002Frequest\n * At 100 req\u002Fmin: $0.15\u002Frequest (+50%)\n * At 500 req\u002Fmin: $0.50\u002Frequest (+400%)\n * At 1000 req\u002Fmin: $2.00\u002Frequest (+1900%)\n *\u002F\n\nclass DynamicPricer {\n  constructor(basePrice, windowMs = 60000) {\n    this.basePrice = basePrice;\n    this.windowMs = windowMs;\n    this.requests = [];\n  }\n\n  recordRequest() {\n    this.requests.push(Date.now());\n    \u002F\u002F Prune old entries\n    const cutoff = Date.now() - this.windowMs;\n    this.requests = this.requests.filter(t => t > cutoff);\n  }\n\n  getCurrentPrice() {\n    const cutoff = Date.now() - this.windowMs;\n    const recentCount = this.requests.filter(t => t > cutoff).length;\n\n    if (recentCount \u003C 50) return this.basePrice;\n    if (recentCount \u003C 100) return this.basePrice * 1.5;\n    if (recentCount \u003C 500) return this.basePrice * 5.0;\n    return this.basePrice * 20.0;\n  }\n}\n\nconst pricer = new DynamicPricer(0.10);\n\n\u002F\u002F In your route handler:\napp.get('\u002Fapi\u002Fv1\u002Fpremium', async (req, res, next) => {\n  pricer.recordRequest();\n  const currentPrice = pricer.getCurrentPrice();\n\n  \u002F\u002F Apply x402 with dynamic price\n  const middleware = x402Paywall({ priceUsd: currentPrice });\n  return middleware(req, res, next);\n}, handler);\n```\n\n### Free Tier + Paid Tier Pattern\n\nThe most common production pattern: give away basic access for free, charge for premium features. This maximizes adoption while monetizing power users.\n\n```javascript\nconst TIER_CONFIG = {\n  free: {\n    rateLimit: 10,      \u002F\u002F requests per minute\n    features: ['summary'],\n  },\n  paid: {\n    rateLimit: 1000,\n    features: ['summary', 'full', 'historical', 'alerts', 'export'],\n    priceUsd: 0.05,\n  },\n};\n\nfunction tierMiddleware(feature) {\n  return (req, res, next) => {\n    const hasPayment = !!req.headers['x-payment'];\n\n    if (TIER_CONFIG.free.features.includes(feature) && !hasPayment) {\n      \u002F\u002F Free tier: serve with rate limiting\n      return next();\n    }\n\n    if (!TIER_CONFIG.paid.features.includes(feature)) {\n      return res.status(404).json({ error: 'Unknown feature' });\n    }\n\n    \u002F\u002F Paid tier: apply x402\n    const paywall = x402Paywall({ priceUsd: TIER_CONFIG.paid.priceUsd });\n    return paywall(req, res, next);\n  };\n}\n\napp.get('\u002Fapi\u002Fv1\u002Fweather\u002Fsummary', tierMiddleware('summary'), summaryHandler);\napp.get('\u002Fapi\u002Fv1\u002Fweather\u002Ffull', tierMiddleware('full'), fullHandler);\napp.get('\u002Fapi\u002Fv1\u002Fweather\u002Fhistorical', tierMiddleware('historical'), historicalHandler);\n```\n\n---\n\n## Chapter 6: Payment Verification Deep Dive\n\n### Facilitator \u002Fverify Endpoint\n\nThe `\u002Fverify` endpoint is the heart of x402 security. It answers one question: \"Is this payment payload valid for these requirements?\" The request format:\n\n```json\n{\n  \"x402Version\": 1,\n  \"paymentPayload\": \"\u003Cbase64-encoded EIP-712 signed authorization>\",\n  \"requirements\": {\n    \"scheme\": \"exact\",\n    \"network\": \"eip155:8453\",\n    \"maxAmountRequired\": \"1000000\",\n    \"resource\": \"https:\u002F\u002Fapi.example.com\u002Fdata\",\n    \"payTo\": \"0xMerchantWallet\",\n    \"asset\": \"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913\",\n    \"maxTimeoutSeconds\": 300\n  }\n}\n```\n\nThe response on success:\n\n```json\n{\n  \"valid\": true\n}\n```\n\nThe response on failure:\n\n```json\n{\n  \"valid\": false,\n  \"error\": \"Insufficient USDC balance\",\n  \"details\": {\n    \"required\": \"1000000\",\n    \"available\": \"500000\"\n  }\n}\n```\n\n### What the Facilitator Checks\n\nThe facilitator performs these checks in order. If any check fails, it returns `valid: false` with a descriptive error:\n\n1. **Payload decoding.** The base64-decoded payload must be a valid JSON object containing an EIP-712 typed data signature.\n\n2. **Signature recovery.** The facilitator recovers the signer's Ethereum address from the EIP-712 signature. If recovery fails, the payload was tampered with or incorrectly signed.\n\n3. **Amount check.** The signed amount must be greater than or equal to `maxAmountRequired`. A payment for $0.50 does not satisfy a $1.00 requirement.\n\n4. **Asset and network match.** The signed payload must reference the same USDC contract address and network ID as the requirements. A payment on Base Sepolia does not satisfy a Base mainnet requirement.\n\n5. **Recipient match.** The `payTo` address in the signed payload must match the `payTo` in the requirements. This prevents a malicious intermediary from substituting their own wallet address.\n\n6. **Expiration check.** The signature must not have expired. The `maxTimeoutSeconds` defines the window from signature creation to verification. A 300-second timeout means the payer has 5 minutes to submit the payment after signing.\n\n7. **Balance check.** The signer's wallet must hold at least `maxAmountRequired` in USDC on the specified network. The facilitator queries the USDC contract's `balanceOf` function.\n\n8. **Allowance check.** The signer must have approved the facilitator's settlement contract to spend at least `maxAmountRequired` of their USDC. Without this approval, settlement will fail even though verification succeeds.\n\n### Handling Verification Failures\n\nDifferent failure modes require different responses:\n\n```python\nasync def handle_verification_result(\n    result: dict,\n    payment_requirements: list[dict],\n) -> tuple[bool, dict]:\n    \"\"\"Process a verification result and determine the appropriate response.\n\n    Returns (should_serve_content, response_info).\n    \"\"\"\n    if result.get(\"valid\"):\n        return True, {\"status\": \"verified\"}\n\n    error = result.get(\"error\", \"Unknown verification error\")\n    details = result.get(\"details\", {})\n\n    # Insufficient balance: tell the client how much they need\n    if \"Insufficient\" in error:\n        return False, {\n            \"status\": \"insufficient_funds\",\n            \"error\": error,\n            \"required\": details.get(\"required\"),\n            \"available\": details.get(\"available\"),\n            \"action\": \"Fund your wallet with more USDC and retry\",\n        }\n\n    # Expired signature: client took too long\n    if \"expired\" in error.lower():\n        return False, {\n            \"status\": \"expired\",\n            \"error\": error,\n            \"action\": \"Sign a new payment payload and retry immediately\",\n        }\n\n    # Invalid signature: payload was tampered with or signed incorrectly\n    if \"signature\" in error.lower():\n        return False, {\n            \"status\": \"invalid_signature\",\n            \"error\": error,\n            \"action\": \"Check your signing logic and retry\",\n        }\n\n    # Allowance issue: client needs to approve the facilitator\n    if \"allowance\" in error.lower():\n        return False, {\n            \"status\": \"insufficient_allowance\",\n            \"error\": error,\n            \"action\": \"Approve the facilitator contract to spend your USDC\",\n        }\n\n    # Generic failure\n    return False, {\n        \"status\": \"verification_failed\",\n        \"error\": error,\n    }\n```\n\n### Timeout Handling\n\nNetwork latency between your server and the facilitator is the primary source of timeout risk. On a healthy network, the facilitator responds in 50-200ms. Under load or with DNS issues, it can take 2-5 seconds.\n\n```javascript\n\u002F**\n * Verify with timeout and circuit breaker.\n *\u002F\nclass FacilitatorClient {\n  constructor(facilitatorUrl, timeoutMs = 5000) {\n    this.facilitatorUrl = facilitatorUrl;\n    this.timeoutMs = timeoutMs;\n    this.consecutiveFailures = 0;\n    this.circuitOpen = false;\n    this.circuitResetTime = 0;\n  }\n\n  async verify(xPayment, requirements) {\n    \u002F\u002F Circuit breaker: if the facilitator has failed N times in a row,\n    \u002F\u002F stop trying for a cooldown period\n    if (this.circuitOpen && Date.now() \u003C this.circuitResetTime) {\n      return { valid: false, error: 'Circuit breaker open: facilitator unavailable' };\n    }\n\n    const controller = new AbortController();\n    const timeout = setTimeout(() => controller.abort(), this.timeoutMs);\n\n    try {\n      const response = await fetch(`${this.facilitatorUrl}\u002Fverify`, {\n        method: 'POST',\n        headers: { 'Content-Type': 'application\u002Fjson' },\n        body: JSON.stringify({\n          x402Version: 1,\n          paymentPayload: xPayment,\n          requirements,\n        }),\n        signal: controller.signal,\n      });\n\n      clearTimeout(timeout);\n      this.consecutiveFailures = 0;\n      this.circuitOpen = false;\n\n      if (response.ok) {\n        return { valid: true };\n      }\n\n      const body = await response.text();\n      return { valid: false, error: body };\n    } catch (err) {\n      clearTimeout(timeout);\n      this.consecutiveFailures += 1;\n\n      \u002F\u002F Open circuit after 5 consecutive failures\n      if (this.consecutiveFailures >= 5) {\n        this.circuitOpen = true;\n        this.circuitResetTime = Date.now() + 30000; \u002F\u002F 30-second cooldown\n        console.error('[x402] Circuit breaker opened: 5 consecutive failures');\n      }\n\n      if (err.name === 'AbortError') {\n        return { valid: false, error: `Verification timed out after ${this.timeoutMs}ms` };\n      }\n      return { valid: false, error: `Network error: ${err.message}` };\n    }\n  }\n}\n```\n\n### What Happens If the Facilitator Is Down\n\nIf the facilitator is unreachable, you have three options:\n\n1. **Fail closed (default).** Return 402 with an error message. The client cannot pay. No content is served. No revenue is lost. This is the safest option.\n\n2. **Fail open (dangerous).** Serve the content anyway and log the unverified payment for later reconciliation. This risks serving content without payment. Only use this for very low-value content where availability matters more than revenue.\n\n3. **Queue and retry.** Accept the request, serve the content, and queue the verification for retry. If verification eventually fails, flag the transaction as suspicious. This is a middle ground but requires careful accounting.\n\n```javascript\n\u002F\u002F Option 1: Fail closed (recommended)\nasync function verifyWithFailClosed(xPayment, requirements) {\n  const result = await facilitatorClient.verify(xPayment, requirements);\n  if (!result.valid) {\n    \u002F\u002F Do not serve content\n    return { serve: false, error: result.error };\n  }\n  return { serve: true };\n}\n\n\u002F\u002F Option 2: Fail open (use with extreme caution)\nasync function verifyWithFailOpen(xPayment, requirements) {\n  const result = await facilitatorClient.verify(xPayment, requirements);\n  if (!result.valid && result.error.includes('Circuit breaker')) {\n    \u002F\u002F Facilitator is down -- serve content but log for reconciliation\n    console.warn('[x402] FAIL OPEN: serving content without verification');\n    logUnverifiedPayment(xPayment, requirements);\n    return { serve: true, unverified: true };\n  }\n  if (!result.valid) {\n    return { serve: false, error: result.error };\n  }\n  return { serve: true };\n}\n```\n\n---\n\n## Chapter 7: Settlement & Revenue\n\n### Settlement Flow\n\nSettlement is the process of actually moving USDC from the payer's wallet to your wallet. Verification confirms that the payer has authorized the transfer; settlement executes it.\n\nThe flow:\n\n1. Your server calls `POST \u002Fsettle` on the facilitator with the `paymentPayload`.\n2. The facilitator submits an on-chain transaction to Base that calls `transferFrom` on the USDC contract, moving the authorized amount from the payer to your `payTo` address.\n3. The transaction confirms on Base (approximately 2 seconds).\n4. The USDC appears in your wallet.\n\nSettlement is asynchronous and fire-and-forget from the merchant's perspective. You serve the content immediately after verification succeeds. Settlement happens in the background. If it fails, the facilitator retries.\n\n### Logging Settlements to Your Database\n\nEvery settlement should be recorded in your database for revenue tracking, reconciliation, and tax reporting.\n\n```python\n\"\"\"\nSettlement logging with SQLite.\n\"\"\"\n\nimport sqlite3\nimport json\nimport hashlib\nimport time\nfrom datetime import datetime, timezone\n\n\nclass SettlementLog:\n    \"\"\"Persistent settlement log backed by SQLite.\"\"\"\n\n    def __init__(self, db_path: str = \"settlements.db\"):\n        self.conn = sqlite3.connect(db_path)\n        self.conn.row_factory = sqlite3.Row\n        self._init_schema()\n\n    def _init_schema(self):\n        self.conn.executescript(\"\"\"\n            CREATE TABLE IF NOT EXISTS settlements (\n                id INTEGER PRIMARY KEY AUTOINCREMENT,\n                payment_hash TEXT UNIQUE NOT NULL,\n                resource TEXT NOT NULL,\n                amount_usdc TEXT NOT NULL,\n                amount_usd REAL NOT NULL,\n                payer_hint TEXT DEFAULT '',\n                status TEXT DEFAULT 'pending',\n                created_at TEXT NOT NULL,\n                settled_at TEXT,\n                error TEXT\n            );\n\n            CREATE INDEX IF NOT EXISTS idx_settlements_status\n                ON settlements(status);\n            CREATE INDEX IF NOT EXISTS idx_settlements_created\n                ON settlements(created_at);\n        \"\"\")\n        self.conn.commit()\n\n    def record_payment(\n        self,\n        payment_payload: str,\n        resource: str,\n        amount_usd: float,\n    ) -> int:\n        \"\"\"Record a verified payment before settlement.\"\"\"\n        payment_hash = hashlib.sha256(payment_payload.encode()).hexdigest()\n        amount_usdc = str(round(amount_usd * 1_000_000))\n        now = datetime.now(timezone.utc).isoformat()\n\n        cursor = self.conn.execute(\n            \"\"\"INSERT OR IGNORE INTO settlements\n               (payment_hash, resource, amount_usdc, amount_usd, status, created_at)\n               VALUES (?, ?, ?, ?, 'pending', ?)\"\"\",\n            (payment_hash, resource, amount_usdc, amount_usd, now),\n        )\n        self.conn.commit()\n        return cursor.lastrowid\n\n    def mark_settled(self, payment_payload: str) -> None:\n        \"\"\"Mark a payment as successfully settled.\"\"\"\n        payment_hash = hashlib.sha256(payment_payload.encode()).hexdigest()\n        now = datetime.now(timezone.utc).isoformat()\n\n        self.conn.execute(\n            \"\"\"UPDATE settlements SET status = 'settled', settled_at = ?\n               WHERE payment_hash = ?\"\"\",\n            (now, payment_hash),\n        )\n        self.conn.commit()\n\n    def mark_failed(self, payment_payload: str, error: str) -> None:\n        \"\"\"Mark a settlement as failed.\"\"\"\n        payment_hash = hashlib.sha256(payment_payload.encode()).hexdigest()\n\n        self.conn.execute(\n            \"\"\"UPDATE settlements SET status = 'failed', error = ?\n               WHERE payment_hash = ?\"\"\",\n            (error, payment_hash),\n        )\n        self.conn.commit()\n\n    def get_revenue(self, hours: int = 24) -> dict:\n        \"\"\"Get revenue stats for the last N hours.\"\"\"\n        cutoff = datetime.now(timezone.utc).timestamp() - (hours * 3600)\n        cutoff_iso = datetime.fromtimestamp(cutoff, tz=timezone.utc).isoformat()\n\n        row = self.conn.execute(\n            \"\"\"SELECT\n                 COUNT(*) as total_payments,\n                 COALESCE(SUM(amount_usd), 0) as total_usd,\n                 COUNT(CASE WHEN status = 'settled' THEN 1 END) as settled_count,\n                 COUNT(CASE WHEN status = 'failed' THEN 1 END) as failed_count,\n                 COUNT(CASE WHEN status = 'pending' THEN 1 END) as pending_count\n               FROM settlements\n               WHERE created_at >= ?\"\"\",\n            (cutoff_iso,),\n        ).fetchone()\n\n        return {\n            \"period_hours\": hours,\n            \"total_payments\": row[\"total_payments\"],\n            \"total_revenue_usd\": round(row[\"total_usd\"], 2),\n            \"settled\": row[\"settled_count\"],\n            \"failed\": row[\"failed_count\"],\n            \"pending\": row[\"pending_count\"],\n            \"settlement_rate\": (\n                round(row[\"settled_count\"] \u002F row[\"total_payments\"], 3)\n                if row[\"total_payments\"] > 0\n                else 0\n            ),\n        }\n\n    def get_revenue_by_resource(self, hours: int = 24) -> list[dict]:\n        \"\"\"Get per-resource revenue breakdown.\"\"\"\n        cutoff = datetime.now(timezone.utc).timestamp() - (hours * 3600)\n        cutoff_iso = datetime.fromtimestamp(cutoff, tz=timezone.utc).isoformat()\n\n        rows = self.conn.execute(\n            \"\"\"SELECT\n                 resource,\n                 COUNT(*) as request_count,\n                 COALESCE(SUM(amount_usd), 0) as total_usd\n               FROM settlements\n               WHERE created_at >= ? AND status = 'settled'\n               GROUP BY resource\n               ORDER BY total_usd DESC\"\"\",\n            (cutoff_iso,),\n        ).fetchall()\n\n        return [\n            {\n                \"resource\": row[\"resource\"],\n                \"request_count\": row[\"request_count\"],\n                \"revenue_usd\": round(row[\"total_usd\"], 2),\n            }\n            for row in rows\n        ]\n```\n\n### Revenue Tracking and Reporting\n\nIntegrate the settlement log with your x402 middleware:\n\n```python\nsettlement_log = SettlementLog(\"data\u002Fsettlements.db\")\n\n# In your x402 dependency, after verification succeeds:\nasync def x402_with_logging(request: Request) -> dict:\n    # ... (verification logic from Chapter 3) ...\n\n    # Record the payment\n    settlement_log.record_payment(\n        payment_payload=x_payment,\n        resource=resource,\n        amount_usd=price_usd,\n    )\n\n    # Trigger settlement with callback\n    async def settle_and_log():\n        try:\n            await settle_payment(x_payment)\n            settlement_log.mark_settled(x_payment)\n        except Exception as e:\n            settlement_log.mark_failed(x_payment, str(e))\n\n    asyncio.create_task(settle_and_log())\n\n    return {\"verified\": True}\n\n\n# Revenue reporting endpoint (admin-only)\n@app.get(\"\u002Fadmin\u002Frevenue\")\nasync def revenue_report(hours: int = 24):\n    stats = settlement_log.get_revenue(hours)\n    by_resource = settlement_log.get_revenue_by_resource(hours)\n    return {\n        \"summary\": stats,\n        \"by_resource\": by_resource,\n    }\n```\n\n### Handling Failed Settlements\n\nSettlement can fail for several reasons:\n\n- **Insufficient balance at settlement time.** The payer had enough USDC at verification but transferred it away before settlement. This is the most common failure mode.\n- **Revoked allowance.** The payer revoked the facilitator's approval between verification and settlement.\n- **Network congestion.** The Base network is congested and the transaction did not confirm in time.\n\nFor the first two cases, there is nothing the merchant can do. The content was already served. This is the fundamental risk of the \"verify first, settle later\" model. Mitigations:\n\n1. **Minimize the verification-to-settlement gap.** Call `\u002Fsettle` immediately after serving content, not in a batch job.\n2. **Monitor settlement failure rate.** If it exceeds 2%, investigate. It may indicate a bot exploiting the gap.\n3. **Block wallets with repeated settlement failures.** Maintain a blocklist of wallet addresses (extracted from payment payloads) that have failed settlement more than N times.\n\n```python\nclass SettlementFailureTracker:\n    \"\"\"Track wallets with repeated settlement failures.\"\"\"\n\n    def __init__(self, max_failures: int = 3):\n        self.max_failures = max_failures\n        self.failure_counts: dict[str, int] = {}\n        self.blocked_wallets: set[str] = set()\n\n    def record_failure(self, wallet_address: str) -> bool:\n        \"\"\"Record a settlement failure. Returns True if wallet is now blocked.\"\"\"\n        self.failure_counts[wallet_address] = (\n            self.failure_counts.get(wallet_address, 0) + 1\n        )\n\n        if self.failure_counts[wallet_address] >= self.max_failures:\n            self.blocked_wallets.add(wallet_address)\n            return True\n        return False\n\n    def is_blocked(self, wallet_address: str) -> bool:\n        return wallet_address in self.blocked_wallets\n\n    def record_success(self, wallet_address: str) -> None:\n        \"\"\"Reset failure count on successful settlement.\"\"\"\n        self.failure_counts.pop(wallet_address, None)\n```\n\n### Reconciliation Patterns\n\nDaily reconciliation compares your settlement log against your actual on-chain USDC balance:\n\n```python\nasync def daily_reconciliation(\n    settlement_log: SettlementLog,\n    wallet_address: str,\n    rpc_url: str,\n) -> dict:\n    \"\"\"Compare recorded settlements against on-chain balance.\n\n    Run this daily via cron to detect discrepancies.\n    \"\"\"\n    # Get recorded revenue\n    stats = settlement_log.get_revenue(hours=24)\n    recorded_revenue = stats[\"total_revenue_usd\"]\n    settled_count = stats[\"settled\"]\n    failed_count = stats[\"failed\"]\n\n    # Query on-chain USDC balance (via RPC or block explorer API)\n    # This is a simplified example -- in production, track balance deltas\n    balance_info = await query_usdc_balance(wallet_address, rpc_url)\n    on_chain_balance = balance_info[\"balance_usd\"]\n\n    discrepancy = abs(recorded_revenue - on_chain_balance)\n\n    return {\n        \"date\": datetime.now(timezone.utc).date().isoformat(),\n        \"recorded_revenue_usd\": recorded_revenue,\n        \"on_chain_balance_usd\": on_chain_balance,\n        \"discrepancy_usd\": round(discrepancy, 2),\n        \"settled_payments\": settled_count,\n        \"failed_settlements\": failed_count,\n        \"settlement_rate\": stats[\"settlement_rate\"],\n        \"status\": \"ok\" if discrepancy \u003C 1.00 else \"DISCREPANCY_DETECTED\",\n    }\n```\n\n### Tax Implications\n\nUSDC revenue is taxable income in most jurisdictions. Key considerations:\n\n- **Record keeping.** Every settlement must be logged with timestamp, amount, and counterparty information (wallet address). The settlement log in this chapter satisfies this requirement.\n- **USD valuation.** USDC is pegged 1:1 to USD. Revenue in USDC is valued at face value. No fair market value calculation is needed (unlike volatile cryptocurrencies).\n- **Reporting.** In the US, report USDC revenue as ordinary income. For businesses, this appears on Schedule C or the corporate return. Consult a tax professional for your jurisdiction.\n- **Off-ramping.** When you convert USDC to fiat (via Coinbase, Circle, or a bank), there is no taxable event beyond the original income recognition -- assuming USDC maintained its peg.\n\n---\n\n## Next Steps\n\nFor deployment patterns, monitoring, and production hardening, see the\n[Agent Production Hardening Guide](https:\u002F\u002Fclawhub.ai\u002Fskills\u002Fgreenhelix-agent-production-hardening).\n\n---\n\n## Chapter 9: Testing\n\n### Testnet (Base Sepolia) Setup\n\nFor development and integration testing, use Base Sepolia testnet. The only configuration change is the network identifier and USDC contract address.\n\n```bash\n# Environment variables for testnet\nexport X402_NETWORK=base-sepolia\nexport MERCHANT_WALLET_ADDRESS=0xYourTestnetWallet\nexport X402_FACILITATOR_URL=https:\u002F\u002Fx402.org\u002Ffacilitator\n```\n\nTo get testnet USDC:\n1. Get Sepolia ETH from the Base Sepolia faucet (https:\u002F\u002Fwww.coinbase.com\u002Ffaucets\u002Fbase-ethereum-sepolia-faucet).\n2. Use the testnet USDC faucet or mint test tokens.\n3. Approve the facilitator contract to spend your test USDC.\n\n### Mock Facilitator for Unit Tests\n\nFor unit tests, you do not want to hit the real facilitator. Mock it entirely.\n\n**Node.js (Jest\u002FVitest):**\n\n```javascript\n\u002F**\n * Mock facilitator for unit tests.\n *\n * Replaces the real facilitator with deterministic responses.\n *\u002F\n\nclass MockFacilitator {\n  constructor() {\n    this.verifyResponses = new Map();\n    this.settleLog = [];\n    this.defaultVerifyResult = { valid: true };\n  }\n\n  \u002F**\n   * Configure the response for a specific payment payload.\n   *\u002F\n  setVerifyResponse(payloadSubstring, response) {\n    this.verifyResponses.set(payloadSubstring, response);\n  }\n\n  \u002F**\n   * Mock \u002Fverify endpoint.\n   *\u002F\n  async verify(body) {\n    const payload = body.paymentPayload || '';\n\n    for (const [substring, response] of this.verifyResponses) {\n      if (payload.includes(substring)) {\n        return response;\n      }\n    }\n\n    return this.defaultVerifyResult;\n  }\n\n  \u002F**\n   * Mock \u002Fsettle endpoint. Logs the settlement for assertions.\n   *\u002F\n  async settle(body) {\n    this.settleLog.push({\n      payload: body.paymentPayload,\n      timestamp: Date.now(),\n    });\n    return { success: true };\n  }\n\n  \u002F**\n   * Assert that settlement was triggered for a specific payload.\n   *\u002F\n  assertSettled(payloadSubstring) {\n    const found = this.settleLog.some(s => s.payload.includes(payloadSubstring));\n    if (!found) {\n      throw new Error(`Expected settlement for payload containing \"${payloadSubstring}\"`);\n    }\n  }\n\n  reset() {\n    this.verifyResponses.clear();\n    this.settleLog = [];\n    this.defaultVerifyResult = { valid: true };\n  }\n}\n\n\u002F\u002F In tests:\nconst mockFacilitator = new MockFacilitator();\n\n\u002F\u002F Override fetch globally for tests\nglobal.fetch = jest.fn(async (url, options) => {\n  const body = JSON.parse(options.body);\n\n  if (url.includes('\u002Fverify')) {\n    const result = await mockFacilitator.verify(body);\n    return {\n      ok: result.valid,\n      status: result.valid ? 200 : 400,\n      json: async () => result,\n      text: async () => JSON.stringify(result),\n    };\n  }\n\n  if (url.includes('\u002Fsettle')) {\n    const result = await mockFacilitator.settle(body);\n    return {\n      ok: true,\n      status: 200,\n      json: async () => result,\n    };\n  }\n\n  return { ok: false, status: 404 };\n});\n```\n\n**Python (pytest):**\n\n```python\n\"\"\"\nMock facilitator for pytest.\n\"\"\"\n\nimport pytest\nfrom unittest.mock import AsyncMock, patch\n\n\n@pytest.fixture\ndef mock_facilitator():\n    \"\"\"Fixture that mocks the x402 facilitator for unit tests.\"\"\"\n\n    class MockFacilitator:\n        def __init__(self):\n            self.verify_result = {\"valid\": True}\n            self.settle_log = []\n            self.verify_calls = []\n\n        def set_verify_result(self, result):\n            self.verify_result = result\n\n        async def mock_verify(self, x_payment, requirements):\n            self.verify_calls.append({\n                \"payment\": x_payment,\n                \"requirements\": requirements,\n            })\n            return self.verify_result\n\n        async def mock_settle(self, x_payment, max_retries=3):\n            self.settle_log.append(x_payment)\n\n    mock = MockFacilitator()\n\n    with patch(\"x402_deps.verify_payment\", side_effect=mock.mock_verify):\n        with patch(\"x402_deps.settle_payment\", side_effect=mock.mock_settle):\n            yield mock\n\n\n# Usage in tests:\nclass TestPaidEndpoint:\n    def test_verified_payment_returns_content(self, client, mock_facilitator):\n        mock_facilitator.set_verify_result({\"valid\": True})\n        response = client.get(\n            \"\u002Fapi\u002Fv1\u002Fweather\u002Ffull\",\n            headers={\"X-Payment\": \"test-payload-123\"},\n        )\n        assert response.status_code == 200\n        assert len(mock_facilitator.verify_calls) == 1\n        assert mock_facilitator.verify_calls[0][\"payment\"] == \"test-payload-123\"\n\n    def test_failed_verification_returns_402(self, client, mock_facilitator):\n        mock_facilitator.set_verify_result({\n            \"valid\": False,\n            \"error\": \"Insufficient balance\",\n        })\n        response = client.get(\n            \"\u002Fapi\u002Fv1\u002Fweather\u002Ffull\",\n            headers={\"X-Payment\": \"insufficient-funds-payload\"},\n        )\n        assert response.status_code == 402\n\n    def test_settlement_triggered_after_success(self, client, mock_facilitator):\n        mock_facilitator.set_verify_result({\"valid\": True})\n        client.get(\n            \"\u002Fapi\u002Fv1\u002Fweather\u002Ffull\",\n            headers={\"X-Payment\": \"settle-test-payload\"},\n        )\n        assert \"settle-test-payload\" in mock_facilitator.settle_log\n```\n\n### Integration Test Patterns\n\nIntegration tests hit the real facilitator on testnet. They verify the full flow: 402 response, payment construction, verification, content delivery, settlement.\n\n```python\n\"\"\"\nIntegration tests against Base Sepolia testnet.\n\nRequires:\n  - MERCHANT_WALLET_ADDRESS set to a testnet wallet\n  - PAYER_PRIVATE_KEY set to a funded testnet wallet's private key\n  - Server running on localhost:8000\n\nRun:\n    X402_NETWORK=base-sepolia pytest test_integration.py -x -q\n\"\"\"\n\nimport os\nimport httpx\nimport pytest\n\nBASE_URL = os.environ.get(\"TEST_SERVER_URL\", \"http:\u002F\u002Flocalhost:8000\")\n\n\n@pytest.mark.integration\nclass TestFullX402Flow:\n    \"\"\"End-to-end tests using real facilitator on testnet.\"\"\"\n\n    def test_free_endpoint_works(self):\n        \"\"\"Free endpoints should respond without payment.\"\"\"\n        response = httpx.get(f\"{BASE_URL}\u002Fapi\u002Fv1\u002Fhealth\")\n        assert response.status_code == 200\n        assert response.json()[\"status\"] == \"ok\"\n\n    def test_paid_endpoint_returns_402(self):\n        \"\"\"Paid endpoint without payment returns 402.\"\"\"\n        response = httpx.get(f\"{BASE_URL}\u002Fapi\u002Fv1\u002Fweather\u002Ffull\")\n        assert response.status_code == 402\n\n        body = response.json()\n        assert body[\"x402Version\"] == 1\n        assert len(body[\"accepts\"]) >= 1\n\n        req = body[\"accepts\"][0]\n        assert req[\"scheme\"] == \"exact\"\n        assert req[\"network\"] == \"eip155:84532\"  # Sepolia\n        assert int(req[\"maxAmountRequired\"]) > 0\n        assert req[\"payTo\"].startswith(\"0x\")\n\n    def test_402_contains_payment_required_header(self):\n        \"\"\"The PAYMENT-REQUIRED header should be present and base64-decodable.\"\"\"\n        response = httpx.get(f\"{BASE_URL}\u002Fapi\u002Fv1\u002Fweather\u002Ffull\")\n        assert \"payment-required\" in response.headers\n\n        import base64, json\n        decoded = json.loads(\n            base64.b64decode(response.headers[\"payment-required\"])\n        )\n        assert decoded[\"x402Version\"] == 1\n\n    def test_invalid_payment_header_returns_402(self):\n        \"\"\"An invalid X-Payment header should return 402 with error.\"\"\"\n        response = httpx.get(\n            f\"{BASE_URL}\u002Fapi\u002Fv1\u002Fweather\u002Ffull\",\n            headers={\"X-Payment\": \"totally-invalid-payload\"},\n        )\n        assert response.status_code == 402\n        body = response.json()\n        detail = body.get(\"detail\", body)\n        assert detail.get(\"error\") is not None\n```\n\n### Load Testing Payment Flows\n\nLoad testing x402 is different from load testing a standard API because each request involves an external facilitator call. Focus on three scenarios:\n\n```python\n\"\"\"\nLoad test scenarios for x402 APIs.\n\nUses locust for load generation.\n\nRun:\n    locust -f test_load.py --host http:\u002F\u002Flocalhost:8000\n\"\"\"\n\nfrom locust import HttpUser, task, between\n\n\nclass FreeEndpointUser(HttpUser):\n    \"\"\"Simulates traffic to free endpoints (baseline throughput).\"\"\"\n    wait_time = between(0.1, 0.5)\n\n    @task\n    def health_check(self):\n        self.client.get(\"\u002Fapi\u002Fv1\u002Fhealth\")\n\n    @task(3)\n    def weather_summary(self):\n        self.client.get(\"\u002Fapi\u002Fv1\u002Fweather\u002Fsummary\")\n\n\nclass UnpaidRequestUser(HttpUser):\n    \"\"\"Simulates traffic without payment (402 response throughput).\"\"\"\n    wait_time = between(0.1, 0.5)\n\n    @task\n    def trigger_402(self):\n        with self.client.get(\n            \"\u002Fapi\u002Fv1\u002Fweather\u002Ffull\",\n            catch_response=True,\n        ) as response:\n            if response.status_code == 402:\n                response.success()\n            else:\n                response.failure(f\"Expected 402, got {response.status_code}\")\n\n\nclass PaidRequestUser(HttpUser):\n    \"\"\"Simulates paid requests (verification + settlement throughput).\n\n    Uses a mock payment header. For real load testing on testnet,\n    replace with actual signed payloads.\n    \"\"\"\n    wait_time = between(0.5, 2.0)\n\n    @task\n    def paid_weather(self):\n        with self.client.get(\n            \"\u002Fapi\u002Fv1\u002Fweather\u002Ffull\",\n            headers={\"X-Payment\": \"load-test-payload\"},\n            catch_response=True,\n        ) as response:\n            # With a mock facilitator, this should return 200\n            # With the real facilitator, this will return 402 (invalid payload)\n            if response.status_code in (200, 402):\n                response.success()\n            else:\n                response.failure(f\"Unexpected status {response.status_code}\")\n```\n\n---\n\n## Chapter 10: Recipes\n\n### Recipe 1: Blog Paywall (Markdown Content)\n\nA blog where some posts are free and others require payment. The Felix dashboard pattern, simplified.\n\n```javascript\n'use strict';\n\n\u002F**\n * Blog with x402 paywall.\n *\n * Free posts: \u002Fblog\u002Fgetting-started, \u002Fblog\u002Fabout\n * Paid posts: \u002Fblog\u002Fadvanced-techniques ($2.00), \u002Fblog\u002Fcase-study ($5.00)\n *\u002F\n\nconst express = require('express');\nconst { marked } = require('marked');\nconst { x402Paywall } = require('.\u002Fx402-middleware');\n\nconst app = express();\n\n\u002F\u002F Blog content (in production, load from filesystem or CMS)\nconst POSTS = {\n  'getting-started': {\n    title: 'Getting Started with x402',\n    content: '# Getting Started\\n\\nThis is a free post...',\n    price: 0,\n  },\n  'advanced-techniques': {\n    title: 'Advanced x402 Techniques',\n    content: '# Advanced Techniques\\n\\nThis premium post covers...',\n    price: 2.00,\n  },\n  'case-study': {\n    title: 'Case Study: 10x Revenue with x402',\n    content: '# Case Study\\n\\nHow Company X increased API revenue...',\n    price: 5.00,\n  },\n};\n\n\u002F\u002F Blog listing (free)\napp.get('\u002Fblog', (_req, res) => {\n  const listing = Object.entries(POSTS).map(([slug, post]) => ({\n    slug,\n    title: post.title,\n    price: post.price,\n    url: `\u002Fblog\u002F${slug}`,\n  }));\n  res.json({ posts: listing });\n});\n\n\u002F\u002F Individual blog posts\napp.get('\u002Fblog\u002F:slug', (req, res, next) => {\n  const post = POSTS[req.params.slug];\n  if (!post) return res.status(404).json({ error: 'Post not found' });\n\n  \u002F\u002F Free posts: serve directly\n  if (post.price === 0) {\n    return res.json({\n      title: post.title,\n      content_html: marked(post.content),\n      content_markdown: post.content,\n    });\n  }\n\n  \u002F\u002F Paid posts: apply x402\n  const paywall = x402Paywall({\n    priceUsd: post.price,\n    description: `Blog post: ${post.title}`,\n  });\n\n  paywall(req, res, () => {\n    res.json({\n      title: post.title,\n      content_html: marked(post.content),\n      content_markdown: post.content,\n    });\n  });\n});\n\napp.listen(3000, () => console.log('Blog running on port 3000'));\n```\n\n### Recipe 2: API Rate Limiting with x402 (Pay to Exceed Free Tier)\n\nGive every user 100 free requests per day. After that, each request costs $0.01. No signup required -- rate limiting is by IP for free tier and by wallet for paid tier.\n\n```javascript\n'use strict';\n\n\u002F**\n * Free tier + x402 overflow pricing.\n *\n * Free: 100 requests\u002Fday per IP\n * Paid: $0.01\u002Frequest after free tier exhausted\n *\u002F\n\nconst express = require('express');\nconst { x402Paywall } = require('.\u002Fx402-middleware');\n\nconst app = express();\n\n\u002F\u002F In-memory rate counter (use Redis in production)\nconst requestCounts = new Map();\nconst FREE_LIMIT = 100;\nconst WINDOW_MS = 24 * 60 * 60 * 1000; \u002F\u002F 24 hours\n\nfunction getRequestCount(ip) {\n  const entry = requestCounts.get(ip);\n  if (!entry || Date.now() - entry.windowStart > WINDOW_MS) {\n    requestCounts.set(ip, { count: 0, windowStart: Date.now() });\n    return 0;\n  }\n  return entry.count;\n}\n\nfunction incrementRequestCount(ip) {\n  const entry = requestCounts.get(ip) || { count: 0, windowStart: Date.now() };\n  entry.count += 1;\n  requestCounts.set(ip, entry);\n}\n\n\u002F\u002F Middleware: free tier or x402 payment\nfunction freeTierOrPay(priceUsd) {\n  return async (req, res, next) => {\n    const ip = req.ip;\n    const count = getRequestCount(ip);\n\n    if (count \u003C FREE_LIMIT) {\n      \u002F\u002F Free tier: serve and count\n      incrementRequestCount(ip);\n      res.setHeader('X-RateLimit-Remaining', String(FREE_LIMIT - count - 1));\n      res.setHeader('X-RateLimit-Limit', String(FREE_LIMIT));\n      return next();\n    }\n\n    \u002F\u002F Free tier exhausted: require payment\n    res.setHeader('X-RateLimit-Remaining', '0');\n    res.setHeader('X-RateLimit-Limit', String(FREE_LIMIT));\n\n    const paywall = x402Paywall({\n      priceUsd,\n      description: `API access (free tier of ${FREE_LIMIT}\u002Fday exhausted)`,\n    });\n\n    return paywall(req, res, next);\n  };\n}\n\napp.get('\u002Fapi\u002Fv1\u002Fdata', freeTierOrPay(0.01), (_req, res) => {\n  res.json({\n    data: 'Your API response here',\n    timestamp: new Date().toISOString(),\n  });\n});\n\napp.listen(3000, () => console.log('Free tier + x402 API running on port 3000'));\n```\n\n### Recipe 3: Dataset Marketplace (Pay Per Download)\n\nA marketplace where data providers list datasets and buyers pay per download. Each dataset has its own price.\n\n```python\n\"\"\"\nDataset marketplace with x402 payment per download.\n\nProviders upload datasets. Buyers browse for free, pay to download.\n\"\"\"\n\nimport os\nimport json\nfrom pathlib import Path\n\nfrom fastapi import FastAPI, Depends, Response\nfrom fastapi.responses import FileResponse, JSONResponse\n\nfrom x402_deps import x402_required\n\napp = FastAPI(title=\"Dataset Marketplace\")\n\nDATASETS_DIR = Path(\"data\u002Fdatasets\")\nCATALOG_FILE = Path(\"data\u002Fcatalog.json\")\n\n\ndef load_catalog() -> list[dict]:\n    \"\"\"Load the dataset catalog.\"\"\"\n    if not CATALOG_FILE.exists():\n        return []\n    return json.loads(CATALOG_FILE.read_text())\n\n\ndef get_dataset_by_slug(slug: str) -> dict | None:\n    \"\"\"Find a dataset in the catalog by slug.\"\"\"\n    for ds in load_catalog():\n        if ds[\"slug\"] == slug:\n            return ds\n    return None\n\n\n@app.get(\"\u002Fdatasets\")\nasync def list_datasets():\n    \"\"\"Browse all available datasets (free).\"\"\"\n    catalog = load_catalog()\n    return {\n        \"datasets\": [\n            {\n                \"slug\": ds[\"slug\"],\n                \"title\": ds[\"title\"],\n                \"description\": ds[\"description\"],\n                \"price_usd\": ds[\"price_usd\"],\n                \"size_mb\": ds[\"size_mb\"],\n                \"format\": ds[\"format\"],\n                \"download_url\": f\"\u002Fdatasets\u002F{ds['slug']}\u002Fdownload\",\n            }\n            for ds in catalog\n        ]\n    }\n\n\n@app.get(\"\u002Fdatasets\u002F{slug}\")\nasync def dataset_detail(slug: str):\n    \"\"\"Get dataset metadata (free).\"\"\"\n    ds = get_dataset_by_slug(slug)\n    if not ds:\n        return JSONResponse({\"error\": \"Dataset not found\"}, status_code=404)\n\n    return {\n        \"slug\": ds[\"slug\"],\n        \"title\": ds[\"title\"],\n        \"description\": ds[\"description\"],\n        \"price_usd\": ds[\"price_usd\"],\n        \"size_mb\": ds[\"size_mb\"],\n        \"format\": ds[\"format\"],\n        \"columns\": ds.get(\"columns\", []),\n        \"row_count\": ds.get(\"row_count\", 0),\n        \"sample_rows\": ds.get(\"sample_rows\", []),\n        \"download_url\": f\"\u002Fdatasets\u002F{slug}\u002Fdownload\",\n    }\n\n\n@app.get(\"\u002Fdatasets\u002F{slug}\u002Fdownload\")\nasync def download_dataset(\n    slug: str,\n    response: Response,\n    payment: dict = Depends(x402_required(\n        price_usd=0,  # Will be overridden dynamically\n        description=\"Dataset download\",\n    )),\n):\n    \"\"\"Download a dataset (paid via x402).\"\"\"\n    ds = get_dataset_by_slug(slug)\n    if not ds:\n        return JSONResponse({\"error\": \"Dataset not found\"}, status_code=404)\n\n    file_path = DATASETS_DIR \u002F ds[\"filename\"]\n    if not file_path.exists():\n        return JSONResponse({\"error\": \"File not available\"}, status_code=503)\n\n    return FileResponse(\n        path=str(file_path),\n        filename=ds[\"filename\"],\n        media_type=\"application\u002Foctet-stream\",\n    )\n```\n\nIn production, override the `price_usd` in `x402_required` dynamically based on the dataset's catalog entry. One approach is to use a custom dependency that reads the price from the catalog:\n\n```python\ndef dataset_x402(slug_param: str = \"slug\"):\n    \"\"\"Dynamic x402 dependency that reads price from dataset catalog.\"\"\"\n\n    async def dependency(request: Request) -> dict:\n        slug = request.path_params.get(slug_param)\n        ds = get_dataset_by_slug(slug)\n        if not ds:\n            raise HTTPException(status_code=404, detail=\"Dataset not found\")\n\n        # Create the x402 dependency with the dataset's price\n        x402_dep = x402_required(\n            price_usd=ds[\"price_usd\"],\n            description=f\"Download: {ds['title']}\",\n        )\n        return await x402_dep(request)\n\n    return dependency\n```\n\n### Recipe 4: Agent-to-Agent Service (Autonomous Buyer + Seller)\n\nThe most powerful x402 pattern: two AI agents transacting without human involvement. The seller agent exposes an API behind an x402 paywall. The buyer agent detects the 402, constructs a payment, and completes the purchase autonomously.\n\n**Seller agent (Express.js):**\n\n```javascript\n'use strict';\n\n\u002F**\n * Seller agent: exposes a code review service behind x402.\n *\n * POST \u002Freview\n * Body: { \"code\": \"...\" }\n * Price: $0.50 per review\n *\u002F\n\nconst express = require('express');\nconst { x402Paywall } = require('.\u002Fx402-middleware');\n\nconst app = express();\napp.use(express.json({ limit: '50kb' }));\n\napp.post('\u002Freview',\n  x402Paywall({\n    priceUsd: 0.50,\n    description: 'AI code review service',\n  }),\n  async (req, res) => {\n    const { code } = req.body;\n    if (!code) {\n      return res.status(400).json({ error: 'code field required' });\n    }\n\n    \u002F\u002F Perform the code review (your AI logic here)\n    const review = await performCodeReview(code);\n\n    res.json({\n      review,\n      lines_analyzed: code.split('\\n').length,\n      timestamp: new Date().toISOString(),\n    });\n  }\n);\n\nasync function performCodeReview(code) {\n  \u002F\u002F Placeholder: integrate with your LLM or static analysis tool\n  return {\n    issues: [\n      { line: 3, severity: 'warning', message: 'Consider using const instead of let' },\n      { line: 15, severity: 'info', message: 'This function could be simplified' },\n    ],\n    overall_quality: 'good',\n    suggestions: ['Add type annotations', 'Extract helper function on line 15'],\n  };\n}\n\napp.listen(4000, () => console.log('Seller agent running on port 4000'));\n```\n\n**Buyer agent (Python):**\n\n```python\n\"\"\"\nBuyer agent: autonomously purchases code review from the seller.\n\nDetects 402, constructs payment, and completes the transaction.\n\nIn production, the payment construction uses a wallet SDK\n(e.g., coinbase-sdk or viem) to sign EIP-712 payloads.\n\"\"\"\n\nimport httpx\nimport json\nimport base64\nimport asyncio\n\n\nSELLER_URL = \"https:\u002F\u002Fseller-agent.example.com\"\n\n\nasync def buy_code_review(code: str) -> dict:\n    \"\"\"Submit code for review, handling x402 payment flow.\"\"\"\n\n    async with httpx.AsyncClient(timeout=30.0) as client:\n        # Step 1: Initial request (expect 402)\n        response = await client.post(\n            f\"{SELLER_URL}\u002Freview\",\n            json={\"code\": code},\n        )\n\n        if response.status_code == 200:\n            # Free or already paid\n            return response.json()\n\n        if response.status_code != 402:\n            raise Exception(f\"Unexpected status: {response.status_code}\")\n\n        # Step 2: Parse payment requirements from 402 response\n        payment_info = response.json()\n        requirements = payment_info[\"accepts\"][0]\n\n        print(f\"Payment required: {requirements['maxAmountRequired']} \"\n              f\"{requirements['extra']['name']} on {requirements['network']}\")\n        print(f\"Pay to: {requirements['payTo']}\")\n\n        # Step 3: Construct payment payload\n        # In production, use your wallet SDK to sign an EIP-712 payload:\n        #\n        #   from coinbase_sdk import Wallet\n        #   wallet = Wallet.load(\"my-wallet\")\n        #   payment_payload = wallet.sign_x402_payment(\n        #       amount=requirements[\"maxAmountRequired\"],\n        #       asset=requirements[\"asset\"],\n        #       pay_to=requirements[\"payTo\"],\n        #       network=requirements[\"network\"],\n        #       resource=requirements[\"resource\"],\n        #       timeout=requirements[\"maxTimeoutSeconds\"],\n        #   )\n        #\n        # For this example, we use a placeholder:\n        payment_payload = construct_payment_payload(requirements)\n\n        # Step 4: Retry with payment\n        response = await client.post(\n            f\"{SELLER_URL}\u002Freview\",\n            json={\"code\": code},\n            headers={\"X-Payment\": payment_payload},\n        )\n\n        if response.status_code == 200:\n            print(\"Payment accepted. Review received.\")\n            return response.json()\n\n        if response.status_code == 402:\n            error = response.json().get(\"error\", \"Unknown payment error\")\n            raise Exception(f\"Payment rejected: {error}\")\n\n        raise Exception(f\"Unexpected status after payment: {response.status_code}\")\n\n\ndef construct_payment_payload(requirements: dict) -> str:\n    \"\"\"Construct an x402 payment payload.\n\n    IMPORTANT: This is a placeholder. In production, use a wallet SDK\n    to sign a real EIP-712 typed data structure that authorizes the\n    USDC transfer. The facilitator will reject unsigned payloads.\n\n    Libraries that support x402 payment construction:\n    - @coinbase\u002Fx402 (Node.js)\n    - coinbase-sdk (Python)\n    - viem (TypeScript, via signTypedData)\n    \"\"\"\n    # Placeholder -- replace with real wallet signing\n    payload = {\n        \"x402Version\": 1,\n        \"scheme\": requirements[\"scheme\"],\n        \"network\": requirements[\"network\"],\n        \"amount\": requirements[\"maxAmountRequired\"],\n        \"asset\": requirements[\"asset\"],\n        \"payTo\": requirements[\"payTo\"],\n        \"resource\": requirements[\"resource\"],\n    }\n    return base64.b64encode(json.dumps(payload).encode()).decode()\n\n\nasync def main():\n    code = \"\"\"\ndef fibonacci(n):\n    if n \u003C= 1:\n        return n\n    return fibonacci(n-1) + fibonacci(n-2)\n    \"\"\"\n\n    result = await buy_code_review(code)\n    print(json.dumps(result, indent=2))\n\n\nif __name__ == \"__main__\":\n    asyncio.run(main())\n```\n\nThe buyer agent pattern is the core of agent-to-agent commerce with x402. The agent does not need an account, an API key, or a subscription. It needs a wallet with USDC and the ability to sign EIP-712 payloads. The seller does not need to know who the buyer is. The payment is the authentication.\n\nThis pattern scales to any number of agents. A research agent can autonomously pay for data from a data provider agent. A coding agent can pay for testing from a QA agent. A planning agent can pay for analysis from a specialist agent. Each transaction is a single HTTP request with an `X-Payment` header. No orchestration platform required. No billing integration. No API key management. Just HTTP and money.\n\n---\n\n## Appendix: Quick Reference\n\n### Environment Variables\n\n| Variable | Description | Default |\n|----------|-------------|---------|\n| `MERCHANT_WALLET_ADDRESS` | Your wallet address (receives payments) | Required |\n| `X402_NETWORK` | `base-mainnet` or `base-sepolia` | `base-sepolia` |\n| `X402_FACILITATOR_URL` | Facilitator URL | `https:\u002F\u002Fx402.org\u002Ffacilitator` |\n\n### USDC Contract Addresses\n\n| Network | CAIP-2 ID | USDC Address |\n|---------|-----------|-------------|\n| Base Mainnet | `eip155:8453` | `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913` |\n| Base Sepolia | `eip155:84532` | `0x036CbD53842c5426634e7929541eC2318f3dCF7e` |\n\n### Price Conversion\n\n```\nUSDC amount (6 decimals) = USD price * 1,000,000\n$0.01 = \"10000\"\n$0.10 = \"100000\"\n$1.00 = \"1000000\"\n$29.00 = \"29000000\"\n```\n\n### Facilitator Endpoints\n\n| Endpoint | Method | Purpose |\n|----------|--------|---------|\n| `\u002Fverify` | POST | Validate a payment payload against requirements |\n| `\u002Fsettle` | POST | Trigger on-chain USDC transfer |\n\n### HTTP Headers\n\n| Header | Direction | Purpose |\n|--------|-----------|---------|\n| `X-Payment` | Request | Base64-encoded payment payload from client |\n| `PAYMENT-REQUIRED` | Response (402) | Base64-encoded payment requirements |\n| `X-PAYMENT-RESPONSE` | Response (200) | Base64-encoded payment confirmation |\n\n### Cross-References\n\n- For agent-to-agent escrow, marketplace discovery, and reputation-gated hiring on top of x402 micropayments, see **The Multi-Agent Commerce Cookbook**.\n- For multi-protocol comparison (x402 vs ACP vs AP2 vs MPP), see **The Agent Payment Rails Playbook**.\n- For fleet-wide cost attribution and spend dashboards, see **The AI Agent FinOps Playbook**.\n\nFor the full x402 protocol specification, visit [https:\u002F\u002Fwww.x402.org](https:\u002F\u002Fwww.x402.org).\n\n---\n\n*Price: $29 | Format: Digital Guide | Updates: Lifetime access*\n\n",{"name":5,"tags":24,"type":34,"author":35,"install":36,"license":15,"version":37,"metadata":38,"price_usd":45,"executable":20,"credentials":46,"description":7,"content_type":47,"compatibility":48},[25,26,27,28,29,30,31,32,33,34],"x402","payments","usdc","base","crypto-paywall","api-monetization","greenhelix","openclaw","ai-agent","guide","felix-agent","none","1.3.1",{"openclaw":39},{"requires":40,"primaryEnv":42},{"env":41},[42,43,44],"WALLET_ADDRESS","AGENT_SIGNING_KEY","STRIPE_API_KEY",29,[42,43,44],"markdown",[32],"master","4aa004da461d820f4ea5499e58eb8d196cf99016","community\u002Fclawhub\u002Fg\u002Fgreenhelix-x402-merchant-cookbook",0,"https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge","https:\u002F\u002Fskill-explorer-rho.vercel.app","https:\u002F\u002Fgithub.com\u002FLord1Egypt","Unbreakable. Unstoppable. Unmatched⚡.\r\n Speaker of machine tongues 🤖  | World-builder of decentralized dreams 🌐 | Defender of the digital realm🛡️.","2026-06-10 08:21:01",{"source":8,"skillName":5,"commands":59,"prompt":69,"zipAvailable":70},[60,63,66],{"tool":61,"command":62},"npx","npx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-x402-merchant-cookbook",{"tool":64,"command":65},"bunx","bunx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-x402-merchant-cookbook",{"tool":67,"command":68},"pnpm","pnpm dlx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-x402-merchant-cookbook","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fg\u002Fgreenhelix-x402-merchant-cookbook\u002FSKILL.md",true,[],[73,80,87,94,101,108],{"skillNo":74,"name":75,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":19},"01M785WKJB99G3STR1NF9NRTJW","youtube-content","YouTube transcripts to summaries, threads, blogs.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fyoutube-content\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":19},"01M785WEFHB0G2S9YA6EPR3H0E","xurl","X\u002FTwitter via xurl CLI: post, search, DM, media, v2 API.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fxurl\u002FSKILL.md",[],[],{"skillNo":88,"name":89,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":91,"categories":92,"keywords":93,"publishedAt":19},"01M785W98EDN4EFJXJPMQEHCRC","touchdesigner-mcp","Control a running TouchDesigner instance via twozero MCP — create operators, set parameters, wire connections, execute Python, build real-time visuals. 36 native tools.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftouchdesigner-mcp\u002FSKILL.md",[],[],{"skillNo":95,"name":96,"nameZh":6,"description":97,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":98,"categories":99,"keywords":100,"publishedAt":19},"01M785W5S9FP3QBH2V191E025P","test-driven-development","TDD: enforce RED-GREEN-REFACTOR, tests before code.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftest-driven-development\u002FSKILL.md",[],[],{"skillNo":102,"name":103,"nameZh":6,"description":104,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":105,"categories":106,"keywords":107,"publishedAt":19},"01M785W2AS08NSSH9YATCV6FJB","teams-meeting-pipeline","Operate the Teams meeting summary pipeline via Hermes CLI — summarize meetings, inspect pipeline status, replay jobs, manage Microsoft Graph subscriptions.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fteams-meeting-pipeline\u002FSKILL.md",[],[],{"skillNo":109,"name":110,"nameZh":6,"description":111,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":112,"categories":113,"keywords":114,"publishedAt":19},"01M785VXKW4T34BTP1SCHW1R7F","systematic-debugging","4-phase root cause debugging: understand bugs before fixing.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fsystematic-debugging\u002FSKILL.md",[],[]]