[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7ECXRMDVVNYPZPFPZY9JZD7":3,"skill-same:01M7ECXRMDVVNYPZPFPZY9JZD7":49},{"skillNo":4,"name":5,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":20,"frontMatter":21,"refName":22,"commitSha":23,"skillDirectory":24,"forksCount":13,"repositoryHtmlUrl":25,"repositoryHomepageUrl":6,"ownerHtmlUrl":26,"ownerBlogUrl":6,"ownerDescription":27,"updatedAt":28,"install":29,"resources":42},"01M7ECXRMDVVNYPZPFPZY9JZD7","x402-payment-gateway",null,"jonahthan433\u002FCortexOS","jonahthan433","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F211465495?v=4","01M7ECH9HPHGA89DCXHHJBTS3C","jonah.ai","01M7ECH9JCEM45DZMWPT7148S1",0,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fimported\u002Fmlops\u002Fx402-payment-gateway\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"# x402-payment-gateway\n\n# x402 Payment Gateway\n\nClass-level playbook for shipping an x402 v2 payment-gated API. Covers the server-side 402\nchallenge + CDP facilitator verify\u002Fsettle, the client-side payment flow, and packaging the\ngateway as an MCP server agents can `npx` install. Everything below was validated against a\nlive Base-mainnet settlement (USDC actually moved and was confirmed on-chain).\n\n## When to use\n- Build or fix an x402 `402 Payment Required` challenge (v2 shape).\n- Wire the CDP (Coinbase) facilitator `\u002Fverify` + `\u002Fsettle`.\n- Debug: `missing EIP-712 domain`, `Unauthorized` from the facilitator, 402 returned but the\n  client never pays, x402scan listing shows a \"C\" avatar or stale title.\n- Build an `@cortexcloud.org\u002Fmcp`-style MCP server with x402 payments built in (NOTE: the\n  org slug is `cortexcloud.org`, so the published package is `@cortexcloud.org\u002Fmcp`, NOT\n  `@cortexcloud\u002Fmcp` — the slug mismatch caused ~16 failed publishes; see `npm-publishing`).\n- Deploy \u002F edit code on the CortexCloud CT 105 (Proxmox unprivileged LXC).\n\n## Mental model\n- **Server** emits a 402 with a `PaymentRequirements` challenge; on receiving a payment\n  header it calls CDP `\u002Fverify` then `\u002Fsettle`. Payment IS authentication — no API key.\n- **Client \u002F agent** signs an EIP-3009 USDC authorization locally (gasless — needs USDC but\n  **no ETH**) and resends with a single `PAYMENT-SIGNATURE` header (base64 JSON of\n  `{x402Version, payload:{authorization, signature}, resource, accepted, extensions}`).\n  Modern clients (2.20) send NO separate `X-PAYMENT` header.\n- **Buyer wallet** pays USDC with no ETH (EIP-3009 is gasless). To *sweep* a wallet you DO\n  need ETH for gas. See Pitfall 4.\n\n## Server challenge — required v2 shape\n`accepts[0]` MUST carry the EIP-712 domain in `extra`, or the CDP facilitator rejects with\n`missing EIP-712 domain name\u002Fversion in requirements.extra`:\n```python\nrequirements = {\n    \"x402Version\": 2,\n    \"resource\": {\"url\": resource_url, \"description\": description, \"mimeType\": \"application\u002Fjson\"},\n    \"accepts\": [{\n        \"scheme\": \"exact\",\n        \"network\": \"eip155:8453\",\n        \"asset\": \"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913\",  # USDC on Base\n        \"amount\": str(price_atomic),                              # USD * 1_000_000\n        \"payTo\": \"\u003Cmerchant wallet>\",\n        \"maxTimeoutSeconds\": 60,\n        \"extra\": {\"name\": \"USD Coin\", \"version\": \"2\"},            # REQUIRED\n    }],\n    \"extensions\": {\"bazaar\": {\"schema\": {\"properties\": {\n        \"input\":  {\"properties\": {\"body\": input_schema}},\n        \"output\": {\"properties\": {\"example\": output_schema}},\n    }}}},\n}\n```\nx402scan hard-errors (`SCHEMA_INPUT_MISSING`) without the `extensions.bazaar.schema`.\n\n## CDP facilitator auth — SIGNED, not Bearer\nCDP v2 facilitator requires **per-request ES256 JWTs**, not a static `Authorization` header.\n- Import is `from cdp.x402.x402 import create_cdp_auth_headers` — NOT `cdp.x402`\n  (that raises `ImportError`). `cdp-sdk` must be installed in the app venv.\n- `h = create_cdp_auth_headers(api_key_id, api_key_secret)()` returns a dict with\n  `verify` \u002F `settle` \u002F `supported` header sets. Merge the matching set into each\n  facilitator POST.\n- Config: `X402_FACILITATOR_API_KEY_ID` + `X402_FACILITATOR_API_KEY_SECRET`\n  (keep the legacy single `X402_FACILITATOR_API_KEY` as a fallback `Bearer`).\n- Prove it: `GET {facilitator_url}\u002Fsupported` returns 200 with a valid `Authorization` JWT.\nFull detail + verified snippet → `references\u002Fcdp-facilitator-auth.md`.\n\n## Client-side payment\n`@x402\u002Ffetch` bundles `x402Client` + `wrapFetchWithPayment`. Register the EVM scheme:\n```ts\nimport { x402Client, wrapFetchWithPayment } from \"@x402\u002Ffetch\";\nimport { registerExactEvmScheme } from \"@x402\u002Fevm\u002Fexact\u002Fclient\";\nimport { privateKeyToAccount } from \"viem\u002Faccounts\";\nconst pk = process.env.KEY!.startsWith(\"0x\") ? process.env.KEY! : `0x${process.env.KEY!}`;\nconst signer = privateKeyToAccount(pk as `0x${string}`);\nconst client = new x402Client();\nregisterExactEvmScheme(client, { signer });\nconst paidFetch = wrapFetchWithPayment(fetch, client);\n```\nviem `privateKeyToAccount` REQUIRES the `0x` prefix (raw 64-hex throws). See\n`references\u002Fmcp-server-x402.md`.\n\n## MCP server (so agents can `npx @cortexcloud\u002Fmcp`)\n- `@modelcontextprotocol\u002Fsdk` `McpServer` + `StdioServerTransport`; register tools with\n  `server.tool(name, desc, zodShape, handler)`.\n- Make the paid fetch **lazy** (built on first paid call) so free tools (e.g. `models`)\n  work even when no wallet key is set — otherwise `createPaidFetch()` at module load throws\n  and the whole server crashes on startup.\n- Build with the project's `tsc` (Node16 moduleResolution). A system\u002Fglobal `tsc` may\n  false-error on viem's internal `.d.ts`; trust `npx tsc -p tsconfig.json`.\nScaffolding (package.json, tsconfig, client.ts, tools.ts, index.ts, smoke test) →\n`references\u002Fmcp-server-x402.md`.\n\n## Deploy on CortexCloud CT 105 (Proxmox unpriv LXC)\nDirect SSH to CT 105 fails (idmap\u002FStrictModes). Access from ninyi via `pct exec` \u002F `pct mount`:\n- **Edit a file:** `pct mount 105` → write to `\u002Fvar\u002Flib\u002Flxc\u002F105\u002Frootfs\u002F\u003Cct-abs-path>` →\n  `pct unmount 105`. Host paths like `\u002Fopt\u002FCortexCloudAPI\u002F...` are NOT reachable from inside\n  the CT; you must write into the rootfs mountpoint.\n- **Restart the service:** `pct exec 105 -- systemctl restart cortexcloud.service`.\n- **Run a script:** base64 it, `pct mount` → `base64 -d > \u002Fvar\u002Flib\u002Flxc\u002F105\u002Frootfs\u002Froot\u002Fx.py`\n  → `pct unmount` → `pct exec 105 -- python \u002Froot\u002Fx.py`.\nFull recipe → `references\u002Fproxmox-ct105-deploy.md`.\n\n## Adding new resources \u002F mirroring a competitor catalog\nTo add payment-gated endpoints (e.g. mirror BlockRun's 97-endpoint catalog): the\nmiddleware auto-gates any path in `ROUTE_PRICING`, so it's (1) write an\n`APIRouter` in `app\u002Fx402\u002F\u003Cgroup>_routes.py` + mount at `\u002Fx402\u002Fv1`, (2) add\n`\"\u003CMETHOD> \u003Cpath>\": \"$price\"` to `pricing.py`, (3) restart. ALWAYS use `Query()`\nparams (never path params) so the gated path matches the static price key. Guard\nkeyed-provider routes with a length+prefix `_need()` check so stub keys return a\nclean 503 (not an upstream 403) — and check `.env` keys are REAL (source it,\ncheck length) before claiming a keyed route works. Full recipe + `_need` snippet\n→ `references\u002Fadding-resources.md`. Scraping a competitor's x402scan resource\nlist (past the lazy \"Show N more\") → `references\u002Fx402scan-resource-extraction.md`.\n\n## Node\u002FTS gateway (cortexcloud-gateway, Fastify in LXC 105) — x402 reality\nThe TS gateway (`~\u002Fcortexcloud-gateway`) is a SEPARATE surface from the Python API. Its\nx402 `verifyPayment` (`src\u002Fx402.ts`) is a **stub: logs + returns true, writes\n`payment` row with status \"settled\" BEFORE any chain check**. The audit consequence:\n- Bazaar does NOT index it (only settled, not \"verified\", payments get indexed).\n- `POST \u002Fv1\u002Fsettle` with a FAKE tx hash returns 200 `settled:true` (proven live) — it accepts anything.\n- 402 shape itself is correct (verified: over-budget chat → 402 with PaymentRequirements).\n\n**Real fix (v2 SDK):** replace the stub with `HTTPFacilitatorClient` from `@x402\u002Fcore\u002Fserver`\n+ `createFacilitatorConfig` (or `facilitator`) from `@coinbase\u002Fx402`. The package split is:\n- `@coinbase\u002Fx402` → exports `facilitator` (a `FacilitatorConfig` whose `.url` defaults to the\n  CDP prod endpoint `https:\u002F\u002Fapi.cdp.coinbase.com\u002Fplatform\u002Fv2\u002Fx402`) and `createFacilitatorConfig()`.\n- `@x402\u002Fcore` → the real machinery: `HTTPFacilitatorClient` (in `@x402\u002Fcore\u002Fserver`),\n  `x402HTTPResourceServer`\u002F`x402ResourceServer` (full resource-server middleware with Bazaar\n  `discoverable` extensions), `x402Client` (client side). `verify`\u002F`settle` are methods on\n  `HTTPFacilitatorClient`, NOT on the `@coinbase\u002Fx402` `facilitator` object (that one only has\n  `url` + `createAuthHeaders`).\n- CDP facilitator needs an API key for verify\u002Fsettle (set `X402_FACILITATOR_API_KEY_ID` +\n  secret, or use the public test facilitator `https:\u002F\u002Fx402.org\u002Ffacilitator` for non-custodial\n  verify — but then item 1.1 \"CDP-compatible facilitator\" is only partially met).\n- Bazaar `discoverable:true` + per-route NL description\u002Finput\u002Foutput schemas are NOT in our\n  `x402.json` (it lists only `path`+`price`). Add the Bazaar `extensions` block per route.\n- README has NO x402 call sample (402→pay→retry→settle). Devs can't copy-paste wiring — add one.\nPonytail: don't rewrite the whole gateway into `x402HTTPResourceServer` unless asked; the lazy\ncorrect fix is to call `HTTPFacilitatorClient.verify()`\u002F`settle()` inside the existing\n`verifyPayment` and mark `settled` only after the facilitator confirms on-chain.\n\n## Pitfalls (cont.)\n1. `from cdp.x402 import create_cdp_auth_headers` → `ImportError`. Use `cdp.x402.x402`.\n2. Static `Bearer \u003Ckey>` to CDP → `401 Unauthorized`. Use signed JWTs — and use the\n   cdp-sdk's `create_cdp_auth_headers()`, do NOT hand-roll the ES256K JWT (secret is\n   base64 of 32-byte-priv||32-byte-pub; even correct-looking JWTs 401 — the SDK gets\n   the claims right). `\u002Fvalidate` is public; `\u002Fsettle` needs the JWT.\n3. 402 challenge missing `extra.name\u002Fversion` → facilitator `missing EIP-712 domain`.\n4. Buyer wallet with 0 ETH **cannot sweep** — EIP-3009 needs no ETH to PAY, but a\n   `transfer`\u002Fsweep needs ETH for gas. Fund a wallet or do an EIP-3009 sweep (needs a\n   submitter holding ETH).\n5. `web3` 7.x: `AsyncWeb3(AsyncHTTPProvider(url))` (no `__aenter__`);\n   `w3.eth.contract(address=..., abi=...)`.\n6. **npm org publish 404\u002F403** with granular tokens — token not scoped to the org, or needs\n   bypass-2FA \u002F OTP. Diagnostic + fixes → `references\u002Fnpm-org-publish.md`.\n7. x402scan title\u002Ffavicon derive from the served HTML homepage `\u003Ctitle>` and\n   `og:image`\u002F`favicon.ico`, not `\u002Fopenapi.json` `info.title` and not `\u002Ffavicon.ico` directly.\n   **The homepage is NO LONGER the inline `CORTEXCLOUD_HOME_HTML` string** (that was replaced\n   during the BlockRun-parity landing-page rebuild). It now serves `static\u002Findex.html` via a\n   `FileResponse` at the `\u002F` route in `app\u002Fmain.py`:\n   ```python\n   @app.get(\"\u002F\", include_in_schema=False)\n   async def home():\n       from fastapi.responses import FileResponse\n       return FileResponse(\"\u002Fopt\u002FCortexCloudAPI\u002Fstatic\u002Findex.html\")\n   ```\n   To change the landing page, edit `static\u002Findex.html` (NOT a Python string). The live stats\n   card + model\u002Fprice tables are driven by JS `fetch()` to backend endpoints (see #8) — they\n   are NOT server-rendered, so editing HTML alone won't populate data.\n8. **Live landing-page data endpoints** (added in the BlockRun-parity rebuild). The homepage\n   fetches real backend routes; add new ones the same way:\n   - `GET \u002Fx402\u002Fv1\u002Factivity` → real merchant-wallet USDC settlements, read from the Base\n     public RPC (`https:\u002F\u002Fmainnet.base.org`) via `eth_getLogs` on the USDC `Transfer` event\n     (`0xddf2...3ef`) to the merchant wallet `0xE816eA741a0084748DC9f2BEeB86Be6705862365`.\n     Fetch each tx's block timestamp via `eth_getBlockByNumber` for real ages. Falls back to\n     the one verified test settlement (`0.015 USDC`) when no on-chain tx exist yet. Returns\n     `{count, volume_usdc, txns:[{tx_hash, amount_usdc, ts, age_s}]}`.\n   - `GET \u002Fx402\u002Fv1\u002Fpricing` → returns model IDs (real, from `\u002Fx402\u002Fv1\u002Fmodels`) + invented\n     competitive prices. `app\u002Fpricing.py` holds the table: chat `$in\u002F$out` per 1M tokens,\n     modality cards (image\u002Fvideo\u002Fmusic\u002Fvoice w\u002F per-unit price), on-chain tool cards. Prices\n     are competitive market rates (provider cost + ~5% margin), NOT real costs — label honestly.\n   Wire a new endpoint: create `app\u002F\u003Cname>.py` (`APIRouter`) + `app\u002F\u003Cname>_route.py`\n   (`include_router(..., prefix=\"\u002Fx402\u002Fv1\")`), patch `main.py` to import+include, copy BOTH\n   into the CT rootfs via `pct mount` with `chmod 644`, then restart the service. CRITICAL:\n   `cortexcloud.service` runs INSIDE CT 105 — restart with `pct exec 105 -- systemctl restart\n   cortexcloud.service`, NOT from the ninyi host namespace (where the unit \"does not exist\").\n9. **MCP package scope is `@cortexcloud.org\u002Fmcp`** (org slug includes `.org`), NOT\n   `@cortexcloud\u002Fmcp`. Install: `npx @cortexcloud.org\u002Fmcp`. The scope-slug mismatch was the\n   root cause of ~16 failed publishes — full diagnostic in the `npm-publishing` skill.\n10. **Verifying a JS-fed landing page:** the browser tool's `browser_console(expression=...)`\n    is SANDBOXED and blocks `fetch()`\u002Fnetwork calls (\"sensitive browser JavaScript primitive\"),\n    and the accessibility snapshot can show \"Loading…\" because it captures before the async\n    `fetch()` resolves — even when the endpoint is fine. Don't conclude the page is broken.\n    Verify instead by: (a) `curl` the backing endpoint directly (e.g. `\u002Fx402\u002Fv1\u002Factivity`,\n    `\u002Fx402\u002Fv1\u002Fpricing`) to confirm JSON, (b) `curl` the homepage and `grep` for the expected\n    static markup + the fetch path, (c) a `browser_vision` screenshot for visual layout. The\n    vision model sees the rendered result (post-fetch), the text snapshot may not.\n11. **Paid routes live under `\u002Fx402\u002Fv1\u002F*`, NOT `\u002Fv1\u002F*`.** `\u002Fv1\u002Fchat\u002Fcompletions` requires a\n    Bearer API key (returns `Missing Authorization Header`); the payment-gated mirror is\n    `\u002Fx402\u002Fv1\u002Fchat\u002Fcompletions`, which returns the 402. A client that targets `\u002Fv1\u002F...` can\n    never exercise the x402 flow. Proxy\u002FSDK code MUST forward `\u002Fx402\u002Fv1\u002F*` untouched.\n12. **x402 settlement needs USDC AND a little ETH for gas.** Even with USDC present, the\n    on-chain USDC transfer reverts if the payer wallet holds 0 ETH (facilitator error:\n    `contract call failed: execution reverted` \u002F `invalid_payload`). An auto-created wallet\n    has 0 of both — fund it with ~$0.50 USDC + ~0.001 ETH before a real paid call will land.\n    A Binance withdrawal screenshot (amount\u002Faddress\u002Ftxid) only proves a deposit arrived; it\n    does NOT prove the private key is reachable or that the wallet can pay (0 ETH). Provenance\n    check: read balance with `eth_call` to USDC `balanceOf` + `eth_getBalance`.\n13. **`@x402\u002Fevm\u002Fexact\u002Fclient` is a deep subpath, not a top-level export.** `registerExactEvmScheme`\n    is NOT exported from `@x402\u002Fevm` root — import from `@x402\u002Fevm\u002Fexact\u002Fclient`. With\n    `moduleResolution: bundler`, do NOT add a `paths` alias pointing at the `.d.mts` (esbuild\n    then follows the broken declaration and fails to resolve `..\u002F..\u002Fscheme-*.mjs`). Let the\n    package's own exports map resolve it; the real `.mjs` correctly imports existing chunks.\n14. **`tsc` build breaks on viem\u002F`ox` deep types even though the code is fine.** viem 2.x +\n    `@x402\u002F*` pull `ox` types that fail type-checking under NodeNext; the errors are in\n    node_modules and harmless at runtime (suppressed by `skipLibCheck`). Build with **esbuild**\n    (transpile-only, `--packages=external --format=esm --target=node20`) instead of `tsc` so\n    the proxy actually compiles and runs. `tsc` still EMITS `dist\u002F` despite the noise, but\n    esbuild gives a clean, trustworthy build.\n\n15. **Landing page is now a Next.js static export, NOT `static\u002Findex.html`.** The\n    BlockRun-parity page was replaced by a Next.js 15 build exported to `site\u002F` and\n    served by FastAPI: `\u002F` returns `FileResponse(\"site\u002Findex.html\")`, `\u002F_next` is a\n    `StaticFiles` mount, and root-level assets (logo, og.svg, robots.txt) are served\n    by a `@app.get(\"\u002F{asset}\")` extension-whitelist route registered LAST (explicit\n    routes take priority; the whitelist blocks non-asset paths). To change the\n    landing: rebuild the Next project, `tar` the `out\u002F` dir, base64 over SSH into\n    `\u002Fopt\u002FCortexCloudAPI\u002Fsite\u002F`, restart. Pitfall #7's inline-HTML\u002F`static\u002Findex.html`\n    notes are superseded for the landing itself (the JS-fed live data model still holds).\n16. **Next 16's prebuilt SWC binary Bus-errors (exit 135) on Debian 13 \u002F glibc 2.41.**\n    `node -e \"require('@next\u002Fswc-linux-x64-gnu')\"` crashes with a bare Bus error and no\n    stack. Fix: pin **Next 15** (`npm i next@15.5.4 eslint-config-next@15.5.4 --save-exact`)\n    — its SWC binary loads fine. Not an OOM (raising `--max-old-space-size` doesn't help);\n    it's a native glibc\u002FCPU incompat. Next 15 also uses the FlatCompat eslint config\n    (`@eslint\u002Feslintrc` + `FlatCompat().extends(\"next\u002Fcore-web-vitals\")`), not Next 16's flat style.\n17. **Cloudflare fronts `api.cortexcloud.org` and caches 404s for ~4h.** If you request\n    an asset before deploying it, the edge caches the 404 (`cf-cache-status: HIT`,\n    `age: NNN`, `cache-control: max-age=14400`) and keeps serving it even after the origin\n    (uvicorn :8000) returns 200. Diagnose: `curl -sI \u003Cpublic-url>` shows `cf-cache-status: HIT`\n    while `pct exec 105 -- curl -sI http:\u002F\u002F127.0.0.1:8000\u002F\u003Cpath>` shows 200. Fix within your\n    control: deploy the asset under a **fresh, never-cached filename** (e.g. `logo-v2.png`)\n    — or purge the CF cache if you have dashboard access. Always verify the ORIGIN\n    (127.0.0.1:8000 inside CT) before assuming your code is broken.\n18. **CDP facilitator `\u002Fvalidate`+`\u002Fsettle` body is TOP-LEVEL** `{resource, method,\n    headers, body}` — a `{payload:{...}}` wrapper → `400 property \"resource\" is missing`.\n    `body` must be a STRING (bytes → `Object of type bytes is not JSON serializable`).\n    This path had never been exercised — the gateway couldn't settle a payment since day one.\n19. **CDP `\u002Fvalidate` runs a discovery preflight that REQUIRES `extensions.bazaar.info`**\n    (`input.type\u002Fmethod\u002FbodyType\u002Fbody` + `output.type\u002Fformat\u002Fexample`) — missing →\n    `simulation.rejectionReason: \"invalid discovery configuration\"`. Also: validate\n    response field is `valid`, not `success`. Full contract + checklist →\n    `references\u002Fcdp-facilitator-settlement.md`.\n20. **\"Client never pays\" (returns raw 402) usually means the SERVER rejected the\n    payment headers** — check the gateway log for facilitator errors, not the client.\n    Server gate must accept the single `payment-signature` header alone (requiring a\n    legacy `x-payment` too blocks every modern client).\n21. **Stateless\u002Flocal verification belongs in-process, not only via the facilitator.**\n    A hardened gateway verifies the proof itself (ECDSA signer recovery via `eth_account`,\n    amount >= your price, chainId==8453, asset==USDC, payTo==your wallet, validBefore\n    30s\u002F5min window) BEFORE calling the facilitator — and fail-closes to 402 on any\n    error. CDP `\u002Fsettle` then remains the actual on-chain broadcast rail. Two traps\n    that silently reject EVERY real client payment (found + fixed + on-chain verified\n    when adding a second wallet):\n    - **primaryType name**: the @x402 client (2.20) signs `TransferWithAuthorization` —\n      your `_AUTH_TYPES` key MUST be that exact name. `TransferAuthorization` (off by\n      one word) passes unit tests but makes ECDSA recovery fail for real signatures →\n      `signature does not match payer`.\n    - **signature location**: the client stores the 65-byte sig at `payload.signature`,\n      a SIBLING of `payload.authorization` — `_extract_sig(auth)` finds nothing →\n      `missing signature`. Merge the sibling into auth before extracting.\n    Full corrected struct + merge snippet + the missing-sig\u002Fmismatch debug ladder →\n    `references\u002Fin-process-proof-verification.md`.\n22. **Middleware ordering in FastAPI is \"add LAST, run FIRST\" (outermost).** The last\n    `add_middleware()` is the outermost wrapper. Put a body-reading validation\n    middleware last so it short-circuits malformed\u002Foversized bodies before the payment\n    gateway touches them. Read the body with `await request.body()` — starlette buffers\n    it so downstream middleware (x402) can re-read safely; do NOT re-inject\n    `request._receive` (breaks SSE on starlette 1.3.x). For path matching use a suffix\n    (`\"\u002Fdata\u002F\" in path`) not `path.startswith(\"\u002Fdata\u002F\")` — paid data routes live under\n    `\u002Fx402\u002Fv1\u002Fdata\u002F...`.\n    **PROVEN consequence of skipping it (2026-08 paid sweep):** the x402 gate settles\n    BEFORE the input-validation middleware runs — a malformed-body request (422) still\n    charged the buyer $0.05 (ledger showed 2 classical payments for 1 successful run).\n    Without the outermost body-validation short-circuit, every rejected paid request\n    bills the customer. When debugging \"charged but failed\", diff `x402_payments` rows\n    against successful jobs.\n26. **Quantum\u002Fbraket backend auto-routing must respect device CAPABILITY, not just\n    ONLINE status.** Discovery (`braket.py`) accepts any `deviceType==QPU` + ONLINE —\n    but QuEra **Aquila is AHS-only** (analog program IR), so a routed job charges\n    $0.85 then fails `CreateQuantumTask ... Device arn:aws:braket:...\u002Fquera\u002FAquila\n    supports ['braket.ir.ahs.program']`. Fix: filter discovered devices on\n    `deviceCapabilities` containing the gate-model IR (`braket.ir.jaqcd`) and\u002For\n    restrict auto-route to benchmark-verified devices (Cepheus us-west-1) until a\n    device earns a benchmark row. Test paid quantum via the one-off flag only:\n    add `QUANTUM_LIVE_EXECUTION=true` to the unit's Environment, restart, run, then\n    REMOVE the flag and restart (margin guard + `QUANTUM_MAX_COST_USD` stay intact).\n27. **Paid-sweep harness for the current `\u002Fv1\u002Foptimize` surface (2026-08):** python\n    x402 SDK client flow — `x402Client()` + `register(\"eip155:8453\",\n    ExactEvmScheme(signer=buyer))` + `prefer_network` policy + `x402HTTPClient`:\n    POST `\u002Fv1\u002Foptimize` → expect 402 → `get_payment_required_response` →\n    `create_payment_payload` → `encode_payment_signature_header` → resend → poll\n    `\u002Fv1\u002Fjobs\u002F{id}`. Request body is `{\"mode\": \u003Cclassical|hybrid|quantum>,\n    \"problem\": {\"problem_type\":\"qubo\",\"n\":4,\"data\":{...}}}` (a `problem` WRAPPER is\n    required — flat body 422s). Buyer key: `\u002Froot\u002Fbzcheck\u002Ftest_buyer.key` on CT105\n    (derive address via `eth_account`); SDK lives in `\u002Fopt\u002Fcortexcloud-venv`.\n    Imports: `from x402 import x402Client, prefer_network` +\n    `from x402.http.x402_http_client import x402HTTPClient` +\n    `from x402.mechanisms.evm.exact import ExactEvmScheme` (NOT `from x402 import\n    ExactEvmScheme` — ImportError).\n23. **`pct push` reads SOURCE files from the Proxmox HOST, not your workstation.**\n    `scp \u003Cfile> root@ninyi:\u002Ftmp\u002F && pct push 105 \u002Ftmp\u002F\u003Cfile> \u003Cct-path>` — the file must\n    be on ninyi first, or you get `failed to open \u003Cpath> for reading`.\n24. **A default `x402Client` pays `accepts[0]` — if the server advertises multiple payout\n    wallets, a test\u002Fsweep harness silently settles to the FIRST one.** The constructor's\n    default paymentRequirementsSelector returns index 0. When the challenge lists\n    `[primary, second]`, `(_v, a) => a[0]` pays the primary (proven: a $0.19 sweep landed\n    on the primary while the \"new\" wallet only ever got the one targeted call). To force a\n    specific recipient, pin the selector to its `payTo`:\n    ```ts\n    const TARGET = \"0x5a03...\";                            \u002F\u002F lowercased\n    const client = new x402Client((_v, accepts) => {\n      const hit = accepts.find((a) => a.payTo?.toLowerCase() === TARGET);\n      if (!hit) throw new Error(\"target wallet not in challenge accepts\");\n      return hit;\n    });\n    ```\n    Verify the recipient BEFORE running a sweep by reading both wallets' `balanceOf`\n    (eth_call to USDC on `https:\u002F\u002Fmainnet.base.org`, curl with a UA — bot-filtered\n    otherwise). Don't assume which wallet got the money.\n25. **Testing ALL paid endpoints (a real-money sweep):** the same signer loop over every\n    path in the live spec that declares a `responses.402` proves the payment gate is open\n    on each plus surfaces upstream\u002Fprovider\u002Fparam faults. `$0.005`×38 ≈ `$0.19` from a\n    ~$7 buyer — cheap. Classify each result:\n    - **200** → gate + upstream OK.\n    - **non-402** → the gate accepted payment (that's the pass condition); a 400\u002F401\u002F5xx\n      is a separate upstream\u002Fparam problem, NOT a payment failure.\n    - **402** with a reject reason → payment genuinely failed; see the missing-sig\u002Fmismatch\n      ladder (pitfall 21 → `references\u002Fin-process-proof-verification.md`).\n    Common causes of \"failures\" that are NOT bugs: wrong model id (`\u002Fmodels` lists the real\n    ids; the Bazaar examples in SDK code can be stale — e.g. `text-embedding-3-small` vs the\n    registered `gemini-text-embedding-004`); an address-shaped param (`pair`\u002F`token`) that\n    passes a *symbol*; and missing AUDIO base64. Also note the `\u002Fdata\u002F*` address guard is\n    ERC-55 (checksum hex) only — a Solana base58 address → `invalid address param`. That's a\n    real gateway bug (solana\u002Fbalance unreachable); fix is a base58 branch in the shared\n    `_valid_addr`, not per-caller.\n\n## Principles (CortexCloud)\n- Keep control: own CT 105 app server, own merchant wallet, CDP facilitator allowed (user\n  chose it). No external managed key services.\n- Confirm before the first real on-chain payment (done via funded test buyer), before public\n  internet exposure, wallet\u002Fpayment-recipient change, or DB migration.\n\n## References\n- `references\u002Fadding-resources.md` — add new x402-gated routes; `_need` key guard; keyless upstream quirks.\n- `references\u002Fx402scan-resource-extraction.md` — scrape a competitor's full resource catalog past lazy render.\n- `references\u002Fcdp-facilitator-auth.md` — exact CDP import, signed-auth snippet, \u002Fsupported probe.\n- `references\u002Fcdp-facilitator-settlement.md` — verified validate\u002Fsettle contract: request shape,\n  bazaar.info preflight checklist, `valid` field, body re-injection, JWT-via-SDK rule, buyer-wallet key.\n- `references\u002Feip712-usdc-domain.md` — the exact error and the one-line fix.\n- `references\u002Fmcp-server-x402.md` — full MCP package scaffolding + smoke test.\n- `references\u002Fproxmox-ct105-deploy.md` — pct mount\u002Fedit\u002Frestart\u002Fcopy-script recipes.\n- `references\u002Fnpm-org-publish.md` — granular-token scoping 404\u002F403 diagnostic + resolutions.\n- `references\u002Fblockrun-volume-model.md` — how BlockRun pulls 15.45M tx via agent-native\n  auto-paying clients (ClawRouter\u002FFranklin\u002FMCP); our parity status + proxy approach.\n- `references\u002Fin-process-proof-verification.md` — in-process EIP-712 proof verification\n  (amount\u002Fchain\u002Fasset\u002FpayTo\u002Fexpiry guards + `eth_account` signer recovery) + test pitfalls.\n",{},"main","38b32c99e7ed0b8e215d638e92cfa452c1ec3079","skills\u002Fimported\u002Fmlops\u002Fx402-payment-gateway","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS","https:\u002F\u002Fgithub.com\u002Fjonahthan433","AI Consultant","2026-10-24 05:13:39",{"source":7,"skillName":5,"commands":30,"prompt":40,"zipAvailable":41},[31,34,37],{"tool":32,"command":33},"npx","npx skills add jonahthan433\u002FCortexOS --skill x402-payment-gateway",{"tool":35,"command":36},"bunx","bunx skills add jonahthan433\u002FCortexOS --skill x402-payment-gateway",{"tool":38,"command":39},"pnpm","pnpm dlx skills add jonahthan433\u002FCortexOS --skill x402-payment-gateway","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fimported\u002Fmlops\u002Fx402-payment-gateway\u002FSKILL.md",true,[43],{"path":44,"resourceType":45,"resourceTypeDesc":46,"sizeBytes":47,"sourceHtmlUrl":48},"skill.json","REFERENCE","参考文档",606,"https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fimported\u002Fmlops\u002Fx402-payment-gateway\u002Fskill.json",[50,56,62,68,74,80],{"skillNo":51,"name":52,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":18},"01M7EDQZDQX3Q8Y7GCQX6KN9V7","opportunity-brief","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fsales\u002Fopportunity-brief\u002FSKILL.md",[],[],{"skillNo":57,"name":58,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":18},"01M7EDQYA0V9Y99VKBREJJ3MRT","morning-intel","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fresearch\u002Fmorning-intel\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":18},"01M7EDQVX1JVY0B6PDHKKGM19G","decision-brief","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fresearch\u002Fdecision-brief\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":18},"01M7EDQV1GENZAC2SZSD8KZ3GM","weekly-review","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fproductivity\u002Fweekly-review\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":18},"01M7EDQT2KETJ1Y3CGVN9EKW2J","system-health","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fops\u002Fsystem-health\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":18},"01M7EDQQN2JK3XPWMS1M4T0F3K","backup-restore","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fops\u002Fbackup-restore\u002FSKILL.md",[],[]]