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): re-read the challenge and settle once more when a paid replay 402s
nirholasf53f44089609
diff --git a/api/_lib/x402/pay.js b/api/_lib/x402/pay.jsindex 5e0640f20..2e6260183 100644--- a/api/_lib/x402/pay.js+++ b/api/_lib/x402/pay.js@@ -344,110 +344,148 @@ export async function payX402({};}- const accept = parseSolanaAccept(probe.body);+ let accept = parseSolanaAccept(probe.body);if (!accept) {return { success: false, paid: false, free: false, skipped: true, amountAtomic: 0, txSig: null, status: 402, responseBody: probe.body, errorMsg: 'no_solana_accept' };}- if (!USDC_MINT || accept.asset !== USDC_MINT) {- return { success: false, paid: false, free: false, skipped: true, amountAtomic: 0, txSig: null, status: 402, responseBody: probe.body, errorMsg: `unexpected_asset:${accept.asset}` };- }- if (!selfPay && !accept.extra?.feePayer) {- return { success: false, paid: false, free: false, skipped: true, amountAtomic: 0, txSig: null, status: 402, responseBody: probe.body, errorMsg: 'missing_fee_payer' };- }- // Pre-broadcast recipient gate. A thrown hook is a fail-closed refusal, never- // a crash — the whole point is to stop money moving to an unexpected payTo.- if (typeof onAccept === 'function') {- let hook;- try {- hook = await onAccept(accept);- } catch (err) {- hook = { abort: true, reason: `onaccept_error:${String(err?.message || err).slice(0, 80)}` };+ // One attempt = validate THIS accept, build + sign a transaction for it, and+ // replay the request carrying the payment. Returns either a terminal `skip`+ // (a guard refused before money could move) or the paid response.+ async function attemptSettle(currentAccept, attemptNonce) {+ if (!USDC_MINT || currentAccept.asset !== USDC_MINT) {+ return { skip: { success: false, paid: false, free: false, skipped: true, amountAtomic: 0, txSig: null, status: 402, responseBody: probe.body, errorMsg: `unexpected_asset:${currentAccept.asset}` } };}- if (hook?.abort) {- return {- success: false, paid: false, free: false, skipped: true, refusedByHook: true,- amountAtomic: Number(accept.amount || 0), txSig: null, status: 402,- responseBody: probe.body, errorMsg: hook.reason || 'onaccept_abort',- };+ if (!selfPay && !currentAccept.extra?.feePayer) {+ return { skip: { success: false, paid: false, free: false, skipped: true, amountAtomic: 0, txSig: null, status: 402, responseBody: probe.body, errorMsg: 'missing_fee_payer' } };}- }- const amountAtomic = Number(accept.amount || 0);- if (amountAtomic > remainingCap) {- warnCapExceeded(url, amountAtomic, Number.isFinite(remainingCap) ? remainingCap : 0);- return { success: false, paid: false, free: false, skipped: true, amountAtomic, txSig: null, status: 402, responseBody: probe.body, errorMsg: 'cap_would_exceed' };- }+ // Pre-broadcast recipient gate. A thrown hook is a fail-closed refusal, never+ // a crash. The whole point is to stop money moving to an unexpected payTo.+ // Re-run per attempt: a re-fetched challenge may name a different payTo, and+ // the ring's allowlist must judge the accept we are actually paying.+ if (typeof onAccept === 'function') {+ let hook;+ try {+ hook = await onAccept(currentAccept);+ } catch (err) {+ hook = { abort: true, reason: `onaccept_error:${String(err?.message || err).slice(0, 80)}` };+ }+ if (hook?.abort) {+ return { skip: {+ success: false, paid: false, free: false, skipped: true, refusedByHook: true,+ amountAtomic: Number(currentAccept.amount || 0), txSig: null, status: 402,+ responseBody: probe.body, errorMsg: hook.reason || 'onaccept_abort',+ } };+ }+ }- // Fee ceiling — refuse to send a payment whose fee config could exceed- // X402_RING_MAX_FEE_PER_TX_LAMPORTS. A structured skip, not a throw: the- // caller records it like any other guard rejection. This is the runtime- // twin of the fee-floor regression tests over expectedFeeLamports().- const feeConfig = ringFeeConfig(nonce, { selfPay });- const worstCaseFeeLamports = expectedFeeLamports({- selfPay,- priorityMicrolamports: feeConfig.microLamports,- cuLimit: feeConfig.cuLimit,- });- const maxFeeLamports = ringMaxFeePerTxLamports();- if (worstCaseFeeLamports > maxFeeLamports) {- return {- success: false, paid: false, free: false, skipped: true,- amountAtomic, txSig: null, status: 402, responseBody: probe.body,- errorMsg: `fee_ceiling_exceeded:${worstCaseFeeLamports}>${maxFeeLamports}`,- };- }+ const attemptAmount = Number(currentAccept.amount || 0);+ if (attemptAmount > remainingCap) {+ warnCapExceeded(url, attemptAmount, Number.isFinite(remainingCap) ? remainingCap : 0);+ return { skip: { success: false, paid: false, free: false, skipped: true, amountAtomic: attemptAmount, txSig: null, status: 402, responseBody: probe.body, errorMsg: 'cap_would_exceed' } };+ }- // Fee-budget admission: the caller-side twin of the settle path's wallet fee- // governor. Everything past this point (an ATA read, a signature, a facilitator- // verify that simulates against an RPC node) is wasted when the fee wallet's- // daily budget is already spent, because settleRingPayment() refuses at the end- // regardless. Checking here collapses a full handshake into one skipped call.- // Fails open: assessFeeAdmission() admits whenever it cannot price the call,- // so this can only ever remove doomed work, never block a fundable payment.- const feeWalletB58 = selfPay ? buyer?.publicKey?.toBase58() : accept.extra?.feePayer;- if (feeWalletB58) {- const admission = await assessFeeAdmission({- feeWalletB58,- estFeeLamports: worstCaseFeeLamports,- connection: conn,+ // Fee ceiling: refuse to send a payment whose fee config could exceed+ // X402_RING_MAX_FEE_PER_TX_LAMPORTS. A structured skip, not a throw: the+ // caller records it like any other guard rejection. This is the runtime+ // twin of the fee-floor regression tests over expectedFeeLamports().+ const feeConfig = ringFeeConfig(attemptNonce, { selfPay });+ const worstCaseFeeLamports = expectedFeeLamports({+ selfPay,+ priorityMicrolamports: feeConfig.microLamports,+ cuLimit: feeConfig.cuLimit,});- if (!admission.ok) {- return {+ const maxFeeLamports = ringMaxFeePerTxLamports();+ if (worstCaseFeeLamports > maxFeeLamports) {+ return { skip: {success: false, paid: false, free: false, skipped: true,- amountAtomic, txSig: null, status: 402, responseBody: probe.body,- errorMsg: admission.reason || 'fee_runway_exhausted',- };+ amountAtomic: attemptAmount, txSig: null, status: 402, responseBody: probe.body,+ errorMsg: `fee_ceiling_exceeded:${worstCaseFeeLamports}>${maxFeeLamports}`,+ } };+ }++ // Fee-budget admission: the caller-side twin of the settle path's wallet fee+ // governor. Everything past this point (an ATA read, a signature, a facilitator+ // verify that simulates against an RPC node) is wasted when the fee wallet's+ // daily budget is already spent, because settleRingPayment() refuses at the end+ // regardless. Checking here collapses a full handshake into one skipped call.+ // Fails open: assessFeeAdmission() admits whenever it cannot price the call,+ // so this can only ever remove doomed work, never block a fundable payment.+ const feeWalletB58 = selfPay ? buyer?.publicKey?.toBase58() : currentAccept.extra?.feePayer;+ if (feeWalletB58) {+ const admission = await assessFeeAdmission({+ feeWalletB58,+ estFeeLamports: worstCaseFeeLamports,+ connection: conn,+ });+ if (!admission.ok) {+ return { skip: {+ success: false, paid: false, free: false, skipped: true,+ amountAtomic: attemptAmount, txSig: null, status: 402, responseBody: probe.body,+ errorMsg: admission.reason || 'fee_runway_exhausted',+ } };+ }}++ // Step 2: does the receiver ATA already exist? (saves an idempotent create ix)+ const receiverAta = getAssociatedTokenAddressSync(+ new PublicKey(currentAccept.asset), new PublicKey(currentAccept.payTo),+ false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,+ );+ const receiverAtaInfo = await conn.getAccountInfo(receiverAta).catch(() => null);++ // Step 3: build the signed transaction + X-PAYMENT envelope.+ const txBase64 = buildPaymentTx({+ accept: currentAccept, buyer, blockhash, mintInfo,+ receiverAtaExists: receiverAtaInfo !== null,+ nonce: attemptNonce, selfPay,+ });+ const xPayment = Buffer.from(JSON.stringify({+ x402Version: 2,+ scheme: 'exact',+ network: currentAccept.network,+ resource: { url, mimeType: 'application/json' },+ payload: { transaction: txBase64 },+ accepted: currentAccept,+ })).toString('base64');++ // Step 4: replay the request carrying the payment.+ const paidRes = await fetchWithTimeout(url, {+ ...reqInit,+ headers: { ...reqInit.headers, 'x-payment': xPayment },+ });+ return { paidRes, amountAtomic: attemptAmount };}- // Step 2 — does the receiver ATA already exist? (saves an idempotent create ix)- const receiverAta = getAssociatedTokenAddressSync(- new PublicKey(accept.asset), new PublicKey(accept.payTo),- false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,- );- const receiverAtaInfo = await conn.getAccountInfo(receiverAta).catch(() => null);-- // Step 3 — build the signed transaction + X-PAYMENT envelope.- const txBase64 = buildPaymentTx({- accept, buyer, blockhash, mintInfo,- receiverAtaExists: receiverAtaInfo !== null,- nonce, selfPay,- });- const xPayment = Buffer.from(JSON.stringify({- x402Version: 2,- scheme: 'exact',- network: accept.network,- resource: { url, mimeType: 'application/json' },- payload: { transaction: txBase64 },- accepted: accept,- })).toString('base64');-- // Step 4 — replay the request carrying the payment.- const paidRes = await fetchWithTimeout(url, {- ...reqInit,- headers: { ...reqInit.headers, 'x-payment': xPayment },- });+ // A 402 on the PAID replay means the endpoint refused the payment we just+ // built: the quote moved between probe and replay, the requirements were+ // re-issued, or the proof did not match what the route now advertises. The+ // signed transfer is never broadcast in that case (the facilitator settles only+ // after verify passes), so no money moved and exactly one retry against a+ // FRESHLY fetched challenge is safe. Bounded at one: a route that 402s twice+ // is reported as before. Every other status (200, 4xx, 5xx) is returned on the+ // first attempt, so nothing changes for a call that already works.+ let currentAccept = accept;+ let attemptNonce = nonce;+ let retriedAfter402 = false;+ let paidRes;+ let amountAtomic = 0;+ for (;;) {+ const outcome = await attemptSettle(currentAccept, attemptNonce);+ if (outcome.skip) return { ...outcome.skip, retriedAfter402 };+ paidRes = outcome.paidRes;+ amountAtomic = outcome.amountAtomic;+ if (paidRes.status !== 402 || retriedAfter402) break;+ const reprobe = await fetchWithTimeout(url, reqInit).catch(() => null);+ const fresh = reprobe?.status === 402 ? parseSolanaAccept(reprobe.body) : null;+ if (!fresh) break;+ retriedAfter402 = true;+ currentAccept = fresh;+ // A fresh nonce keeps the retry transaction byte-distinct from the refused+ // one, so a re-quote at the SAME amount cannot compile to the same signature.+ attemptNonce = nextAutoNonce();+ }let txSig = null;if (paidRes.ok) {@@ -465,5 +503,6 @@ export async function payX402({amountAtomic, txSig, status: paidRes.status,responseBody: paidRes.body,errorMsg: paidRes.ok ? null : `http_${paidRes.status}`,+ retriedAfter402,};}diff --git a/docs/autonomous-x402.md b/docs/autonomous-x402.mdindex 2a67e6cf2..0178ea520 100644--- a/docs/autonomous-x402.md+++ b/docs/autonomous-x402.md@@ -29,10 +29,17 @@ Each tick:those whose Redis cooldown has elapsed — sorted by priority descending.2. For each entry, probes the endpoint for a `402` challenge, builds a SolanaUSDC payment, and fires the request with an `X-PAYMENT` header.-3. Records every call (success **and** failure) to `x402_autonomous_log`.-4. For `oracle` / `sniper` pipeline entries, extracts signal data and upserts it+3. If the paid replay itself answers `402`, re-fetches the challenge once and+ settles against the **fresh** requirements before giving up. A 402 on the+ replay means the endpoint refused the proof (a re-quote between probe and+ replay, or re-issued requirements), and the signed transfer is never+ broadcast in that case, so no money moved and one retry is safe. The retry is+ bounded at one attempt, re-applies the spend cap and the recipient allowlist+ to the new quote, and is reported as `retriedAfter402` by the buyer client.+4. Records every call (success **and** failure) to `x402_autonomous_log`.+5. For `oracle` / `sniper` pipeline entries, extracts signal data and upserts itinto `oracle_intel_signals` for the sniper oracle gate to consume.-5. Enforces a **daily USDC spend cap** across all calls in the loop.+6. Enforces a **daily USDC spend cap** across all calls in the loop.Payments are real on chain — no mocks, no simulations.@@ -197,7 +204,7 @@ corroborate — the ops financial-integrity surface alerts on those. Detail:| Sink | Written by ||---|---|-| `x402_autonomous_log` | Every call (success or failure), with `signal_data` / `value_extracted`. |+| `x402_autonomous_log` | Every call (success or failure), with `signal_data` / `value_extracted`. `error_msg` is reserved for calls that actually failed: the external uptime monitor probes third-party services for free and records an alive-but-unexpected status (a templated path answering 400, a verb-picky route answering 405) in `value_extracted.status` only, so a liveness observation never lands in the loop's failure stats. || `oracle_intel_signals` | `oracle` / `sniper` entries, keyed by source + topic; consumed by the sniper oracle gate. Each row carries `tx_signature`, the settle signature of the paid call that bought it, so a gate decision can cite its receipt (surfaced as `signal_receipts` on gate results). || `forge_creations` | Every settled `POST /api/x402/forge` generation (any buyer, not just this loop). The row lands in the public community gallery with `x402_payer` / `x402_tx_sig` / `x402_price_atomic` provenance; the gallery renders a Solscan-linked "x402 · $price" badge. Inline-done lanes materialize immediately; async lanes store the full job token and `api/cron/forge-finalize` completes them server-side. || `agent_custody_events` | The USDC spend, with `category: 'x402'` (see [Money feed](money-feed.md)). |diff --git a/tests/x402-pay-402-retry.test.js b/tests/x402-pay-402-retry.test.jsnew file mode 100644index 000000000..4f7df29d5--- /dev/null+++ b/tests/x402-pay-402-retry.test.js@@ -0,0 +1,171 @@+import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'vitest';+import http from 'node:http';+import { Keypair } from '@solana/web3.js';++// A 402 on the PAID replay (not the probe) means the endpoint refused the proof+// we just built: the quote moved between probe and replay, or the requirements+// were re-issued. payX402 used to report that as terminal `http_402` and drop the+// call, which is what the autonomous log recorded across skill-marketplace,+// club-cover and billboard. The signed transfer is never broadcast when verify+// refuses, so no money moved and one retry against a FRESHLY fetched challenge+// is safe.+//+// These tests drive the real payX402 against a local 402 server: the Solana+// transfer is genuinely built and signed (valid base58 keys below), but the mock+// never touches a chain, so nothing is broadcast and nothing is spent.++const USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';+process.env.X402_ASSET_MINT_SOLANA = USDC;++const { payX402 } = await import('../api/_lib/x402/pay.js');++const payTo = Keypair.generate().publicKey.toBase58();+const feePayer = Keypair.generate().publicKey.toBase58();++function accept(amount) {+ return {+ scheme: 'exact',+ network: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',+ asset: USDC,+ payTo,+ amount: String(amount),+ extra: { name: 'USDC', decimals: 6, feePayer },+ };+}++// Per-test script: how many PAID replays answer 402 before the endpoint accepts.+let paidReplays402 = 0;+// Quote handed out by the challenge. Bumped by the server to model a re-price.+let quote = 1000;+// Observed traffic, so a test can assert how many probes and paid attempts ran.+let probes = 0;+let paidAttempts = 0;++let server;+let origin;++beforeAll(async () => {+ server = http.createServer((req, res) => {+ const paymentHeader = req.headers['x-payment'];+ if (!paymentHeader) {+ probes++;+ res.statusCode = 402;+ res.setHeader('content-type', 'application/json');+ res.end(JSON.stringify({ x402Version: 2, accepts: [accept(quote)] }));+ return;+ }+ paidAttempts++;+ if (paidReplays402 > 0) {+ paidReplays402--;+ // Re-price on refusal so the retry has to read the FRESH challenge to+ // pay the right amount. A retry that replayed the cached requirements+ // would keep paying the stale quote and 402 forever.+ quote += 500;+ res.statusCode = 402;+ res.setHeader('content-type', 'application/json');+ res.end(JSON.stringify({ x402Version: 2, accepts: [accept(quote)], error: 'requirements_changed' }));+ return;+ }+ const decoded = JSON.parse(Buffer.from(paymentHeader, 'base64').toString('utf8'));+ res.statusCode = 200;+ res.setHeader('content-type', 'application/json');+ res.setHeader(+ 'x-payment-response',+ Buffer.from(JSON.stringify({ success: true, transaction: `SIG_${decoded.accepted.amount}` })).toString('base64'),+ );+ res.end(JSON.stringify({ ok: true, paidAmount: decoded.accepted.amount }));+ });+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));+ origin = `http://127.0.0.1:${server.address().port}`;+});++afterAll(async () => {+ await new Promise((resolve) => server.close(resolve));+});++beforeEach(() => {+ paidReplays402 = 0;+ quote = 1000;+ probes = 0;+ paidAttempts = 0;+});++// A buyer keypair is enough: buildPaymentTx only needs a signer, a blockhash and+// the mint decimals, and self-pay skips the sponsor co-sign entirely.+const buyer = Keypair.generate();+const payCtx = {+ buyer,+ conn: { getAccountInfo: async () => ({ lamports: 1 }) },+ blockhash: '11111111111111111111111111111111',+ mintInfo: { decimals: 6 },+ selfPay: true,+};++describe('payX402 402-on-replay handling', () => {+ it('leaves a call that settles on the first replay untouched', async () => {+ const r = await payX402({ url: `${origin}/ok`, method: 'GET', ...payCtx, remainingCap: 100_000 });+ expect(r.paid).toBe(true);+ expect(r.status).toBe(200);+ expect(r.amountAtomic).toBe(1000);+ expect(r.retriedAfter402).toBe(false);+ // Exactly one probe and one paid attempt: no extra traffic for working routes.+ expect(probes).toBe(1);+ expect(paidAttempts).toBe(1);+ });++ it('re-fetches the challenge and settles the re-quoted amount after one 402', async () => {+ paidReplays402 = 1;+ const r = await payX402({ url: `${origin}/requote`, method: 'GET', ...payCtx, remainingCap: 100_000 });+ expect(r.paid).toBe(true);+ expect(r.status).toBe(200);+ expect(r.retriedAfter402).toBe(true);+ // The retry paid the NEW quote, which is only possible by re-reading the+ // challenge rather than replaying the stale requirements.+ expect(r.amountAtomic).toBe(1500);+ expect(r.responseBody.paidAmount).toBe('1500');+ expect(probes).toBe(2);+ expect(paidAttempts).toBe(2);+ });++ it('gives up after exactly one retry when the endpoint 402s again', async () => {+ paidReplays402 = 5;+ const r = await payX402({ url: `${origin}/always402`, method: 'GET', ...payCtx, remainingCap: 100_000 });+ expect(r.paid).toBe(false);+ expect(r.status).toBe(402);+ expect(r.errorMsg).toBe('http_402');+ expect(r.retriedAfter402).toBe(true);+ // Bounded: two paid attempts total, never a retry storm.+ expect(paidAttempts).toBe(2);+ });++ it('re-applies the spend cap to the re-quoted amount instead of overpaying', async () => {+ paidReplays402 = 1;+ // The first quote (1000) fits the cap; the re-quote (1500) does not.+ const r = await payX402({ url: `${origin}/requote`, method: 'GET', ...payCtx, remainingCap: 1200 });+ expect(r.paid).toBe(false);+ expect(r.skipped).toBe(true);+ expect(r.errorMsg).toBe('cap_would_exceed');+ expect(r.amountAtomic).toBe(1500);+ // The over-cap re-quote was refused before a second payment was sent.+ expect(paidAttempts).toBe(1);+ });++ it('re-runs the recipient gate against the re-fetched accept', async () => {+ paidReplays402 = 1;+ const seen = [];+ const r = await payX402({+ url: `${origin}/requote`, method: 'GET', ...payCtx, remainingCap: 100_000,+ onAccept: (a) => {+ seen.push(Number(a.amount));+ // Refuse the re-quoted challenge: an allowlist must judge the accept+ // actually being paid, not only the first one.+ return seen.length > 1 ? { abort: true, reason: 'requote_refused' } : null;+ },+ });+ expect(seen).toEqual([1000, 1500]);+ expect(r.paid).toBe(false);+ expect(r.refusedByHook).toBe(true);+ expect(r.errorMsg).toBe('requote_refused');+ expect(paidAttempts).toBe(1);+ });+});