Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(x402): pay-for-what-you-use on Solana with the upto scheme, first on the LLM proxy
nirholas744292da3961
diff --git a/STRUCTURE.md b/STRUCTURE.mdindex 5d78176f5..6d1c387e3 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -43,6 +43,7 @@ packages, a generated standalone GitHub mirror). See| Live Docs (runnable code samples) | Pure decisions [public/docs-live-core.js](public/docs-live-core.js), runner [public/docs-live.js](public/docs-live.js), styles [public/docs-live.css](public/docs-live.css), mounted by the docs viewer [docs/index.html](docs/index.html) | Live | Every code sample across the ~318 documentation pages is editable, and the runnable ones execute in place: an `html` snippet containing `<agent-3d>` renders a real animated avatar in a sandboxed frame directly under the code, a single-`curl` `bash` block sends a real request and reports status, latency, size, body and response headers, and a `js` snippet runs as a module with its console streamed back. Slots such as `$API_KEY` or `<agent-id>` become input fields, with credential-shaped names held in memory and never written to storage. The safety split is the design: everything deciding what a reader may fire lives in the pure core and is unit-tested rather than trusted to a click handler. Only three.ws hosts are reachable, any path that can move funds or mint is refused outright on every verb, writes arm before they send, every fetch goes out with `credentials: omit`, and frames run `sandbox="allow-scripts"` without `allow-same-origin`. Authors opt a block out with `<!-- live:off -->`. Loaded lazily after the first page render, so a page with no runnable samples costs nothing. Docs: [docs/live-docs.md](docs/live-docs.md) `→ /docs/live-docs`. Tests: [tests/docs-live-core.test.js](tests/docs-live-core.test.js) || Docs World (immersive 3D docs) | [pages/docs-world.html](pages/docs-world.html) `→ /docs/world`, app [src/docs-world/](src/docs-world) (world/player/controls/overlays), styles [public/docs-world.css](public/docs-world.css), shared manifest [docs/nav.json](docs/nav.json) | Live | The documentation as a walkable place: each section of the docs sidebar is a glowing pavilion on a ring; walk up (WASD / touch joystick, four shared camera modes via [src/game/camera-modes.js](src/game/camera-modes.js)) or tap one to list its pages, and read the live markdown in an in-world DOM reader ([src/shared/markdown.js](src/shared/markdown.js)). One content source: both surfaces read `docs/nav.json` + `/docs/<slug>.md`, so classic and immersive docs cannot drift. Deep links mirror the classic hash routes (`/docs/world#forge`); the classic header's "3D world" button carries the open page across. Avatar is the platform's default rigged body (the same one `/walk` uses, since the agent mannequin ships unskinned and cannot be clip-driven) or any rigged GLB via `?avatar=`, animated by the canonical clip library. No-WebGL devices get a designed fallback routing to `/docs`. Docs: [docs/docs-world.md](docs/docs-world.md). Tests: [tests/docs-world.test.js](tests/docs-world.test.js) || x402 prepaid balances and batch settlement | ledger [api/_lib/x402/prepaid-ledger.js](api/_lib/x402/prepaid-ledger.js), batcher [api/_lib/x402/prepaid-settle.js](api/_lib/x402/prepaid-settle.js), chain legs [api/_lib/x402/prepaid-chain.js](api/_lib/x402/prepaid-chain.js), route hook [api/_lib/x402/prepaid-route.js](api/_lib/x402/prepaid-route.js) (`paidEndpoint({ mode: 'prepaid' })`), endpoints [api/x402-prepaid/](api/x402-prepaid), crons [x402-prepaid-settle](api/cron/x402-prepaid-settle.js) and [x402-prepaid-reconcile](api/cron/x402-prepaid-reconcile.js), reconcile CLI [scripts/x402-prepaid-reconcile.mjs](scripts/x402-prepaid-reconcile.mjs), migration [api/_lib/migrations/20261023160000_x402_prepaid_ledger.sql](api/_lib/migrations/20261023160000_x402_prepaid_ledger.sql) | Built; live settlement gated on the owner | A buyer deposits USDC once and each paid call debits a ledger row (never negative, charged only on success), then one Solana transaction per window pays every seller above a floor, so cent-sized calls stop starving the settle floor. A nightly reconciliation proves deposits minus debits minus settled equals held and alerts on any drift. Docs: [docs/ops/x402-prepaid.md](docs/ops/x402-prepaid.md). Tests: [tests/x402-prepaid-ledger.test.js](tests/x402-prepaid-ledger.test.js) |+| x402 `upto` (pay for what the call used) | scheme module [api/_lib/x402/upto.js](api/_lib/x402/upto.js), verify and claim in [api/_lib/x402-spec.js](api/_lib/x402-spec.js), seller option `paidEndpoint({ upto: { capAtomics, charge } })` in [api/_lib/x402-paid-endpoint.js](api/_lib/x402-paid-endpoint.js), buyer [api/_lib/x402/a2a-client.js](api/_lib/x402/a2a-client.js) (`buildSolanaUptoPayload`), first route [api/x402/llm-proxy.js](api/x402/llm-proxy.js) | Built; on-chain run gated on the owner | The buyer escrows a cap, the seller settles only the measured charge and the rest of the deposit is refunded; a failed handler settles nothing. Opt in with `X402_UPTO_ENABLED=true`. Docs: [docs/x402-upto.md](docs/x402-upto.md). Tests: [tests/x402-upto.test.js](tests/x402-upto.test.js) || Prompt library (`/prompts`) | Source [data/prompt-library.json](data/prompt-library.json), builder [scripts/build-prompt-library.mjs](scripts/build-prompt-library.mjs) → `public/prompts.json` + `public/prompts.txt`, page [pages/prompts.html](pages/prompts.html) `→ /prompts` + [src/prompt-library/](src/prompt-library) (page.js, page.css) | Live | Prompts written to be copied out and pasted into someone else's assistant, grouped by what they build (3D models and rigged avatars, site embeds, the x402 economy, platform integrations) and by what they need first (nothing at all, the free MCP server, the skills pack, a funded wallet). Every prompt names a real endpoint or tool, says what to do when a job comes back pending, and says what to hand back; the ones that can spend money are written so the assistant stops and shows the amount and the recipient first. Each card copies to the clipboard or opens straight in claude.ai with the text already in the box, and the whole library is fetchable as `/prompts.json` or `/prompts.txt` so an agent can read it without scraping. The builder validates the data on every build (unique kebab-case ids, known category and setup, balanced `<placeholder>` brackets, internal links that resolve to routes in [data/pages.json](data/pages.json)) and `npm run check:prompt-library` holds the published copies in sync inside `npm run gate`. Docs: [docs/prompts.md](docs/prompts.md) `→ /docs/prompts`. Tests: [tests/prompt-library.test.js](tests/prompt-library.test.js) || React avatar creator | [avatar-sdk/](avatar-sdk) `→ /react` `/creator` | Published as `@three-ws/avatar` | Same package, React subpath || Avatar CLI (manifests in the build pipeline) | [packages/avatar-cli/](packages/avatar-cli), landing [pages/avatar-cli.html](pages/avatar-cli.html) `→ /avatar-cli`, styles [public/avatar-cli.css](public/avatar-cli.css), page runtime [src/avatar-cli-page.js](src/avatar-cli-page.js) | Published as `@three-ws/avatar-cli` | The terminal half of the avatar story, and the half that makes an avatar auditable. Four commands over one file: `init` scaffolds a schema-valid manifest from a wallet plus a mesh (reading the GLB once to compute its SHA-256 and size, so the document cannot disagree with the bytes it was built from), `validate` checks it against [packages/avatar-schema/](packages/avatar-schema) and exits non-zero so it works as a build gate, `hash` prints a bare digest that composes in a shell, and `preview` emits a resolver URL, an `<agent-3d>` snippet paired with the loader that registers it, and a zero-install iframe. Offline and deterministic throughout: no account, no API key, no network call, which is what makes it safe in a release script. `preview` warns instead of printing a dead snippet when `mesh.uri` is still a local `file://` path. The landing page proves the emitted markup by rendering it live rather than screenshotting it. Docs: [docs/avatar-cli.md](docs/avatar-cli.md) `→ /docs/avatar-cli`, tutorial [docs/tutorials/ship-an-avatar-manifest.md](docs/tutorials/ship-an-avatar-manifest.md). Tests: [packages/avatar-cli/test/](packages/avatar-cli/test) |diff --git a/api/x402/llm-proxy.js b/api/x402/llm-proxy.jsindex d6b2ae3d4..b888958e3 100644--- a/api/x402/llm-proxy.js+++ b/api/x402/llm-proxy.js@@ -49,6 +49,19 @@ import llmProxyListing from '../_lib/service-catalog/services/llm-proxy.js';const ROUTE = '/api/x402/llm-proxy';+// `upto` metering: 5 atomics per token (=$0.005 per 1k tokens), never less than+// UPTO_MIN_CHARGE_ATOMICS, never more than the cap. The cap is 5x the flat+// `exact` price, enough for a full 2048-token completion plus a long prompt.+const UPTO_ATOMICS_PER_TOKEN = 5n;+const UPTO_MIN_CHARGE_ATOMICS = 500n;+const UPTO_CAP_ATOMICS = BigInt(priceFor('llm-proxy', '5000')) * 5n;++function uptoChargeFor(tokensUsed) {+ const tokens = BigInt(Math.max(0, Math.trunc(Number(tokensUsed) || 0)));+ const metered = tokens * UPTO_ATOMICS_PER_TOKEN;+ return metered < UPTO_MIN_CHARGE_ATOMICS ? UPTO_MIN_CHARGE_ATOMICS : metered;+}+// Map the caller-facing model alias to llmComplete options.// "fast" → Groq leads the free chain (sub-second latency, sufficient for short prompts)// "smart" → same chain, Anthropic backstop moves to the preferred position via anthropicModel@@ -181,6 +194,14 @@ export default paidEndpoint({requiredScope: 'x402:bypass',accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),+ // Pay-for-what-you-use on Solana: the buyer authorizes up to UPTO_CAP_ATOMICS+ // and is charged for the tokens the completion actually used (the rest of the+ // escrowed deposit returns to them). `exact` stays advertised beside it.+ upto: {+ capAtomics: UPTO_CAP_ATOMICS,+ charge: ({ result }) => uptoChargeFor(result?.tokens_used),+ },+async handler({ req }) {const chunks = [await readBody(req, 1_000_000)];const rawBody = Buffer.concat(chunks).toString();diff --git a/data/changelog.json b/data/changelog.jsonindex dcda70e74..3d4d2f47c 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,13 @@{"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security, desktop (desktop entries become the desktop app's release notes). `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-10-23",+ "title": "x402 pay-for-what-you-use on Solana (upto)",+ "summary": "A paid route can now advertise an upto offer beside its fixed price: the buyer authorizes a cap, the seller measures the work and settles only that amount, and the rest of the escrowed deposit returns to the buyer. A handler that fails settles nothing. The LLM proxy is the first route converted (5 atomics per token, capped at 5x the flat price). Agent payers refuse a cap above their per-call limit before signing, and the unused part of the cap is released from their budget. Existing exact clients are unaffected.",+ "tags": ["feature", "improvement"],+ "link": "/docs/x402-upto"+ },{"date": "2026-10-23","title": "News reader recovers blocked stories and gives a structured trading read",diff --git a/data/pages.json b/data/pages.jsonindex bba661fb5..4f79510c2 100644--- a/data/pages.json+++ b/data/pages.json@@ -4383,6 +4383,13 @@"description": "How three.ws implements x402 HTTP 402 paid agent skills: the challenge, verify, and settle mechanics.","added": "2026-04-29"},+ {+ "path": "/docs/x402-upto",+ "title": "Docs · x402 upto on Solana",+ "description": "Pay for what the call used: the buyer authorizes a cap, the seller settles the measured charge and the rest of the deposit is refunded. Seller and buyer APIs, failure behavior, and the batch-settlement finding.",+ "priority": 0.6,+ "changefreq": "monthly"+ },{"path": "/docs/x402-vscode","title": "Docs · x402 for VS Code",diff --git a/docs/x402-upto.md b/docs/x402-upto.mdnew file mode 100644index 000000000..bcc04ff84--- /dev/null+++ b/docs/x402-upto.md@@ -0,0 +1,67 @@+# x402 v2 `upto` on Solana++`upto` lets a buyer authorize a ceiling and pay only for what the call used. The seller declares a cap, runs the work, measures the charge, and settles that amount. The unused part of the escrowed deposit goes back to the buyer. A handler that throws settles nothing: the whole deposit is refunded.++three.ws runs the `upto` facilitator in-process. It uses the sponsor key that already backs the `exact` self-facilitator (`X402_FEE_PAYER_SECRET_BASE58`) as the transaction fee payer and as the channel's receiver authorizer, so no third-party facilitator has to support `upto`. All signing is done by the official `@x402/svm` (>= 2.28) client, server and facilitator schemes; nothing in this repo hand-rolls a payment signature.++## How a call flows++1. **402.** The challenge lists the usual `exact` accepts and one extra accept: `{ scheme: "upto", amount: <cap>, extra: { feePayer, receiverAuthorizer, withdrawDelay, tokenProgram, ... } }`.+2. **Buyer signs.** The `upto` client scheme signs a payment-channel `open` transaction that deposits the cap. The payload carries the transaction, not a transfer.+3. **Verify.** `x402-spec.js` runs the facilitator verify: program, deposit equals cap, payee, fee payer, simulation.+4. **Deposit settles before the handler.** The cap is escrowed on chain first, so the seller never does work it cannot collect. If the deposit fails, the handler does not run.+5. **Handler runs, charge is measured.** `upto.charge({ req, result, requirement, payer })` returns the atomic amount used (bigint, number or string). It is clamped to `0..cap`.+6. **Claim settles.** The requirement amount becomes the measured charge and the server signs a voucher for that cumulative amount. The program pays the seller the charge and refunds the rest.+7. **Cancel.** If the handler throws, or the charge hook fails, a claim of `0` is submitted and the whole deposit returns to the buyer.++Receipts, spend ledgers, `onSettled`, SIWX grants and the signed offer-receipt all read the charge from the settled requirement, so they record what was actually paid. An `upto` call that measured `0` charged nothing and earns no SIWX session.++## Seller++```js+export default paidEndpoint({+ route: '/api/x402/llm-proxy',+ priceAtomics: '5000',+ upto: {+ capAtomics: 25000n,+ charge: ({ result }) => BigInt(result.tokens_used) * 5n,+ },+ handler: async ({ req }) => { /* ... */ },+});+```++`upto` is additive: the `exact` accepts stay in the challenge, so existing clients keep working unchanged. It is advertised only when the deployment opts in (`X402_UPTO_ENABLED=true`, plus the sponsor key and `X402_PAY_TO_SOLANA` / `X402_ASSET_MINT_SOLANA`). It cannot be combined with `streaming` (the body would ship before the charge is known). `api/x402/llm-proxy.js` is the first route converted: 5 atomics per token, at least 500, capped at five times the flat price.++SIWX is a poor fit for per-call metered routes (a returning wallet is served without paying again), so the llm-proxy route does not enable it. A fixed-price or time-boxed `upto` route can set `siwx` normally.++## Buyer++`buildSolanaUptoPayload` in `api/_lib/x402/a2a-client.js` builds the payload with the official client scheme. It checks the offered cap against the agent's `maxPerCallAtomics` before anything is signed and throws `cap_exceeds_limit` when the cap is higher, exactly as the spending-cap layer treats an `exact` price. `x402-buyer-fetch.js` accepts `preferScheme: 'upto'` and releases the unused part of the reserved cap (`releaseUnusedCap`) after the claim lands, so a 25,000-atomic cap that settled 500 only counts 500 against the daily budget.++## Extensions++- **sign-in-with-x** works unchanged on `upto` routes that opt in with `siwx`. The grant is recorded from the charged amount.+- **offer-receipt**: the 402 carries a signed offer per accept (including the `upto` one) and the paid response carries a signed receipt for the measured charge when `OFFER_RECEIPT_SIGNING_PRIVATE_KEY` is configured. Buyers store it in the receipts ledger as before.++## Operating notes and limits++- Channel state is in the facilitator's in-memory store. A crash between the deposit and the claim leaves the channel open until the payer's `withdrawDelay` (900 s) elapses; the payer can then withdraw the deposit. Nothing is lost, but the seller forfeits that call's revenue.+- The sponsor key doubles as voucher signer. Keep it out of any `X402_PAY_TO_*` wallet and rotate it like the other sponsor secrets.+- The offered `maxTimeoutSeconds` is 600; the facilitator refuses channels that live longer than 3600 s.++## Batch settlement: finding++`@x402/svm` 2.28.0 ships `batch-settlement/{client,server,facilitator}`, so this is not a missing-package gap. What `batch-settlement` needs that `upto` does not:++1. A **durable voucher store**. The package exports only `MemoryBatchOperationStore`; vouchers are worth nothing until claimed, so losing the process loses revenue. A Postgres-backed `BatchOperationStore` plus a migration is required.+2. A **redemption worker**. `BatchSvmScheme.createChannelManager(...)` claims accumulated vouchers and distributes what settles, and must run on a schedule well inside the forced-close grace period (a Cloud Scheduler cron).+3. **Wiring the scheme's lifecycle hooks into `paidEndpoint`**: pre-settle (commit voucher charges for steady-state requests), post-settle (finalize deposits and refunds), and the abort and cancel hooks that drop reservations.+4. An **on-chain run**. The claim and distribute transactions can only be proven against a funded cluster; the local facilitator in `tests/helpers/` cannot stand in for them.++`upto` ships first because it needs none of that state. The `upto` spec option and the deposit-before-handler and cancel paths in `x402-paid-endpoint.js` are the template for the batch hooks.++## Tests++`tests/x402-upto.test.js` drives `paidEndpoint()` end to end with the real `upto` client and server schemes. The facilitator (`tests/helpers/upto-local-facilitator.js`) is test-controlled and replaces only the chain with an in-memory ledger; the buyer's ed25519 signature over the open transaction and the server's ed25519 voucher are both verified for real. Cases: the 402 shape, partial settlement and refund, a throwing handler settling nothing, clamping above the cap, a tampered deposit, the buyer cap refusal, and the offer-receipt on the paid response.++A real on-chain check needs funded wallets and is run by the owner; the commands are in the work-order close-out.diff --git a/prompts/finish/_context/beat-PROGRESS.md b/prompts/finish/_context/beat-PROGRESS.mdindex fd84b5e41..ac69abe5c 100644--- a/prompts/finish/_context/beat-PROGRESS.md+++ b/prompts/finish/_context/beat-PROGRESS.md@@ -7,3 +7,4 @@ Append one dated entry per finished or partially finished order: order number, c- 2026-10-23: order 612 (prepaid balances settled on-chain in batches) done. Ledger, batcher, route hook (`paidEndpoint({ mode: 'prepaid' })`), endpoints, crons and migration landed in a37074e67 (swept by another agent's commit); the interval fix, constants split, reconcile script, triage entry and docs landed in ed75c5946 (also swept by another agent); this commit closes the order and logs it. Remaining, owner-gated: apply migration 20261023160000 (`npm run db:status` first), fund the settler and set `X402_PREPAID_SETTLE_LIVE=1` for the first mainnet batch settlement (gate 1), details in the final report.- 2026-10-23: order 605 (owner-funded on-chain allowance budgets) done except the real devnet run: faucet 429 (owner or faucet is the dependency); the same lifecycle script passed on a local validator running the real program. Code landed in ed75c5946 (swept by another agent's commit); docs, pages, changelog and STRUCTURE row in the commit titled docs(wallet): document owner-funded on-chain agent budgets. Run `node scripts/allowance-devnet-proof.mjs` when devnet SOL is available.- 2026-10-23: order 602 (outcome-weighted memory and chained decision trail) implemented and proven against the live dev database: clean chain verifies ok, a manual edit fails at exactly the edited index, a loss-tied memory ranks below an equal win-tied one and is still returned. Code, migration 20261023150000 (applied alone via --file after db:status), tests, docs, STRUCTURE row and changelog landed in 22a5a1f49 and 2b7bb3921 (swept by other agents' commits). The per-agent hash chain, verify route and badge already existed, so no backfill was needed. Order file left in place: the full `npm test` and `npm run audit:docs` could not be run cleanly here (broken local node_modules install; audit polluted by node_modules.bak). Owner: reinstall deps, then run both and delete the order file if green.+- 2026-10-23: order 607 (x402 upto, sign-in-with-x and offer-receipt) PARTIAL: upto done and tested; the order file stays. The scheme module, spec and paidEndpoint wiring, buyer cap refusal and the local test facilitator landed in 22a5a1f49 and 2b7bb3921 (swept by other agents' commits); the llm-proxy conversion, tests/x402-upto.test.js, docs/x402-upto.md, STRUCTURE row, pages entry and changelog landed in the commit titled feat(x402). Remaining: step 5 batch settlement. @x402/svm 2.28 ships batch-settlement, so it is not a package gap; it needs a Postgres BatchOperationStore with a migration, a scheduled redemption worker around createChannelManager, and the scheme lifecycle hooks wired into paidEndpoint (detail in docs/x402-upto.md). Owner-gated: the first real mainnet upto settlement (gate 1), command in the final report.diff --git a/tests/x402-upto.test.js b/tests/x402-upto.test.jsnew file mode 100644index 000000000..46ebf311e--- /dev/null+++ b/tests/x402-upto.test.js@@ -0,0 +1,370 @@+// x402 v2 `upto` on Solana, end to end through paidEndpoint().+//+// Real: the @x402/svm upto CLIENT (builds and signs the channel open+// transaction), the @x402/svm upto SERVER scheme (advertises the offer and signs+// the claim voucher), x402-spec.js, and the paidEndpoint wrapper. Test-controlled:+// the facilitator (tests/helpers/upto-local-facilitator.js), which keeps every+// signature check real (buyer open-tx ed25519, server voucher ed25519) and+// replaces only the chain with an in-memory ledger.++import { Readable } from 'node:stream';++import { generateKeyPairSigner } from '@solana/kit';+import { beforeAll, afterAll, beforeEach, describe, expect, it, vi } from 'vitest';++import { UptoLocalFacilitator } from './helpers/upto-local-facilitator.js';++vi.mock('@coinbase/x402', () => ({ createCdpAuthHeaders: vi.fn(async () => ({})) }));++const USDC_MAINNET = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';+const SOLANA_MAINNET = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';+const CAP = 50_000n; // 0.05 USDC++let paidEndpoint;+let uptoMod;+let specMod;+let facilitator;+let operator;+let payer;+let payTo;++function mockReqRes({ method = 'GET', headers = {}, url = '/api/x402/upto-test' } = {}) {+ const lower = {};+ for (const [k, v] of Object.entries(headers)) lower[k.toLowerCase()] = v;+ const req = Object.assign(new Readable({ read() {} }), {+ method,+ url,+ headers: lower,+ connection: { remoteAddress: '127.0.0.1' },+ socket: { remoteAddress: '127.0.0.1' },+ });+ req.push(null);+ const chunks = [];+ const resHeaders = {};+ const res = {+ statusCode: 200,+ writableEnded: false,+ setHeader(k, v) {+ resHeaders[k.toLowerCase()] = v;+ },+ getHeader(k) {+ return resHeaders[k.toLowerCase()];+ },+ end(body) {+ if (body !== undefined) chunks.push(body);+ res.writableEnded = true;+ },+ write(chunk) {+ chunks.push(chunk);+ },+ get body() {+ return chunks.join('');+ },+ get headers() {+ return resHeaders;+ },+ };+ return { req, res };+}++function decodeHeader(res, name) {+ return JSON.parse(Buffer.from(String(res.getHeader(name)), 'base64').toString('utf8'));+}++function make402Challenge(res) {+ const header = res.getHeader('payment-required');+ return header ? decodeHeader(res, 'payment-required') : JSON.parse(res.body);+}++const BAZAAR = {+ discoverable: true,+ info: {+ input: { type: 'object', properties: {}, required: [] },+ output: { type: 'object', properties: { ok: { type: 'boolean' } } },+ },+ schema: { type: 'object' },+};++let routeSeq = 0;+function makeEndpoint({ handler, upto, siwx }) {+ routeSeq += 1;+ return paidEndpoint({+ route: `/api/x402/upto-test-${routeSeq}`,+ method: 'GET',+ networks: ['solana'],+ description: 'upto integration test',+ bazaar: BAZAAR,+ handler,+ upto,+ siwx,+ });+}++async function uptoAccept(endpoint, route) {+ const { req, res } = mockReqRes({ url: route });+ await endpoint(req, res);+ expect(res.statusCode).toBe(402);+ const challenge = make402Challenge(res);+ const accept = challenge.accepts.find((a) => a.scheme === 'upto');+ return { challenge, accept };+}++async function signPayment(accept, signer = payer) {+ const { UptoSvmScheme } = await import('@x402/svm/upto/client');+ const built = await new UptoSvmScheme(signer).createPaymentPayload(2, accept);+ return Buffer.from(+ JSON.stringify({ x402Version: 2, accepted: accept, payload: built.payload }),+ ).toString('base64');+}++beforeAll(async () => {+ process.env.X402_ALLOW_MEMORY_FALLBACK = '1';+ delete process.env.DATABASE_URL;+ delete process.env.CDP_API_KEY_ID;+ delete process.env.CDP_API_KEY_SECRET;+ delete process.env.X402_BUILDER_CODE_APP;++ operator = await generateKeyPairSigner();+ payer = await generateKeyPairSigner();+ payTo = (await generateKeyPairSigner()).address;++ process.env.X402_PAY_TO_SOLANA = payTo;+ process.env.X402_ASSET_MINT_SOLANA = USDC_MAINNET;+ process.env.X402_MAX_AMOUNT_REQUIRED = '1000';+ const { generatePrivateKey } = await import('viem/accounts');+ process.env.OFFER_RECEIPT_SIGNING_PRIVATE_KEY = generatePrivateKey();++ uptoMod = await import('../api/_lib/x402/upto.js');+ specMod = await import('../api/_lib/x402-spec.js');+ ({ paidEndpoint } = await import('../api/_lib/x402-paid-endpoint.js'));++ // A real blockhash-shaped value and slot so the client never needs an RPC.+ const fakeChainState = (await generateKeyPairSigner()).address;+ facilitator = new UptoLocalFacilitator({ feePayerAddress: operator.address });+ const baseExtra = facilitator.getExtra.bind(facilitator);+ facilitator.getExtra = () => ({+ ...baseExtra(),+ recentBlockhash: fakeChainState,+ lastValidBlockHeight: '1000',+ recentSlot: '500',+ });++ const { UptoSvmScheme: ServerScheme } = await import('@x402/svm/upto/server');+ uptoMod.setUptoBundleForTests({+ facilitator,+ server: new ServerScheme({ receiverAuthorizerSigner: operator }),+ signer: operator,+ });+});++afterAll(() => {+ uptoMod?.setUptoBundleForTests(null);+});++beforeEach(() => {+ facilitator.events.length = 0;+});++describe('upto 402 challenge', () => {+ it('advertises the upto scheme with the cap, receiver authorizer and fee payer', async () => {+ const endpoint = makeEndpoint({+ handler: async () => ({ ok: true }),+ upto: { capAtomics: CAP, charge: () => 10_000n },+ });+ const { challenge, accept } = await uptoAccept(endpoint, '/api/x402/upto-test-1');+ console.log('402 body:\n' + JSON.stringify(challenge, null, 2));+ expect(accept).toBeTruthy();+ expect(accept.amount).toBe(String(CAP));+ expect(accept.network).toBe(SOLANA_MAINNET);+ expect(accept.asset).toBe(USDC_MAINNET);+ expect(accept.payTo).toBe(payTo);+ expect(accept.extra.receiverAuthorizer).toBe(operator.address);+ expect(accept.extra.feePayer).toBe(operator.address);+ expect(accept.extra.withdrawDelay).toBeGreaterThan(0);+ expect(accept.maxTimeoutSeconds).toBeLessThanOrEqual(uptoMod.UPTO_MAX_TIMEOUT_SECONDS);+ });+});++describe('upto extensions', () => {+ it('advertises sign-in-with-x and offer-receipt beside the upto accept', async () => {+ const endpoint = makeEndpoint({+ handler: async () => ({ ok: true }),+ upto: { capAtomics: CAP, charge: () => 1n },+ siwx: { statement: 'Sign in to re-access without paying again', ttlSeconds: 3600 },+ });+ const { challenge, accept } = await uptoAccept(endpoint, '/api/x402/upto-test-' + routeSeq);+ console.log('402 extensions:\n' + JSON.stringify(Object.keys(challenge.extensions)));+ expect(accept.scheme).toBe('upto');+ expect(challenge.extensions['sign-in-with-x']).toBeTruthy();+ expect(challenge.extensions['offer-receipt']).toBeTruthy();+ });+});++describe('llm-proxy route', () => {+ it('offers upto beside exact on the live route, with the extensions', async () => {+ const mod = await import('../api/x402/llm-proxy.js');+ const { req, res } = mockReqRes({ method: 'POST', url: '/api/x402/llm-proxy' });+ await mod.default(req, res);+ expect(res.statusCode).toBe(402);+ const challenge = JSON.parse(res.body);+ console.log('llm-proxy 402 accepts:\n' + JSON.stringify(challenge.accepts, null, 2));+ console.log('llm-proxy 402 extensions: ' + Object.keys(challenge.extensions).join(', '));+ const schemes = challenge.accepts.map((a) => a.scheme);+ expect(schemes).toContain('exact');+ expect(schemes).toContain('upto');+ expect(challenge.accepts.find((a) => a.scheme === 'upto').amount).toBe('25000');+ expect(challenge.extensions['offer-receipt']).toBeTruthy();+ });+});++describe('upto receipt', () => {+ it('returns a signed offer-receipt for the measured charge', async () => {+ const endpoint = makeEndpoint({+ handler: async () => ({ ok: true }),+ upto: { capAtomics: CAP, charge: () => 7_000n },+ });+ const route = '/api/x402/upto-test-' + routeSeq;+ const { accept } = await uptoAccept(endpoint, route);+ const header = await signPayment(accept);+ const { req, res } = mockReqRes({ url: route, headers: { 'x-payment': header } });+ await endpoint(req, res);+ expect(res.statusCode).toBe(200);+ const settled = decodeHeader(res, 'x-payment-response');+ const receipt = settled.extensions?.['offer-receipt'];+ console.log('offer-receipt:\n' + JSON.stringify(receipt, null, 2));+ expect(receipt?.info?.receipt).toBeTruthy();+ expect(receipt.info.receipt.signature).toBeTruthy();+ });+});++describe('upto settlement', () => {+ it('settles the measured amount, not the cap, and refunds the rest', async () => {+ const handler = vi.fn(async () => ({ ok: true }));+ const endpoint = makeEndpoint({+ handler,+ upto: { capAtomics: CAP, charge: () => 12_345n },+ });+ const route = '/api/x402/upto-test-' + routeSeq;+ const { accept } = await uptoAccept(endpoint, route);+ const header = await signPayment(accept);++ const { req, res } = mockReqRes({ url: route, headers: { 'x-payment': header } });+ await endpoint(req, res);++ expect(res.statusCode).toBe(200);+ expect(JSON.parse(res.body)).toEqual({ ok: true });+ expect(handler).toHaveBeenCalledTimes(1);++ const [deposit, claim] = facilitator.events;+ expect(deposit.kind).toBe('deposit');+ expect(deposit.amount).toBe(CAP);+ expect(claim.kind).toBe('claim');+ expect(claim.paid).toBe(12_345n);+ expect(claim.refunded).toBe(CAP - 12_345n);+ expect(claim.payTo).toBe(payTo);++ const receipt = decodeHeader(res, 'x-payment-response');+ expect(receipt.success).toBe(true);+ });++ it('settles nothing and refunds the whole deposit when the handler throws', async () => {+ const endpoint = makeEndpoint({+ handler: async () => {+ throw new Error('handler exploded');+ },+ upto: { capAtomics: CAP, charge: () => 10_000n },+ });+ const route = '/api/x402/upto-test-' + routeSeq;+ const { accept } = await uptoAccept(endpoint, route);+ const header = await signPayment(accept);++ const { req, res } = mockReqRes({ url: route, headers: { 'x-payment': header } });+ await endpoint(req, res).catch(() => {});++ expect(res.statusCode).toBeGreaterThanOrEqual(500);+ const paid = facilitator.events.filter((e) => e.kind === 'claim');+ expect(paid).toHaveLength(0);+ const cancel = facilitator.events.find((e) => e.kind === 'cancel');+ expect(cancel).toBeTruthy();+ expect(cancel.paid).toBe(0n);+ expect(cancel.refunded).toBe(CAP);+ });++ it('clamps a charge above the cap to the cap', async () => {+ const endpoint = makeEndpoint({+ handler: async () => ({ ok: true }),+ upto: { capAtomics: CAP, charge: () => CAP * 10n },+ });+ const route = '/api/x402/upto-test-' + routeSeq;+ const { accept } = await uptoAccept(endpoint, route);+ const header = await signPayment(accept);+ const { req, res } = mockReqRes({ url: route, headers: { 'x-payment': header } });+ await endpoint(req, res);+ expect(res.statusCode).toBe(200);+ expect(facilitator.events.find((e) => e.kind === 'claim').paid).toBe(CAP);+ });++ it('rejects a payment whose signed deposit differs from the cap', async () => {+ const endpoint = makeEndpoint({+ handler: async () => ({ ok: true }),+ upto: { capAtomics: CAP, charge: () => 1n },+ });+ const route = '/api/x402/upto-test-' + routeSeq;+ const { accept } = await uptoAccept(endpoint, route);+ const lowered = { ...accept, amount: String(CAP / 2n) };+ const header = await signPayment(lowered);+ const { req, res } = mockReqRes({ url: route, headers: { 'x-payment': header } });+ await endpoint(req, res);+ expect(res.statusCode).toBe(402);+ expect(facilitator.events).toHaveLength(0);+ });+});++describe('upto buyer', () => {+ it('refuses a cap above the agent per-call limit before signing anything', async () => {+ const { buildSolanaUptoPayload } = await import('../api/_lib/x402/a2a-client.js');+ const endpoint = makeEndpoint({+ handler: async () => ({ ok: true }),+ upto: { capAtomics: CAP, charge: () => 1n },+ });+ const { accept } = await uptoAccept(endpoint, '/api/x402/upto-test-' + routeSeq);+ await expect(+ buildSolanaUptoPayload({+ accept,+ signer: payer,+ resource: 'https://three.ws/x',+ maxPerCallAtomics: CAP - 1n,+ }),+ ).rejects.toMatchObject({ code: 'cap_exceeds_limit' });+ });++ it('signs when the cap is within the per-call limit', async () => {+ const { buildSolanaUptoPayload } = await import('../api/_lib/x402/a2a-client.js');+ const endpoint = makeEndpoint({+ handler: async () => ({ ok: true }),+ upto: { capAtomics: CAP, charge: () => 1n },+ });+ const { accept } = await uptoAccept(endpoint, '/api/x402/upto-test-' + routeSeq);+ const built = await buildSolanaUptoPayload({+ accept,+ signer: payer,+ resource: 'https://three.ws/x',+ maxPerCallAtomics: CAP,+ });+ expect(built.scheme).toBe('upto');+ expect(built.payload.deposit).toBe(String(CAP));+ expect(built.payload.from).toBe(payer.address);+ });+});++describe('upto spec helpers', () => {+ it('exports the scheme helpers', () => {+ expect(typeof specMod.verifyPayment).toBe('function');+ expect(uptoMod.isUptoRequirement({ scheme: 'upto' })).toBe(true);+ expect(uptoMod.isUptoRequirement({ scheme: 'exact' })).toBe(false);+ expect(uptoMod.normaliseCharge('5', '10')).toBe(5n);+ expect(uptoMod.normaliseCharge('50', '10')).toBe(10n);+ expect(() => uptoMod.normaliseCharge('-1', '10')).toThrow(/negative/);+ expect(() => uptoMod.normaliseCharge('abc', '10')).toThrow(/integer/);+ });+});