Skip to content

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.

fix(x402): verify a Solana payment against the token the buyer chose, not the first accept on the network

ni3a299a2a0bc341
diff --git a/api/_lib/x402-paid-endpoint.js b/api/_lib/x402-paid-endpoint.js
index 5cb568ebb..30f5b099c 100644
--- a/api/_lib/x402-paid-endpoint.js
+++ b/api/_lib/x402-paid-endpoint.js
@@ -1005,6 +1005,11 @@ export function paidEndpoint(spec) {
metadata: {
reason: err.code || (err.status === 402 ? 'verify_rejected' : 'verify_failed'),
kind: err.status === 402 ? 'rejected_proof' : 'upstream_fault',
+ // The facilitator's own words (ata_create_wrong_account,
+ // transfer_wrong_mint, ...). The code above is the same
+ // invalid_payment for every rejected proof, which names the
+ // class and hides the cause.
+ detail: String(err.message || '').slice(0, 300) || null,
},
});
recordPaymentMetric({
diff --git a/api/_lib/x402-solana-confirm.js b/api/_lib/x402-solana-confirm.js
index 4157750e3..fd2981eb8 100644
--- a/api/_lib/x402-solana-confirm.js
+++ b/api/_lib/x402-solana-confirm.js
@@ -25,9 +25,15 @@ import { PublicKey, VersionedTransaction } from '@solana/web3.js';
import {
ASSOCIATED_TOKEN_PROGRAM_ID,
TOKEN_PROGRAM_ID,
+ TOKEN_2022_PROGRAM_ID,
getAssociatedTokenAddressSync,
} from '@solana/spl-token';
+// Both token programs share the Transfer / TransferChecked layout. USDC is
+// classic SPL Token and $THREE is Token-2022, so a decoder that only reads the
+// classic program sees no transfer at all in a $THREE payment.
+const TOKEN_PROGRAMS = [TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID];
+
// SPL-Token instruction discriminators (first byte of instruction data).
const IX_TRANSFER = 3;
const IX_TRANSFER_CHECKED = 12;
@@ -84,29 +90,30 @@ function decodeSolanaTransfer({ transactionBase64, asset, payTo }) {
if (!instructions) return { inconclusive: true, reason: 'unreadable_message' };
let mint;
- let receiverAta;
+ // The receiver ATA address commits to the token program, so there is one
+ // candidate per program. A transfer is only credited when its destination is
+ // the ATA derived under the program that instruction actually calls.
+ const receiverAtaByProgram = new Map();
try {
mint = new PublicKey(asset);
- // allowOwnerOffCurve=true so a PDA payTo never throws here; for a normal
- // wallet this yields the same ATA the buyer-side builder derived.
- receiverAta = getAssociatedTokenAddressSync(
- mint,
- new PublicKey(payTo),
- true,
- TOKEN_PROGRAM_ID,
- ASSOCIATED_TOKEN_PROGRAM_ID,
- );
+ const owner = new PublicKey(payTo);
+ for (const program of TOKEN_PROGRAMS) {
+ // allowOwnerOffCurve=true so a PDA payTo never throws here; for a normal
+ // wallet this yields the same ATA the buyer-side builder derived.
+ const ata = getAssociatedTokenAddressSync(mint, owner, true, program, ASSOCIATED_TOKEN_PROGRAM_ID);
+ receiverAtaByProgram.set(program.toBase58(), ata.toBase58());
+ }
} catch {
return { inconclusive: true, reason: 'bad_asset_or_payto' };
}
- const receiverAtaStr = receiverAta.toBase58();
const mintStr = mint.toBase58();
let paidToPayTo = 0n;
let sawTokenTransfer = false;
for (const ix of instructions) {
- if (!ix.programId.equals(TOKEN_PROGRAM_ID) || !ix.data || ix.data.length < 1) continue;
+ const receiverAtaStr = receiverAtaByProgram.get(ix.programId.toBase58());
+ if (!receiverAtaStr || !ix.data || ix.data.length < 1) continue;
const kind = ix.data[0];
if (kind === IX_TRANSFER_CHECKED) {
@@ -135,6 +142,31 @@ function decodeSolanaTransfer({ transactionBase64, asset, payTo }) {
return { ok: true, paidToPayTo, sawTokenTransfer };
}
+// The mints the buyer's signed transaction moves, read off its TransferChecked
+// instructions (the only transfer form that names its mint). verifyPayment uses
+// this to tell which accepts[] entry a Solana payment answers when a resource
+// quotes several tokens on one network and the payload does not echo the chosen
+// entry. Returns [] when the payload carries no decodable transaction.
+export function signedSolanaMints(paymentPayload) {
+ const transactionBase64 = paymentPayload?.payload?.transaction;
+ if (typeof transactionBase64 !== 'string' || !transactionBase64) return [];
+ let instructions;
+ try {
+ const tx = VersionedTransaction.deserialize(Buffer.from(transactionBase64, 'base64'));
+ instructions = readInstructions(tx.message);
+ } catch {
+ return [];
+ }
+ if (!instructions) return [];
+ const mints = new Set();
+ for (const ix of instructions) {
+ if (!TOKEN_PROGRAMS.some((program) => program.equals(ix.programId))) continue;
+ if (!ix.data || ix.data[0] !== IX_TRANSFER_CHECKED || ix.accountKeys.length < 2) continue;
+ mints.add(ix.accountKeys[1].toBase58());
+ }
+ return [...mints];
+}
+
// Public entry point used by verifyPayment. Returns:
// { confirmed: true } — signed tx pays >= required to payTo.
// { confirmed: false, reason } — definitively underpaid / mis-routed.
diff --git a/api/_lib/x402-spec.js b/api/_lib/x402-spec.js
index d7685933b..ec231be5b 100644
--- a/api/_lib/x402-spec.js
+++ b/api/_lib/x402-spec.js
@@ -51,7 +51,7 @@ import {
import { env } from './env.js';
import { X402Error } from './x402-errors.js';
-import { confirmSolanaPayment } from './x402-solana-confirm.js';
+import { confirmSolanaPayment, signedSolanaMints } from './x402-solana-confirm.js';
import {
NETWORK_SOLANA_MAINNET,
NETWORK_SOLANA_DEVNET,
@@ -814,13 +814,28 @@ function isAuthHintAccept(requirement) {
return String(requirement.amount) === '0';
}
+// Assets are compared exactly on Solana (base58 is case-sensitive) and
+// case-insensitively on EVM, where clients send checksummed or lowercased hex.
+function sameAsset(a, b) {
+ if (!a || !b) return false;
+ const x = String(a);
+ const y = String(b);
+ return x.startsWith('0x') && y.startsWith('0x') ? x.toLowerCase() === y.toLowerCase() : x === y;
+}
+
// Match the decoded payload to one of the offered requirements. The match is
-// by (network, assetTransferMethod) when we can detect the method from the
-// payload shape, needed because we now publish two accept entries per EVM
-// network (EIP-3009 first, Permit2 sibling second), and the facilitator's
-// /verify call has to receive the same `extra` block the client signed
-// against. Falls back to first-match-by-network for non-EVM payloads (Solana
-// SPL, BSC direct).
+// by (network, assetTransferMethod, asset). The method matters because we
+// publish two accept entries per EVM network (EIP-3009 first, Permit2 sibling
+// second) and the facilitator's /verify call has to receive the same `extra`
+// block the client signed against. The asset matters because a resource can
+// quote several tokens on one network (USDC and $THREE on Solana): matching by
+// network alone judged every $THREE payment against the USDC entry, so the
+// facilitator looked for a USDC recipient account in a $THREE transaction and
+// refused it, and no buyer could ever pay in the second token.
+//
+// The asset comes from the payload's echoed `accepted` entry (x402 v2) when it
+// is there. A Solana payload without one is read from the signed transaction
+// itself. Only when neither names an asset does the first network match win.
function selectRequirement(paymentPayload, allRequirements) {
// OKX-dialect payloads (PAYMENT-SIGNATURE header) carry the chosen entry as
// `accepted` instead of top-level scheme/network, see x402-xlayer-okx.js.
@@ -835,14 +850,30 @@ function selectRequirement(paymentPayload, allRequirements) {
return reqMethod === method;
};
if (network) {
- const found = allRequirements.find((r) => r.network === network && matchesMethod(r));
- if (!found)
+ const candidates = allRequirements.filter((r) => r.network === network && matchesMethod(r));
+ if (!candidates.length)
throw new X402Error(
'unsupported_network',
`payment network "${network}" (assetTransferMethod="${method || 'unknown'}") is not offered`,
402,
);
- return found;
+ const echoedAsset = paymentPayload?.accepted?.asset || paymentPayload?.paymentRequirements?.asset;
+ if (echoedAsset) {
+ const found = candidates.find((r) => sameAsset(r.asset, echoedAsset));
+ if (!found)
+ throw new X402Error(
+ 'unsupported_asset',
+ `payment asset "${echoedAsset}" is not offered on ${network}; offered: ${candidates.map((r) => r.asset).join(', ')}`,
+ 402,
+ );
+ return found;
+ }
+ if (candidates.length > 1 && isSolanaNetwork(network)) {
+ const signedMints = signedSolanaMints(paymentPayload);
+ const found = candidates.find((r) => signedMints.includes(r.asset));
+ if (found) return found;
+ }
+ return candidates[0];
}
if (method) {
const found = allRequirements.find(matchesMethod);
diff --git a/tests/api/x402-multi-asset-select.test.js b/tests/api/x402-multi-asset-select.test.js
new file mode 100644
index 000000000..ee3612387
--- /dev/null
+++ b/tests/api/x402-multi-asset-select.test.js
@@ -0,0 +1,170 @@
+// A resource can quote several tokens on one network: every Solana paid endpoint
+// advertises USDC and $THREE side by side. verifyPayment has to judge a payment
+// against the accepts[] entry the buyer actually chose. Matching by network
+// alone sent every $THREE payment to the facilitator as a USDC requirement, so
+// the facilitator looked for a USDC recipient account inside a $THREE
+// transaction and refused it (ata_create_wrong_account in production), and the
+// second token was quoted everywhere and payable nowhere.
+//
+// These tests pin the selection: by the payload's echoed `accepted.asset` when
+// present, by the mint the signed transaction moves when it is not, and with a
+// named refusal when the payload asks for an asset the resource never offered.
+
+import { beforeAll, beforeEach, afterEach, describe, it, expect, vi } from 'vitest';
+
+vi.mock('@coinbase/x402', () => ({
+ createCdpAuthHeaders: vi.fn(async () => ({})),
+}));
+vi.mock('@x402/extensions', () => ({
+ EIP2612_GAS_SPONSORING: { key: 'eip2612GasSponsoring' },
+ ERC20_APPROVAL_GAS_SPONSORING: { key: 'erc20ApprovalGasSponsoring' },
+ declareEip2612GasSponsoringExtension: () => ({ eip2612GasSponsoring: { info: {}, schema: {} } }),
+ declareErc20ApprovalGasSponsoringExtension: () => ({ erc20ApprovalGasSponsoring: { info: {}, schema: {} } }),
+}));
+vi.mock('../../api/_lib/x402-bsc-direct.js', () => ({
+ PAYMENT_EVENT_TOPIC: '0x' + 'a'.repeat(64),
+ settleDirectPayment: vi.fn(async () => ({ success: true })),
+ verifyDirectPayment: vi.fn(async () => ({ isValid: true })),
+}));
+
+vi.setConfig({ testTimeout: 15_000, hookTimeout: 60_000 });
+
+const SOLANA = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';
+const USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+const THREE = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+const PAY_TO = 'wwwwwDxFWRn7grgr3Esrsg5C6NvDoDHSA4gaCffccrU';
+
+const usdcAccept = { scheme: 'exact', network: SOLANA, payTo: PAY_TO, asset: USDC, amount: '10000' };
+const threeAccept = { scheme: 'exact', network: SOLANA, payTo: PAY_TO, asset: THREE, amount: '10000000' };
+// Same order the live challenge uses: USDC first, $THREE second.
+const requirements = [usdcAccept, threeAccept];
+
+let spec;
+let web3;
+let splToken;
+beforeAll(async () => {
+ spec = await import('../../api/_lib/x402-spec.js');
+ web3 = await import('@solana/web3.js');
+ splToken = await import('@solana/spl-token');
+}, 60_000);
+
+const ORIG_ENV = { ...process.env };
+const REAL_FETCH = global.fetch;
+let sentRequirement;
+beforeEach(() => {
+ process.env.X402_FACILITATOR_URL_SOLANA = 'https://facilitator.test';
+ process.env.X402_FACILITATOR_TOKEN_SOLANA = 'tok';
+ sentRequirement = null;
+ global.fetch = vi.fn(async (_url, init) => {
+ const body = JSON.parse(init.body);
+ sentRequirement = body.paymentRequirements;
+ return {
+ ok: true,
+ status: 200,
+ text: async () =>
+ JSON.stringify({ isValid: true, payer: 'PAYER', network: SOLANA, asset: sentRequirement.asset }),
+ };
+ });
+});
+afterEach(() => {
+ for (const k of Object.keys(process.env)) if (!(k in ORIG_ENV)) delete process.env[k];
+ Object.assign(process.env, ORIG_ENV);
+ global.fetch = REAL_FETCH;
+ vi.restoreAllMocks();
+});
+
+// A signed-shape transaction transferring `amount` of `mint` to PAY_TO under
+// the given token program ('classic' for USDC, 'token2022' for $THREE).
+function txPaying({ mint, amount, program }) {
+ const { Keypair, PublicKey, TransactionMessage, VersionedTransaction } = web3;
+ const {
+ createTransferCheckedInstruction,
+ getAssociatedTokenAddressSync,
+ TOKEN_PROGRAM_ID,
+ TOKEN_2022_PROGRAM_ID,
+ ASSOCIATED_TOKEN_PROGRAM_ID,
+ } = splToken;
+ const tokenProgram = program === 'token2022' ? TOKEN_2022_PROGRAM_ID : TOKEN_PROGRAM_ID;
+ const owner = Keypair.generate().publicKey;
+ const mintPk = new PublicKey(mint);
+ const senderAta = getAssociatedTokenAddressSync(mintPk, owner, false, tokenProgram, ASSOCIATED_TOKEN_PROGRAM_ID);
+ const receiverAta = getAssociatedTokenAddressSync(mintPk, new PublicKey(PAY_TO), false, tokenProgram, ASSOCIATED_TOKEN_PROGRAM_ID);
+ const ix = createTransferCheckedInstruction(senderAta, mintPk, receiverAta, owner, amount, 6, [], tokenProgram);
+ const msg = new TransactionMessage({
+ payerKey: owner,
+ recentBlockhash: '11111111111111111111111111111111',
+ instructions: [ix],
+ }).compileToV0Message();
+ return Buffer.from(new VersionedTransaction(msg).serialize()).toString('base64');
+}
+
+function header({ transaction, accepted }) {
+ const payload = {
+ x402Version: 2,
+ scheme: 'exact',
+ network: SOLANA,
+ ...(accepted ? { accepted } : {}),
+ payload: { transaction },
+ };
+ return Buffer.from(JSON.stringify(payload)).toString('base64');
+}
+
+describe('verifyPayment: picks the accept the buyer chose on a multi-token network', () => {
+ it('verifies a $THREE payment against the $THREE accept, not the first Solana entry', async () => {
+ const transaction = txPaying({ mint: THREE, amount: 10_000_000, program: 'token2022' });
+ const result = await spec.verifyPayment({
+ paymentHeader: header({ transaction, accepted: threeAccept }),
+ requirements,
+ builderCode: null,
+ });
+ expect(sentRequirement.asset).toBe(THREE);
+ expect(sentRequirement.amount).toBe('10000000');
+ expect(result.requirement.asset).toBe(THREE);
+ });
+
+ it('still verifies a USDC payment against the USDC accept', async () => {
+ const transaction = txPaying({ mint: USDC, amount: 10_000, program: 'classic' });
+ const result = await spec.verifyPayment({
+ paymentHeader: header({ transaction, accepted: usdcAccept }),
+ requirements,
+ builderCode: null,
+ });
+ expect(sentRequirement.asset).toBe(USDC);
+ expect(result.requirement.asset).toBe(USDC);
+ });
+
+ it('reads the asset off the signed transaction when the payload echoes no accept', async () => {
+ const transaction = txPaying({ mint: THREE, amount: 10_000_000, program: 'token2022' });
+ const result = await spec.verifyPayment({
+ paymentHeader: header({ transaction }),
+ requirements,
+ builderCode: null,
+ });
+ expect(sentRequirement.asset).toBe(THREE);
+ expect(result.requirement.asset).toBe(THREE);
+ });
+
+ it('refuses an asset the resource never offered, by name, before the facilitator is called', async () => {
+ const transaction = txPaying({ mint: USDC, amount: 10_000, program: 'classic' });
+ const stranger = { ...usdcAccept, asset: 'THREEsynthetic1111111111111111111111111111' };
+ await expect(
+ spec.verifyPayment({
+ paymentHeader: header({ transaction, accepted: stranger }),
+ requirements,
+ builderCode: null,
+ }),
+ ).rejects.toMatchObject({ code: 'unsupported_asset', status: 402 });
+ expect(global.fetch).not.toHaveBeenCalled();
+ });
+
+ it('rejects a $THREE underpayment through the static Token-2022 decode', async () => {
+ const transaction = txPaying({ mint: THREE, amount: 10_000, program: 'token2022' });
+ await expect(
+ spec.verifyPayment({
+ paymentHeader: header({ transaction, accepted: threeAccept }),
+ requirements,
+ builderCode: null,
+ }),
+ ).rejects.toMatchObject({ code: 'invalid_payment', status: 402 });
+ });
+});