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): let wallet priority-fee rewrites through the Solana checkout
nirholas56e7786667af
diff --git a/public/x402.js b/public/x402.jsindex e432c3416..5f4e42f94 100644--- a/public/x402.js+++ b/public/x402.js@@ -1611,20 +1611,27 @@ class CheckoutModal {// PayAI during /settle.const SolanaWeb3 = await loadSolanaWeb3();const tx = SolanaWeb3.VersionedTransaction.deserialize(txBytes);- // The merchant's facilitator only settles the exact transaction that- // /prepare built — a wallet that rewrites it before signing (injected- // priority-fee or guard instructions) produces a payment the verifier- // deterministically rejects. Snapshot the message bytes before the- // wallet touches the object (some wallets mutate in place), then- // compare after signing: a mismatch becomes an immediate, named- // explanation instead of a silent 402-retry loop.+ // Wallets with auto priority fees or "transaction protection" (Phantom,+ // Solflare) rewrite a transaction before signing. The facilitator settles+ // a rewritten tx fine as long as the rewrite only touches ComputeBudget+ // instructions or the blockhash: it re-validates shape, recipient,+ // amount, and fee caps server-side on every settle. Anything else (guard+ // programs, a changed transfer, a swapped fee payer) it deterministically+ // rejects, so those become an immediate, named explanation here instead+ // of a silent 402-retry loop. Snapshot the message bytes before the+ // wallet touches the object (some wallets mutate in place); the deep+ // classification re-reads the prepared tx from the original bytes.const preparedMsg = tx.message.serialize();const signed = await provider.signTransaction(tx);const signedMsg = signed?.message?.serialize?.();if (signedMsg && !bytesEqual(preparedMsg, signedMsg)) {- throw new Error(- `${walletName} altered the payment transaction before signing (wallets sometimes inject fee or guard instructions). Nothing was sent or charged. Turn off transaction modification in the wallet settings, or pay with a different Solana wallet.`,- );+ const prepared = SolanaWeb3.VersionedTransaction.deserialize(txBytes);+ const veto = classifyWalletTxMutation(prepared, signed);+ if (veto) {+ throw new Error(+ `${walletName} rewrote the payment transaction before signing (${veto}), so it can no longer settle. Nothing was sent or charged. Turn off transaction modification in the wallet settings, or pay with a different Solana wallet.`,+ );+ }}const signedB64 = uint8ArrayToBase64(signed.serialize());@@ -2146,6 +2153,70 @@ function bytesEqual(a, b) {for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;return true;}++// Wallet-rewrite classifier for the Solana checkout. The self-hosted+// facilitator's validateRingTransaction in api/_lib/x402/self-facilitator.js+// accepts any ComputeBudget instruction set within its fee caps and never pins+// the blockhash to what /prepare issued, so a wallet that only injects or+// retunes priority-fee instructions (Phantom and Solflare both do) still+// produces a settleable payment. What it hard-rejects is any other change:+// foreign programs (e.g. wallet-guard instructions), a modified transfer, or a+// swapped fee payer. Mirror exactly that line here.+const COMPUTE_BUDGET_PROGRAM = 'ComputeBudget111111111111111111111111111111';++// Resolve a v0 message's instructions to index-independent form so the+// comparison survives the wallet reordering or appending account keys.+function resolveNonBudgetInstructions(message) {+ const keys = message.staticAccountKeys.map((k) => k.toBase58());+ return message.compiledInstructions+ .map((ix) => ({+ program: keys[ix.programIdIndex],+ accounts: ix.accountKeyIndexes.map((i) => keys[i]),+ data: ix.data,+ }))+ .filter((ix) => ix.program !== COMPUTE_BUDGET_PROGRAM);+}++// Decide whether a wallet's pre-signing rewrite of the prepared transaction is+// benign (ComputeBudget/blockhash only → returns null, proceed to settle) or+// blocking (returns a short human-readable reason for the checkout error).+// Never throws on an odd wallet-returned object: unverifiable means blocking,+// since the facilitator would reject what we cannot vouch for.+export function classifyWalletTxMutation(preparedTx, signedTx) {+ try {+ const prepared = preparedTx.message;+ const signed = signedTx.message;+ const preparedFeePayer = prepared.staticAccountKeys[0]?.toBase58();+ const signedFeePayer = signed.staticAccountKeys[0]?.toBase58();+ if (preparedFeePayer !== signedFeePayer) {+ return 'it changed the transaction fee payer';+ }+ const preparedIxs = resolveNonBudgetInstructions(prepared);+ const signedIxs = resolveNonBudgetInstructions(signed);+ if (signedIxs.length !== preparedIxs.length) {+ const preparedPrograms = new Set(preparedIxs.map((ix) => ix.program));+ const added = signedIxs.find((ix) => !preparedPrograms.has(ix.program));+ return added+ ? `it injected instructions from program ${added.program}`+ : 'it added or removed payment instructions';+ }+ for (let i = 0; i < preparedIxs.length; i++) {+ const a = preparedIxs[i];+ const b = signedIxs[i];+ if (+ a.program !== b.program ||+ a.accounts.length !== b.accounts.length ||+ a.accounts.some((key, j) => key !== b.accounts[j]) ||+ !bytesEqual(a.data, b.data)+ ) {+ return 'it changed the payment instructions';+ }+ }+ return null;+ } catch {+ return 'the rewrite could not be verified';+ }+}function randomHex(bytes) {const arr = new Uint8Array(bytes);crypto.getRandomValues(arr);diff --git a/tests/x402-wallet-rewrite.test.js b/tests/x402-wallet-rewrite.test.jsnew file mode 100644index 000000000..57615c3b1--- /dev/null+++ b/tests/x402-wallet-rewrite.test.js@@ -0,0 +1,147 @@+// @vitest-environment jsdom+// public/x402.js reads location.origin at import time, so this suite runs under+// a DOM environment.+import { describe, it, expect } from 'vitest';+import {+ Keypair,+ PublicKey,+ TransactionInstruction,+ TransactionMessage,+ VersionedTransaction,+} from '@solana/web3.js';++import { classifyWalletTxMutation } from '../public/x402.js';++// Regression guard for the /club "transaction modification" checkout failure:+// wallets with auto priority fees or transaction protection (Phantom, Solflare)+// rewrite the prepared payment before signing. The self-hosted facilitator+// settles ComputeBudget-only rewrites fine (validateRingTransaction accepts any+// compute-budget set within its fee caps and never pins the blockhash), so the+// modal must not bounce those buyers. Everything else must stay blocked with a+// named reason, because the facilitator deterministically rejects it.++const feePayer = Keypair.generate().publicKey;+const buyer = Keypair.generate().publicKey;+const tokenProgram = new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA');+const guardProgram = Keypair.generate().publicKey;+const BLOCKHASH_A = '9SKUcvUFmCzhu9nRCYX3et4vinLLNPTVQhh6BLNRSTgV';+const BLOCKHASH_B = 'EETubP5AKHgjPAhzPAFcb8BAY1hMH639CWCFTqi3hq1k';+const computeBudgetProgram = new PublicKey('ComputeBudget111111111111111111111111111111');++// Hand-encoded ComputeBudget instructions (tag 2 = SetComputeUnitLimit u32,+// tag 3 = SetComputeUnitPrice u64). web3.js's ComputeBudgetProgram encoder+// trips over jsdom's foreign-realm Buffers, and the wire bytes are trivial.+function setComputeUnitLimit(units) {+ const data = Buffer.alloc(5);+ data[0] = 2;+ data.writeUInt32LE(units, 1);+ return new TransactionInstruction({ programId: computeBudgetProgram, keys: [], data });+}++function setComputeUnitPrice(microLamports) {+ const data = Buffer.alloc(9);+ data[0] = 3;+ data.writeBigUInt64LE(BigInt(microLamports), 1);+ return new TransactionInstruction({ programId: computeBudgetProgram, keys: [], data });+}++function transferIx({ amount = 1000 } = {}) {+ const data = new Uint8Array(10);+ data[0] = 12; // TransferChecked tag+ data[1] = amount & 0xff;+ return new TransactionInstruction({+ programId: tokenProgram,+ keys: [+ { pubkey: Keypair.generate().publicKey, isSigner: false, isWritable: true },+ { pubkey: buyer, isSigner: true, isWritable: false },+ ],+ data: Buffer.from(data),+ });+}++function buildTx({ payerKey = feePayer, recentBlockhash = BLOCKHASH_A, instructions }) {+ const message = new TransactionMessage({+ payerKey,+ recentBlockhash,+ instructions,+ }).compileToV0Message();+ return new VersionedTransaction(message);+}++describe('classifyWalletTxMutation', () => {+ // The one shared instruction set: prepare's compute budget pair + transfer.+ const transfer = transferIx();+ const preparedIxs = [+ setComputeUnitLimit(60_000),+ setComputeUnitPrice(1),+ transfer,+ ];++ it('accepts an untouched transaction', () => {+ const prepared = buildTx({ instructions: preparedIxs });+ const signed = buildTx({ instructions: preparedIxs });+ expect(classifyWalletTxMutation(prepared, signed)).toBeNull();+ });++ it('accepts a wallet retuning the priority fee (ComputeBudget-only rewrite)', () => {+ const prepared = buildTx({ instructions: preparedIxs });+ const signed = buildTx({+ instructions: [+ setComputeUnitLimit(120_000),+ setComputeUnitPrice(50_000),+ transfer,+ ],+ });+ expect(classifyWalletTxMutation(prepared, signed)).toBeNull();+ });++ it('accepts a wallet stripping the compute budget entirely', () => {+ const prepared = buildTx({ instructions: preparedIxs });+ const signed = buildTx({ instructions: [transfer] });+ expect(classifyWalletTxMutation(prepared, signed)).toBeNull();+ });++ it('accepts a refreshed blockhash', () => {+ const prepared = buildTx({ instructions: preparedIxs });+ const signed = buildTx({ instructions: preparedIxs, recentBlockhash: BLOCKHASH_B });+ expect(classifyWalletTxMutation(prepared, signed)).toBeNull();+ });++ it('names the program when a wallet injects guard instructions', () => {+ const prepared = buildTx({ instructions: preparedIxs });+ const signed = buildTx({+ instructions: [+ ...preparedIxs,+ new TransactionInstruction({ programId: guardProgram, keys: [], data: Buffer.from([1]) }),+ ],+ });+ expect(classifyWalletTxMutation(prepared, signed)).toBe(+ `it injected instructions from program ${guardProgram.toBase58()}`,+ );+ });++ it('blocks a changed transfer amount', () => {+ const prepared = buildTx({ instructions: preparedIxs });+ const signed = buildTx({+ instructions: [preparedIxs[0], preparedIxs[1], transferIx({ amount: 255 })],+ });+ expect(classifyWalletTxMutation(prepared, signed)).toBe('it changed the payment instructions');+ });++ it('blocks a swapped fee payer', () => {+ const prepared = buildTx({ instructions: preparedIxs });+ const signed = buildTx({ payerKey: buyer, instructions: preparedIxs });+ expect(classifyWalletTxMutation(prepared, signed)).toBe('it changed the transaction fee payer');+ });++ it('blocks a dropped transfer instruction', () => {+ const prepared = buildTx({ instructions: preparedIxs });+ const signed = buildTx({ instructions: [preparedIxs[0], preparedIxs[1]] });+ expect(classifyWalletTxMutation(prepared, signed)).toBe('it added or removed payment instructions');+ });++ it('blocks an unverifiable wallet-returned object instead of throwing', () => {+ const prepared = buildTx({ instructions: preparedIxs });+ expect(classifyWalletTxMutation(prepared, {})).toBe('the rewrite could not be verified');+ });+});