Skip to content

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.

fix(pump): confirm a withdrawal only when the tx invoked the payments program

nirholas72320640b46d
diff --git a/api/_lib/pump.js b/api/_lib/pump.js
index bd92a5f15..1851c236b 100644
--- a/api/_lib/pump.js
+++ b/api/_lib/pump.js
@@ -20,7 +20,7 @@
import { PublicKey } from '@solana/web3.js';
import { solanaConnection } from './solana/connection.js';
import { rpcFallbackFromEnv } from './solana/rpc-fallback.js';
-import { PUMP_PROGRAM_ID } from './solana/programs.js';
+import { PUMP_PROGRAM_ID, PUMP_AGENT_PAYMENTS_PROGRAM_ID } from './solana/programs.js';
// @solana/web3.js calls console.error() on every 429 retry attempt. Those
// retries succeed (callers see a resolved value, not a thrown error), but
@@ -246,6 +246,15 @@ export function txInvokesPumpProgram(tx) {
return txProgramIds(tx).has(PUMP_PROGRAM_ID);
}
+// True when a confirmed tx actually invoked the three.ws agent-payments program.
+// withdraw-confirm uses this for the same reason launch-confirm asserts the
+// bonding-curve program: a succeeded tx that merely *lists* the agent mint and
+// its authority among its accounts (any transfer or memo touching them does)
+// would otherwise be reported back as a confirmed payout.
+export function txInvokesAgentPaymentsProgram(tx) {
+ return txProgramIds(tx).has(PUMP_AGENT_PAYMENTS_PROGRAM_ID);
+}
+
// Resolve the canonical pump.fun AMM pool for `mint` (post-graduation). Pass
// `quoteMint` for USDC-paired coins — derives the PDA with the explicit quote
// mint instead of the default WSOL PDA. Omit (or pass null) for SOL-paired coins.
diff --git a/api/_lib/solana/gasless-tx.js b/api/_lib/solana/gasless-tx.js
index 30570f711..a5c6977b6 100644
--- a/api/_lib/solana/gasless-tx.js
+++ b/api/_lib/solana/gasless-tx.js
@@ -127,9 +127,14 @@ export async function buildGaslessPurchaseTx({
);
creatorIx.keys.push({ pubkey: referenceKey, isSigner: false, isWritable: false });
- const instructions = [creatorIx];
+ const instructions = [];
- // Platform fee leg — same transaction, atomic with the seller leg.
+ // Platform fee leg — same transaction, atomic with the seller leg. It goes
+ // FIRST because @solana/pay's validateTransfer only ever inspects the LAST
+ // instruction: with the fee leg last, confirm would decode the treasury
+ // transfer, find no reference key on it, and reject a perfectly good payment
+ // as "invalid references". The seller leg therefore always closes the
+ // transaction (api/_lib/purchase-confirm.js validates exactly this shape).
if (platformFeeAtomics > 0n && platformFeeWallet) {
const feeAta = getAssociatedTokenAddressSync(mintKey, new PublicKey(platformFeeWallet));
instructions.push(
@@ -144,6 +149,8 @@ export async function buildGaslessPurchaseTx({
);
}
+ instructions.push(creatorIx);
+
const { blockhash } = await connection.getLatestBlockhash('confirmed');
const messageV0 = new TransactionMessage({
payerKey: payer.publicKey, // platform pays the network fee
diff --git a/api/_lib/solana/programs.js b/api/_lib/solana/programs.js
index 71ed64754..b8fa3b143 100644
--- a/api/_lib/solana/programs.js
+++ b/api/_lib/solana/programs.js
@@ -13,6 +13,11 @@
export const PUMP_PROGRAM_ID = '6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P';
export const PUMP_AMM_PROGRAM_ID = 'pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA';
export const PUMP_FEE_PROGRAM_ID = 'pfeeUxB6jkeY1Hxd7CsFCAjcbHA9rWtchMGdZ6VojVZ';
+// three.ws agent-payments program: the on-chain escrow that agent tokens
+// receive payments into and that `withdraw` pays out from. Mirrors
+// PUMP_AGENT_PAYMENTS_PROGRAM_ID exported by @three-ws/agent-payments; kept here
+// so a confirm handler can assert the program ran without importing the SDK.
+export const PUMP_AGENT_PAYMENTS_PROGRAM_ID = 'AgenTMiC2hvxGebTsgmsD4HHBa8WEcqGFf87iwRRxLo7';
export const PUMPFUN_FEE_ACCOUNT = 'CebN5WGQ4jvEPvsVU4EoHEpgzq1VV7AbCJ5GEFDM97zC';
export const PUMPFUN_MIGRATION_AUTHORITY = '39azUYFWPz3VHgKCf3VChUwbpURdCHRxjWVowf5jUJjg';
export const WSOL_MINT = 'So11111111111111111111111111111111111111112';
diff --git a/api/pump/[action].js b/api/pump/[action].js
index 8b40c77d9..803a9d95b 100644
--- a/api/pump/[action].js
+++ b/api/pump/[action].js
@@ -86,6 +86,7 @@ import {
buildUnsignedTxBase64,
verifySignature,
txInvokesPumpProgram,
+ txInvokesAgentPaymentsProgram,
solanaPubkey,
} from '../_lib/pump.js';
@@ -2946,8 +2947,8 @@ async function handleWithdrawPrep(req, res) {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['POST'])) return;
- const user = await getSessionUser(req);
- if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
const rl = await limits.authIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl);
@@ -2962,7 +2963,7 @@ async function handleWithdrawPrep(req, res) {
where m.mint=${body.mint} and m.network=${body.network} limit 1
`;
if (!row) return error(res, 404, 'not_found', 'agent mint not registered');
- if (row.user_id !== user.id) return error(res, 403, 'forbidden', 'not your agent');
+ if (row.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');
if (row.agent_authority && row.agent_authority !== body.authority_wallet) {
return error(res, 403, 'forbidden', 'authority does not match');
}
@@ -2973,15 +2974,22 @@ async function handleWithdrawPrep(req, res) {
const currency = solanaPubkey(currencyStr);
if (!currency) return error(res, 400, 'validation_error', 'invalid currency_mint');
+ // An unparseable token program used to be dropped silently, which built a tx
+ // against the default SPL program and only failed once the user had signed it.
+ // Reject it here instead, where the caller can still fix the request.
+ let tokenProgram;
+ if (body.currency_token_program) {
+ tokenProgram = solanaPubkey(body.currency_token_program);
+ if (!tokenProgram) {
+ return error(res, 400, 'validation_error', 'invalid currency_token_program');
+ }
+ }
+
const { offline } = await getPumpAgentOffline({
network: body.network,
mint: body.mint,
});
- const tokenProgram = body.currency_token_program
- ? solanaPubkey(body.currency_token_program)
- : undefined;
-
const ix = await offline.withdraw({
authority,
currencyMint: currency,
@@ -3015,8 +3023,8 @@ async function handleWithdrawConfirm(req, res) {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['POST'])) return;
- const user = await getSessionUser(req);
- if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
const rl = await limits.authIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl);
@@ -3028,7 +3036,7 @@ async function handleWithdrawConfirm(req, res) {
where mint=${body.mint} and network=${body.network} limit 1
`;
if (!row) return error(res, 404, 'not_found', 'agent mint not registered');
- if (row.user_id !== user.id) return error(res, 403, 'forbidden', 'not your agent');
+ if (row.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');
let tx;
try {
@@ -3037,13 +3045,29 @@ async function handleWithdrawConfirm(req, res) {
return error(res, e.status || 422, e.code || 'tx_failed', e.message);
}
- const accountKeys = tx.transaction.message.accountKeys.map((k) => (k.pubkey || k).toString());
+ // A versioned tx resolved through an address-lookup table can come back with
+ // its account list under a different shape; treat a missing list as "no match"
+ // rather than letting `.map` throw the whole confirm into a 500.
+ const accountKeys = (tx.transaction?.message?.accountKeys || []).map((k) =>
+ (k.pubkey || k).toString(),
+ );
if (!accountKeys.includes(body.mint)) {
return error(res, 422, 'mint_not_in_tx', 'mint not present in tx accounts');
}
if (row.agent_authority && !accountKeys.includes(row.agent_authority)) {
return error(res, 422, 'authority_not_in_tx', 'agent authority not present in tx');
}
+ // Account presence alone is not a payout: any succeeded transfer or memo that
+ // touches the mint and the authority satisfies it. Require that the
+ // agent-payments program actually ran before reporting a confirmed withdrawal.
+ if (!txInvokesAgentPaymentsProgram(tx)) {
+ return error(
+ res,
+ 422,
+ 'not_a_withdrawal',
+ 'tx did not invoke the agent-payments program',
+ );
+ }
return json(res, 200, {
ok: true,
diff --git a/api/pump/launch-studio.js b/api/pump/launch-studio.js
index 41912a49a..7f36f9ec2 100644
--- a/api/pump/launch-studio.js
+++ b/api/pump/launch-studio.js
@@ -48,5 +48,5 @@ export default wrap(async (req, res) => {
return json(res, 200, plan, { 'cache-control': 'public, max-age=30, s-maxage=120' });
}
- return error(res, 400, 'bad_request', "unknown action — use 'list' or 'preview'");
+ return error(res, 400, 'bad_request', "unknown action: use 'list' or 'preview'");
});
diff --git a/api/pump/smart-money.js b/api/pump/smart-money.js
index cb0c2d528..cb46a5113 100644
--- a/api/pump/smart-money.js
+++ b/api/pump/smart-money.js
@@ -18,11 +18,16 @@
* recorded on-chain.
*/
-import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';
+import { cors, json, method, error, wrap, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { sql } from '../_lib/db.js';
const NETWORK = 'mainnet';
+// Solana addresses are base58 and 32-44 chars. Rejecting anything else at the
+// boundary keeps a malformed address from spending a DB round-trip, and answers
+// "that is not an address" instead of the "no track record yet" a real-but-unknown
+// wallet gets, which are different facts.
+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
const lamportsToSol = (v) => (v == null ? 0 : Math.round((Number(BigInt(v)) / 1e9) * 1000) / 1000);
const numOr = (v, d = 0) => (v == null ? d : Number(v));
@@ -36,8 +41,20 @@ export default wrap(async (req, res) => {
const wallet = url.searchParams.get('wallet');
const mint = url.searchParams.get('mint');
- if (wallet) return walletCard(res, wallet.trim());
- if (mint) return coinDetail(res, mint.trim());
+ if (wallet) {
+ const addr = wallet.trim();
+ if (!BASE58_RE.test(addr)) {
+ return error(res, 400, 'invalid_wallet', 'wallet must be a base58 Solana address');
+ }
+ return walletCard(res, addr);
+ }
+ if (mint) {
+ const addr = mint.trim();
+ if (!BASE58_RE.test(addr)) {
+ return error(res, 400, 'invalid_mint', 'mint must be a base58 Solana address');
+ }
+ return coinDetail(res, addr);
+ }
if (url.searchParams.has('leaderboard')) return leaderboard(res, url);
return feed(res, url);
});
diff --git a/tests/api/gasless-tx.test.js b/tests/api/gasless-tx.test.js
index 31a1d5175..2625f41b5 100644
--- a/tests/api/gasless-tx.test.js
+++ b/tests/api/gasless-tx.test.js
@@ -7,7 +7,8 @@
// fee split / reference key land in the compiled message.
import { describe, it, expect, beforeEach } from 'vitest';
-import { Keypair, PublicKey, VersionedTransaction } from '@solana/web3.js';
+import { Keypair, VersionedTransaction } from '@solana/web3.js';
+import { getAssociatedTokenAddressSync } from '@solana/spl-token';
import {
buildGaslessPurchaseTx,
@@ -107,6 +108,25 @@ describe('buildGaslessPurchaseTx', () => {
txSingle.message.staticAccountKeys.length,
);
});
+
+ it('closes a split transaction with the reference-carrying seller leg', async () => {
+ // @solana/pay's validateTransfer only inspects the LAST instruction and
+ // requires the reference to ride it, so the fee leg must come first. With
+ // the order flipped, confirm rejects a paid purchase as "invalid references".
+ const split = await buildGaslessPurchaseTx({
+ ...baseArgs,
+ creatorAtomics: 900_000n,
+ platformFeeAtomics: 100_000n,
+ platformFeeWallet: TREASURY.publicKey.toBase58(),
+ });
+ const tx = VersionedTransaction.deserialize(Buffer.from(split.transaction, 'base64'));
+ const keys = tx.message.staticAccountKeys;
+ const last = tx.message.compiledInstructions[tx.message.compiledInstructions.length - 1];
+ expect(keys[last.accountKeyIndexes[last.accountKeyIndexes.length - 1]].equals(REFERENCE)).toBe(true);
+
+ const sellerAta = getAssociatedTokenAddressSync(MINT.publicKey, SELLER.publicKey);
+ expect(last.accountKeyIndexes.some((i) => keys[i].equals(sellerAta))).toBe(true);
+ });
});
describe('resolveMarketplacePayer', () => {