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(solana): resolve the owning token program per mint so $THREE transfers stop failing simulation
nirholas42d5473c242f
diff --git a/src/credits.js b/src/credits.jsindex 9063cfaa7..5a598596e 100644--- a/src/credits.js+++ b/src/credits.js@@ -9,6 +9,7 @@// page paints instantly for the read-only balance view.import { getAdapter } from './onchain/adapters/index.js';+import { resolveTokenProgramId } from './shared/spl-token-program.js';const SOL_MINT = 'So11111111111111111111111111111111111111112';@@ -266,14 +267,53 @@ async function buildThreeTransfer({ web3, spl, conn, from, to, amount, mintStr,const owner = new web3.PublicKey(from);const dest = new web3.PublicKey(to);const mint = new web3.PublicKey(mintStr);- const srcAta = await spl.getAssociatedTokenAddress(mint, owner);- const dstAta = await spl.getAssociatedTokenAddress(mint, dest);++ // $THREE is a Token-2022 mint, so every derivation and instruction below must+ // target the mint's real owning program. The spl-token defaults (legacy+ // TOKEN_PROGRAM_ID) derive the wrong ATAs and fail simulation with "incorrect+ // program id for instruction".+ const tokenProgramId = await resolveTokenProgramId(conn, mint, spl);+ const ataArgs = [false, tokenProgramId, spl.ASSOCIATED_TOKEN_PROGRAM_ID];+ const srcAta = await spl.getAssociatedTokenAddress(mint, owner, ...ataArgs);+ const dstAta = await spl.getAssociatedTokenAddress(mint, dest, ...ataArgs);++ const [srcInfo, dstInfo] = await Promise.all([+ conn.getAccountInfo(srcAta),+ conn.getAccountInfo(dstAta),+ ]);+ if (!srcInfo) throw new Error('This wallet holds no $THREE. Buy some first, then deposit.');+ const held = BigInt((await conn.getTokenAccountBalance(srcAta)).value.amount);+ if (held < atomics) {+ throw new Error(+ `Not enough $THREE. This wallet holds ${fmtAmount(Number(held) / 10 ** decimals)}.`,+ );+ }+const tx = new web3.Transaction();- const dstInfo = await conn.getAccountInfo(dstAta);if (!dstInfo) {- tx.add(spl.createAssociatedTokenAccountInstruction(owner, dstAta, dest, mint));+ tx.add(+ spl.createAssociatedTokenAccountInstruction(+ owner,+ dstAta,+ dest,+ mint,+ tokenProgramId,+ spl.ASSOCIATED_TOKEN_PROGRAM_ID,+ ),+ );}- tx.add(spl.createTransferCheckedInstruction(srcAta, mint, dstAta, owner, atomics, decimals));+ tx.add(+ spl.createTransferCheckedInstruction(+ srcAta,+ mint,+ dstAta,+ owner,+ atomics,+ decimals,+ [],+ tokenProgramId,+ ),+ );return tx;}diff --git a/src/payment-modal.js b/src/payment-modal.jsindex c6ead0e6b..bde1154d4 100644--- a/src/payment-modal.js+++ b/src/payment-modal.js@@ -651,12 +651,17 @@ export class SkillPaymentModal {const mintKey = new PublicKey(purchase.currency_mint);const referenceKey = new PublicKey(purchase.reference);- const fromAta = getAssociatedTokenAddressSync(mintKey, payerKey);- const toAta = getAssociatedTokenAddressSync(mintKey, recipientKey);+ // The seller picks the currency mint, so it may be Token-2022 (as $THREE is)+ // rather than classic SPL. Derive the ATAs and build the transfer against the+ // mint's real owning program; the spl-token default would produce addresses+ // that do not exist and a transfer the chain rejects at simulation.+ const tokenProgramId = await resolveTokenProgramId(this._connection, mintKey, spl);+ const fromAta = getAssociatedTokenAddressSync(mintKey, payerKey, false, tokenProgramId);+ const toAta = getAssociatedTokenAddressSync(mintKey, recipientKey, false, tokenProgramId);// Pre-flight balance check: surface "Add funds" before wallet prompttry {- const ataInfo = await getAccount(this._connection, fromAta, 'confirmed');+ const ataInfo = await getAccount(this._connection, fromAta, 'confirmed', tokenProgramId);const balance = BigInt(ataInfo.amount);const required = BigInt(purchase.amount);if (balance < required) {@@ -667,7 +672,14 @@ export class SkillPaymentModal {// ATA may not exist yet — let sendTransaction surface the real error}- const ix = createTransferInstruction(fromAta, toAta, payerKey, BigInt(purchase.amount));+ const ix = createTransferInstruction(+ fromAta,+ toAta,+ payerKey,+ BigInt(purchase.amount),+ [],+ tokenProgramId,+ );ix.keys.push({ pubkey: referenceKey, isSigner: false, isWritable: false });const { blockhash, lastValidBlockHeight } = await this._connection.getLatestBlockhash('confirmed');diff --git a/src/shared/agent-tip.js b/src/shared/agent-tip.jsindex 6f48c716c..fff5b8016 100644--- a/src/shared/agent-tip.js+++ b/src/shared/agent-tip.js@@ -27,14 +27,17 @@ import {Transaction,LAMPORTS_PER_SOL,} from '@solana/web3.js';+import * as splToken from '@solana/spl-token';import {getAssociatedTokenAddress,getAccount,createAssociatedTokenAccountInstruction,createTransferCheckedInstruction,TOKEN_PROGRAM_ID,+ ASSOCIATED_TOKEN_PROGRAM_ID,} from '@solana/spl-token';import { detectSolanaWallet, SOLANA_RPC, solanaTxExplorerUrl } from '../erc8004/solana-deploy.js';+import { resolveTokenProgramId } from './spl-token-program.js';const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;@@ -160,24 +163,38 @@ export async function tipAgent({ toAddress, token = 'SOL', amount, mint: splMint}const dec = Number.isInteger(splDecimals) && splDecimals >= 0 && splDecimals <= 18 ? splDecimals : 6;const mint = new PublicKey(String(splMint));- const fromAta = await getAssociatedTokenAddress(mint, from);- const toAta = await getAssociatedTokenAddress(mint, to);+ // The caller's mint may be Token-2022 ($THREE is), and the spl-token defaults+ // are the legacy program, which derives the wrong ATAs and fails simulation+ // with "incorrect program id for instruction". Read the owning program off+ // the mint and build every leg against it.+ const tokenProgramId = await resolveTokenProgramId(connection, mint, splToken);+ const fromAta = await getAssociatedTokenAddress(mint, from, false, tokenProgramId, ASSOCIATED_TOKEN_PROGRAM_ID);+ const toAta = await getAssociatedTokenAddress(mint, to, false, tokenProgramId, ASSOCIATED_TOKEN_PROGRAM_ID);try {- await getAccount(connection, fromAta);+ await getAccount(connection, fromAta, undefined, tokenProgramId);} catch {throw new TipError(noBalanceMsg || 'Your wallet holds none of this token to tip with.', 'no_balance');}let recipientHasAta = true;try {- await getAccount(connection, toAta);+ await getAccount(connection, toAta, undefined, tokenProgramId);} catch {recipientHasAta = false;}if (!recipientHasAta) {- tx.add(createAssociatedTokenAccountInstruction(from, toAta, to, mint));+ tx.add(+ createAssociatedTokenAccountInstruction(+ from,+ toAta,+ to,+ mint,+ tokenProgramId,+ ASSOCIATED_TOKEN_PROGRAM_ID,+ ),+ );}const raw = BigInt(Math.round(amt * 10 ** dec));- tx.add(createTransferCheckedInstruction(fromAta, mint, toAta, from, raw, dec, [], TOKEN_PROGRAM_ID));+ tx.add(createTransferCheckedInstruction(fromAta, mint, toAta, from, raw, dec, [], tokenProgramId));} else {const lamports = Math.round(amt * LAMPORTS_PER_SOL);tx.add(SystemProgram.transfer({ fromPubkey: from, toPubkey: to, lamports }));diff --git a/src/shared/spl-token-program.js b/src/shared/spl-token-program.jsnew file mode 100644index 000000000..3341a329e--- /dev/null+++ b/src/shared/spl-token-program.js@@ -0,0 +1,41 @@+// Resolve which SPL token program owns a mint, for browser transaction builders.+//+// $THREE (and every pump.fun mint minted after the Token-2022 switch) is a+// Token-2022 mint, not a classic SPL Token mint. @solana/spl-token defaults every+// helper to the legacy TOKEN_PROGRAM_ID, so a builder that omits the program id+// derives the WRONG associated-token address and points the instruction at the+// wrong program. The chain rejects that with "incorrect program id for instruction"+// during simulation, which reads like a malformed transaction rather than what it+// is: the right transfer aimed at the wrong token program.+//+// The mint account's owner is the canonical, on-chain way to tell the two apart,+// and it is fixed for the life of the mint, so the answer is cached per mint.+//+// Node/agent code has the same helper in solana-agent-sdk/src/utils/token-program.ts;+// this is the browser-side counterpart (dynamic spl-token import, no TS types).++const cache = new Map();++/**+ * @param {import('@solana/web3.js').Connection} connection+ * @param {import('@solana/web3.js').PublicKey} mint+ * @param {object} spl the loaded @solana/spl-token module+ * @returns {Promise<import('@solana/web3.js').PublicKey>} TOKEN_PROGRAM_ID or TOKEN_2022_PROGRAM_ID+ * @throws if the mint account is missing or is not owned by either SPL token program+ */+export async function resolveTokenProgramId(connection, mint, spl) {+ const key = mint.toBase58();+ const cached = cache.get(key);+ if (cached) return cached;++ const info = await connection.getAccountInfo(mint);+ if (!info) throw new Error(`Token mint not found on this network: ${key}`);++ let programId;+ if (info.owner.equals(spl.TOKEN_2022_PROGRAM_ID)) programId = spl.TOKEN_2022_PROGRAM_ID;+ else if (info.owner.equals(spl.TOKEN_PROGRAM_ID)) programId = spl.TOKEN_PROGRAM_ID;+ else throw new Error(`Not an SPL token mint (owned by ${info.owner.toBase58()}): ${key}`);++ cache.set(key, programId);+ return programId;+}diff --git a/src/token-pay.js b/src/token-pay.jsindex f148b808a..1faa71f24 100644--- a/src/token-pay.js+++ b/src/token-pay.js@@ -22,6 +22,7 @@*/import { ensureRiskAck } from './shared/risk-ack.js';+import { resolveTokenProgramId } from './shared/spl-token-program.js';const MEMO_PROGRAM_ID = 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr';@@ -141,8 +142,6 @@ export async function payWithToken({getAssociatedTokenAddressSync,createTransferInstruction,createAssociatedTokenAccountIdempotentInstruction,- TOKEN_PROGRAM_ID,- TOKEN_2022_PROGRAM_ID,ASSOCIATED_TOKEN_PROGRAM_ID,} = spl;@@ -153,13 +152,10 @@ export async function payWithToken({const connection = new Connection(rpcEndpoint(), 'confirmed');const mint = new PublicKey(quote.mint);- // $THREE is a Token-2022 mint, and the mint may differ per network — so the ATA+ // $THREE is a Token-2022 mint, and the mint may differ per network, so the ATA// derivation and transfers MUST target the mint's actual owning token program,- // not the legacy default. Read it from the mint account; fall back to the legacy- // program only if the lookup fails (a classic-SPL mint).- const mintInfo = await connection.getAccountInfo(mint);- const tokenProgramId =- mintInfo && mintInfo.owner.equals(TOKEN_2022_PROGRAM_ID) ? TOKEN_2022_PROGRAM_ID : TOKEN_PROGRAM_ID;+ // not the legacy default. Read it from the mint account.+ const tokenProgramId = await resolveTokenProgramId(connection, mint, spl);const fromAta = getAssociatedTokenAddressSync(mint, payer, false, tokenProgramId, ASSOCIATED_TOKEN_PROGRAM_ID);