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
fix(x402): give each loop payment its own nonce so same-price calls stop colliding into 502s
nirholas674173cff882
diff --git a/api/_lib/ops/x402-settle-health.js b/api/_lib/ops/x402-settle-health.jsindex f32847e53..3dc83d1a0 100644--- a/api/_lib/ops/x402-settle-health.js+++ b/api/_lib/ops/x402-settle-health.js@@ -73,6 +73,14 @@ const MIN_ATTEMPTS = 20;const OK_RATE = 0.9;const DOWN_RATE = 0.5;+// Pipelines that record rows in x402_autonomous_log but never pay: their+// failures are a third party being slow, not our settle rail. The external+// service uptime monitor (`reliability`, price_atomic 0 in autonomous-registry.js)+// sends unpaid HEAD probes with a short timeout, and on 2026-09-30 its+// `This operation was aborted` rows for slow third-party hosts were 5 of the 60+// "rail faults" behind a degraded 74.9%, while not one of them touched a payment.+export const UNPAID_PROBE_PIPELINES = Object.freeze(['reliability']);+// A recorded failure is a SETTLE/PAYMENT-RAIL fault when its reason (the first// `:`-delimited token of error_msg) matches these. Two rules: any 5xx or a 402,// and any RPC/broadcast/settle/confirm/simulation/timeout signature.@@ -509,6 +517,7 @@ export async function gatherX402SettleHealth() {count(*)::int AS nFROM x402_autonomous_logWHERE ts >= now() - ${WINDOW_INTERVAL}::interval+ AND COALESCE(pipeline, '') <> ALL(${[...UNPAID_PROBE_PIPELINES]}::text[])GROUP BY success, paid, reason, rent`);diff --git a/api/_lib/x402/pipelines/builder-code-attribution.js b/api/_lib/x402/pipelines/builder-code-attribution.jsindex 679fb3d04..e620e92f0 100644--- a/api/_lib/x402/pipelines/builder-code-attribution.js+++ b/api/_lib/x402/pipelines/builder-code-attribution.js@@ -68,6 +68,7 @@ import {buildPaymentTx,bootstrapSolanaContext,admitSponsorSettle,+ nextAutoNonce,USDC_MINT,} from '../pay.js';@@ -270,7 +271,11 @@ async function settleAttributed({ row, buyer, conn, blockhash, mintInfo, remainiconst amountAtomic = Number(accept.amount || 0);if (amountAtomic > (remainingCap ?? Infinity)) { out.error = 'cap_would_exceed'; return out; }- const admission = await admitSponsorSettle({ accept, connection: conn });+ // The loop hands every pipeline the tick's shared blockhash: a random nonce+ // keeps this payment's signature distinct from any other same-amount payment+ // to the same payTo in the tick (see x402-autonomous-loop.js).+ const payNonce = nextAutoNonce();+ const admission = await admitSponsorSettle({ accept, connection: conn, nonce: payNonce });if (!admission.ok) { out.error = admission.reason || 'fee_runway_exhausted'; return out; }// Echo the declared app code (anti-tamper: the server rejects a mismatch) and@@ -291,6 +296,7 @@ async function settleAttributed({ row, buyer, conn, blockhash, mintInfo, remainiconst txBase64 = buildPaymentTx({accept, buyer, blockhash, mintInfo,receiverAtaExists: receiverAtaInfo !== null,+ nonce: payNonce,});const xPayment = Buffer.from(JSON.stringify({x402Version: 2,diff --git a/api/_lib/x402/pipelines/payment-proof-idempotency-audit.js b/api/_lib/x402/pipelines/payment-proof-idempotency-audit.jsindex 7c4154066..7bea65a25 100644--- a/api/_lib/x402/pipelines/payment-proof-idempotency-audit.js+++ b/api/_lib/x402/pipelines/payment-proof-idempotency-audit.js@@ -65,6 +65,7 @@ import {buildPaymentTx,fetchWithTimeout,admitSponsorSettle,+ nextAutoNonce,USDC_MINT,SOLANA_RPC,} from '../pay.js';@@ -238,7 +239,11 @@ export async function runIdempotencyAudit(ctx = {}) {const amountAtomic = Number(accept.amount || 0);if (!(amountAtomic > 0)) return fail('zero_price');if (amountAtomic > remainingCap) return fail('cap_would_exceed', { skipped: true });- const admission = await admitSponsorSettle({ accept, connection: conn });+ // The loop hands every pipeline the tick's shared blockhash: a random nonce+ // keeps this payment's signature distinct from any other same-amount payment+ // to the same payTo in the tick (see x402-autonomous-loop.js).+ const payNonce = nextAutoNonce();+ const admission = await admitSponsorSettle({ accept, connection: conn, nonce: payNonce });if (!admission.ok) return fail(admission.reason || 'fee_runway_exhausted', { skipped: true });// ── Step 2: build ONE signed payment proof carrying a payment-identifier ───@@ -256,6 +261,7 @@ export async function runIdempotencyAudit(ctx = {}) {const receiverAtaInfo = await conn.getAccountInfo(receiverAta).catch(() => null);const txBase64 = buildPaymentTx({accept, buyer, blockhash, mintInfo, receiverAtaExists: receiverAtaInfo !== null,+ nonce: payNonce,});xPayment = Buffer.from(JSON.stringify({x402Version: 2,diff --git a/api/_lib/x402/pipelines/streaming-mcp-health.js b/api/_lib/x402/pipelines/streaming-mcp-health.jsindex 9a339094d..b9c6b47cf 100644--- a/api/_lib/x402/pipelines/streaming-mcp-health.js+++ b/api/_lib/x402/pipelines/streaming-mcp-health.js@@ -61,6 +61,7 @@ import {buildPaymentTx,fetchWithTimeout,admitSponsorSettle,+ nextAutoNonce,USDC_MINT,SOLANA_RPC,} from '../pay.js';@@ -296,7 +297,11 @@ export async function runStreamingMcpHealth(ctx = {}) {const amountAtomic = Number(accept.amount || 0);if (!(amountAtomic > 0)) return fail('zero_price');if (amountAtomic > remainingCap) return fail('cap_would_exceed', { skipped: true });- const admission = await admitSponsorSettle({ accept, connection: conn });+ // The loop hands every pipeline the tick's shared blockhash: a random nonce+ // keeps this payment's signature distinct from any other same-amount payment+ // to the same payTo in the tick (see x402-autonomous-loop.js).+ const payNonce = nextAutoNonce();+ const admission = await admitSponsorSettle({ accept, connection: conn, nonce: payNonce });if (!admission.ok) return fail(admission.reason || 'fee_runway_exhausted', { skipped: true });// ── Step 2: build the signed payment tx + X-PAYMENT envelope ───────────────@@ -309,6 +314,7 @@ export async function runStreamingMcpHealth(ctx = {}) {const receiverAtaInfo = await conn.getAccountInfo(receiverAta).catch(() => null);const txBase64 = buildPaymentTx({accept, buyer, blockhash, mintInfo, receiverAtaExists: receiverAtaInfo !== null,+ nonce: payNonce,});xPayment = Buffer.from(JSON.stringify({x402Version: 2,diff --git a/api/cron/x402-autonomous-loop.js b/api/cron/x402-autonomous-loop.jsindex d53c2bb98..97ce06b76 100644--- a/api/cron/x402-autonomous-loop.js+++ b/api/cron/x402-autonomous-loop.js@@ -44,6 +44,7 @@ import {buildPaymentTx,ringFeeConfig,expectedFeeLamports,+ nextAutoNonce,} from '../_lib/x402/pay.js';import { assessFeeAdmission } from '../_lib/x402/wallet-fee-meter.js';import {@@ -596,7 +597,18 @@ export default wrapCron(async (req, res) => {// arriving after a full handshake. Skipping here removes only doomed work:// assessFeeAdmission() fails open whenever it cannot price the call, and// it settles nothing extra when the budget is healthy.- const feeConfig = ringFeeConfig(0, { selfPay: false });+ // Every inline payment in a tick shares one blockhash, so two entries+ // paying the same amount to the same payTo would compile to the SAME+ // transaction and signature if they also shared a fee config. Only the+ // first can land; the facilitator refuses the rest with+ // `signature_already_settled`, which reaches this loop as `http_502`.+ // Measured 2026-09-30: 51 such refusals in 20 minutes, the whole of the+ // settle sensor's http_502 count, from $0.001 health, volume and+ // canonicalize entries that all built with nonce 0. A random nonce per+ // payment keeps each transaction byte-unique at no extra fee (every+ // sponsor-mode fee config costs the same 10,000 lamports).+ const payNonce = nextAutoNonce();+ const feeConfig = ringFeeConfig(payNonce, { selfPay: false });const admission = await assessFeeAdmission({feeWalletB58: accept.extra.feePayer,estFeeLamports: expectedFeeLamports({@@ -633,6 +645,7 @@ export default wrapCron(async (req, res) => {const txBase64 = buildPaymentTx({accept, buyer, blockhash, mintInfo,receiverAtaExists: receiverAtaInfo !== null,+ nonce: payNonce,});const xPayment = Buffer.from(JSON.stringify({diff --git a/api/cron/x402-seed-cron.js b/api/cron/x402-seed-cron.jsindex 2ea94d0b7..b43db8e1b 100644--- a/api/cron/x402-seed-cron.js+++ b/api/cron/x402-seed-cron.js@@ -43,7 +43,7 @@ import { logger } from '../_lib/usage.js';import { SPONSOR_SOL_FLOOR_LAMPORTS } from '../_lib/x402/self-facilitator.js';import {loadSeedKeypair, fetchWithTimeout, parseSolanaAccept, buildPaymentTx,- ringFeeConfig, expectedFeeLamports,+ ringFeeConfig, expectedFeeLamports, nextAutoNonce, RING_CU_JITTER_SLOTS,} from '../_lib/x402/pay.js';import { reserveFeeAdmissions } from '../_lib/x402/wallet-fee-meter.js';import { readPayerUsdcAtomic } from './x402-autonomous-loop.js';@@ -121,13 +121,20 @@ export function seedFeeReserveLamports(e = process.env) {return raw && Number.isFinite(n) && n >= 0 ? Math.floor(n) : 200_000;}-// Worst-case SOL fee of one seed payment. The batch uses nonces 0..batch-1 in-// sponsor mode, so the ceiling over that range is what every admission is priced-// at: the same expectedFeeLamports() math payX402 prices its own admissions with.-export function seedFeeEstimateLamports(batch) {+// Sponsor mode may only use the price slots whose priority floors to zero+// lamports (see ringFeeConfig in api/_lib/x402/pay.js).+const SPONSOR_PRICE_SLOTS = 11;++// Worst-case SOL fee of one seed payment. The batch starts at a random nonce, so+// every admission is priced at the dearest sponsor-mode fee config there is: the+// highest price slot at the largest compute limit, which ringFeeConfig reaches at+// the top of its jitter range. Same expectedFeeLamports() math payX402 uses.+export function seedFeeEstimateLamports() {let worst = 0;- for (let i = 0; i < Math.max(1, batch); i += 1) {- const { microLamports, cuLimit } = ringFeeConfig(i, { selfPay: false });+ for (let slot = 0; slot < SPONSOR_PRICE_SLOTS; slot += 1) {+ const { microLamports, cuLimit } = ringFeeConfig(+ SPONSOR_PRICE_SLOTS * (RING_CU_JITTER_SLOTS - 1) + slot, { selfPay: false },+ );worst = Math.max(worst, expectedFeeLamports({selfPay: false, priorityMicrolamports: microLamports, cuLimit,}));@@ -282,7 +289,7 @@ export default wrapCron(async (req, res) => {// settle attempt the platform made, each after a simulated verify. The seeder// sends only what the governor will admit, and leaves the reserve for the// pipelines that buy real data from the same wallet.- const feeEstimate = seedFeeEstimateLamports(plan.batch);+ const feeEstimate = seedFeeEstimateLamports();const admission = await reserveFeeAdmissions({feeWalletB58: accept.extra.feePayer,estFeeLamports: feeEstimate,@@ -307,9 +314,14 @@ export default wrapCron(async (req, res) => {// ── Step 3: build the signed transactions (synchronous) ───────────────────// The nonce spread is what makes each batch member a distinct transaction;// see ringFeeConfig in api/_lib/x402/pay.js for why it costs ~nothing.+ // A random base keeps the batch clear of the autonomous loop's payments to+ // the same endpoint: both are fired by economy-tick and can sign against the+ // same blockhash, and a batch that always started at nonce 0 was guaranteed to+ // share a fee config with anything else that did.const affordable = Math.min(plan.batch, admission.admitted);+ const nonceBase = nextAutoNonce();const txBases = Array.from({ length: affordable }, (_, index) =>- buildPaymentTx({ accept, buyer, blockhash, mintInfo, receiverAtaExists, nonce: index }),+ buildPaymentTx({ accept, buyer, blockhash, mintInfo, receiverAtaExists, nonce: nonceBase + index }),);// ── Step 4: fire all in parallel ──────────────────────────────────────────diff --git a/docs/ops/production-log-triage.md b/docs/ops/production-log-triage.mdindex f408f18c0..83c263a79 100644--- a/docs/ops/production-log-triage.md+++ b/docs/ops/production-log-triage.md@@ -330,6 +330,15 @@ HTTP 502/503 GET|POST /api/x402/*, /api/mcp ua: threews-x402-autonomous/1.0 orin the caller, not the budget: funding the fee wallet only moves the line such acaller runs into.+ Two things the sensor deliberately does not count. Rows from pipelines that never+ pay (`UNPAID_PROBE_PIPELINES` in `api/_lib/ops/x402-settle-health.js`, today the+ external uptime monitor `reliability`) are dropped before the rate is taken: an+ unpaid HEAD probe timing out on a slow third-party host is not our rail. And an+ `http_502` cluster whose facilitator rows read `signature_already_settled` with+ a matching `ok` row for the same `tx_sig` seconds earlier is a nonce collision+ (two same-amount payments built against one blockhash), not the chain: see+ "Every payment picks its own nonce" in `docs/x402-ring-economy.md`.+On 2026-09-09 production was `settle_refused` verbatim: **0** `no_solana_accept`,164 `fee_wallet_below_floor:1167627<2000000`, and 126 `http_402` recorded by thering on the paid replay (a 402 there means the payment we built was rejected,diff --git a/docs/x402-ring-economy.md b/docs/x402-ring-economy.mdindex 7c3cfc501..37f4e6391 100644--- a/docs/x402-ring-economy.md+++ b/docs/x402-ring-economy.md@@ -225,6 +225,21 @@ reclaimable. So the practical minimum is: **self-pay + the biggest per-call sizeyour float supports.** $100/call settles thousands of dollars of volume for a fewcents of SOL.+### Every payment picks its own nonce++`buildPaymentTx()` is deterministic: the same inputs rebuild the same bytes, so+a retry is safe, and its default nonce is 0. Two payments with the same payer,+payTo, mint and amount, signed against one blockhash with the same nonce, are+one transaction with one signature. Only the first lands; the facilitator+refuses the others with `signature_already_settled`, which the caller sees as+`http_502`. The autonomous loop and every pipeline it runs sign against one+tick-wide blockhash, so each payment passes `nonce: nextAutoNonce()` (the seed+cron uses a random base plus the batch position). In sponsor mode every nonce+costs the same 10,000 lamports, so uniqueness is free. On 2026-09-30 the loop's+inline path still built with nonce 0, and its $0.001 health, volume and+canonicalize entries collided 51 times in 20 minutes. `tests/x402-payment-nonce-guard.test.js`+now fails any `buildPaymentTx` call under `api/` that does not name a nonce.+### Fee floor, enforced — ceiling + continuous auditThe floor is not just a default; it is guarded on both the write and the readdiff --git a/tests/api/x402-settle-health.test.js b/tests/api/x402-settle-health.test.jsindex e3315ff6f..ca4d900bf 100644--- a/tests/api/x402-settle-health.test.js+++ b/tests/api/x402-settle-health.test.js@@ -657,3 +657,21 @@ describe('classifySettleBuckets: a caller that skips the admission gate is not aexpect(v.gateBypass).toBe(5_000);});});++describe('the settle sensor ignores pipelines that never pay', () => {+ it('excludes the external uptime monitor, and that monitor is still free', async () => {+ const { UNPAID_PROBE_PIPELINES } = await import('../../api/_lib/ops/x402-settle-health.js');+ expect(UNPAID_PROBE_PIPELINES).toContain('reliability');+ // The exclusion is only honest while every registry entry in these pipelines+ // is priced at zero. A paid entry added under one of them must fail here+ // rather than vanish from the settle rate.+ const registry = await readFile('api/_lib/x402/autonomous-registry.js', 'utf8');+ for (const pipeline of UNPAID_PROBE_PIPELINES) {+ const entries = registry.split(/\n\t\{\n/).filter((block) => block.includes(`pipeline: '${pipeline}'`));+ expect(entries.length).toBeGreaterThan(0);+ for (const block of entries) expect(block).toMatch(/price_atomic:\s*0\b/);+ }+ const source = await readFile('api/_lib/ops/x402-settle-health.js', 'utf8');+ expect(source).toMatch(/<> ALL\(\$\{\[\.\.\.UNPAID_PROBE_PIPELINES\]\}::text\[\]\)/);+ });+});diff --git a/tests/x402-payment-nonce-guard.test.js b/tests/x402-payment-nonce-guard.test.jsnew file mode 100644index 000000000..624c9c767--- /dev/null+++ b/tests/x402-payment-nonce-guard.test.js@@ -0,0 +1,73 @@+// Every server-side payment builder call must choose its nonce.+//+// buildPaymentTx() is deterministic by design (a retry rebuilds the same bytes),+// so its default nonce is 0. Two payments with the same payer, payTo, mint and+// amount, signed against the same blockhash with nonce 0, compile to one+// transaction and one Ed25519 signature: only the first can land, and the+// facilitator refuses the rest with `signature_already_settled`. The autonomous+// loop and the pipelines it runs all sign against one tick-wide blockhash, so+// that is not a corner case. Measured on production 2026-09-30: 51 such+// refusals in 20 minutes, which the loop recorded as `http_502` and which were+// the whole of the settle sensor's rail faults behind a degraded 74.9%.+//+// A source-level guard, because the failure only shows up on mainnet with two+// same-priced entries in one tick: it pins that every buildPaymentTx({...}) call+// under api/ names a nonce, so a new caller cannot silently fall back to 0.++import { describe, it, expect } from 'vitest';+import { readFile, readdir } from 'node:fs/promises';+import { join } from 'node:path';++async function listJs(dir) {+ const out = [];+ for (const entry of await readdir(dir, { withFileTypes: true })) {+ if (entry.name === 'node_modules') continue;+ const full = join(dir, entry.name);+ if (entry.isDirectory()) out.push(...(await listJs(full)));+ else if (entry.name.endsWith('.js')) out.push(full);+ }+ return out;+}++// The argument object of each `buildPaymentTx({ ... })` call, found by brace+// matching from the call's opening brace.+function callArguments(source) {+ const calls = [];+ const re = /buildPaymentTx\(\s*\{/g;+ let match;+ while ((match = re.exec(source))) {+ if (/function\s+$/.test(source.slice(Math.max(0, match.index - 20), match.index))) continue;+ let depth = 0;+ let i = match.index + match[0].length - 1;+ const start = i;+ for (; i < source.length; i += 1) {+ if (source[i] === '{') depth += 1;+ else if (source[i] === '}') {+ depth -= 1;+ if (depth === 0) break;+ }+ }+ calls.push(source.slice(start, i + 1));+ }+ return calls;+}++describe('payment nonce guard', () => {+ it('every buildPaymentTx call under api/ passes an explicit nonce', async () => {+ const files = await listJs('api');+ const offenders = [];+ let seen = 0;+ for (const file of files) {+ const source = await readFile(file, 'utf8');+ if (!source.includes('buildPaymentTx(')) continue;+ for (const args of callArguments(source)) {+ seen += 1;+ if (!/\bnonce\s*[:,}]/.test(args)) offenders.push(`${file}: ${args.replace(/\s+/g, ' ').slice(0, 120)}`);+ }+ }+ // The loop, three pipelines, the seed cron, payX402, the wallet bridge and+ // the inference top-up: if this drops, the scan stopped finding callers.+ expect(seen).toBeGreaterThanOrEqual(8);+ expect(offenders).toEqual([]);+ });+});diff --git a/tests/x402-seed-batch-plan.test.js b/tests/x402-seed-batch-plan.test.jsindex a860e2f17..33fa44039 100644--- a/tests/x402-seed-batch-plan.test.js+++ b/tests/x402-seed-batch-plan.test.js@@ -113,9 +113,7 @@ describe('seed fee pricing and reserve', () => {it('prices every batch member at the sponsor-mode worst case the facilitator meters', () => {// Two signatures, and sponsor-mode price slots that floor to zero priority// lamports: exactly the `+10000` in the production refusal string.- expect(seedFeeEstimateLamports(60)).toBe(10_000);- expect(seedFeeEstimateLamports(120)).toBe(10_000);- expect(seedFeeEstimateLamports(0)).toBe(10_000);+ expect(seedFeeEstimateLamports()).toBe(10_000);});it('leaves twenty sponsor settles of budget for paid pipelines by default', () => {