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): settle $THREE payments by handling Token-2022 mints on the Solana rail
ni3a624e1a6f8b41
diff --git a/api/_lib/solana-token-program.js b/api/_lib/solana-token-program.jsnew file mode 100644index 000000000..c87f9b72f--- /dev/null+++ b/api/_lib/solana-token-program.js@@ -0,0 +1,75 @@+// Which SPL token program owns a mint: classic Token or Token-2022.+//+// Every associated token account address is derived from the owning program, and+// every transfer instruction is addressed to it, so code that assumes the classic+// program builds a transaction that cannot execute against a Token-2022 mint: the+// derived source ATA does not exist and the instruction is sent to a program that+// does not own the mint. $THREE is a Token-2022 mint (pump.fun has minted under+// Token-2022 since its metadata-extension launch format), USDC is classic, and the+// x402 rail accepts both, so nothing on that rail may hardcode either program.+//+// A mint's owning program is fixed at creation and can never change, so the+// answer is cached for the life of the process and the two mints the platform+// settles are seeded, which keeps the hot path free of an RPC round-trip.++import { PublicKey } from '@solana/web3.js';+import { TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID } from '@solana/spl-token';++export const SUPPORTED_TOKEN_PROGRAMS = [TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID];++const USDC_MAINNET = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';+const USDC_DEVNET = '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU';+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';++const programByMint = new Map([+ [USDC_MAINNET, TOKEN_PROGRAM_ID],+ [USDC_DEVNET, TOKEN_PROGRAM_ID],+ [THREE_MINT, TOKEN_2022_PROGRAM_ID],+]);++function mintKey(mint) {+ return typeof mint === 'string' ? mint : mint.toBase58();+}++export function isSupportedTokenProgram(programId) {+ return SUPPORTED_TOKEN_PROGRAMS.some((id) => id.equals(programId));+}++// Record a mint's owning program without an RPC read, for a caller that already+// knows it (it created the mint, or just read the account for another reason).+// Refuses an unsupported program so the map can never hold a wrong answer.+export function seedTokenProgramForMint(mint, programId) {+ const program = SUPPORTED_TOKEN_PROGRAMS.find((id) => id.equals(programId));+ if (!program) throw new Error(`not a token program: ${programId}`);+ programByMint.set(mintKey(mint), program);+ return program;+}++// Sync lookup for callers that cannot await (static transaction validators).+// Returns null when the mint has not been seeded or resolved yet.+export function knownTokenProgramForMint(mint) {+ return programByMint.get(mintKey(mint)) || null;+}++// Authoritative lookup: reads the mint account's owner once, then serves the+// cache. Throws when the account is missing or owned by anything other than a+// token program, because a caller that proceeds on a guess derives wrong ATAs.+export async function tokenProgramForMint(connection, mint) {+ const key = mintKey(mint);+ const cached = programByMint.get(key);+ if (cached) return cached;+ const info = await connection.getAccountInfo(new PublicKey(key), 'confirmed');+ if (!info) {+ const err = new Error(`mint account not found: ${key}`);+ err.code = 'mint_not_found';+ throw err;+ }+ const program = SUPPORTED_TOKEN_PROGRAMS.find((id) => id.equals(info.owner));+ if (!program) {+ const err = new Error(`mint ${key} is owned by ${info.owner.toBase58()}, not a token program`);+ err.code = 'mint_not_token';+ throw err;+ }+ programByMint.set(key, program);+ return program;+}diff --git a/api/_lib/x402/self-facilitator.js b/api/_lib/x402/self-facilitator.jsindex 296cb6253..776fb6e7d 100644--- a/api/_lib/x402/self-facilitator.js+++ b/api/_lib/x402/self-facilitator.js@@ -27,11 +27,17 @@ import { PublicKey, Keypair, VersionedTransaction } from '@solana/web3.js';import {getAssociatedTokenAddressSync,TOKEN_PROGRAM_ID,+ TOKEN_2022_PROGRAM_ID,ASSOCIATED_TOKEN_PROGRAM_ID,} from '@solana/spl-token';import { env } from '../env.js';import { solanaConnection } from '../solana/connection.js';+import {+ isSupportedTokenProgram,+ knownTokenProgramForMint,+ tokenProgramForMint,+} from '../solana-token-program.js';// Pure DB/crypto helpers: no cycle back into this module.import {SETTLEMENT_PENDING_REASON,@@ -76,7 +82,18 @@ const MAX_PRIORITY_LAMPORTS = Number();// Rent an idempotent ATA-create locks on the sponsor for a NEW recipient token// account (~0.00204 SOL). Reclaimable by closing the ATA. Bounded, one-time.+// A Token-2022 ATA carries the ImmutableOwner extension, so it is 170 bytes+// rather than 165 and its rent-exempt minimum is higher. Under-estimating it+// lets a settle clear the fee-floor gate and then die on chain for rent.+// Both figures are ceilings, priced at the 6960 lamports/byte-year rate. Mainnet+// charged less than that when last read (2026-09-20: 1,488,440 and 1,513,840),+// and an over-estimate only makes the floor gate stricter, never unsafe.const ATA_RENT_LAMPORTS = 2_039_280;+const ATA_RENT_LAMPORTS_TOKEN_2022 = 2_074_080;+const ataRentLamports = (tokenProgram) =>+ String(tokenProgram) === TOKEN_2022_PROGRAM_ID.toBase58()+ ? ATA_RENT_LAMPORTS_TOKEN_2022+ : ATA_RENT_LAMPORTS;export const SELF_FACILITATOR_ENABLED =String(process.env.X402_SELF_FACILITATOR_ENABLED || '').toLowerCase() === 'true';@@ -161,7 +178,7 @@ function readU64LE(data, offset) {// { ok:true, decoded } when it is a clean single-USDC-transfer to an allowlisted// recipient with a bounded sponsor fee, or { ok:false, reason } otherwise. Never// throws on adversarial input — a bad tx is a clean refusal, not a 5xx.-export function validateRingTransaction({ txBase64, requirement, feePayerPubkey, allowlist }) {+export function validateRingTransaction({ txBase64, requirement, feePayerPubkey, allowlist, tokenProgramId }) {let tx;try {tx = VersionedTransaction.deserialize(Buffer.from(txBase64, 'base64'));@@ -209,8 +226,17 @@ export function validateRingTransaction({ txBase64, requirement, feePayerPubkey,return { ok: false, reason: `mint_not_settleable:${mint.toBase58()}` };}+ // The program that owns the mint decides every ATA address below and is the+ // only token program this transaction may call. USDC is classic SPL Token and+ // $THREE is Token-2022. It is pinned from the mint, never read off the buyer's+ // instruction: a buyer who picks the program picks the ATA derivation too, and+ // could steer the sponsor into funding an account the mint's real program+ // will never credit.+ const tokenProgram =+ tokenProgramId || knownTokenProgramForMint(mint) || TOKEN_PROGRAM_ID;+const expectedReceiverAta = getAssociatedTokenAddressSync(- mint, payTo, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,+ mint, payTo, false, tokenProgram, ASSOCIATED_TOKEN_PROGRAM_ID,);let transferCount = 0;@@ -267,13 +293,24 @@ export function validateRingTransaction({ txBase64, requirement, feePayerPubkey,if (!owner.equals(payTo)) return { ok: false, reason: 'ata_create_wrong_owner' };if (!ixMint.equals(mint)) return { ok: false, reason: 'ata_create_wrong_mint' };if (!funder.equals(feePayer)) return { ok: false, reason: 'ata_create_wrong_funder' };+ // Accounts 4 and 5 are the System and token programs. The ATA address+ // already commits to the token program, so a mismatch here can only+ // fail on chain, after the sponsor paid the fee. Refuse it up front.+ if (accts.length >= 6 && idxInRange(accts[5]) && !keys[accts[5]].equals(tokenProgram)) {+ return { ok: false, reason: 'ata_create_wrong_token_program' };+ }ataCreatePresent = true;continue;}- if (programId.equals(TOKEN_PROGRAM_ID)) {+ if (isSupportedTokenProgram(programId)) {+ // A real token program, but not the one that owns this mint: the+ // transfer would revert on chain. Name it instead of settling it.+ if (!programId.equals(tokenProgram)) {+ return { ok: false, reason: `wrong_token_program:${programId.toBase58()}` };+ }// The ONLY value-moving instruction we permit: one TransferChecked of- // the required USDC from the buyer to OUR recipient ATA.+ // the required amount from the buyer to OUR recipient ATA.// Accounts: [source, mint, destination, authority].if (data[0] !== SPL_TRANSFER_CHECKED) {return { ok: false, reason: `token_ix_not_transfer_checked:${data[0]}` };@@ -296,7 +333,7 @@ export function validateRingTransaction({ txBase64, requirement, feePayerPubkey,}// The buyer (authority) must own the source ATA and must be a signer.const expectedSource = getAssociatedTokenAddressSync(- mint, authority, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,+ mint, authority, false, tokenProgram, ASSOCIATED_TOKEN_PROGRAM_ID,);if (!source.equals(expectedSource)) {return { ok: false, reason: 'transfer_source_not_authority_ata' };@@ -354,7 +391,8 @@ export function validateRingTransaction({ txBase64, requirement, feePayerPubkey,}const baseFee = 5000 * msg.header.numRequiredSignatures;- const estFeeLamports = baseFee + priorityLamports + (ataCreatePresent ? ATA_RENT_LAMPORTS : 0);+ const estFeeLamports =+ baseFee + priorityLamports + (ataCreatePresent ? ataRentLamports(tokenProgram.toBase58()) : 0);return {ok: true,@@ -363,6 +401,7 @@ export function validateRingTransaction({ txBase64, requirement, feePayerPubkey,payer,payTo: payTo.toBase58(),mint: mint.toBase58(),+ tokenProgram: tokenProgram.toBase58(),amountAtomic: Number(transferAmount),feePayer: feePayer.toBase58(),selfPay,@@ -681,11 +720,14 @@ export async function settleRingPayment({// The sponsor pubkey only authorizes SPONSOR-mode payments; a self-pay tx// carries its own fee payer and needs no sponsor key at all.const sponsorPubkey = feePayer?.publicKey?.toBase58() || env.X402_FEE_PAYER_SOLANA || null;+ const program = await resolveRingTokenProgram(connection, requirement);+ if (!program.ok) return { success: false, reason: program.reason };const validation = validateRingTransaction({txBase64,requirement,feePayerPubkey: sponsorPubkey,allowlist: payToAllowlist(),+ tokenProgramId: program.tokenProgramId,});if (!validation.ok) return { success: false, reason: validation.reason };const decoded = validation.decoded;@@ -1006,7 +1048,8 @@ export async function settleRingPayment({commitment: 'confirmed',});if (parsed?.meta?.fee != null) {- feeLamports = parsed.meta.fee + (decoded.ataCreatePresent ? ATA_RENT_LAMPORTS : 0);+ feeLamports =+ parsed.meta.fee + (decoded.ataCreatePresent ? ataRentLamports(decoded.tokenProgram) : 0);}} catch { /* estimate stands */ }@@ -1084,7 +1127,7 @@ async function assertSettleable({ tx, connection, requirement, decoded }) {const mint = new PublicKey(decoded.mint);const authority = new PublicKey(decoded.payer);const sourceAta = getAssociatedTokenAddressSync(- mint, authority, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,+ mint, authority, false, new PublicKey(decoded.tokenProgram), ASSOCIATED_TOKEN_PROGRAM_ID,);const bal = await connection.getTokenAccountBalance(sourceAta, 'confirmed');const have = BigInt(bal?.value?.amount ?? '0');@@ -1104,21 +1147,46 @@ async function assertSettleable({ tx, connection, requirement, decoded }) {}}+// Resolve the token program for the requirement's mint before static validation.+// The two mints the platform settles are seeded, so this is a map read on the hot+// path. A deployment that points THREE_TOKEN_MINT or X402_ASSET_MINT_SOLANA at a+// different mint costs one cached account read. Mints outside that set are left+// unresolved on purpose: the requirement is caller-supplied, and validation+// refuses them as `mint_not_settleable` without spending an RPC call on junk.+async function resolveRingTokenProgram(connection, requirement) {+ const mint = String(requirement?.asset || '');+ const known = knownTokenProgramForMint(mint);+ if (known) return { ok: true, tokenProgramId: known };+ const settleable = [env.X402_ASSET_MINT_SOLANA, env.THREE_TOKEN_MINT].filter(Boolean);+ if (!settleable.includes(mint)) return { ok: true, tokenProgramId: null };+ try {+ return { ok: true, tokenProgramId: await tokenProgramForMint(connection, mint) };+ } catch (err) {+ return {+ ok: false,+ reason: `token_program_unresolved:${String(err?.code || err?.message || err).slice(0, 100)}`,+ };+ }+}+// Verify shape for /verify — validate statically, then prove settleability on-chain// WITHOUT broadcasting. Async: the settleability proof is one RPC round-trip.export async function verifyRingPayment({ paymentPayload, requirement, feePayerPubkey, conn }) {const txBase64 = txBase64FromPayload(paymentPayload);if (!txBase64) return { isValid: false, invalidReason: 'missing_transaction' };+ const connection =+ conn || solanaConnection({ url: env.SOLANA_RPC_URL, commitment: 'confirmed' });+ const program = await resolveRingTokenProgram(connection, requirement);+ if (!program.ok) return { isValid: false, invalidReason: program.reason };const validation = validateRingTransaction({txBase64,requirement,feePayerPubkey: feePayerPubkey || (env.X402_FEE_PAYER_SOLANA || null),allowlist: payToAllowlist(),+ tokenProgramId: program.tokenProgramId,});if (!validation.ok) return { isValid: false, invalidReason: validation.reason };- const connection =- conn || solanaConnection({ url: env.SOLANA_RPC_URL, commitment: 'confirmed' });const settleable = await assertSettleable({tx: validation.decoded.tx,connection,diff --git a/api/x402-checkout.js b/api/x402-checkout.jsindex 9b5495e6b..65cd43501 100644--- a/api/x402-checkout.js+++ b/api/x402-checkout.js@@ -29,7 +29,6 @@ import {ComputeBudgetProgram,} from '@solana/web3.js';import {- TOKEN_PROGRAM_ID,ASSOCIATED_TOKEN_PROGRAM_ID,getAssociatedTokenAddressSync,createAssociatedTokenAccountIdempotentInstruction,@@ -42,6 +41,7 @@ import { NETWORK_SOLANA_MAINNET, NETWORK_SOLANA_DEVNET } from './_lib/x402-spec.import { confirmSolanaPayment } from './_lib/x402-solana-confirm.js';import { ataExists, getRecentBlockhash, mintDecimals, respondRpcUnavailable } from './_lib/solana/read-guards.js';import { env } from './_lib/env.js';+import { tokenProgramForMint } from './_lib/solana-token-program.js';// Routed through env.* so the `api-mainnet.helius-rpc.com` misconfig is repaired// (env.normalizeRpcUrl) — a bad host 404'd getAccountInfo on the USDC mint here.@@ -244,21 +244,27 @@ async function handlePrepare(req, res) {const feePayer = selfPay ? buyerPubkey : toPubkey(accept.extra.feePayer, 'feePayer');const amount = BigInt(accept.amount);+ // The owning program decides every ATA address and the transfer's program id.+ // USDC is classic SPL Token and $THREE is Token-2022, so resolve it per mint+ // instead of assuming classic: a classic-built $THREE transfer names a source+ // ATA that does not exist and can never settle.+ const tokenProgram = await tokenProgramForMint(conn, mint);+const senderAta = getAssociatedTokenAddressSync(mint,buyerPubkey,false,- TOKEN_PROGRAM_ID,+ tokenProgram,ASSOCIATED_TOKEN_PROGRAM_ID,);const receiverAta = getAssociatedTokenAddressSync(mint,payTo,false,- TOKEN_PROGRAM_ID,+ tokenProgram,ASSOCIATED_TOKEN_PROGRAM_ID,);- const decimals = await mintDecimals(conn, mint);+ const decimals = await mintDecimals(conn, mint, { programId: tokenProgram });// Base payment needs ~60k CU; each donation adds a transfer (+ possibly an ATA// create), so budget headroom per tip. Unused CU isn't charged — this only@@ -275,7 +281,7 @@ async function handlePrepare(req, res) {receiverAta,payTo,mint,- TOKEN_PROGRAM_ID,+ tokenProgram,ASSOCIATED_TOKEN_PROGRAM_ID,),);@@ -289,7 +295,7 @@ async function handlePrepare(req, res) {amount,decimals,[],- TOKEN_PROGRAM_ID,+ tokenProgram,),);@@ -302,14 +308,14 @@ async function handlePrepare(req, res) {const v = validateTip(tip, { payTo, paymentAmount: amount });if (v.skip) continue; // zero/negative amount, nothing to sendif (!v.ok) return error(res, 400, v.code, v.message);- const tipAta = getAssociatedTokenAddressSync(mint, v.to, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID);+ const tipAta = getAssociatedTokenAddressSync(mint, v.to, false, tokenProgram, ASSOCIATED_TOKEN_PROGRAM_ID);if (!(await ataExists(conn, tipAta))) {ixs.push(- createAssociatedTokenAccountIdempotentInstruction(feePayer, tipAta, v.to, mint, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID),+ createAssociatedTokenAccountIdempotentInstruction(feePayer, tipAta, v.to, mint, tokenProgram, ASSOCIATED_TOKEN_PROGRAM_ID),);}ixs.push(- createTransferCheckedInstruction(senderAta, mint, tipAta, buyerPubkey, v.amount, decimals, [], TOKEN_PROGRAM_ID),+ createTransferCheckedInstruction(senderAta, mint, tipAta, buyerPubkey, v.amount, decimals, [], tokenProgram),);}}diff --git a/docs/x402-ring-economy.md b/docs/x402-ring-economy.mdindex f15c1e6ed..a94d829b8 100644--- a/docs/x402-ring-economy.md+++ b/docs/x402-ring-economy.md@@ -312,6 +312,16 @@ then kept in a verified, watched, auto-fundable state:allowlisted payTo}`. No System instructions (no SOL transfer out), cappedpriority fee, recipient must be allowlisted. This blocks the "anyone drainsthe sponsor" attack **and** enforces "only our wallets settle here".+ - **Both token programs.** USDC is a classic SPL Token mint and `$THREE` is a+ Token-2022 mint, and the two derive different associated token accounts for+ the same wallet. The facilitator pins the program from the mint+ ([api/_lib/solana-token-program.js](../api/_lib/solana-token-program.js)),+ never from the buyer's instruction, and derives every ATA under it. A transfer+ addressed to the other program is refused as `wrong_token_program:<id>` before+ any simulation. The transaction builder in+ [api/x402-checkout.js](../api/x402-checkout.js) resolves the program the same+ way, so what it builds is what the facilitator accepts. The ATA rent estimate+ is per program too: a Token-2022 ATA is 170 bytes, not 165.- **SOL floor.** Below `X402_SPONSOR_SOL_FLOOR_LAMPORTS` (default 0.02 SOL) thesponsor cannot settle, pausing the loop before it can drain your SOL. The flooris a **reserve that must survive the settle**, not a line the balance merely hasdiff --git a/tests/x402-self-facilitator-fee-meter.test.js b/tests/x402-self-facilitator-fee-meter.test.jsindex 1f4a86ffd..0bfadae0b 100644--- a/tests/x402-self-facilitator-fee-meter.test.js+++ b/tests/x402-self-facilitator-fee-meter.test.js@@ -15,10 +15,12 @@ import {ComputeBudgetProgram,} from '@solana/web3.js';import {+ TOKEN_PROGRAM_ID,getAssociatedTokenAddressSync,createTransferCheckedInstruction,} from '@solana/spl-token';+const { seedTokenProgramForMint } = await import('../api/_lib/solana-token-program.js');const { settleRingPayment } = await import('../api/_lib/x402/self-facilitator.js');const DECIMALS = 6;@@ -31,6 +33,9 @@ function buildPayment({ amount, sponsor } = {}) {const recipientOwner = Keypair.generate();const mint = Keypair.generate().publicKey;process.env.X402_ASSET_MINT_SOLANA = mint.toBase58();+ // The facilitator pins the token program from the mint, and this synthetic+ // mint has no account to read it from. Model it as classic SPL Token.+ seedTokenProgramForMint(mint, TOKEN_PROGRAM_ID);const feePayerKey = sponsor ? sponsor.publicKey : buyer.publicKey;const sourceAta = getAssociatedTokenAddressSync(mint, buyer.publicKey);diff --git a/tests/x402-self-facilitator-floor-accounting.test.js b/tests/x402-self-facilitator-floor-accounting.test.jsindex 12f84b90f..536d02d7d 100644--- a/tests/x402-self-facilitator-floor-accounting.test.js+++ b/tests/x402-self-facilitator-floor-accounting.test.js@@ -24,10 +24,12 @@ import {ComputeBudgetProgram,} from '@solana/web3.js';import {+ TOKEN_PROGRAM_ID,getAssociatedTokenAddressSync,createTransferCheckedInstruction,createAssociatedTokenAccountIdempotentInstruction,} from '@solana/spl-token';+import { seedTokenProgramForMint } from '../api/_lib/solana-token-program.js';const { settleRingPayment, sponsorKnownBelowFloor, SPONSOR_SOL_FLOOR_LAMPORTS } =await import('../api/_lib/x402/self-facilitator.js');@@ -45,6 +47,9 @@ function buildPayment({ amount = 10_000n, sponsor, withAtaCreate = false } = {})const recipientOwner = Keypair.generate();const mint = Keypair.generate().publicKey;process.env.X402_ASSET_MINT_SOLANA = mint.toBase58();+ // The facilitator pins the token program from the mint, and this synthetic+ // mint has no account to read it from. Model it as classic SPL Token.+ seedTokenProgramForMint(mint, TOKEN_PROGRAM_ID);const feePayerKey = sponsor ? sponsor.publicKey : buyer.publicKey;const sourceAta = getAssociatedTokenAddressSync(mint, buyer.publicKey);diff --git a/tests/x402-self-facilitator-min-settle.test.js b/tests/x402-self-facilitator-min-settle.test.jsindex 91ad8ba34..43d793929 100644--- a/tests/x402-self-facilitator-min-settle.test.js+++ b/tests/x402-self-facilitator-min-settle.test.js@@ -16,9 +16,11 @@ import {ComputeBudgetProgram,} from '@solana/web3.js';import {+ TOKEN_PROGRAM_ID,getAssociatedTokenAddressSync,createTransferCheckedInstruction,} from '@solana/spl-token';+import { seedTokenProgramForMint } from '../api/_lib/solana-token-program.js';const { settleRingPayment } = await import('../api/_lib/x402/self-facilitator.js');@@ -34,6 +36,9 @@ function buildPayment({ amount, sponsor } = {}) {// The facilitator only settles mints the platform issues 402s for (env-pinned// after the 2026-07-23 audit); model this synthetic mint as configured.process.env.X402_ASSET_MINT_SOLANA = mint.toBase58();+ // The facilitator pins the token program from the mint, and this synthetic+ // mint has no account to read it from. Model it as classic SPL Token.+ seedTokenProgramForMint(mint, TOKEN_PROGRAM_ID);const feePayerKey = sponsor ? sponsor.publicKey : buyer.publicKey;const sourceAta = getAssociatedTokenAddressSync(mint, buyer.publicKey);diff --git a/tests/x402-self-facilitator-settle-recovery.test.js b/tests/x402-self-facilitator-settle-recovery.test.jsindex 8e8162160..f7c83f80c 100644--- a/tests/x402-self-facilitator-settle-recovery.test.js+++ b/tests/x402-self-facilitator-settle-recovery.test.js@@ -13,9 +13,11 @@ import {ComputeBudgetProgram,} from '@solana/web3.js';import {+ TOKEN_PROGRAM_ID,getAssociatedTokenAddressSync,createTransferCheckedInstruction,} from '@solana/spl-token';+import { seedTokenProgramForMint } from '../api/_lib/solana-token-program.js';import bs58 from 'bs58';const { settleRingPayment } = await import('../api/_lib/x402/self-facilitator.js');@@ -31,6 +33,9 @@ function buildSelfPay(amount = 10_000) {// The facilitator only settles mints the platform issues 402s for (env-pinned// after the 2026-07-23 audit); model this synthetic mint as configured.process.env.X402_ASSET_MINT_SOLANA = mint.toBase58();+ // The facilitator pins the token program from the mint, and this synthetic+ // mint has no account to read it from. Model it as classic SPL Token.+ seedTokenProgramForMint(mint, TOKEN_PROGRAM_ID);const sourceAta = getAssociatedTokenAddressSync(mint, buyer.publicKey);const destAta = getAssociatedTokenAddressSync(mint, recipientOwner.publicKey);const transferIx = createTransferCheckedInstruction(diff --git a/tests/x402-self-facilitator-settleable.test.js b/tests/x402-self-facilitator-settleable.test.jsindex 56eca3244..a64fc0bff 100644--- a/tests/x402-self-facilitator-settleable.test.js+++ b/tests/x402-self-facilitator-settleable.test.js@@ -13,12 +13,17 @@import { describe, it, expect, beforeEach, afterEach } from 'vitest';import {Keypair,+ PublicKey,TransactionMessage,VersionedTransaction,ComputeBudgetProgram,} from '@solana/web3.js';import {+ TOKEN_PROGRAM_ID,+ TOKEN_2022_PROGRAM_ID,+ ASSOCIATED_TOKEN_PROGRAM_ID,getAssociatedTokenAddressSync,+ createAssociatedTokenAccountIdempotentInstruction,createTransferCheckedInstruction,} from '@solana/spl-token';@@ -27,6 +32,10 @@ const { verifyRingPayment, validateRingTransaction } = await import('../api/_libconst DECIMALS = 6;const AMOUNT_ATOMIC = 1000n; // 0.001 USDC+// The facilitator reads the mint account's owner to learn which token program+// the payment must call. These synthetic mints are modeled as classic SPL Token.+const classicMintOwner = async () => ({ owner: TOKEN_PROGRAM_ID });+// Build a real, buyer-signed SELF-PAY ring transaction: fee payer == the USDC// authority, so no sponsor key is needed and validateRingTransaction accepts it as// long as payTo is allowlisted. Returns the payment payload + requirement the@@ -94,6 +103,7 @@ describe('verifyRingPayment settleability gate', () => {process.env.X402_PAY_TO_SOLANA = p.payTo;// Simulation of a transfer from an unfunded ATA returns an InstructionError.const conn = {+ getAccountInfo: classicMintOwner,simulateTransaction: async () => ({ value: { err: { InstructionError: [1, { Custom: 1 }] } } }),getTokenAccountBalance: async () => { throw new Error('should not be called'); },};@@ -110,6 +120,7 @@ describe('verifyRingPayment settleability gate', () => {const p = buildSelfPayPayment();process.env.X402_PAY_TO_SOLANA = p.payTo;const conn = {+ getAccountInfo: classicMintOwner,simulateTransaction: async () => ({ value: { err: null, logs: [] } }),getTokenAccountBalance: async () => { throw new Error('should not be called'); },};@@ -127,6 +138,7 @@ describe('verifyRingPayment settleability gate', () => {const p = buildSelfPayPayment();process.env.X402_PAY_TO_SOLANA = p.payTo;const conn = {+ getAccountInfo: classicMintOwner,simulateTransaction: async () => { throw new Error('rpc down'); },getTokenAccountBalance: async () => ({ value: { amount: '0' } }),};@@ -143,6 +155,7 @@ describe('verifyRingPayment settleability gate', () => {const p = buildSelfPayPayment();process.env.X402_PAY_TO_SOLANA = p.payTo;const conn = {+ getAccountInfo: classicMintOwner,simulateTransaction: async () => { throw new Error('rpc down'); },getTokenAccountBalance: async () => ({ value: { amount: String(AMOUNT_ATOMIC) } }),};@@ -158,6 +171,7 @@ describe('verifyRingPayment settleability gate', () => {const p = buildSelfPayPayment();process.env.X402_PAY_TO_SOLANA = p.payTo;const conn = {+ getAccountInfo: classicMintOwner,simulateTransaction: async () => { throw new Error('rpc down'); },getTokenAccountBalance: async () => { throw new Error('rpc down'); },};@@ -175,6 +189,7 @@ describe('verifyRingPayment settleability gate', () => {process.env.X402_PAY_TO_SOLANA = p.payTo;let simulated = false;const conn = {+ getAccountInfo: classicMintOwner,simulateTransaction: async () => { simulated = true; return { value: { err: null } }; },getTokenAccountBalance: async () => ({ value: { amount: '0' } }),};@@ -200,6 +215,7 @@ describe('mint pin (2026-07-23 audit: junk-mint sponsor drain)', () => {delete process.env.THREE_TOKEN_MINT;let simulated = false;const conn = {+ getAccountInfo: classicMintOwner,simulateTransaction: async () => { simulated = true; return { value: { err: null } }; },getTokenAccountBalance: async () => ({ value: { amount: '999999999' } }),};@@ -251,6 +267,7 @@ describe('fee-payer rent failures are their own reason class', () => {process.env.X402_PAY_TO_SOLANA = p.payTo;process.env.X402_FEE_PAYER_SOLANA = p.feePayer;const conn = {+ getAccountInfo: classicMintOwner,simulateTransaction: async () => ({ value: { err: RENT_ERR } }),getTokenAccountBalance: async () => { throw new Error('should not be called'); },};@@ -270,6 +287,7 @@ describe('fee-payer rent failures are their own reason class', () => {process.env.X402_PAY_TO_SOLANA = p.payTo;process.env.X402_FEE_PAYER_SOLANA = Keypair.generate().publicKey.toBase58();const conn = {+ getAccountInfo: classicMintOwner,simulateTransaction: async () => ({ value: { err: RENT_ERR } }),getTokenAccountBalance: async () => { throw new Error('should not be called'); },};@@ -288,6 +306,7 @@ describe('fee-payer rent failures are their own reason class', () => {process.env.X402_PAY_TO_SOLANA = p.payTo;process.env.X402_FEE_PAYER_SOLANA = p.feePayer;const conn = {+ getAccountInfo: classicMintOwner,// A rent failure on a NON-fee-payer account is a different condition and// must not be reclassified: only index 0 is the fee payer.simulateTransaction: async () => ({@@ -304,3 +323,119 @@ describe('fee-payer rent failures are their own reason class', () => {expect(res.invalidReason.split(':')[0]).toBe('simulation_failed');});});++// $THREE is a Token-2022 mint. The facilitator used to pin the classic SPL Token+// program for the allowed program id and for every ATA derivation, so a $THREE+// payment could never verify: a classic-built transfer named a source ATA that+// does not exist, and a correctly built Token-2022 transfer was refused outright+// as `program_not_allowed`. Live on three.ws/club on 2026-09-20, where the cover+// charge quoted $THREE and every attempt to pay it failed at verify.+describe('Token-2022 mints settle on the same rail as classic ones', () => {+ const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';++ function buildThreePayment({ program, createRecipientAta = false }) {+ const buyer = Keypair.generate();+ const recipientOwner = Keypair.generate();+ const mint = new PublicKey(THREE_MINT);+ const sourceAta = getAssociatedTokenAddressSync(+ mint, buyer.publicKey, false, program, ASSOCIATED_TOKEN_PROGRAM_ID,+ );+ const destAta = getAssociatedTokenAddressSync(+ mint, recipientOwner.publicKey, false, program, ASSOCIATED_TOKEN_PROGRAM_ID,+ );+ const transferIx = createTransferCheckedInstruction(+ sourceAta, mint, destAta, buyer.publicKey, 10_000_000n, DECIMALS, [], program,+ );+ const message = new TransactionMessage({+ payerKey: buyer.publicKey,+ recentBlockhash: '11111111111111111111111111111111',+ instructions: [+ ComputeBudgetProgram.setComputeUnitLimit({ units: 60_000 }),+ ...(createRecipientAta+ ? [createAssociatedTokenAccountIdempotentInstruction(+ buyer.publicKey, destAta, recipientOwner.publicKey, mint, program, ASSOCIATED_TOKEN_PROGRAM_ID,+ )]+ : []),+ transferIx,+ ],+ }).compileToV0Message();+ const tx = new VersionedTransaction(message);+ tx.sign([buyer]);+ process.env.THREE_TOKEN_MINT = THREE_MINT;+ process.env.X402_PAY_TO_SOLANA = recipientOwner.publicKey.toBase58();+ return {+ requirement: {+ network: 'solana',+ asset: THREE_MINT,+ amount: '10000000',+ payTo: recipientOwner.publicKey.toBase58(),+ },+ paymentPayload: { transaction: Buffer.from(tx.serialize()).toString('base64') },+ };+ }++ it('verifies a $THREE payment built against the Token-2022 program', async () => {+ const p = buildThreePayment({ program: TOKEN_2022_PROGRAM_ID });+ const conn = {+ // The mint is seeded, so the hot path must not spend an RPC read on it.+ getAccountInfo: async () => { throw new Error('should not be called'); },+ simulateTransaction: async () => ({ value: { err: null, logs: [] } }),+ };+ const res = await verifyRingPayment({+ paymentPayload: p.paymentPayload,+ requirement: p.requirement,+ conn,+ });+ expect(res.invalidReason).toBeUndefined();+ expect(res.isValid).toBe(true);+ expect(res.asset).toBe(THREE_MINT);+ });++ it('names the wrong program when a $THREE transfer is built against classic SPL Token', async () => {+ const p = buildThreePayment({ program: TOKEN_PROGRAM_ID });+ let simulated = false;+ const conn = {+ simulateTransaction: async () => { simulated = true; return { value: { err: null } }; },+ };+ const res = await verifyRingPayment({+ paymentPayload: p.paymentPayload,+ requirement: p.requirement,+ conn,+ });+ expect(res.isValid).toBe(false);+ expect(res.invalidReason).toBe(`wrong_token_program:${TOKEN_PROGRAM_ID.toBase58()}`);+ expect(simulated).toBe(false);+ });++ it('budgets the larger Token-2022 ATA rent when the recipient account is new', () => {+ const p = buildThreePayment({ program: TOKEN_2022_PROGRAM_ID, createRecipientAta: true });+ const out = validateRingTransaction({+ txBase64: p.paymentPayload.transaction,+ requirement: p.requirement,+ feePayerPubkey: null,+ allowlist: new Set([p.requirement.payTo]),+ });+ expect(out.ok).toBe(true);+ expect(out.decoded.tokenProgram).toBe(TOKEN_2022_PROGRAM_ID.toBase58());+ expect(out.decoded.ataCreatePresent).toBe(true);+ // One signature (5000) plus the rent ceiling for a 170-byte Token-2022 ATA,+ // which must sit above the classic 165-byte figure (2,039,280).+ expect(out.decoded.estFeeLamports).toBe(5000 + 2_074_080);+ });++ it('fails closed when a configured mint cannot be resolved to a token program', async () => {+ const p = buildSelfPayPayment();+ process.env.X402_PAY_TO_SOLANA = p.payTo;+ const conn = {+ getAccountInfo: async () => { throw new Error('rpc down'); },+ simulateTransaction: async () => { throw new Error('should not be called'); },+ };+ const res = await verifyRingPayment({+ paymentPayload: p.paymentPayload,+ requirement: p.requirement,+ conn,+ });+ expect(res.isValid).toBe(false);+ expect(res.invalidReason).toMatch(/^token_program_unresolved:/);+ });+});diff --git a/tests/x402-settlement-pending.test.js b/tests/x402-settlement-pending.test.jsindex 845b59360..e299de041 100644--- a/tests/x402-settlement-pending.test.js+++ b/tests/x402-settlement-pending.test.js@@ -27,9 +27,11 @@ import {ComputeBudgetProgram,} from '@solana/web3.js';import {+ TOKEN_PROGRAM_ID,getAssociatedTokenAddressSync,createTransferCheckedInstruction,} from '@solana/spl-token';+import { seedTokenProgramForMint } from '../api/_lib/solana-token-program.js';import bs58 from 'bs58';const { settleRingPayment, probeSettlementSignature } = await import(@@ -52,6 +54,9 @@ function buildSelfPay(amount = 10_000) {const recipientOwner = Keypair.generate();const mint = Keypair.generate().publicKey;process.env.X402_ASSET_MINT_SOLANA = mint.toBase58();+ // The facilitator pins the token program from the mint, and this synthetic+ // mint has no account to read it from. Model it as classic SPL Token.+ seedTokenProgramForMint(mint, TOKEN_PROGRAM_ID);const sourceAta = getAssociatedTokenAddressSync(mint, buyer.publicKey);const destAta = getAssociatedTokenAddressSync(mint, recipientOwner.publicKey);const transferIx = createTransferCheckedInstruction(