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): stop signing payments against a tick-old blockhash that dies at broadcast
nirholas58d8046d9954
diff --git a/api/_lib/x402/pay.js b/api/_lib/x402/pay.jsindex 2e6260183..60139142e 100644--- a/api/_lib/x402/pay.js+++ b/api/_lib/x402/pay.js@@ -276,6 +276,36 @@ export function buildPaymentTx({ accept, buyer, blockhash, mintInfo, receiverAtareturn Buffer.from(vtx.serialize()).toString('base64');}+// A signed transaction carrying a blockhash older than ~60-90s (151 blocks) is+// rejected at broadcast with BlockhashNotFound. The tick-wide shared blockhash+// below ages exactly like that across a long cron tick, and the facilitator+// cannot re-sign on our behalf (the buyer signature covers the message,+// blockhash included), so freshness is the payer's job. This cache keeps the+// one-fetch-per-tick economy for fast ticks and transparently re-fetches once+// the hash is old enough to be a broadcast risk.+const BLOCKHASH_TTL_MS = 20_000;+let blockhashCache = { value: null, fetchedAt: 0 };++function seedBlockhash(value) {+ if (value) blockhashCache = { value, fetchedAt: Date.now() };+}++// Resolve the blockhash to sign with: the cached one while younger than the+// TTL, else a fresh fetch. Falls back to the caller-supplied tick blockhash+// when the RPC fetch fails (a stale attempt beats no attempt: the facilitator+// side still retries preflight-off for provably-unlanded blockhash misses).+async function currentBlockhash(conn, fallback, { forceFresh = false } = {}) {+ const age = Date.now() - blockhashCache.fetchedAt;+ if (!forceFresh && blockhashCache.value && age < BLOCKHASH_TTL_MS) return blockhashCache.value;+ try {+ const { blockhash } = await conn.getLatestBlockhash('confirmed');+ seedBlockhash(blockhash);+ return blockhash;+ } catch {+ return blockhashCache.value || fallback;+ }+}+// Build the per-tick shared Solana state once (blockhash + USDC mint info) so a// run() that pays several rows reuses one blockhash. Standalone callers (manual// tests) call this to bootstrap a full context without the cron loop.@@ -287,6 +317,7 @@ export async function bootstrapSolanaContext({ buyer } = {}) {conn.getLatestBlockhash('confirmed'),getMint(conn, new PublicKey(USDC_MINT)),]);+ seedBlockhash(blockhash);return { buyer: payer, conn, blockhash, mintInfo };}@@ -352,7 +383,10 @@ export async function payX402({// 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) {+ // `forceFreshBlockhash` is set on the post-402 retry: the refused attempt may+ // have died on a stale hash, and re-signing the retry against the same one+ // would reproduce the failure.+ async function attemptSettle(currentAccept, attemptNonce, { forceFreshBlockhash = false } = {}) {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}` } };}@@ -435,9 +469,12 @@ export async function payX402({);const receiverAtaInfo = await conn.getAccountInfo(receiverAta).catch(() => null);- // Step 3: build the signed transaction + X-PAYMENT envelope.+ // Step 3: build the signed transaction + X-PAYMENT envelope. The signing+ // blockhash reads through the freshness cache: the tick-wide hash while it+ // is young, a re-fetched one once it has aged past broadcast safety.+ const signBlockhash = await currentBlockhash(conn, blockhash, { forceFresh: forceFreshBlockhash });const txBase64 = buildPaymentTx({- accept: currentAccept, buyer, blockhash, mintInfo,+ accept: currentAccept, buyer, blockhash: signBlockhash, mintInfo,receiverAtaExists: receiverAtaInfo !== null,nonce: attemptNonce, selfPay,});@@ -472,7 +509,7 @@ export async function payX402({let paidRes;let amountAtomic = 0;for (;;) {- const outcome = await attemptSettle(currentAccept, attemptNonce);+ const outcome = await attemptSettle(currentAccept, attemptNonce, { forceFreshBlockhash: retriedAfter402 });if (outcome.skip) return { ...outcome.skip, retriedAfter402 };paidRes = outcome.paidRes;amountAtomic = outcome.amountAtomic;diff --git a/tests/x402-pay-blockhash-freshness.test.js b/tests/x402-pay-blockhash-freshness.test.jsnew file mode 100644index 000000000..019055bc9--- /dev/null+++ b/tests/x402-pay-blockhash-freshness.test.js@@ -0,0 +1,139 @@+import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'vitest';+import http from 'node:http';+import { Keypair, VersionedTransaction } from '@solana/web3.js';++// The autonomous payer used to sign every payment in a tick against ONE+// blockhash fetched at tick start. A long tick ages that hash past the ~60-90s+// broadcast window and the facilitator (which cannot re-sign: the buyer+// signature covers the message, blockhash included) dies with+// broadcast_failed cause:BlockhashNotFound. payX402 now reads the signing+// blockhash through a TTL cache and force-refreshes it on the post-402 retry.+// These tests decode the actually-signed transaction out of the X-PAYMENT+// envelope and assert which blockhash it carries. Nothing is broadcast.++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();++function accept(amount) {+ return {+ scheme: 'exact',+ network: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',+ asset: USDC,+ payTo,+ amount: String(amount),+ extra: { name: 'USDC', decimals: 6 },+ };+}++// Valid 32-byte base58 strings: any pubkey qualifies as a blockhash shape.+const STALE_TICK_HASH = Keypair.generate().publicKey.toBase58();+const freshHashes = [Keypair.generate().publicKey.toBase58(), Keypair.generate().publicKey.toBase58()];++let paidReplays402 = 0;+// recentBlockhash of every signed transaction the server received, in order.+let signedWith = [];++let server;+let origin;++beforeAll(async () => {+ server = http.createServer((req, res) => {+ const paymentHeader = req.headers['x-payment'];+ if (!paymentHeader) {+ res.statusCode = 402;+ res.setHeader('content-type', 'application/json');+ res.end(JSON.stringify({ x402Version: 2, accepts: [accept(1000)] }));+ return;+ }+ const decoded = JSON.parse(Buffer.from(paymentHeader, 'base64').toString('utf8'));+ const vtx = VersionedTransaction.deserialize(Buffer.from(decoded.payload.transaction, 'base64'));+ signedWith.push(vtx.message.recentBlockhash);+ if (paidReplays402 > 0) {+ paidReplays402--;+ res.statusCode = 402;+ res.setHeader('content-type', 'application/json');+ res.end(JSON.stringify({ x402Version: 2, accepts: [accept(1000)], error: 'requirements_changed' }));+ return;+ }+ res.statusCode = 200;+ res.setHeader('content-type', 'application/json');+ res.end(JSON.stringify({ ok: true }));+ });+ 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;+ signedWith = [];+});++const buyer = Keypair.generate();++function ctx({ hashes }) {+ let i = 0;+ return {+ buyer,+ conn: {+ getAccountInfo: async () => ({ lamports: 1 }),+ getLatestBlockhash: async () => ({ blockhash: hashes[Math.min(i++, hashes.length - 1)] }),+ },+ blockhash: STALE_TICK_HASH,+ mintInfo: { decimals: 6 },+ selfPay: true,+ };+}++describe('payX402 blockhash freshness', () => {+ it('signs with an RPC-fresh blockhash, not the caller-supplied tick hash, once the cache is stale', async () => {+ const r = await payX402({ url: `${origin}/ok`, method: 'GET', ...ctx({ hashes: freshHashes }), remainingCap: 100_000 });+ expect(r.paid).toBe(true);+ expect(signedWith).toHaveLength(1);+ // The tick-wide hash is only the fetch-failure fallback; a reachable RPC+ // always wins. (The shared cache may still hold a young hash seeded by a+ // sibling test in this process, so assert against the stale hash, not for+ // one specific fresh value.)+ expect(signedWith[0]).not.toBe(STALE_TICK_HASH);+ });++ it('force-refreshes the blockhash on the post-402 retry instead of re-signing the refused one', async () => {+ paidReplays402 = 1;+ const ownHashes = [Keypair.generate().publicKey.toBase58(), Keypair.generate().publicKey.toBase58()];+ const r = await payX402({ url: `${origin}/requote`, method: 'GET', ...ctx({ hashes: ownHashes }), remainingCap: 100_000 });+ expect(r.paid).toBe(true);+ expect(r.retriedAfter402).toBe(true);+ expect(signedWith).toHaveLength(2);+ // The retry MUST have hit the RPC again: forceFresh bypasses the TTL cache+ // (whatever a sibling test left in it), so the second signed tx wears a+ // hash from THIS test's mock RPC, distinct from the refused attempt's.+ expect(ownHashes).toContain(signedWith[1]);+ expect(signedWith[1]).not.toBe(signedWith[0]);+ expect(signedWith[1]).not.toBe(STALE_TICK_HASH);+ });++ it('still pays when the RPC blockhash fetch fails (cached or caller-supplied fallback)', async () => {+ const failingCtx = {+ buyer,+ conn: {+ getAccountInfo: async () => ({ lamports: 1 }),+ getLatestBlockhash: async () => { throw new Error('rpc down'); },+ },+ blockhash: STALE_TICK_HASH,+ mintInfo: { decimals: 6 },+ selfPay: true,+ };+ const r = await payX402({ url: `${origin}/ok`, method: 'GET', ...failingCtx, remainingCap: 100_000 });+ expect(r.paid).toBe(true);+ expect(signedWith).toHaveLength(1);+ // A stale attempt beats no attempt; the facilitator side still has its+ // preflight-off resend for provably-unlanded blockhash misses.+ });+});