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(tx): validate a Solana signature before the explainer calls out to the RPC
nirholasc64091ac9ba8
diff --git a/api/tx/explain.js b/api/tx/explain.jsindex 9eaaa8ffd..b3340ee60 100644--- a/api/tx/explain.js+++ b/api/tx/explain.js@@ -1,4 +1,5 @@import { Interface } from 'ethers';+import bs58 from 'bs58';import { env } from '../_lib/env.js';import { wrap, cors, error, json, readJson, method, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';@@ -63,6 +64,20 @@ function parsedTxToExplain(tx) {// Cache the finished explanation by chain:sig; a hit serves with zero upstream cost.const EXPLAIN_TTL_SECONDS = 24 * 60 * 60; // 24h+// A Solana transaction signature is exactly 64 raw bytes. The base58 alphabet ++// length check alone is not enough: `'1'.repeat(88)` passes it and decodes to 88+// zero bytes, which the RPC rejects as a bad argument — so a plainly malformed+// input was billed as an upstream failure (502) instead of answered as the client+// fault (400) it is. Decode and measure instead of counting characters.+function isSolanaSignature(sig) {+ if (!/^[1-9A-HJ-NP-Za-km-z]{64,96}$/.test(sig)) return false;+ try {+ return bs58.decode(sig).length === 64;+ } catch {+ return false;+ }+}+const ERC20_TRANSFER_TOPIC ='0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef';const erc20Iface = new Interface([@@ -92,7 +107,7 @@ export default wrap(async (req, res) => {if (!sig) return error(res, 400, 'bad_request', 'sig required');// Validate the signature shape before forwarding to a keyed upstream so a// malformed value is rejected here, not bounced through Helius/Alchemy.- if (chain === 'solana' && !/^[1-9A-HJ-NP-Za-km-z]{64,96}$/.test(sig)) {+ if (chain === 'solana' && !isSolanaSignature(sig)) {return error(res, 400, 'bad_request', 'sig must be a base58 transaction signature');}if (chain === 'evm' && !/^0x[0-9a-fA-F]{64}$/.test(sig)) {@@ -223,7 +238,7 @@ export default wrap(async (req, res) => {const receipt = receiptJson?.result;const logs = [];for (const log of receipt?.logs || []) {- if (log.topics[0] !== ERC20_TRANSFER_TOPIC) continue;+ if (log?.topics?.[0] !== ERC20_TRANSFER_TOPIC) continue;try {const parsed = erc20Iface.parseLog({ topics: log.topics, data: log.data });logs.push({diff --git a/api/tx/solana/[action].js b/api/tx/solana/[action].jsindex 9f07c99b6..f1dcc382c 100644--- a/api/tx/solana/[action].js+++ b/api/tx/solana/[action].js@@ -1,30 +1,101 @@import { z } from 'zod';import { solanaConnection } from '../../_lib/solana/connection.js';import {- Connection, PublicKey, Transaction, SystemProgram, LAMPORTS_PER_SOL,+ PublicKey, Transaction, SystemProgram, LAMPORTS_PER_SOL,TransactionInstruction,} from '@solana/web3.js';import {- createTransferInstruction, getMint, getAssociatedTokenAddress,+ createTransferCheckedInstruction, getMint, getAssociatedTokenAddressSync,createAssociatedTokenAccountInstruction,+ TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,} from '@solana/spl-token';import { cors, json, method, readJson, wrap, error, rateLimited } from '../../_lib/http.js';import { getSessionUser } from '../../_lib/auth.js';import { limits, clientIp } from '../../_lib/rate-limit.js';-import { parse } from '../../_lib/validate.js';+import { parse, isValidSolanaAddress } from '../../_lib/validate.js';+import { jupiterQuote, jupiterSwapTx } from '../../_lib/token/jupiter.js';-const SOLANA_RPC_MAINNET = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';-const SOLANA_RPC_DEVNET = process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com';-const MEMO_PROGRAM_ID = new PublicKey('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr');+const MEMO_PROGRAM_ID = new PublicKey('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr');+// The memo program accepts up to 566 bytes of instruction data. Cap below that so+// an oversized memo is a 400 here instead of a serialize failure (a 500) after the+// transaction has already been assembled.+const MEMO_MAX_BYTES = 512;++// A base58 Solana address, rejected at the schema so a typo answers 400 with the+// offending field named. Without this, `new PublicKey(...)` throws deep inside the+// handler and wrap() can only report an opaque 500 for what is plainly client input.+const solanaAddress = z+ .string()+ .trim()+ .refine(isValidSolanaAddress, 'must be a base58 Solana address');++// Amounts arrive as JSON numbers (doubles). Multiplying by 10**decimals loses+// precision well before the u64 ceiling, so the conversion below goes through+// fixed-point string math instead — and this bound keeps the value in the range+// where toFixed() is exact rather than exponential.+const MAX_UI_AMOUNT = 1e12;+const uiAmount = z.number().positive().finite().max(MAX_UI_AMOUNT);++// A tagged client error: wrap() turns any thrown error carrying a 4xx `status`+// into `{ error: code, error_description: message }` with that status, which is+// how a helper several calls deep reports a caller fault without threading `res`.+function clientError(code, message) {+ return Object.assign(new Error(message), { status: 400, code });+}++function upstreamError(message) {+ return Object.assign(new Error(message), { status: 502, code: 'upstream_error', expose: true });+}++// Convert a UI amount to raw base units without a float multiply: render at the+// mint's precision, then shift the decimal point in string space. `0.1` at 9+// decimals is 100000000 here, not 99999999.99999999.+function toRawUnits(amount, decimals) {+ const [whole, frac = ''] = amount.toFixed(decimals).split('.');+ return BigInt(whole + frac.padEnd(decimals, '0'));+}++// Resolve which token program owns a mint, plus its decimals. $THREE and every+// other pump.fun-era mint is Token-2022, so assuming the original TOKEN_PROGRAM_ID+// (the spl-token default) made the SPL path unable to transfer the platform's own+// coin: getMint rejected with TokenInvalidAccountOwnerError and the caller got a 500.+async function resolveMint(connection, mintPk) {+ let account;+ try {+ account = await connection.getAccountInfo(mintPk);+ } catch (err) {+ throw upstreamError(`mint lookup failed upstream: ${err?.message || 'rpc error'}`);+ }+ if (!account) throw clientError('invalid_mint', 'token mint not found on this network');++ const programId = account.owner.equals(TOKEN_2022_PROGRAM_ID)+ ? TOKEN_2022_PROGRAM_ID+ : account.owner.equals(TOKEN_PROGRAM_ID)+ ? TOKEN_PROGRAM_ID+ : null;+ if (!programId) throw clientError('invalid_mint', 'address is not an SPL token mint');++ let info;+ try {+ info = await getMint(connection, mintPk, 'confirmed', programId);+ } catch {+ throw clientError('invalid_mint', 'could not read token mint');+ }+ return { programId, decimals: info.decimals };+}// ── build-transfer ────────────────────────────────────────────────────────────const transferSchema = z.object({- sender: z.string(),- recipient: z.string(),- amount: z.number().positive(),- token: z.string().default('SOL'),- memo: z.string().optional(),+ sender: solanaAddress,+ recipient: solanaAddress,+ amount: uiAmount,+ // 'SOL' for the native transfer, otherwise the SPL mint to move.+ token: z.union([z.literal('SOL'), solanaAddress]).default('SOL'),+ memo: z+ .string()+ .refine((v) => Buffer.byteLength(v, 'utf8') <= MEMO_MAX_BYTES, `memo must be at most ${MEMO_MAX_BYTES} bytes`)+ .optional(),network: z.enum(['mainnet', 'devnet']).default('mainnet'),});@@ -38,32 +109,71 @@ async function handleBuildTransfer(req, res) {const { sender, recipient, amount, token, memo, network } = parse(transferSchema, await readJson(req));- const rpcUrl = network === 'devnet' ? SOLANA_RPC_DEVNET : SOLANA_RPC_MAINNET;- const connection = solanaConnection({ url: rpcUrl, commitment: 'confirmed' });+ // Resolve the endpoint through the shared multi-provider chain rather than+ // pinning the public mainnet node: it is the most aggressively rate-limited+ // lane and passing it as an explicit url put it at the HEAD of the failover+ // order, ahead of every keyed provider.+ const connection = solanaConnection({ network, commitment: 'confirmed' });const senderPubkey = new PublicKey(sender);const recipientPubkey = new PublicKey(recipient);const tx = new Transaction();if (token === 'SOL') {+ const lamports = toRawUnits(amount, 9);+ if (lamports <= 0n) return error(res, 400, 'invalid_amount', 'amount rounds to zero lamports');+ if (lamports > BigInt(Number.MAX_SAFE_INTEGER)) {+ return error(res, 400, 'invalid_amount', `amount exceeds ${Number.MAX_SAFE_INTEGER / LAMPORTS_PER_SOL} SOL`);+ }tx.add(SystemProgram.transfer({fromPubkey: senderPubkey,toPubkey: recipientPubkey,- lamports: Math.round(amount * LAMPORTS_PER_SOL),+ lamports,}));} else {- const mint = new PublicKey(token);- const mintInfo = await getMint(connection, mint);- const senderATA = await getAssociatedTokenAddress(mint, senderPubkey);- const recipientATA = await getAssociatedTokenAddress(mint, recipientPubkey);+ const mint = new PublicKey(token);+ const { programId, decimals } = await resolveMint(connection, mint);++ const amountInSmallestUnit = toRawUnits(amount, decimals);+ if (amountInSmallestUnit <= 0n) {+ return error(res, 400, 'invalid_amount', `amount rounds to zero at ${decimals} decimals`);+ }++ const senderATA = getAssociatedTokenAddressSync(mint, senderPubkey, false, programId, ASSOCIATED_TOKEN_PROGRAM_ID);+ const recipientATA = getAssociatedTokenAddressSync(mint, recipientPubkey, false, programId, ASSOCIATED_TOKEN_PROGRAM_ID);++ // Tell the sender their balance is short BEFORE they approve a transaction+ // that can only fail on-chain and still cost them the fee.+ let senderBalance = 0n;+ try {+ const bal = await connection.getTokenAccountBalance(senderATA);+ senderBalance = BigInt(bal.value.amount);+ } catch {+ senderBalance = 0n;+ }+ if (senderBalance < amountInSmallestUnit) {+ return error(res, 400, 'insufficient_balance', 'sender holds less of this token than the requested amount');+ }- const recipientAccount = await connection.getAccountInfo(recipientATA);+ let recipientAccount;+ try {+ recipientAccount = await connection.getAccountInfo(recipientATA);+ } catch (err) {+ throw upstreamError(`recipient account lookup failed upstream: ${err?.message || 'rpc error'}`);+ }if (!recipientAccount) {- tx.add(createAssociatedTokenAccountInstruction(senderPubkey, recipientATA, recipientPubkey, mint));+ tx.add(createAssociatedTokenAccountInstruction(+ senderPubkey, recipientATA, recipientPubkey, mint, programId, ASSOCIATED_TOKEN_PROGRAM_ID,+ ));}- const amountInSmallestUnit = BigInt(Math.round(amount * 10 ** mintInfo.decimals));- tx.add(createTransferInstruction(senderATA, recipientATA, senderPubkey, amountInSmallestUnit));+ // TransferChecked, not Transfer: Token-2022 mints carrying a transfer-fee+ // extension reject the unchecked variant, and the mint/decimals it pins+ // make a wrong-decimals build fail at simulation instead of silently+ // moving the wrong amount.+ tx.add(createTransferCheckedInstruction(+ senderATA, mint, recipientATA, senderPubkey, amountInSmallestUnit, decimals, [], programId,+ ));}if (memo) {@@ -74,8 +184,13 @@ async function handleBuildTransfer(req, res) {}));}- const latestBlockhash = await connection.getLatestBlockhash();- tx.feePayer = senderPubkey;+ let latestBlockhash;+ try {+ latestBlockhash = await connection.getLatestBlockhash();+ } catch (err) {+ throw upstreamError(`blockhash fetch failed upstream: ${err?.message || 'rpc error'}`);+ }+ tx.feePayer = senderPubkey;tx.recentBlockhash = latestBlockhash.blockhash;const serialized = tx.serialize({ requireAllSignatures: false });@@ -90,10 +205,10 @@ async function handleBuildTransfer(req, res) {// ── build-swap ────────────────────────────────────────────────────────────────const swapSchema = z.object({- sender: z.string(),- inputMint: z.string(),- outputMint: z.string(),- amount: z.number().positive(),+ sender: solanaAddress,+ inputMint: solanaAddress,+ outputMint: solanaAddress,+ amount: uiAmount,slippageBps: z.number().int().min(1).max(5000).default(50),network: z.enum(['mainnet']).default('mainnet'),});@@ -107,36 +222,63 @@ async function handleBuildSwap(req, res) {if (!rl.success) return rateLimited(res, rl);const { sender, inputMint, outputMint, amount, slippageBps } = parse(swapSchema, await readJson(req));+ if (inputMint === outputMint) {+ return error(res, 400, 'invalid_route', 'inputMint and outputMint must differ');+ }- const connection = solanaConnection({ url: SOLANA_RPC_MAINNET, commitment: 'confirmed' });- const inputMintPk = new PublicKey(inputMint);- const mintInfo = await getMint(connection, inputMintPk);- const amountInSmallestUnit = Math.round(amount * 10 ** mintInfo.decimals);-- const quoteUrl = `https://quote-api.jup.ag/v6/quote?inputMint=${inputMint}&outputMint=${outputMint}&amount=${amountInSmallestUnit}&slippageBps=${slippageBps}`;- const quoteRes = await fetch(quoteUrl);- if (!quoteRes.ok) return error(res, 422, 'no_route', 'No swap route found');- const quoteResponse = await quoteRes.json();- if (!quoteResponse || quoteResponse.error) return error(res, 422, 'no_route', 'No swap route found');-- const swapRes = await fetch('https://quote-api.jup.ag/v6/swap', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ quoteResponse, userPublicKey: sender, wrapAndUnwrapSol: true }),- });- if (!swapRes.ok) return error(res, 422, 'swap_failed', 'Jupiter swap transaction fetch failed');- const swapResponse = await swapRes.json();+ const connection = solanaConnection({ network: 'mainnet', commitment: 'confirmed' });+ const { decimals: inputDecimals } = await resolveMint(connection, new PublicKey(inputMint));+ const { decimals: outputDecimals } = await resolveMint(connection, new PublicKey(outputMint));++ const amountInSmallestUnit = toRawUnits(amount, inputDecimals);+ if (amountInSmallestUnit <= 0n) {+ return error(res, 400, 'invalid_amount', `amount rounds to zero at ${inputDecimals} decimals`);+ }++ // Route through the shared Jupiter client (api/_lib/token/jupiter.js) so this+ // endpoint can never drift from the rest of the platform's swap lanes on+ // endpoint or error handling. It previously called quote-api.jup.ag/v6+ // directly, a host that no longer resolves at all — every swap build failed,+ // and the bare `fetch failed` was misread downstream as a database outage.+ let quote;+ try {+ quote = await jupiterQuote({+ inputMint,+ outputMint,+ amount: amountInSmallestUnit.toString(),+ slippageBps,+ });+ } catch (err) {+ if (err?.status >= 400 && err.status < 500) {+ return error(res, 422, 'no_route', 'No swap route found for this pair and amount');+ }+ throw upstreamError(`swap quote failed upstream: ${err?.message || 'network error'}`);+ }+ if (!quote?.outAmount) return error(res, 422, 'no_route', 'No swap route found for this pair and amount');- const outputMintInfo = await getMint(connection, new PublicKey(outputMint));- const outputDecimals = outputMintInfo.decimals;+ let swapTransaction;+ try {+ swapTransaction = await jupiterSwapTx({+ quote,+ userPublicKey: sender,+ // This lane swaps arbitrary pairs including native SOL, so Jupiter has+ // to open and close the wrapped-SOL account itself.+ wrapAndUnwrapSol: true,+ });+ } catch (err) {+ if (err?.status >= 400 && err.status < 500) {+ return error(res, 422, 'swap_failed', 'Jupiter could not build a transaction for this route');+ }+ throw upstreamError(`swap build failed upstream: ${err?.message || 'network error'}`);+ }return json(res, 200, {- transaction: swapResponse.swapTransaction,+ transaction: swapTransaction,network: 'mainnet',inputAmount: amount,- outputAmount: Number(quoteResponse.outAmount) / 10 ** outputDecimals,+ outputAmount: Number(quote.outAmount) / 10 ** outputDecimals,outputMint,- priceImpactPct: quoteResponse.priceImpactPct,+ priceImpactPct: quote.priceImpactPct,});}