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
// Tests for pump.fun integration endpoints. SDKs and Solana RPC are fully
// mocked: no network, no chain. Verifies request/response shapes, auth,
// validation, and that the right SDK calls are issued in the right order.
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { Readable } from 'node:stream';
// ── Auth state ────────────────────────────────────────────────────────────
const authState = { session: null, bearer: null };
vi.mock('../../api/_lib/auth.js', async () => {
const actual = await vi.importActual('../../api/_lib/auth.js');
return {
...actual,
getSessionUser: vi.fn(async () => authState.session),
authenticateBearer: vi.fn(async () => authState.bearer),
extractBearer: vi.fn(() => null),
};
});
// ── SQL mock ──────────────────────────────────────────────────────────────
// by-agent also reads the agent's non-Solana launches from
// fixed_supply_launches (the main query plus its where/join fragment). Those
// answer from their own slot so they never consume a row queued for the
// pump.fun mint, stats, or burns reads.
const sqlState = { queue: [], calls: [], fixedSupply: [] };
vi.mock('../../api/_lib/db.js', () => ({
sql: vi.fn(async (strings, ...values) => {
const query = strings.join('?');
sqlState.calls.push({ query, values });
if (/fixed_supply_launches|\bf\.agent_id\b/.test(query)) return sqlState.fixedSupply;
if (sqlState.queue.length === 0) return [];
return sqlState.queue.shift();
}),
isDbUnavailableError: () => false,
isDbCapacityError: () => false,
}));
// Any bucket resolves to "allowed". The handlers under test move between buckets
// as page-load reads get isolated from write paths (authIp → authedReadIp → …);
// enumerating names here just means a silent 500 ("limits.<name> is not a
// function") the next time one is renamed: which is exactly what this mock did.
vi.mock('../../api/_lib/rate-limit.js', () => ({
limits: new Proxy({}, { get: () => vi.fn(async () => ({ success: true })) }),
clientIp: vi.fn(() => '127.0.0.1'),
}));
vi.mock('../../api/_lib/crypto.js', () => ({
randomToken: vi.fn(async (n) => 'a'.repeat((n || 16) * 2)),
}));
// ── pump-fun SDK mocks ────────────────────────────────────────────────────
const mockPumpAgentOffline = {
create: vi.fn(async () => ({ programId: 'agent', keys: [], data: Buffer.alloc(0) })),
acceptPayment: vi.fn(async () => ({ programId: 'pay', keys: [], data: Buffer.alloc(0) })),
withdraw: vi.fn(async () => ({ programId: 'wd', keys: [], data: Buffer.alloc(0) })),
updateBuybackBps: vi.fn(async () => ({ programId: 'bp', keys: [], data: Buffer.alloc(0) })),
distributePayments: vi.fn(async () => [{ programId: 'd', keys: [], data: Buffer.alloc(0) }]),
buybackTrigger: vi.fn(async () => ({ programId: 'b', keys: [], data: Buffer.alloc(0) })),
};
const mockPumpAgent = {
getBalances: vi.fn(async () => ({
paymentVault: { address: 'PaymPda', balance: 1_000_000n }, // 1 USDC
buybackVault: { address: 'BuybkPda', balance: 0n },
withdrawVault: { address: 'WdrwPda', balance: 0n },
})),
};
const launchTxState = vi.hoisted(() => ({ buybackAvailable: true }));
// ── launch transaction assembly (lookup tables / v1 need a live RPC) ─────────
vi.mock('../../api/_lib/pump-launch-tx.js', () => ({
buildLaunchTransaction: vi.fn(async () => ({ tx_base64: 'BASE64TX', transaction_version: 0, bytes: 900, limit_bytes: 1232 })),
getPumpLookupTables: vi.fn(async () => []),
pumpAgentBuybackAvailable: vi.fn(() => launchTxState.buybackAvailable),
transactionV1Status: vi.fn(async () => ({ active: true, activation_slot: 1 })),
}));
vi.mock('../../api/_lib/pump.js', () => ({
getConnection: vi.fn(() => ({})),
solanaPubkey: vi.fn((s) => (s ? { toBase58: () => s, toString: () => s } : null)),
getPumpSdk: vi.fn(async () => ({
sdk: {
fetchGlobal: async () => ({}),
createInstruction: async () => ({ keys: [], data: Buffer.alloc(0) }),
createAndBuyInstructions: async () => [{ keys: [], data: Buffer.alloc(0) }],
createV2Instruction: async () => ({ keys: [], data: Buffer.alloc(0) }),
createV2AndBuyInstructions: async () => [{ keys: [], data: Buffer.alloc(0) }],
createV2AndBuyV2Instructions: async () => [{ keys: [], data: Buffer.alloc(0) }],
},
BN: function MockBN(v) { this.v = v; this.toString = () => String(v); },
web3: { LAMPORTS_PER_SOL: 1_000_000_000 },
})),
getPumpSwapSdk: vi.fn(async () => ({ sdk: {}, BN: class {}, web3: {} })),
getPumpAgent: vi.fn(async () => ({
agent: mockPumpAgent,
agentPda: { toString: () => 'AgentPda' },
BN: class {},
web3: {},
})),
getPumpAgentOffline: vi.fn(async () => ({
offline: mockPumpAgentOffline,
BN: function MockBN(v) {
const inst = { v, toString: () => String(v) };
return inst;
},
web3: {},
agentPda: { toString: () => 'AgentPda' },
})),
verifySignature: vi.fn(async () => ({
transaction: { message: { accountKeys: [{ pubkey: { toString: () => 'MintPubkey1111111111111111111111111111' } }] } },
meta: {},
})),
// The confirm guards are pure functions over an already-parsed tx; their own
// program-id logic is covered in tests/pump-tx-program-guard.test.js against
// the real module. Here they are switches the confirm tests flip per case.
txInvokesPumpProgram: vi.fn(() => true),
txInvokesAgentPaymentsProgram: vi.fn(() => true),
buildUnsignedTxBase64: vi.fn(async () => 'BASE64TX'),
}));
// ── helpers ───────────────────────────────────────────────────────────────
function makeReq({ method = 'GET', url = '/', headers = {}, body = null, query = null } = {}) {
const base = body ? Readable.from([Buffer.from(JSON.stringify(body))]) : Readable.from([]);
base.method = method;
base.url = url;
// The /api/pump/[action].js catch-all routes on req.query.action (populated by
// Vercel's filesystem router in prod); set it explicitly under test.
if (query) base.query = query;
base.headers = {
host: 'localhost',
// Same-site Origin: the pump dispatchers gate cookie-authed mutations on
// isSameSiteOrigin (browsers always send Origin on POST).
origin: 'https://three.ws',
...(body ? { 'content-type': 'application/json' } : {}),
...headers,
};
return base;
}
function makeRes() {
return {
statusCode: 200, headers: {}, body: '', writableEnded: false,
setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
end(chunk) { if (chunk !== undefined) this.body += chunk; this.writableEnded = true; },
};
}
async function invoke(handler, opts) {
const req = makeReq(opts); const res = makeRes();
await handler(req, res);
return { res, json: res.body ? JSON.parse(res.body) : null };
}
// Every /api/pump/<action> path is rewritten to the consolidated dispatcher, so
// the dispatcher is the only code a real request runs. This binds one action the
// way the filesystem router does, which keeps each test naming its endpoint
// while still exercising exactly what production serves.
function pumpAction(action) {
return async (req, res) => {
req.query = { ...(req.query ?? {}), action };
const { default: dispatcher } = await import('../../api/pump/[action].js');
return dispatcher(req, res);
};
}
function resetAll() {
authState.session = null; authState.bearer = null;
sqlState.queue = []; sqlState.calls = []; sqlState.fixedSupply = [];
mockPumpAgentOffline.create.mockClear();
mockPumpAgentOffline.acceptPayment.mockClear();
mockPumpAgentOffline.withdraw.mockClear();
mockPumpAgentOffline.updateBuybackBps.mockClear();
mockPumpAgentOffline.distributePayments.mockClear();
mockPumpAgentOffline.buybackTrigger.mockClear();
mockPumpAgent.getBalances.mockClear();
}
// Restore the pump.js mock's per-test overrides. Kept separate from resetAll so
// only the suites that flip a guard pay the dynamic import.
async function resetPumpMod() {
const pumpMod = await import('../../api/_lib/pump.js');
pumpMod.txInvokesPumpProgram.mockReturnValue(true);
pumpMod.txInvokesAgentPaymentsProgram.mockReturnValue(true);
pumpMod.solanaPubkey.mockImplementation((s) =>
s ? { toBase58: () => s, toString: () => s } : null,
);
}
// ── Tests ─────────────────────────────────────────────────────────────────
const mintB58 = 'MintPubkey1111111111111111111111111111';
const walletB58 = 'WalletPubkey111111111111111111111111111';
const ataB58 = 'AtaPubkey1111111111111111111111111111111';
// Long enough to clear the schema's 32-char floor, but not decodable as base58.
// This is the shape that used to slip past pubkey validation.
const badPubkey = '0OIl0OIl0OIl0OIl0OIl0OIl0OIl0OIl0OIl';
describe('GET /api/pump/balances', () => {
beforeEach(resetAll);
it('returns three vault balances', async () => {
const handler = pumpAction('balances');
const { res, json } = await invoke(handler, {
method: 'GET',
url: `/api/pump/balances?mint=${mintB58}&network=devnet`,
});
expect(res.statusCode).toBe(200);
expect(json.balances.payment.balance).toBe('1000000');
expect(json.balances.buyback.balance).toBe('0');
expect(json.balances.withdraw.balance).toBe('0');
expect(mockPumpAgent.getBalances).toHaveBeenCalledOnce();
});
it('400s on bad mint', async () => {
const handler = pumpAction('balances');
const pumpMod = await import('../../api/_lib/pump.js');
pumpMod.solanaPubkey.mockReturnValueOnce(null); // invalid mint
const { res, json } = await invoke(handler, {
method: 'GET', url: '/api/pump/balances?mint=bad',
});
expect(res.statusCode).toBe(400);
expect(json.error).toBe('validation_error');
});
});
describe('POST /api/pump/launch-prep', () => {
beforeEach(resetAll);
it('rejects unauthenticated', async () => {
const handler = pumpAction('launch-prep');
const { res } = await invoke(handler, {
method: 'POST', url: '/api/pump/launch-prep',
body: { agent_id: '00000000-0000-4000-8000-000000000001',
wallet_address: walletB58, name: 'X', symbol: 'X', uri: 'https://x/m.json' },
});
expect(res.statusCode).toBe(401);
});
it('builds unsigned tx for valid request', async () => {
authState.session = { id: 'user-1' };
sqlState.queue = [
[{ id: 'wallet-1' }], // wallet check
[{ id: 'agent-1', name: 'Foo' }], // agent check
[], // insert pending
];
const handler = pumpAction('launch-prep');
const { res, json } = await invoke(handler, {
method: 'POST', url: '/api/pump/launch-prep',
body: {
agent_id: '00000000-0000-4000-8000-000000000001',
wallet_address: walletB58,
name: 'Foo', symbol: 'FOO', uri: 'https://x/m.json',
network: 'devnet', buyback_bps: 500,
},
});
expect(res.statusCode).toBe(201);
expect(json.tx_base64).toBe('BASE64TX');
expect(json.buyback_bps).toBe(500);
expect(mockPumpAgentOffline.create).toHaveBeenCalledOnce();
expect(mockPumpAgentOffline.create.mock.calls[0][0].buybackBps).toBe(500);
});
it('launches without the buyback binding while PumpAgent refuses new agents', async () => {
launchTxState.buybackAvailable = false;
authState.session = { id: 'user-1' };
sqlState.queue = [[{ id: 'wallet-1' }], [{ id: 'agent-1', name: 'Foo' }], []];
mockPumpAgentOffline.create.mockClear();
const { res, json } = await invoke(pumpAction('launch-prep'), {
method: 'POST', url: '/api/pump/launch-prep',
body: {
agent_id: '00000000-0000-4000-8000-000000000001',
wallet_address: walletB58,
name: 'Foo', symbol: 'FOO', uri: 'https://x/m.json',
network: 'devnet', buyback_bps: 500,
},
});
launchTxState.buybackAvailable = true;
expect(res.statusCode).toBe(201);
expect(json.buyback_bps).toBe(0);
expect(json.buyback_available).toBe(false);
expect(mockPumpAgentOffline.create).not.toHaveBeenCalled();
});
});
describe('POST /api/pump/accept-payment-prep', () => {
beforeEach(resetAll);
it('builds acceptPayment ix and persists pending row', async () => {
authState.session = { id: 'user-1' };
sqlState.queue = [
[{ id: 'mint-1', mint: mintB58, network: 'devnet', buyback_bps: 500 }], // mint lookup
[{ id: 'pay-1', invoice_id: '1234', start_time: '2026-01-01', end_time: '2026-01-02', status: 'pending' }],
];
const handler = pumpAction('accept-payment-prep');
const { res, json } = await invoke(handler, {
method: 'POST', url: '/api/pump/accept-payment-prep',
body: {
mint: mintB58, payer_wallet: walletB58, amount_usdc: 1.5,
user_token_account: ataB58, network: 'devnet', duration_seconds: 60,
skill_id: 'optimize',
},
});
expect(res.statusCode).toBe(201);
expect(json.tx_base64).toBe('BASE64TX');
expect(json.amount_atomics).toBe('1500000');
expect(mockPumpAgentOffline.acceptPayment).toHaveBeenCalledOnce();
});
it('404s if mint not registered', async () => {
authState.session = { id: 'user-1' };
sqlState.queue = [[]]; // mint lookup empty
const handler = pumpAction('accept-payment-prep');
const { res, json } = await invoke(handler, {
method: 'POST', url: '/api/pump/accept-payment-prep',
body: {
mint: mintB58, payer_wallet: walletB58, amount_usdc: 1,
user_token_account: ataB58, network: 'devnet',
},
});
expect(res.statusCode).toBe(404);
expect(json.error).toBe('not_found');
});
});
describe('POST /api/pump/accept-payment-confirm', () => {
beforeEach(resetAll);
it('marks payment confirmed when tx verifies', async () => {
authState.session = { id: 'user-1' };
const currencyMint = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
sqlState.queue = [
// payment + joined mint row
[{
id: 'pay-1', mint: mintB58, network: 'devnet', invoice_id: '1234',
status: 'pending', payer_wallet: walletB58,
currency_mint: currencyMint, amount_atomics: '1000000',
}],
[], // sig dupe check
[], // update confirmed
];
const pumpMod = await import('../../api/_lib/pump.js');
pumpMod.verifySignature.mockResolvedValueOnce({
transaction: { message: { accountKeys: [
{ pubkey: { toString: () => mintB58 }, signer: false },
{ pubkey: { toString: () => walletB58 }, signer: true },
] } },
meta: {
postTokenBalances: [{
accountIndex: 0, mint: currencyMint, owner: 'AgentPda',
uiTokenAmount: { amount: '2000000' },
}],
preTokenBalances: [{
accountIndex: 0, mint: currencyMint, owner: 'AgentPda',
uiTokenAmount: { amount: '1000000' },
}],
},
});
const handler = pumpAction('accept-payment-confirm');
const { res, json } = await invoke(handler, {
method: 'POST', url: '/api/pump/accept-payment-confirm',
body: {
payment_id: '00000000-0000-4000-8000-000000000001',
tx_signature: 'a'.repeat(88),
},
});
expect(res.statusCode).toBe(200);
expect(json.ok).toBe(true);
});
});
describe('POST /api/pump/buy-confirm (quote-aware trade recording)', () => {
beforeEach(resetAll);
const USDC_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
// Find the recorded pump_agent_trades INSERT and return its bound values.
function tradeInsert() {
const call = sqlState.calls.find((c) => /insert into pump_agent_trades/i.test(c.query));
return call?.values ?? null;
}
it('records a USDC-paired buy with quote columns, not in the SOL column', async () => {
authState.session = { id: 'user-1' };
// mint lookup returns the coin's USDC pairing mint; insert returns nothing.
sqlState.queue = [[{ id: 'mint-1', quote_mint: USDC_MINT }], []];
const pumpMod = await import('../../api/_lib/pump.js');
pumpMod.verifySignature.mockResolvedValueOnce({
transaction: { message: { accountKeys: [
{ pubkey: { toString: () => mintB58 } },
{ pubkey: { toString: () => walletB58 } },
] } },
meta: {},
});
const { default: handler } = await import('../../api/pump/[action].js');
const { res, json } = await invoke(handler, {
method: 'POST',
url: '/api/pump/buy-confirm',
query: { action: 'buy-confirm' },
body: {
mint: mintB58,
network: 'mainnet',
tx_signature: 'a'.repeat(88),
wallet_address: walletB58,
usdc_amount: 5,
route: 'bonding_curve',
slippage_bps: 100,
},
});
expect(res.statusCode).toBe(200);
expect(json.tracked).toBe(true);
const v = tradeInsert();
expect(v).not.toBeNull();
// Bound values (literals like 'buy' aren't params): [0] mint_id, [1] user_id,
// [2] wallet, [3] route, [4] sol_amount, [5] quote_mint, [6] quote_symbol,
// [7] quote_amount, [8] slippage_bps, [9] tx_signature, [10] network.
expect(v[5]).toBe(USDC_MINT); // quote_mint
expect(v[6]).toBe('USDC'); // quote_symbol
expect(v[7]).toBe('5000000'); // quote_amount = 5 USDC in 6-dec atoms
// sol_amount stays null for a USDC trade: never lands in the lamports column.
expect(v[4]).toBeNull();
});
it('records a SOL-paired buy with quote_amount === sol_amount', async () => {
authState.session = { id: 'user-1' };
// quote_mint null → SOL-paired coin.
sqlState.queue = [[{ id: 'mint-1', quote_mint: null }], []];
const pumpMod = await import('../../api/_lib/pump.js');
pumpMod.verifySignature.mockResolvedValueOnce({
transaction: { message: { accountKeys: [
{ pubkey: { toString: () => mintB58 } },
{ pubkey: { toString: () => walletB58 } },
] } },
meta: {},
});
const { default: handler } = await import('../../api/pump/[action].js');
const { res } = await invoke(handler, {
method: 'POST',
url: '/api/pump/buy-confirm',
query: { action: 'buy-confirm' },
body: {
mint: mintB58,
network: 'mainnet',
tx_signature: 'b'.repeat(88),
wallet_address: walletB58,
sol: 0.25,
route: 'bonding_curve',
slippage_bps: 100,
},
});
expect(res.statusCode).toBe(200);
const v = tradeInsert();
expect(v).not.toBeNull();
const lamports = String(Math.floor(0.25 * 1e9)); // 250000000
expect(v[4]).toBe(lamports); // sol_amount
expect(v[5]).toBe('So11111111111111111111111111111111111111112'); // WSOL quote_mint
expect(v[6]).toBe('SOL'); // quote_symbol
// quote_amount === sol_amount for SOL trades (DoD invariant).
expect(v[7]).toBe(lamports);
});
});
describe('POST /api/pump/withdraw-prep', () => {
beforeEach(resetAll);
beforeEach(resetPumpMod);
it('builds withdraw ix for owner', async () => {
authState.session = { id: 'user-1' };
sqlState.queue = [[{
id: 'mint-1', mint: mintB58, user_id: 'user-1',
agent_authority: walletB58, network: 'devnet',
}]];
const handler = pumpAction('withdraw-prep');
const { res, json } = await invoke(handler, {
method: 'POST', url: '/api/pump/withdraw-prep',
body: {
mint: mintB58, authority_wallet: walletB58, receiver_ata: ataB58,
network: 'devnet',
},
});
expect(res.statusCode).toBe(201);
expect(json.tx_base64).toBe('BASE64TX');
expect(mockPumpAgentOffline.withdraw).toHaveBeenCalledOnce();
});
it('forbids non-owner', async () => {
authState.session = { id: 'other-user' };
sqlState.queue = [[{
id: 'mint-1', mint: mintB58, user_id: 'user-1',
agent_authority: walletB58, network: 'devnet',
}]];
const handler = pumpAction('withdraw-prep');
const { res } = await invoke(handler, {
method: 'POST', url: '/api/pump/withdraw-prep',
body: {
mint: mintB58, authority_wallet: walletB58, receiver_ata: ataB58,
network: 'devnet',
},
});
expect(res.statusCode).toBe(403);
});
it('blocks a cross-site cookie-authed POST before it reaches the mint lookup', async () => {
authState.session = { id: 'user-1' };
sqlState.queue = [[{
id: 'mint-1', mint: mintB58, user_id: 'user-1',
agent_authority: walletB58, network: 'devnet',
}]];
const handler = pumpAction('withdraw-prep');
const { res, json } = await invoke(handler, {
method: 'POST', url: '/api/pump/withdraw-prep',
headers: { origin: 'https://evil.example' },
body: {
mint: mintB58, authority_wallet: walletB58, receiver_ata: ataB58,
network: 'devnet',
},
});
expect(res.statusCode).toBe(403);
expect(json.error_description).toMatch(/cross-site/);
expect(mockPumpAgentOffline.withdraw).not.toHaveBeenCalled();
});
it('400s on an unparseable currency_token_program instead of silently dropping it', async () => {
authState.session = { id: 'user-1' };
sqlState.queue = [[{
id: 'mint-1', mint: mintB58, user_id: 'user-1',
agent_authority: walletB58, network: 'devnet',
}]];
const pumpMod = await import('../../api/_lib/pump.js');
pumpMod.solanaPubkey.mockImplementation((s) =>
!s || s === badPubkey ? null : { toBase58: () => s, toString: () => s },
);
const handler = pumpAction('withdraw-prep');
const { res, json } = await invoke(handler, {
method: 'POST', url: '/api/pump/withdraw-prep',
body: {
mint: mintB58, authority_wallet: walletB58, receiver_ata: ataB58,
network: 'devnet', currency_token_program: badPubkey,
},
});
expect(res.statusCode).toBe(400);
expect(json.error_description).toBe('invalid currency_token_program');
expect(mockPumpAgentOffline.withdraw).not.toHaveBeenCalled();
});
});
describe('GET /api/pump/by-agent', () => {
beforeEach(resetAll);
it('returns null when no mint exists', async () => {
sqlState.queue = [[]];
const handler = pumpAction('by-agent');
const { res, json } = await invoke(handler, {
method: 'GET',
url: '/api/pump/by-agent?agent_id=00000000-0000-4000-8000-000000000001',
});
expect(res.statusCode).toBe(200);
expect(json.data).toBe(null);
});
it('returns mint with stats and burns', async () => {
sqlState.queue = [
[{ id: 'mint-1', mint: mintB58, network: 'mainnet', name: 'Foo', symbol: 'FOO', buyback_bps: 500, agent_authority: walletB58 }],
[{ confirmed_payments: 3, unique_payers: 2, total_atomics: '1500000', last_payment_at: '2026-04-29T10:00:00Z' }],
[{ runs: 1, total_burned: '50000', last_burn_at: '2026-04-29T11:00:00Z' }],
];
const handler = pumpAction('by-agent');
const { res, json } = await invoke(handler, {
method: 'GET',
url: '/api/pump/by-agent?agent_id=00000000-0000-4000-8000-000000000001',
});
expect(res.statusCode).toBe(200);
expect(json.data.mint).toBe(mintB58);
expect(json.data.stats.confirmed_payments).toBe(3);
expect(json.data.burns.total_burned).toBe('50000');
});
it('400s without agent_id', async () => {
const handler = pumpAction('by-agent');
const { res } = await invoke(handler, { method: 'GET', url: '/api/pump/by-agent' });
expect(res.statusCode).toBe(400);
});
it('scopes last_burn_at to confirmed runs, not every attempt', async () => {
// A bare max(created_at) reported the last time the buyback cron ran at
// all. An agent with thousands of `skipped` rows and zero burns then
// answered {runs: 0, total_burned: '0', last_burn_at: <minutes ago>},
// and the dashboard rendered a burn that never happened.
sqlState.queue = [
[{ id: 'mint-1', mint: mintB58, network: 'mainnet', name: 'Foo', symbol: 'FOO', buyback_bps: 500, agent_authority: walletB58 }],
[{ confirmed_payments: 0, unique_payers: 0, total_atomics: '0', last_payment_at: null }],
[{ runs: 0, total_burned: '0', last_burn_at: null }],
];
const handler = pumpAction('by-agent');
const { res } = await invoke(handler, {
method: 'GET',
url: '/api/pump/by-agent?agent_id=00000000-0000-4000-8000-000000000001',
});
expect(res.statusCode).toBe(200);
const burnQuery = sqlState.calls.find((c) => /pump_buyback_runs/.test(String(c.query)) && /last_burn_at/.test(String(c.query)));
expect(burnQuery).toBeTruthy();
expect(String(burnQuery.query)).toMatch(/max\(created_at\)\s*filter\s*\(where status='confirmed'\)/);
});
});
describe('POST /api/pump/withdraw-confirm', () => {
beforeEach(resetAll);
beforeEach(resetPumpMod);
it('confirms withdraw tx for owner', async () => {
authState.session = { id: 'user-1' };
sqlState.queue = [
[{ id: 'mint-1', mint: mintB58, user_id: 'user-1', agent_authority: walletB58, network: 'mainnet' }],
];
const pumpMod = await import('../../api/_lib/pump.js');
pumpMod.verifySignature.mockResolvedValueOnce({
transaction: { message: { accountKeys: [
{ pubkey: { toString: () => mintB58 } },
{ pubkey: { toString: () => walletB58 } },
] } },
meta: {},
slot: 12345,
blockTime: 1714492800,
});
const handler = pumpAction('withdraw-confirm');
const { res, json } = await invoke(handler, {
method: 'POST',
url: '/api/pump/withdraw-confirm',
body: {
mint: mintB58,
network: 'mainnet',
tx_signature: 'a'.repeat(88),
},
});
expect(res.statusCode).toBe(200);
expect(json.ok).toBe(true);
expect(json.slot).toBe(12345);
});
it('forbids non-owner', async () => {
authState.session = { id: 'other' };
sqlState.queue = [
[{ id: 'mint-1', mint: mintB58, user_id: 'user-1', agent_authority: walletB58, network: 'mainnet' }],
];
const handler = pumpAction('withdraw-confirm');
const { res } = await invoke(handler, {
method: 'POST',
url: '/api/pump/withdraw-confirm',
body: { mint: mintB58, network: 'mainnet', tx_signature: 'a'.repeat(88) },
});
expect(res.statusCode).toBe(403);
});
it('422s a succeeded tx that never ran the agent-payments program', async () => {
authState.session = { id: 'user-1' };
sqlState.queue = [
[{ id: 'mint-1', mint: mintB58, user_id: 'user-1', agent_authority: walletB58, network: 'mainnet' }],
];
const pumpMod = await import('../../api/_lib/pump.js');
// A plain SPL transfer touching both accounts: confirmed, succeeded, and
// not a withdrawal.
pumpMod.verifySignature.mockResolvedValueOnce({
transaction: { message: { accountKeys: [
{ pubkey: { toString: () => mintB58 } },
{ pubkey: { toString: () => walletB58 } },
] } },
meta: {},
slot: 22222,
});
pumpMod.txInvokesAgentPaymentsProgram.mockReturnValue(false);
const handler = pumpAction('withdraw-confirm');
const { res, json } = await invoke(handler, {
method: 'POST',
url: '/api/pump/withdraw-confirm',
body: { mint: mintB58, network: 'mainnet', tx_signature: 'a'.repeat(88) },
});
expect(res.statusCode).toBe(422);
expect(json.error).toBe('not_a_withdrawal');
});
it('422s rather than 500s when the parsed tx carries no account list', async () => {
authState.session = { id: 'user-1' };
sqlState.queue = [
[{ id: 'mint-1', mint: mintB58, user_id: 'user-1', agent_authority: walletB58, network: 'mainnet' }],
];
const pumpMod = await import('../../api/_lib/pump.js');
pumpMod.verifySignature.mockResolvedValueOnce({ transaction: { message: {} }, meta: {} });
const handler = pumpAction('withdraw-confirm');
const { res, json } = await invoke(handler, {
method: 'POST',
url: '/api/pump/withdraw-confirm',
body: { mint: mintB58, network: 'mainnet', tx_signature: 'a'.repeat(88) },
});
expect(res.statusCode).toBe(422);
expect(json.error).toBe('mint_not_in_tx');
});
it('blocks a cross-site cookie-authed POST', async () => {
authState.session = { id: 'user-1' };
sqlState.queue = [
[{ id: 'mint-1', mint: mintB58, user_id: 'user-1', agent_authority: walletB58, network: 'mainnet' }],
];
const handler = pumpAction('withdraw-confirm');
const { res, json } = await invoke(handler, {
method: 'POST',
url: '/api/pump/withdraw-confirm',
headers: { origin: 'https://evil.example' },
body: { mint: mintB58, network: 'mainnet', tx_signature: 'a'.repeat(88) },
});
expect(res.statusCode).toBe(403);
expect(json.error_description).toMatch(/cross-site/);
});
});
describe('pump-pricing helpers', () => {
beforeEach(resetAll);
it('priceFor returns null for unknown tools', async () => {
const { priceFor, isFreeTool } = await import('../../api/_lib/pump-pricing.js');
expect(priceFor('nonexistent_tool')).toBe(null);
expect(isFreeTool('list_my_avatars')).toBe(true);
});
it('priceFor returns price for paid tools', async () => {
const { priceFor } = await import('../../api/_lib/pump-pricing.js');
const p = priceFor('optimize_model');
expect(p).not.toBe(null);
expect(p.amount_usdc).toBeGreaterThan(0);
});
it('findActiveSubscription queries on (mint, network, payer, tool)', async () => {
sqlState.queue = [
[{ id: 'sub-1', invoice_id: '42', amount_atomics: '1000000', end_time: '2099-01-01', tool_name: 'optimize_model' }],
];
const { findActiveSubscription } = await import('../../api/_lib/pump-pricing.js');
const sub = await findActiveSubscription({
mint: mintB58,
network: 'mainnet',
payerWallet: walletB58,
toolName: 'optimize_model',
});
expect(sub).not.toBe(null);
expect(sub.invoice_id).toBe('42');
});
it('findActiveSubscription returns null when no row', async () => {
sqlState.queue = [[]];
const { findActiveSubscription } = await import('../../api/_lib/pump-pricing.js');
const sub = await findActiveSubscription({
mint: mintB58,
network: 'mainnet',
payerWallet: walletB58,
toolName: 'optimize_model',
});
expect(sub).toBe(null);
});
});
describe('GET /.well-known/x402', () => {
beforeEach(resetAll);
it('advertises pump-agent-payments scheme', async () => {
const { default: handler } = await import('../../api/wk-x402.js');
const { res, json } = await invoke(handler, { method: 'GET', url: '/.well-known/x402' });
expect(res.statusCode).toBe(200);
expect(json.schemes).toContain('pump-agent-payments');
expect(json.pump_agent_payments.prep).toBe('/api/pump/accept-payment-prep');
});
});
describe('cookie-CSRF gate on pump mutations (2026-07-23 audit)', () => {
beforeEach(resetAll);
it('rejects a cross-site POST riding the session cookie before any handler work', async () => {
authState.session = { id: 'user-1' };
const handler = pumpAction('launch-prep');
const { res, json } = await invoke(handler, {
method: 'POST', url: '/api/pump/launch-prep',
headers: { origin: 'https://evil.example' },
// A schema-valid body: launch-prep validates input before auth, so
// the CSRF gate inside resolveAuth is only reached with this shape.
body: { agent_id: '00000000-0000-4000-8000-000000000001',
wallet_address: walletB58, name: 'X', symbol: 'X', uri: 'https://x/m.json' },
});
expect(res.statusCode).toBe(403);
expect(json.error).toBe('forbidden');
// Nothing mutating ran: the gate fires inside resolveAuth, ahead of the
// spend/signing path. (A read-only agent lookup may precede auth.)
expect(
sqlState.calls.every((c) => !/\b(insert|update|delete)\b/i.test(String(c.query))),
).toBe(true);
});
it('rejects a cookie-authed POST with no Origin and no Referer', async () => {
authState.session = { id: 'user-1' };
const handler = pumpAction('launch-prep');
const { res } = await invoke(handler, {
method: 'POST', url: '/api/pump/launch-prep',
headers: { origin: undefined },
body: { agent_id: '00000000-0000-4000-8000-000000000001',
wallet_address: walletB58, name: 'X', symbol: 'X', uri: 'https://x/m.json' },
});
expect(res.statusCode).toBe(403);
});
it('does not gate bearer-authed mutations (agent keys, workers)', async () => {
authState.bearer = { userId: 'user-1' };
const handler = pumpAction('launch-prep');
const { res } = await invoke(handler, {
method: 'POST', url: '/api/pump/launch-prep',
headers: { origin: 'https://evil.example' },
body: {},
});
// Past the gate; may fail later on input validation, never on the CSRF gate.
expect(res.statusCode).not.toBe(403);
});
// The invoice pair authenticated with a bare getSessionUser(), so it took the
// cookie without ever asking for same-site intent: a cross-site POST could
// write pending invoice rows under the victim's identity, or drive an invoice
// to 'failed'. Both now share resolveAuth() with the rest of the dispatcher.
for (const action of ['accept-payment-prep', 'accept-payment-confirm']) {
it(`rejects a cross-site cookie-authed POST to ${action}`, async () => {
authState.session = { id: 'user-1' };
const handler = pumpAction(action);
const { res, json } = await invoke(handler, {
method: 'POST', url: `/api/pump/${action}`,
headers: { origin: 'https://evil.example' },
body: {},
});
expect(res.statusCode).toBe(403);
expect(json.error).toBe('forbidden');
expect(
sqlState.calls.every((c) => !/\b(insert|update|delete)\b/i.test(String(c.query))),
).toBe(true);
});
it(`still admits a bearer-authed POST to ${action}`, async () => {
authState.bearer = { userId: 'user-1' };
const handler = pumpAction(action);
const { res } = await invoke(handler, {
method: 'POST', url: `/api/pump/${action}`,
headers: { origin: 'https://evil.example' },
body: {},
});
expect(res.statusCode).not.toBe(403);
});
}
});