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: harden Solana x402 facilitators and wallet clients
nirholas38c7ca0b838c
diff --git a/agent-payments-sdk/src/solana/PumpAgent.ts b/agent-payments-sdk/src/solana/PumpAgent.tsindex 4736e45c0..2b617be91 100644--- a/agent-payments-sdk/src/solana/PumpAgent.ts+++ b/agent-payments-sdk/src/solana/PumpAgent.ts@@ -38,6 +38,32 @@ import {type ParsedAgentEvent,} from "./events";+/**+ * Bounded-concurrency map: runs `fn` over `items` in chunks of at most `size`+ * so we parallelise RPC round-trips without firing an unbounded fan-out that+ * would trip RPC provider rate limits. Order of results matches input order.+ */+async function mapWithConcurrency<T, R>(+ items: readonly T[],+ size: number,+ fn: (item: T, index: number) => Promise<R>,+): Promise<R[]> {+ const results: R[] = new Array(items.length);+ for (let start = 0; start < items.length; start += size) {+ const slice = items.slice(start, start + size);+ const settled = await Promise.all(+ slice.map((item, offset) => fn(item, start + offset)),+ );+ // settled[i] is in-bounds by construction; the `!` satisfies+ // noUncheckedIndexedAccess (Awaited<R> | undefined → R).+ for (let i = 0; i < settled.length; i++) results[start + i] = settled[i]!;+ }+ return results;+}++/** Max concurrent getTransaction round-trips per chunk (RPC-friendly). */+const TX_FETCH_CONCURRENCY = 10;+export class PumpAgent extends PumpAgentOffline {private connection?: Connection;private environment: PumpEnvironment;@@ -318,15 +344,21 @@ export class PumpAgent extends PumpAgentOffline {{ limit },);- const payments: AgentAcceptPaymentEvent[] = [];+ // Fetch transactions concurrently (chunked) rather than one serial+ // round-trip per signature — up to `limit` (default 50) RPC calls.+ const okSignatures = signatures.filter((sig) => !sig.err);+ const txs = await mapWithConcurrency(+ okSignatures,+ TX_FETCH_CONCURRENCY,+ (sig) =>+ connection.getTransaction(sig.signature, {+ maxSupportedTransactionVersion: 0,+ }),+ );- for (const sig of signatures) {- if (sig.err) continue;- const tx = await connection.getTransaction(sig.signature, {- maxSupportedTransactionVersion: 0,- });+ const payments: AgentAcceptPaymentEvent[] = [];+ for (const tx of txs) {if (!tx?.meta?.logMessages) continue;-const events = parseAgentEvents(tx.meta.logMessages, connection);for (const event of events) {if (event.name === "agentAcceptPaymentEvent") {@@ -356,15 +388,20 @@ export class PumpAgent extends PumpAgentOffline {{ limit },);- const allEvents: ParsedAgentEvent[] = [];+ // Fetch transactions concurrently (chunked) instead of serially.+ const okSignatures = signatures.filter((sig) => !sig.err);+ const txs = await mapWithConcurrency(+ okSignatures,+ TX_FETCH_CONCURRENCY,+ (sig) =>+ connection.getTransaction(sig.signature, {+ maxSupportedTransactionVersion: 0,+ }),+ );- for (const sig of signatures) {- if (sig.err) continue;- const tx = await connection.getTransaction(sig.signature, {- maxSupportedTransactionVersion: 0,- });+ const allEvents: ParsedAgentEvent[] = [];+ for (const tx of txs) {if (!tx?.meta?.logMessages) continue;-const events = parseAgentEvents(tx.meta.logMessages, connection);allEvents.push(...events);}@@ -460,20 +497,12 @@ export class PumpAgent extends PumpAgentOffline {const signatures = await connection.getSignaturesForAddress(invoiceId);- for (const sig of signatures) {- const tx = await connection.getTransaction(sig.signature, {- maxSupportedTransactionVersion: 0,- });- if (!tx || tx.meta?.err) continue;-- const logs = tx.meta?.logMessages;- if (!logs) continue;-- const parser = new EventParser(- this.program.programId,- this.program.coder,- );+ const parser = new EventParser(+ this.program.programId,+ this.program.coder,+ );+ const matchesInvoice = (logs: string[]): boolean => {for (const event of parser.parseLogs(logs)) {if (event.name !== "agentAcceptPaymentEvent") continue;@@ -499,6 +528,27 @@ export class PumpAgent extends PumpAgentOffline {return true;}}+ return false;+ };++ // Fetch the invoice PDA's transactions concurrently (chunked) and+ // short-circuit as soon as a chunk yields a matching payment event.+ for (let start = 0; start < signatures.length; start += TX_FETCH_CONCURRENCY) {+ const slice = signatures.slice(start, start + TX_FETCH_CONCURRENCY);+ const txs = await Promise.all(+ slice.map((sig) =>+ connection.getTransaction(sig.signature, {+ maxSupportedTransactionVersion: 0,+ }),+ ),+ );++ for (const tx of txs) {+ if (!tx || tx.meta?.err) continue;+ const logs = tx.meta?.logMessages;+ if (!logs) continue;+ if (matchesInvoice(logs)) return true;+ }}return false;diff --git a/agent-payments-sdk/src/solana/x402/facilitator.ts b/agent-payments-sdk/src/solana/x402/facilitator.tsindex 6284cbea5..7c84e80ab 100644--- a/agent-payments-sdk/src/solana/x402/facilitator.ts+++ b/agent-payments-sdk/src/solana/x402/facilitator.ts@@ -63,12 +63,21 @@ export interface ReplayStore {// ─── Settlement Cache ───────────────────────────────────────────────────────+/**+ * Default in-process replay-cache TTL. MUST be >= the maximum invoice window+ * (buildPumpAgentRequirements defaults to a 300s window) plus a clock-skew+ * margin, otherwise a proof can age out of the cache while its on-chain invoice+ * is still valid and be replayed for free access (audit #14). 300s window ++ * 120s skew margin = 420s.+ */+const DEFAULT_SETTLEMENT_TTL_MS = 420_000;+class SettlementCache {private cache = new Map<string, number>();private maxSize: number;private ttlMs: number;- constructor(maxSize = 10_000, ttlMs = 120_000) {+ constructor(maxSize = 10_000, ttlMs = DEFAULT_SETTLEMENT_TTL_MS) {this.maxSize = maxSize;this.ttlMs = ttlMs;}@@ -111,6 +120,24 @@ function generateMemo(): string {return `${ts}${String(memoCounter).padStart(6, "0")}`;}+/**+ * Stable logical key for an invoice, mirroring the on-chain invoice-id seeds:+ * (agentMint, currencyMint/asset, amount, memo, startTime, endTime). Used as+ * the replay-store key so a given invoice is single-use regardless of which+ * transaction signature settled it — the memo is freshly minted per 402, so an+ * attacker who pays one invoice cannot redeem it twice (audit #1).+ */+function invoiceKey(req: PumpAgentPaymentRequirements): string {+ return [+ req.extra.agentMint,+ req.asset,+ req.amount,+ String(req.extra.memo),+ String(req.extra.startTime),+ String(req.extra.endTime),+ ].join(":");+}+// ─── Pump Agent Facilitator ─────────────────────────────────────────────────export interface PumpAgentFacilitatorConfig {@@ -221,11 +248,15 @@ export class PumpAgentFacilitator implements FacilitatorClient {const proof = payload.payload as Record<string, unknown>;const signature = proof.signature as string;const payer = proof.payer as string;+ const req = requirements as PumpAgentPaymentRequirements;- // Atomically consume the signature — true exactly once. With a durable+ // Atomically consume the per-request INVOICE (memo + window), not just the+ // signature. The memo is freshly minted per 402, so this makes each invoice+ // single-use: once redeemed it can never be settled again, regardless of+ // the cache TTL or which signature paid it (audit #1, #14). With a durable// ReplayStore this is the cross-instance double-spend guard; with the// in-memory default it only protects within a single process.- const claimed = await this.replayStore.claim(signature);+ const claimed = await this.replayStore.claim(invoiceKey(req));if (!claimed) {return { success: false, errorReason: "Duplicate payment", payer };}@@ -295,6 +326,87 @@ export function buildPumpAgentRequirements(};}+/**+ * Re-mint the per-request invoice fields of a `pump-agent` requirement: a new+ * unique memo and a fresh validity window starting now. Non-invoice fields+ * (amount, asset, payTo, agentMint, network) are preserved from the template.+ * Non-pump-agent requirements are returned unchanged.+ */+function refreshRequirement(req: PaymentRequirements): PaymentRequirements {+ if (req.scheme !== "pump-agent") return req;+ const pump = req as PumpAgentPaymentRequirements;+ const now = Math.floor(Date.now() / 1000);+ const windowSec = Math.max(1, pump.extra.endTime - pump.extra.startTime || 300);+ return {+ ...pump,+ extra: {+ ...pump.extra,+ memo: generateMemo(),+ startTime: now,+ endTime: now + windowSec,+ },+ };+}++/**+ * Produce the `accepts[]` for a 402 response: a caller-supplied+ * {@link ResourceServerConfig.mintRequirements} factory takes precedence;+ * otherwise each configured requirement has its invoice fields refreshed so the+ * memo/window are unique per request (audit #1).+ */+async function mintRequirements(+ config: ResourceServerConfig,+ request: Request,+): Promise<PaymentRequirements[]> {+ if (config.mintRequirements) {+ return config.mintRequirements(request);+ }+ return config.requirements.map(refreshRequirement);+}++/**+ * Guard the client-echoed `accepted` requirement against the configured+ * template: the immutable, server-owned fields (scheme, network, asset, amount,+ * payTo, agentMint) must match exactly so a client cannot downgrade the price,+ * swap the asset, or redirect the recipient by editing the requirement it+ * echoes back. The invoice fields (memo/startTime/endTime) are intentionally+ * NOT compared — they are minted per request and validated on-chain.+ */+function acceptedMatchesTemplate(+ accepted: PaymentRequirements,+ template: PaymentRequirements,+): boolean {+ if (+ accepted.scheme !== template.scheme ||+ accepted.network !== template.network ||+ accepted.asset !== template.asset ||+ accepted.amount !== template.amount ||+ accepted.payTo !== template.payTo+ ) {+ return false;+ }+ if (accepted.scheme === "pump-agent" && template.scheme === "pump-agent") {+ const a = accepted as PumpAgentPaymentRequirements;+ const t = template as PumpAgentPaymentRequirements;+ if (a.extra.agentMint !== t.extra.agentMint) return false;+ // Reject an invoice window outside the configured maximum so a client+ // can't claim an arbitrarily long-lived invoice.+ if (+ !Number.isFinite(a.extra.startTime) ||+ !Number.isFinite(a.extra.endTime) ||+ a.extra.endTime <= a.extra.startTime+ ) {+ return false;+ }+ const templateWindow = Math.max(+ 1,+ t.extra.endTime - t.extra.startTime || 300,+ );+ if (a.extra.endTime - a.extra.startTime > templateWindow) return false;+ }+ return true;+}+// ─── Resource Server Middleware ──────────────────────────────────────────────/**@@ -340,11 +452,16 @@ export function createResourceServer(const paymentHeader = request.headers.get(X402_HEADER_PAYMENT);if (!paymentHeader) {- // Build fresh requirements (with new invoice memos)+ // Mint a FRESH invoice per 402: each pump-agent requirement gets a new+ // memo + validity window so the payment the client makes is bound to a+ // single, single-use invoice (audit #1). A static, reused memo/window+ // would let one on-chain payment be replayed across requests.+ const accepts = await mintRequirements(config, request);+const body: PaymentRequired = {x402Version: X402_VERSION,resource,- accepts: config.requirements,+ accepts,};return new Response(JSON.stringify(body), {@@ -365,16 +482,28 @@ export function createResourceServer(return new Response("Invalid X-PAYMENT header", { status: 400 });}- // Find the matching requirement+ // The authoritative requirement for verification is the per-request invoice+ // the CLIENT echoes back in `accepted` (it carries the fresh memo/window we+ // issued in the matching 402). We do NOT trust a static server template+ // here, because the invoice fields (memo/startTime/endTime) are now unique+ // per request. We still pin the immutable, server-owned fields (scheme,+ // network, asset, amount, payTo, agentMint) to a configured template so a+ // client can't downgrade the price or redirect the recipient.const accepted = paymentPayload.accepted;- const matchedReq = config.requirements.find(+ const template = config.requirements.find((r) => r.scheme === accepted.scheme && r.network === accepted.network,);- if (!matchedReq) {+ if (!template) {return new Response("No matching payment requirement", { status: 400 });}+ if (!acceptedMatchesTemplate(accepted, template)) {+ return new Response("Payment requirement mismatch", { status: 400 });+ }++ const matchedReq = accepted;+// Verifyconst verifyResult = await facilitator.verify(paymentPayload, matchedReq);if (!verifyResult.isValid) {diff --git a/agent-payments-sdk/src/solana/x402/types.ts b/agent-payments-sdk/src/solana/x402/types.tsindex 7afb01cf7..eaf09bb58 100644--- a/agent-payments-sdk/src/solana/x402/types.ts+++ b/agent-payments-sdk/src/solana/x402/types.ts@@ -225,10 +225,28 @@ export interface PaymentResponse {export interface ResourceServerConfig {/** Facilitator client to use for verify + settle */facilitator: FacilitatorClient;- /** Default payment requirements for this resource */+ /**+ * Default payment requirements for this resource.+ *+ * For the `pump-agent` scheme the resource server mints a FRESH invoice+ * (new memo + validity window) per 402 response so each payment is bound to+ * a single, single-use invoice — these entries act as the template for amount+ * / asset / agentMint / payTo, not as a reusable static invoice. Provide+ * {@link mintRequirements} to fully control per-request invoice generation.+ */requirements: PaymentRequirements[];/** Resource info describing what's for sale */resource: ResourceInfo;+ /**+ * Optional factory invoked on every 402 to mint fresh, per-request payment+ * requirements (e.g. via `buildPumpAgentRequirements`). When omitted, the+ * server regenerates the invoice fields (memo/startTime/endTime) of any+ * `pump-agent` entry in {@link requirements} for each 402. Supplying this lets+ * you vary price/asset per request or add per-caller invoice metadata.+ */+ mintRequirements?: (+ request: Request,+ ) => PaymentRequirements[] | Promise<PaymentRequirements[]>;}// ─── Client Configuration ───────────────────────────────────────────────────diff --git a/solana-agent-sdk/src/wallet/browser-client.ts b/solana-agent-sdk/src/wallet/browser-client.tsindex 6e437eff2..e074b721c 100644--- a/solana-agent-sdk/src/wallet/browser-client.ts+++ b/solana-agent-sdk/src/wallet/browser-client.ts@@ -33,6 +33,12 @@ export type ApprovalHandler = () => void;export interface BrowserWalletClientOptions {+ /**+ * Session id issued by the server-side BrowserWalletProvider. Required to+ * authorize /stream, /sign and /reject — the server rejects requests without+ * it. Pass the provider's `sessionId` through to the browser at page load.+ */+ sessionId?: string;/*** Called with each pending tx before the wallet prompt.* Must call approve() or reject() — whichever the user chooses.@@ -90,8 +96,18 @@ export class BrowserWalletClient {}}+ private sessionQuery(): string {+ const sid = this.opts.sessionId;+ return sid ? `?session=${encodeURIComponent(sid)}` : "";+ }++ private authHeaders(extra: Record<string, string> = {}): Record<string, string> {+ const sid = this.opts.sessionId;+ return sid ? { ...extra, "x-wallet-session": sid } : extra;+ }+private openStream(): void {- const es = new EventSource(`${this.baseUrl}/stream`);+ const es = new EventSource(`${this.baseUrl}/stream${this.sessionQuery()}`);this.eventSource = es;es.onmessage = (event: MessageEvent<string>) => {@@ -144,7 +160,7 @@ export class BrowserWalletClient {const serialized = uint8ArrayToBase64(signed.serialize());const res = await fetch(`${this.baseUrl}/sign/${pending.id}`, {method: "POST",- headers: { "Content-Type": "application/json" },+ headers: this.authHeaders({ "Content-Type": "application/json" }),body: JSON.stringify({ signedTransaction: serialized }),});@@ -155,7 +171,10 @@ export class BrowserWalletClient {}private async reject(pending: PendingTx, reason: string): Promise<void> {- await fetch(`${this.baseUrl}/reject/${pending.id}`, { method: "POST" }).catch(() => undefined);+ await fetch(`${this.baseUrl}/reject/${pending.id}`, {+ method: "POST",+ headers: this.authHeaders(),+ }).catch(() => undefined);this.opts.onRejected?.(pending, reason);}}diff --git a/solana-agent-sdk/src/wallet/browser-server.ts b/solana-agent-sdk/src/wallet/browser-server.tsindex 0a09e5ee4..3844f171e 100644--- a/solana-agent-sdk/src/wallet/browser-server.ts+++ b/solana-agent-sdk/src/wallet/browser-server.ts@@ -182,7 +182,7 @@ export class BrowserWalletProvider implements MetaAwareWallet {}getPending(): PendingTx[] {- return Array.from(this.pending.values());+ return Array.from(this.pending.values(), toPublic);}submitSigned(txId: string, signedBase64: string): void {@@ -202,6 +202,19 @@ export class BrowserWalletProvider implements MetaAwareWallet {return () => this.emitter.off("pending", listener);}+ /**+ * Validate that a request carries this provider's session id. The session id+ * is the shared secret that binds these endpoints to the legitimate wallet+ * owner — without it, anyone who learns a (guessable) tx id could sign/reject.+ * The id is read from the `x-wallet-session` header or, for EventSource which+ * cannot set headers, the `session` query parameter.+ */+ private isAuthorized(req: Request, url: URL): boolean {+ const provided =+ req.headers.get("x-wallet-session") ?? url.searchParams.get("session") ?? "";+ return constantTimeEquals(provided, this.sessionId);+ }+/*** Returns a fetch-API Request handler. Mount it in your server:*@@ -209,6 +222,10 @@ export class BrowserWalletProvider implements MetaAwareWallet {* GET {base}/stream → SSE stream of new pending txs* POST {base}/sign/:id → body: { signedTransaction: base64 }* POST {base}/reject/:id → user rejected+ *+ * Every request must carry the provider's `sessionId` (header+ * `x-wallet-session`, or `?session=` for the SSE stream). Requests without it+ * are rejected with 401 so only the legitimate wallet owner can drive signing.*/createHandler(base = ""): (req: Request) => Promise<Response> {return async (req: Request) => {@@ -216,6 +233,10 @@ export class BrowserWalletProvider implements MetaAwareWallet {const path = url.pathname.replace(base, "").replace(/^\//, "");const [action, id] = path.split("/");+ if (!this.isAuthorized(req, url)) {+ return new Response("Unauthorized", { status: 401 });+ }+// GET /pending — snapshot of current queueif (req.method === "GET" && !action) {return Response.json({ pending: this.getPending() });@@ -259,6 +280,9 @@ export class BrowserWalletProvider implements MetaAwareWallet {// POST /sign/:idif (req.method === "POST" && action === "sign" && id) {+ if (!this.pending.has(id)) {+ return new Response("Unknown transaction", { status: 404 });+ }const body = (await req.json()) as { signedTransaction: string };const sigPromise = new Promise<string | null>((resolve) => {const t = setTimeout(() => resolve(null), 60_000);@@ -274,6 +298,9 @@ export class BrowserWalletProvider implements MetaAwareWallet {// POST /reject/:idif (req.method === "POST" && action === "reject" && id) {+ if (!this.pending.has(id)) {+ return new Response("Unknown transaction", { status: 404 });+ }this.submitRejected(id);return Response.json({ ok: true });}@@ -282,3 +309,38 @@ export class BrowserWalletProvider implements MetaAwareWallet {};}}++// ─── Helpers ─────────────────────────────────────────────────────────────────++/** DER SPKI prefix for an Ed25519 public key (RFC 8410). */+const ED25519_SPKI_PREFIX = Buffer.from([+ 0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00,+]);++/** Compiled message bytes used to detect tampering between request and response. */+function compiledMessageBytes(tx: Transaction | VersionedTransaction): Uint8Array {+ return tx instanceof Transaction+ ? Uint8Array.from(tx.serializeMessage())+ : tx.message.serialize();+}++function buffersEqual(a: Uint8Array, b: Uint8Array): boolean {+ if (a.length !== b.length) return false;+ let diff = 0;+ for (let i = 0; i < a.length; i++) diff |= a[i]! ^ b[i]!;+ return diff === 0;+}++/** Constant-time string comparison for session-id checks. */+function constantTimeEquals(a: string, b: string): boolean {+ if (a.length !== b.length) return false;+ let diff = 0;+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);+ return diff === 0;+}++/** Strip internal fields, returning the public PendingTx shape. */+function toPublic(entry: PendingEntry): PendingTx {+ const { messageBytes: _messageBytes, ...rest } = entry;+ return rest;+}diff --git a/solana-agent-sdk/src/x402-exact/facilitator.ts b/solana-agent-sdk/src/x402-exact/facilitator.tsindex 4c6698848..e4537e07d 100644--- a/solana-agent-sdk/src/x402-exact/facilitator.ts+++ b/solana-agent-sdk/src/x402-exact/facilitator.ts@@ -293,12 +293,20 @@ function collectInstructions(return [...top, ...inner];}+interface TransferMatch {+ found: boolean;+ payer: string;+ reason: string;+}+function findTransferChecked(tx: Awaited<ReturnType<Connection["getParsedTransaction"]>>,req: ExactPaymentRequirements,-): { found: true; payer: string } | { found: false; reason: string } {+): TransferMatch {const instructions = collectInstructions(tx);- if (!instructions.length) return { found: false, reason: "No instructions in transaction" };+ if (!instructions.length) {+ return { found: false, payer: "", reason: "No instructions in transaction" };+ }const receiverAta = deriveAta(new PublicKey(req.payTo), new PublicKey(req.asset));@@ -312,11 +320,12 @@ function findTransferChecked(if (info.destination !== receiverAta.toBase58()) continue;if (info.tokenAmount?.amount !== req.amount) continue;- return { found: true, payer: info.authority ?? info.source ?? "" };+ return { found: true, payer: info.authority ?? info.source ?? "", reason: "" };}return {found: false,+ payer: "",reason: `No matching transferChecked to ${req.payTo} for ${req.amount} of ${req.asset}`,};}diff --git a/solana-agent-sdk/tests/actions/swap.test.ts b/solana-agent-sdk/tests/actions/swap.test.tsindex 56ad5cfab..19ef0fb36 100644--- a/solana-agent-sdk/tests/actions/swap.test.ts+++ b/solana-agent-sdk/tests/actions/swap.test.ts@@ -5,24 +5,53 @@ let mockFetch = jest.fn<(url: RequestInfo | URL, init?: RequestInit) => Promise<const { jupiterSwap, getSwapQuote, SOL_MINT } = await import("../../src/actions/swap.js");const { SwapError } = await import("../../src/errors.js");-const { Keypair, TransactionMessage, VersionedTransaction } =+const { Keypair, PublicKey, TransactionMessage, VersionedTransaction } =await import("@solana/web3.js") as typeof import("@solana/web3.js");+const {+ getAssociatedTokenAddressSync,+ createTransferCheckedInstruction,+ TOKEN_PROGRAM_ID,+ ASSOCIATED_TOKEN_PROGRAM_ID,+} = await import("@solana/spl-token") as typeof import("@solana/spl-token");const WALLET_PUBKEY = Keypair.fromSeed(new Uint8Array(32).fill(1)).publicKey;-// Minimal valid VersionedTransaction for mock Jupiter swap response-const MOCK_TX_BASE64 = (() => {+const INPUT_MINT = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"; // USDC+const OUTPUT_MINT = "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump"; // $THREE+const COUNTERPARTY = Keypair.fromSeed(new Uint8Array(32).fill(2)).publicKey;++function ata(mint: string, owner = WALLET_PUBKEY) {+ return getAssociatedTokenAddressSync(+ new PublicKey(mint), owner, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,+ );+}++// A realistic Jupiter swap tx: spend INPUT from the wallet's ATA, credit OUTPUT+// back to the wallet's ATA. The new swap-guard validates exactly this shape.+function buildSwapTx(inAmount: bigint): string {+ const counterpartyOut = ata(OUTPUT_MINT, COUNTERPARTY);const msg = new TransactionMessage({payerKey: WALLET_PUBKEY,recentBlockhash: "11111111111111111111111111111111",- instructions: [],+ instructions: [+ createTransferCheckedInstruction(+ ata(INPUT_MINT), new PublicKey(INPUT_MINT), ata(INPUT_MINT, COUNTERPARTY),+ WALLET_PUBKEY, inAmount, 6, [], TOKEN_PROGRAM_ID,+ ),+ createTransferCheckedInstruction(+ counterpartyOut, new PublicKey(OUTPUT_MINT), ata(OUTPUT_MINT),+ COUNTERPARTY, 990_000_000n, 6, [], TOKEN_PROGRAM_ID,+ ),+ ],}).compileToV0Message();return Buffer.from(new VersionedTransaction(msg).serialize()).toString("base64");-})();+}++const MOCK_TX_BASE64 = buildSwapTx(1_000_000_000n);const MOCK_QUOTE = {- inputMint: SOL_MINT,- outputMint: SOL_MINT,+ inputMint: INPUT_MINT,+ outputMint: OUTPUT_MINT,inAmount: "1000000000",outAmount: "990000000",priceImpactPct: "0.01",@@ -96,7 +125,7 @@ describe("jupiterSwap", () => {.mockResolvedValueOnce({ ok: true, json: async () => ({ swapTransaction: MOCK_TX_BASE64 }) } as unknown as Response);await jupiterSwap(makeWallet(), connection, {- inputMint: SOL_MINT, outputMint: SOL_MINT, amount: 1_000_000_000n,+ inputMint: INPUT_MINT, outputMint: OUTPUT_MINT, amount: 1_000_000_000n,});const swapCall = mockFetch.mock.calls[1]!;@@ -129,7 +158,7 @@ describe("jupiterSwap", () => {const w = makeMetaWallet();await jupiterSwap(w, connection, {- inputMint: SOL_MINT, outputMint: SOL_MINT, amount: 1_000_000_000n,+ inputMint: INPUT_MINT, outputMint: OUTPUT_MINT, amount: 1_000_000_000n,});expect(w.setNextMeta).toHaveBeenCalledTimes(1);@@ -146,7 +175,7 @@ describe("jupiterSwap", () => {await expect(jupiterSwap(makeWallet(), connection, {- inputMint: SOL_MINT, outputMint: SOL_MINT, amount: 1n,+ inputMint: INPUT_MINT, outputMint: OUTPUT_MINT, amount: 1n,}),).resolves.toBeDefined();});diff --git a/solana-agent-sdk/tests/wallet/browser-client.test.ts b/solana-agent-sdk/tests/wallet/browser-client.test.tsindex 9a574e628..1ea0e5b3b 100644--- a/solana-agent-sdk/tests/wallet/browser-client.test.ts+++ b/solana-agent-sdk/tests/wallet/browser-client.test.ts@@ -132,7 +132,7 @@ describe("BrowserWalletClient", () => {expect((globalThis as Record<string, unknown>)["fetch"] as ReturnType<typeof jest.fn>,- ).toHaveBeenCalledWith(`${baseUrl}/reject/${pending.id}`, { method: "POST" });+ ).toHaveBeenCalledWith(`${baseUrl}/reject/${pending.id}`, { method: "POST", headers: {} });expect(signerMock).not.toHaveBeenCalled();});diff --git a/solana-agent-sdk/tests/wallet/browser-server.test.ts b/solana-agent-sdk/tests/wallet/browser-server.test.tsindex 102cc9fb8..790a39741 100644--- a/solana-agent-sdk/tests/wallet/browser-server.test.ts+++ b/solana-agent-sdk/tests/wallet/browser-server.test.ts@@ -5,18 +5,23 @@ import { BrowserWalletProvider } from "../../src/wallet/browser-server.js";describe("BrowserWalletProvider", () => {const keypair = Keypair.generate();- function makeSerializedTx(feePayer = keypair.publicKey): string {+ function makeTx(feePayer = keypair.publicKey): Transaction {const tx = new Transaction();tx.recentBlockhash = "11111111111111111111111111111111";tx.feePayer = feePayer;+ return tx;+ }++ // The provider now validates that the returned, signed transaction matches the+ // requested one and is validly signed by the wallet. Tests must therefore sign+ // the exact tx they submitted back.+ function signSerialized(tx: Transaction): string {+ tx.sign(keypair);return Buffer.from(tx.serialize({ requireAllSignatures: false })).toString("base64");}- function makeTx(feePayer = keypair.publicKey): Transaction {- const tx = new Transaction();- tx.recentBlockhash = "11111111111111111111111111111111";- tx.feePayer = feePayer;- return tx;+ function makeSerializedTx(feePayer = keypair.publicKey): string {+ return signSerialized(makeTx(feePayer));}afterEach(() => {