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.

test(api): cover the input validation, program guard and OG card paths added this batch

nirholascfc5991724f8
diff --git a/package.json b/package.json
index 72c6b67df..6882a87d9 100644
--- a/package.json
+++ b/package.json
@@ -389,6 +389,7 @@
"@bonfida/spl-name-service": "^3.0.26",
"@chenglou/pretext": "^0.0.7",
"@coin-communities/sdk": "^1.2.1",
+ "@coinbase/cdp-sdk": "^1.50.0",
"@coinbase/x402": "^2.1.0",
"@coral-xyz/anchor": "^0.32.1",
"@dimforge/rapier3d-compat": "^0.19.3",
diff --git a/scripts/monetization-api-proof.mjs b/scripts/monetization-api-proof.mjs
index 74070d0c0..941727dd5 100644
--- a/scripts/monetization-api-proof.mjs
+++ b/scripts/monetization-api-proof.mjs
@@ -124,8 +124,11 @@ async function loadPg() {
}
// neon HTTP shim: bridges api/_lib/db.js (neon serverless HTTP driver) onto the
-// local Postgres. Column values are serialized per type OID so the driver sees
-// the same JSON shapes Neon's own endpoint returns.
+// local Postgres. The driver sends `Neon-Raw-Text-Output: true` and runs its own
+// pg-types parsers over every value, so the shim must hand back the raw wire
+// text Neon's endpoint returns. Coercing here (parsing a jsonb column, say)
+// double-parses on the client and blows up as `"[object Object]" is not valid
+// JSON` inside the driver, which surfaces as an opaque handler 500.
function startShim() {
fs.mkdirSync(TMP, { recursive: true });
const preloadPath = path.join(TMP, 'preload.mjs');
@@ -134,17 +137,6 @@ function startShim() {
import http from 'node:http';
import pg from ${JSON.stringify(path.join(root, 'node_modules/pg/esm/index.mjs'))};
const pool = new pg.Pool({ connectionString: ${JSON.stringify(PG_URL)}, max: 8 });
-const NUMERIC_OIDS = new Set([700, 701, 1700]);
-const INT_OIDS = new Set([20, 21, 23, 26]);
-const JSON_OIDS = new Set([114, 3802]);
-function coerce(value, oid) {
- if (value === null || value === undefined) return null;
- if (oid === 16) return value === 't' || value === 'true';
- if (INT_OIDS.has(oid)) { const n = BigInt(value); return n <= 9007199254740991n && n >= -9007199254740991n ? Number(n) : value; }
- if (NUMERIC_OIDS.has(oid)) return Number(value);
- if (JSON_OIDS.has(oid)) { try { return JSON.parse(value); } catch { return value; } }
- return value;
-}
http.createServer(async (req, res) => {
if (req.method !== 'POST') { res.writeHead(405); res.end(); return; }
let body = '';
@@ -161,7 +153,7 @@ http.createServer(async (req, res) => {
});
return {
fields: r.fields.map((f) => ({ name: f.name, dataTypeID: f.dataTypeID })),
- rows: r.rows.map((row) => row.map((v, i) => coerce(v, r.fields[i].dataTypeID))),
+ rows: r.rows,
rowCount: r.rowCount, command: r.command,
};
};
diff --git a/tests/api-persona-endpoints.test.js b/tests/api-persona-endpoints.test.js
new file mode 100644
index 000000000..0532a7b17
--- /dev/null
+++ b/tests/api-persona-endpoints.test.js
@@ -0,0 +1,325 @@
+// Boundary coverage for the two standalone persona endpoints:
+// POST /api/persona/extract interview / freeform text -> structured persona
+// POST /api/persona/preview persona + message -> one in-voice reply
+// Both spend a metered LLM completion per call, so the contract under test is as
+// much about what must NOT reach a provider (unauthenticated calls, malformed
+// bodies, oversized personas) as about the success path.
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const getSessionUserMock = vi.fn();
+const authenticateBearerMock = vi.fn();
+const extractBearerMock = vi.fn();
+vi.mock('../api/_lib/auth.js', () => ({
+ getSessionUser: (...a) => getSessionUserMock(...a),
+ authenticateBearer: (...a) => authenticateBearerMock(...a),
+ extractBearer: (...a) => extractBearerMock(...a),
+ hasScope: (scope, want) => String(scope || '').split(/[\s,]+/).includes(want),
+}));
+
+const personaExtractLimit = vi.fn();
+const personaPreviewLimit = vi.fn();
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ limits: {
+ personaExtract: (...a) => personaExtractLimit(...a),
+ personaPreviewUser: (...a) => personaPreviewLimit(...a),
+ },
+}));
+
+const llmCompleteMock = vi.fn();
+class FakeLlmUnavailable extends Error {}
+vi.mock('../api/_lib/llm.js', () => ({
+ llmComplete: (...a) => llmCompleteMock(...a),
+ LlmUnavailableError: FakeLlmUnavailable,
+ promptTokens: (usage) => (usage?.input ?? 0) + (usage?.cacheWrite ?? 0) + (usage?.cacheRead ?? 0),
+}));
+
+vi.mock('../api/_lib/env.js', () => ({ env: { APP_ORIGIN: 'http://localhost:3000' } }));
+
+const { default: extractHandler } = await import('../api/persona/extract.js');
+const { default: previewHandler } = await import('../api/persona/preview.js');
+
+function mkReq({ method = 'POST', url = '/api/persona/extract', headers = {}, body = null } = {}) {
+ const hdrs = { ...headers };
+ if (body != null && !hdrs['content-type']) hdrs['content-type'] = 'application/json';
+ return {
+ method, url, headers: hdrs,
+ on(event, cb) {
+ if (event === 'data' && body != null) {
+ const buf = Buffer.from(typeof body === 'string' ? body : JSON.stringify(body));
+ queueMicrotask(() => { cb(buf); this._endCb?.(); });
+ } else if (event === 'end') this._endCb = cb;
+ },
+ destroy() {},
+ };
+}
+function mkRes() {
+ return {
+ statusCode: 200, headers: {}, body: undefined, writableEnded: false,
+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
+ end(b) { this.body = b; this.writableEnded = true; },
+ };
+}
+const parse = (res) => (res.body ? JSON.parse(res.body) : undefined);
+
+const OK_USAGE = { input: 300, output: 120 };
+const GOOD_PERSONA = {
+ tone: 'Direct and unadorned, trims every sentence to the load-bearing part',
+ vocabulary: ['ship it', 'no fluff'],
+ interests: ['3D tooling', 'avatars'],
+ communication_style: 'terse',
+ dont_say: ['circle back'],
+ sample_greeting: 'What is the status?',
+};
+
+async function callExtract(body, { url = '/api/persona/extract' } = {}) {
+ const res = mkRes();
+ await extractHandler(mkReq({ url, body }), res);
+ return res;
+}
+async function callPreview(body) {
+ const res = mkRes();
+ await previewHandler(mkReq({ url: '/api/persona/preview', body }), res);
+ return res;
+}
+
+beforeEach(() => {
+ getSessionUserMock.mockReset().mockResolvedValue({ id: 'user-1' });
+ authenticateBearerMock.mockReset().mockResolvedValue(null);
+ extractBearerMock.mockReset().mockReturnValue(null);
+ personaExtractLimit.mockReset().mockResolvedValue({ success: true, limit: 5, remaining: 4, reset: 0 });
+ personaPreviewLimit.mockReset().mockResolvedValue({ success: true, limit: 30, remaining: 29, reset: 0 });
+ llmCompleteMock.mockReset();
+});
+
+describe('POST /api/persona/extract', () => {
+ it('synthesizes a persona from an interview and reports real token usage', async () => {
+ llmCompleteMock.mockResolvedValue({
+ text: JSON.stringify(GOOD_PERSONA), model: 'test-model', usage: OK_USAGE,
+ });
+ const res = await callExtract({
+ answers: [{ question: 'What do you build?', answer: 'Avatar tooling. Ship fast, no fluff.' }],
+ });
+ expect(res.statusCode).toBe(200);
+ const out = parse(res);
+ expect(out.persona).toEqual(GOOD_PERSONA);
+ expect(out.model).toBe('test-model');
+ expect(out.tokens_in).toBe(300);
+ expect(out.tokens_out).toBe(120);
+ expect(out.tokens_used).toBe(420);
+ expect(typeof out.latency_ms).toBe('number');
+ });
+
+ it('accepts freeform text as an alternative to the interview', async () => {
+ llmCompleteMock.mockResolvedValue({ text: JSON.stringify(GOOD_PERSONA), model: 'm', usage: OK_USAGE });
+ const res = await callExtract({ freeform: 'I write terse release notes and hate corporate filler.' });
+ expect(res.statusCode).toBe(200);
+ expect(llmCompleteMock.mock.calls[0][0].user).toContain('corporate filler');
+ });
+
+ it('clamps oversized model output and falls back on an unknown communication_style', async () => {
+ llmCompleteMock.mockResolvedValue({
+ text: JSON.stringify({
+ tone: 'x'.repeat(500),
+ vocabulary: Array.from({ length: 40 }, (_, i) => `word${i}`),
+ interests: Array.from({ length: 40 }, (_, i) => `topic${i}`),
+ communication_style: 'sardonic',
+ dont_say: ['a', 'b', 'c', 'd', 'e'],
+ sample_greeting: 'y'.repeat(900),
+ }),
+ model: 'm', usage: OK_USAGE,
+ });
+ const { persona } = parse(await callExtract({ freeform: 'anything' }));
+ expect(persona.tone).toHaveLength(240);
+ expect(persona.vocabulary).toHaveLength(10);
+ expect(persona.interests).toHaveLength(5);
+ expect(persona.dont_say).toHaveLength(3);
+ expect(persona.sample_greeting).toHaveLength(400);
+ expect(persona.communication_style).toBe('detailed');
+ });
+
+ it('strips a markdown fence the model wrapped the JSON in', async () => {
+ llmCompleteMock.mockResolvedValue({
+ text: '```json\n' + JSON.stringify(GOOD_PERSONA) + '\n```', model: 'm', usage: OK_USAGE,
+ });
+ const res = await callExtract({ freeform: 'anything' });
+ expect(res.statusCode).toBe(200);
+ expect(parse(res).persona.communication_style).toBe('terse');
+ });
+
+ it('rejects an unauthenticated caller before touching the limiter or a provider', async () => {
+ getSessionUserMock.mockResolvedValue(null);
+ const res = await callExtract({ freeform: 'anything' });
+ expect(res.statusCode).toBe(401);
+ expect(parse(res).error).toBe('unauthorized');
+ expect(personaExtractLimit).not.toHaveBeenCalled();
+ expect(llmCompleteMock).not.toHaveBeenCalled();
+ });
+
+ it('rejects a bearer token that carries neither avatars scope', async () => {
+ getSessionUserMock.mockResolvedValue(null);
+ extractBearerMock.mockReturnValue('tok');
+ authenticateBearerMock.mockResolvedValue({ userId: 'user-9', scope: 'wallet:read' });
+ const res = await callExtract({ freeform: 'anything' });
+ expect(res.statusCode).toBe(401);
+ expect(llmCompleteMock).not.toHaveBeenCalled();
+ });
+
+ it('accepts a bearer token scoped for avatars', async () => {
+ getSessionUserMock.mockResolvedValue(null);
+ extractBearerMock.mockReturnValue('tok');
+ authenticateBearerMock.mockResolvedValue({ userId: 'user-9', scope: 'avatars:read' });
+ llmCompleteMock.mockResolvedValue({ text: JSON.stringify(GOOD_PERSONA), model: 'm', usage: OK_USAGE });
+ const res = await callExtract({ freeform: 'anything' });
+ expect(res.statusCode).toBe(200);
+ expect(personaExtractLimit).toHaveBeenCalledWith('user-9');
+ });
+
+ it('does not spend a daily quota token on a malformed body', async () => {
+ for (const body of [{}, { answers: [] }, { answers: ['nope'] }, { answers: [{ question: 'q' }] }]) {
+ const res = await callExtract(body);
+ expect(res.statusCode).toBe(400);
+ }
+ const tooMany = await callExtract({
+ answers: Array.from({ length: 13 }, () => ({ question: 'q', answer: 'a' })),
+ });
+ expect(tooMany.statusCode).toBe(400);
+ expect(parse(tooMany).error_description).toBe('max 12 answers');
+ expect(personaExtractLimit).not.toHaveBeenCalled();
+ expect(llmCompleteMock).not.toHaveBeenCalled();
+ });
+
+ it('returns 429 with the limiter reason once the daily budget is spent', async () => {
+ personaExtractLimit.mockResolvedValue({ success: false, limit: 5, remaining: 0, reset: Date.now() + 60_000 });
+ const res = await callExtract({ freeform: 'anything' });
+ expect(res.statusCode).toBe(429);
+ expect(parse(res).error).toBe('rate_limited');
+ expect(llmCompleteMock).not.toHaveBeenCalled();
+ });
+
+ it('reports a provider-free deployment as 503 without naming server env vars', async () => {
+ llmCompleteMock.mockRejectedValue(new FakeLlmUnavailable());
+ const res = await callExtract({ freeform: 'anything' });
+ expect(res.statusCode).toBe(503);
+ expect(parse(res).error).toBe('config_missing');
+ expect(res.body).not.toMatch(/API_KEY/);
+ });
+
+ it('returns 502 when the model answers with prose instead of JSON', async () => {
+ llmCompleteMock.mockResolvedValue({ text: 'Sure! Here is a persona.', model: 'm', usage: OK_USAGE });
+ const res = await callExtract({ freeform: 'anything' });
+ expect(res.statusCode).toBe(502);
+ expect(parse(res).error).toBe('parse_error');
+ });
+
+ it('returns 502 rather than a blank persona when every provider answered empty', async () => {
+ llmCompleteMock.mockResolvedValue({ text: '', model: 'm', usage: { input: 0, output: 0 } });
+ const res = await callExtract({ freeform: 'anything' });
+ expect(res.statusCode).toBe(502);
+ expect(parse(res).error).toBe('upstream_error');
+ });
+
+ it('returns 502 when the model returns valid JSON with no usable persona in it', async () => {
+ llmCompleteMock.mockResolvedValue({ text: '{}', model: 'm', usage: OK_USAGE });
+ const res = await callExtract({ freeform: 'anything' });
+ expect(res.statusCode).toBe(502);
+ expect(parse(res).error).toBe('parse_error');
+ });
+
+ it('answers a preflight without running the handler body', async () => {
+ const res = mkRes();
+ await extractHandler(mkReq({ method: 'OPTIONS', headers: { origin: 'http://localhost:3000' } }), res);
+ expect(res.statusCode).toBe(204);
+ expect(res.headers['access-control-allow-methods']).toBe('POST,OPTIONS');
+ expect(getSessionUserMock).not.toHaveBeenCalled();
+ });
+
+ it('rejects a non-POST method', async () => {
+ const res = mkRes();
+ await extractHandler(mkReq({ method: 'GET' }), res);
+ expect(res.statusCode).toBe(405);
+ expect(llmCompleteMock).not.toHaveBeenCalled();
+ });
+});
+
+describe('POST /api/persona/preview', () => {
+ it('replies in the persona voice and pins the persona into the system prompt', async () => {
+ llmCompleteMock.mockResolvedValue({ text: 'Send the mesh.', model: 'test-model', usage: OK_USAGE });
+ const res = await callPreview({ persona: GOOD_PERSONA, user_message: 'Can you rig this avatar?' });
+ expect(res.statusCode).toBe(200);
+ const out = parse(res);
+ expect(out.reply).toBe('Send the mesh.');
+ expect(out.tokens_used).toBe(420);
+ const { system, user } = llmCompleteMock.mock.calls[0][0];
+ expect(system).toContain('"communication_style": "terse"');
+ expect(system).toContain('circle back');
+ expect(user).toBe('Can you rig this avatar?');
+ });
+
+ it('truncates an overlong user message to the documented cap', async () => {
+ llmCompleteMock.mockResolvedValue({ text: 'ok', model: 'm', usage: OK_USAGE });
+ await callPreview({ persona: GOOD_PERSONA, user_message: 'z'.repeat(5000) });
+ expect(llmCompleteMock.mock.calls[0][0].user).toHaveLength(1500);
+ });
+
+ it('rejects an unauthenticated caller before touching the limiter or a provider', async () => {
+ getSessionUserMock.mockResolvedValue(null);
+ const res = await callPreview({ persona: GOOD_PERSONA, user_message: 'hi' });
+ expect(res.statusCode).toBe(401);
+ expect(personaPreviewLimit).not.toHaveBeenCalled();
+ expect(llmCompleteMock).not.toHaveBeenCalled();
+ });
+
+ it('does not spend a quota token on a malformed body', async () => {
+ for (const body of [
+ { user_message: 'hi' },
+ { persona: 'terse', user_message: 'hi' },
+ { persona: [GOOD_PERSONA], user_message: 'hi' },
+ { persona: GOOD_PERSONA },
+ { persona: GOOD_PERSONA, user_message: ' ' },
+ ]) {
+ const res = await callPreview(body);
+ expect(res.statusCode).toBe(400);
+ }
+ expect(personaPreviewLimit).not.toHaveBeenCalled();
+ expect(llmCompleteMock).not.toHaveBeenCalled();
+ });
+
+ it('refuses a persona large enough to inflate the prompt into an expensive call', async () => {
+ const res = await callPreview({
+ persona: { ...GOOD_PERSONA, notes: 'x'.repeat(9000) },
+ user_message: 'hi',
+ });
+ expect(res.statusCode).toBe(400);
+ expect(parse(res).error_description).toContain('persona is too large');
+ expect(llmCompleteMock).not.toHaveBeenCalled();
+ });
+
+ it('returns 429 once the per-user budget is spent', async () => {
+ personaPreviewLimit.mockResolvedValue({ success: false, limit: 30, remaining: 0, reset: Date.now() + 60_000 });
+ const res = await callPreview({ persona: GOOD_PERSONA, user_message: 'hi' });
+ expect(res.statusCode).toBe(429);
+ expect(llmCompleteMock).not.toHaveBeenCalled();
+ });
+
+ it('reports a provider-free deployment as 503 without naming server env vars', async () => {
+ llmCompleteMock.mockRejectedValue(new FakeLlmUnavailable());
+ const res = await callPreview({ persona: GOOD_PERSONA, user_message: 'hi' });
+ expect(res.statusCode).toBe(503);
+ expect(parse(res).error).toBe('config_missing');
+ expect(res.body).not.toMatch(/API_KEY/);
+ });
+
+ it('returns 502 rather than an empty bubble when every provider answered empty', async () => {
+ llmCompleteMock.mockResolvedValue({ text: '', model: 'm', usage: { input: 0, output: 0 } });
+ const res = await callPreview({ persona: GOOD_PERSONA, user_message: 'hi' });
+ expect(res.statusCode).toBe(502);
+ expect(parse(res).error).toBe('upstream_error');
+ });
+
+ it('rejects a non-POST method', async () => {
+ const res = mkRes();
+ await previewHandler(mkReq({ method: 'GET', url: '/api/persona/preview' }), res);
+ expect(res.statusCode).toBe(405);
+ expect(llmCompleteMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/tests/api/pump.test.js b/tests/api/pump.test.js
index 0c765256b..7a61409c0 100644
--- a/tests/api/pump.test.js
+++ b/tests/api/pump.test.js
@@ -94,6 +94,11 @@ vi.mock('../../api/_lib/pump.js', () => ({
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'),
}));
@@ -150,10 +155,24 @@ function resetAll() {
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 —
+// the shape that used to slip past pubkey validation.
+const badPubkey = '0OIl0OIl0OIl0OIl0OIl0OIl0OIl0OIl0OIl';
describe('GET /api/pump/balances', () => {
beforeEach(resetAll);
@@ -402,6 +421,7 @@ describe('POST /api/pump/buy-confirm (quote-aware trade recording)', () => {
describe('POST /api/pump/withdraw-prep', () => {
beforeEach(resetAll);
+ beforeEach(resetPumpMod);
it('builds withdraw ix for owner', async () => {
authState.session = { id: 'user-1' };
@@ -438,6 +458,49 @@ describe('POST /api/pump/withdraw-prep', () => {
});
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', () => {
@@ -480,6 +543,7 @@ describe('GET /api/pump/by-agent', () => {
describe('POST /api/pump/withdraw-confirm', () => {
beforeEach(resetAll);
+ beforeEach(resetPumpMod);
it('confirms withdraw tx for owner', async () => {
authState.session = { id: 'user-1' };
@@ -524,6 +588,66 @@ describe('POST /api/pump/withdraw-confirm', () => {
});
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', () => {
diff --git a/tests/api/purchase-skill-tx-request.test.js b/tests/api/purchase-skill-tx-request.test.js
new file mode 100644
index 000000000..0419eeef6
--- /dev/null
+++ b/tests/api/purchase-skill-tx-request.test.js
@@ -0,0 +1,237 @@
+// Tests for /api/purchase/skill — the Solana Pay TRANSACTION request that a
+// mobile wallet hits after scanning a skill-purchase QR.
+//
+// Runs fully offline: real @solana/web3.js + @solana/spl-token, a fake RPC that
+// returns a fixed blockhash, and an in-memory skill_purchases row. The two things
+// that matter here are (a) the endpoint never invents a purchase — it only serves
+// a pending row an authenticated checkout already created — and (b) the built
+// transaction has the exact shape api/_lib/purchase-confirm.js validates: the
+// reference-carrying creator leg LAST.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { Readable } from 'node:stream';
+import { Keypair, PublicKey, Transaction } from '@solana/web3.js';
+import { getAssociatedTokenAddressSync } from '@solana/spl-token';
+
+const PAYER = Keypair.generate();
+const BUYER = Keypair.generate();
+const SELLER = Keypair.generate();
+const TREASURY = Keypair.generate();
+const MINT = Keypair.generate();
+const REFERENCE = Keypair.generate().publicKey.toBase58();
+const BLOCKHASH = Keypair.generate().publicKey.toBase58();
+
+vi.mock('../../api/_lib/zauth.js', () => ({ instrument: () => {}, drain: async () => {} }));
+vi.mock('../../api/_lib/sentry.js', () => ({ captureException: () => {} }));
+
+// One pending purchase row, mutated per test.
+let purchaseRow = null;
+const sqlMock = vi.fn(async (strings) => {
+ const text = strings.join('?').toLowerCase();
+ if (text.includes('from skill_purchases')) return purchaseRow ? [purchaseRow] : [];
+ return [];
+});
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: sqlMock,
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+}));
+
+let payoutAddress = SELLER.publicKey.toBase58();
+const logEventMock = vi.fn(async () => {});
+vi.mock('../../api/_lib/purchase-confirm.js', () => ({
+ logEvent: (...a) => logEventMock(...a),
+ resolvePayoutAddress: async () => payoutAddress,
+}));
+
+vi.mock('../../api/_lib/solana/connection.js', () => ({
+ solanaConnection: () => ({
+ getLatestBlockhash: async () => ({ blockhash: BLOCKHASH, lastValidBlockHeight: 1 }),
+ }),
+}));
+
+let payerConfigured = true;
+vi.mock('../../api/_lib/solana/gasless-tx.js', () => ({
+ resolveMarketplacePayer: async () => (payerConfigured ? PAYER : null),
+}));
+
+const rateLimitResult = { success: true, limit: 240, remaining: 239, reset: Date.now() + 60_000 };
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ clientIp: () => '203.0.113.7',
+ limits: { publicIp: async () => rateLimitResult },
+}));
+
+function basePurchase(overrides = {}) {
+ return {
+ reference: REFERENCE,
+ status: 'pending',
+ expires_at: new Date(Date.now() + 20 * 60_000).toISOString(),
+ agent_id: '11111111-1111-4111-8111-111111111111',
+ skill: 'market-scan',
+ kind: 'purchase',
+ amount: '1000000',
+ currency_mint: MINT.publicKey.toBase58(),
+ chain: 'solana',
+ platform_fee_amount: '0',
+ platform_fee_wallet: null,
+ mint_decimals: 6,
+ agent_name: 'Scout',
+ ...overrides,
+ };
+}
+
+function makeReq({ method = 'GET', query = `?reference=${REFERENCE}`, body = null } = {}) {
+ const buf = Buffer.from(body == null ? '' : JSON.stringify(body), 'utf8');
+ const stream = Readable.from([buf]);
+ stream.method = method;
+ stream.url = `/api/purchase/skill${query}`;
+ stream.headers = {
+ 'content-type': 'application/json',
+ 'content-length': String(buf.length),
+ };
+ return stream;
+}
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ _h: {},
+ writableEnded: false,
+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },
+ getHeader(k) { return this._h[k.toLowerCase()]; },
+ end(body) { this._body = body; this.writableEnded = true; },
+ };
+}
+
+async function call(opts) {
+ const handler = (await import('../../api/purchase/skill.js')).default;
+ const res = makeRes();
+ await handler(makeReq(opts), res);
+ return { res, body: res._body ? JSON.parse(res._body) : null };
+}
+
+beforeEach(() => {
+ purchaseRow = basePurchase();
+ payoutAddress = SELLER.publicKey.toBase58();
+ payerConfigured = true;
+ sqlMock.mockClear();
+ logEventMock.mockClear();
+});
+
+describe('GET /api/purchase/skill', () => {
+ it('returns the Solana Pay label and icon for a known reference', async () => {
+ const { res, body } = await call({ method: 'GET' });
+ expect(res.statusCode).toBe(200);
+ expect(body.label).toContain('market-scan');
+ expect(body.icon).toMatch(/^https?:\/\/.+\.svg$/);
+ });
+
+ it('rejects a malformed reference with a JSON 400', async () => {
+ const { res, body } = await call({ method: 'GET', query: '?reference=not-base58!' });
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toBe('validation_error');
+ expect(body.message).toBeTruthy();
+ });
+
+ it('404s a reference with no purchase behind it', async () => {
+ purchaseRow = null;
+ const { res, body } = await call({ method: 'GET' });
+ expect(res.statusCode).toBe(404);
+ expect(body.error).toBe('not_found');
+ });
+});
+
+describe('POST /api/purchase/skill', () => {
+ it('builds a platform-sponsored transfer whose last leg carries the reference', async () => {
+ const { res, body } = await call({ method: 'POST', body: { account: BUYER.publicKey.toBase58() } });
+ expect(res.statusCode).toBe(200);
+ expect(body.message).toContain('market-scan');
+
+ const tx = Transaction.from(Buffer.from(body.transaction, 'base64'));
+ expect(tx.feePayer.equals(PAYER.publicKey)).toBe(true);
+ // Platform pre-signed as fee payer; the buyer's authority slot is still open.
+ expect(tx.signatures.find((s) => s.publicKey.equals(PAYER.publicKey))?.signature).not.toBeNull();
+ expect(tx.signatures.find((s) => s.publicKey.equals(BUYER.publicKey))?.signature ?? null).toBeNull();
+
+ const last = tx.instructions[tx.instructions.length - 1];
+ expect(last.keys[last.keys.length - 1].pubkey.equals(new PublicKey(REFERENCE))).toBe(true);
+ const sellerAta = getAssociatedTokenAddressSync(MINT.publicKey, SELLER.publicKey);
+ expect(last.keys.some((k) => k.pubkey.equals(sellerAta))).toBe(true);
+ // Idempotent ATA creation for the seller rides ahead of the transfer.
+ expect(tx.instructions).toHaveLength(2);
+ expect(logEventMock).toHaveBeenCalledWith(REFERENCE, 'transaction_request_built', expect.any(Object));
+ });
+
+ it('puts the treasury fee leg before the reference-carrying creator leg', async () => {
+ purchaseRow = basePurchase({
+ platform_fee_amount: '100000',
+ platform_fee_wallet: TREASURY.publicKey.toBase58(),
+ });
+ const { body } = await call({ method: 'POST', body: { account: BUYER.publicKey.toBase58() } });
+ const tx = Transaction.from(Buffer.from(body.transaction, 'base64'));
+ const treasuryAta = getAssociatedTokenAddressSync(MINT.publicKey, TREASURY.publicKey);
+ const feeIdx = tx.instructions.findIndex(
+ (ix) => ix.keys.length === 4 && ix.keys.some((k) => k.pubkey.equals(treasuryAta)),
+ );
+ expect(feeIdx).toBeGreaterThan(-1);
+ expect(feeIdx).toBeLessThan(tx.instructions.length - 1);
+
+ const last = tx.instructions[tx.instructions.length - 1];
+ expect(last.keys[last.keys.length - 1].pubkey.equals(new PublicKey(REFERENCE))).toBe(true);
+ });
+
+ it('makes the buyer the fee payer when no marketplace payer is configured', async () => {
+ payerConfigured = false;
+ const { res, body } = await call({ method: 'POST', body: { account: BUYER.publicKey.toBase58() } });
+ expect(res.statusCode).toBe(200);
+ const tx = Transaction.from(Buffer.from(body.transaction, 'base64'));
+ expect(tx.feePayer.equals(BUYER.publicKey)).toBe(true);
+ });
+
+ it('rejects a body with no wallet account', async () => {
+ const { res, body } = await call({ method: 'POST', body: {} });
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toBe('validation_error');
+ });
+
+ it('rejects an account that is not a base58 public key', async () => {
+ const { res, body } = await call({ method: 'POST', body: { account: 'definitely not a key' } });
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toBe('validation_error');
+ });
+
+ it('410s an expired pending purchase', async () => {
+ purchaseRow = basePurchase({ expires_at: new Date(Date.now() - 60_000).toISOString() });
+ const { res, body } = await call({ method: 'POST', body: { account: BUYER.publicKey.toBase58() } });
+ expect(res.statusCode).toBe(410);
+ expect(body.error).toBe('purchase_expired');
+ });
+
+ it('409s a purchase that is already paid', async () => {
+ purchaseRow = basePurchase({ status: 'confirmed' });
+ const { res, body } = await call({ method: 'POST', body: { account: BUYER.publicKey.toBase58() } });
+ expect(res.statusCode).toBe(409);
+ expect(body.error).toBe('already_confirmed');
+ });
+
+ it('rejects a non-Solana purchase', async () => {
+ purchaseRow = basePurchase({ chain: 'base' });
+ const { res, body } = await call({ method: 'POST', body: { account: BUYER.publicKey.toBase58() } });
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toBe('unsupported_chain');
+ });
+
+ it('412s when the agent owner has no payout wallet', async () => {
+ payoutAddress = null;
+ const { res, body } = await call({ method: 'POST', body: { account: BUYER.publicKey.toBase58() } });
+ expect(res.statusCode).toBe(412);
+ expect(body.error).toBe('creator_wallet_missing');
+ });
+
+ it('never writes a purchase row of its own', async () => {
+ await call({ method: 'POST', body: { account: BUYER.publicKey.toBase58() } });
+ for (const callArgs of sqlMock.mock.calls) {
+ expect(callArgs[0].join(' ').toLowerCase()).not.toContain('insert into skill_purchases');
+ }
+ });
+});
diff --git a/tests/monetization-service.test.js b/tests/monetization-service.test.js
index fa046a92f..43701fbc5 100644
--- a/tests/monetization-service.test.js
+++ b/tests/monetization-service.test.js
@@ -725,3 +725,409 @@ describe('revenue endpoint (getCreatorSalesData)', () => {
expect(body.error).toBe('rate_limited');
});
});
+
+// ── 6. payout wallets — api/monetization/wallet.js ──────────────────────────────
+
+describe('wallet endpoint (payout addresses)', () => {
+ const SOL_ADDRESS = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+ const EVM_ADDRESS = '0x1111111111111111111111111111111111111111';
+
+ it('returns 401 when unauthenticated', async () => {
+ const { agent } = createTestAgent();
+
+ const { status, body } = await invoke(walletHandler, {
+ method: 'GET',
+ url: `/api/monetization/wallet?agent_id=${agent.id}`,
+ });
+
+ expect(status).toBe(401);
+ expect(body.error).toBe('unauthorized');
+ });
+
+ it('returns 400 on a malformed agent_id', async () => {
+ authState.session = { id: 'user-1' };
+
+ const { status, body } = await invoke(walletHandler, {
+ method: 'GET',
+ url: '/api/monetization/wallet?agent_id=not-a-uuid',
+ });
+
+ expect(status).toBe(400);
+ expect(body.error).toBe('validation_error');
+ });
+
+ it("returns 403 for someone else's agent", async () => {
+ const { agent } = createTestAgent();
+ authState.session = { id: 'user-1' };
+
+ sqlState.queue.push([{ id: agent.id, user_id: 'a-different-user' }]);
+
+ const { status, body } = await invoke(walletHandler, {
+ method: 'GET',
+ url: `/api/monetization/wallet?agent_id=${agent.id}`,
+ });
+
+ expect(status).toBe(403);
+ expect(body.error).toBe('forbidden');
+ });
+
+ it('resolves an inherited user-level wallet, matching what a withdrawal pays out to', async () => {
+ const { agent, session } = createTestAgent();
+ authState.session = session;
+
+ sqlState.queue.push([{ id: agent.id, user_id: agent.user_id }]); // ownership
+ // No agent-specific row: only a user-level (agent_id NULL) payout wallet,
+ // which is exactly the row withdrawals.js falls back to.
+ sqlState.queue.push([
+ { id: 'w1', agent_id: null, address: SOL_ADDRESS, chain: 'solana', is_default: true, preferred_network: 'solana' },
+ ]);
+
+ const { status, body } = await invoke(walletHandler, {
+ method: 'GET',
+ url: `/api/monetization/wallet?agent_id=${agent.id}`,
+ });
+
+ expect(status).toBe(200);
+ expect(body.resolved.solana_address).toBe(SOL_ADDRESS);
+ expect(body.resolved.evm_address).toBeNull();
+ });
+
+ it('reports no wallet when the user has none configured', async () => {
+ const { agent, session } = createTestAgent();
+ authState.session = session;
+
+ sqlState.queue.push([{ id: agent.id, user_id: agent.user_id }]);
+ sqlState.queue.push([]);
+
+ const { status, body } = await invoke(walletHandler, {
+ method: 'GET',
+ url: `/api/monetization/wallet?agent_id=${agent.id}`,
+ });
+
+ expect(status).toBe(200);
+ expect(body.wallets).toEqual([]);
+ expect(body.resolved).toEqual({ evm_address: null, solana_address: null, preferred_network: 'solana' });
+ });
+
+ it('rejects a PUT with no address at all', async () => {
+ const { agent, session } = createTestAgent();
+ authState.session = session;
+
+ sqlState.queue.push([{ id: agent.id, user_id: agent.user_id }]);
+
+ const { status, body } = await invoke(walletHandler, {
+ method: 'PUT',
+ url: '/api/monetization/wallet',
+ body: { agent_id: agent.id },
+ });
+
+ expect(status).toBe(400);
+ expect(body.error).toBe('validation_error');
+ });
+
+ it('rejects a malformed Solana payout address', async () => {
+ const { agent, session } = createTestAgent();
+ authState.session = session;
+
+ sqlState.queue.push([{ id: agent.id, user_id: agent.user_id }]);
+
+ const { status, body } = await invoke(walletHandler, {
+ method: 'PUT',
+ url: '/api/monetization/wallet',
+ body: { agent_id: agent.id, solana_address: 'not-base58-0OIl' },
+ });
+
+ expect(status).toBe(400);
+ expect(body.error).toBe('validation_error');
+ });
+
+ it('rejects a malformed EVM payout address', async () => {
+ const { agent, session } = createTestAgent();
+ authState.session = session;
+
+ sqlState.queue.push([{ id: agent.id, user_id: agent.user_id }]);
+
+ const { status, body } = await invoke(walletHandler, {
+ method: 'PUT',
+ url: '/api/monetization/wallet',
+ body: { agent_id: agent.id, evm_address: '0xnope' },
+ });
+
+ expect(status).toBe(400);
+ expect(body.error).toBe('validation_error');
+ });
+
+ it('upserts both chains and echoes the resolved addresses', async () => {
+ const { agent, session } = createTestAgent();
+ authState.session = session;
+
+ sqlState.queue.push([{ id: agent.id, user_id: agent.user_id }]); // ownership
+ sqlState.queue.push([]); // clear solana default
+ sqlState.queue.push([{ id: 'w-sol', agent_id: agent.id, address: SOL_ADDRESS, chain: 'solana', is_default: true, preferred_network: 'solana' }]);
+ sqlState.queue.push([]); // clear base default
+ sqlState.queue.push([{ id: 'w-evm', agent_id: agent.id, address: EVM_ADDRESS, chain: 'base', is_default: true, preferred_network: 'solana' }]);
+
+ const { status, body } = await invoke(walletHandler, {
+ method: 'PUT',
+ url: '/api/monetization/wallet',
+ body: { agent_id: agent.id, solana_address: SOL_ADDRESS, evm_address: EVM_ADDRESS },
+ });
+
+ expect(status).toBe(200);
+ expect(body.wallets).toHaveLength(2);
+ expect(body.resolved.solana_address).toBe(SOL_ADDRESS);
+ expect(body.resolved.evm_address).toBe(EVM_ADDRESS);
+ const upserts = sqlState.calls.filter((c) => c.query.includes('ON CONFLICT'));
+ expect(upserts).toHaveLength(2);
+ });
+
+ it('returns 404 when the agent does not exist', async () => {
+ const { agent, session } = createTestAgent();
+ authState.session = session;
+
+ sqlState.queue.push([]); // no agent row
+
+ const { status, body } = await invoke(walletHandler, {
+ method: 'PUT',
+ url: '/api/monetization/wallet',
+ body: { agent_id: agent.id, solana_address: SOL_ADDRESS },
+ });
+
+ expect(status).toBe(404);
+ expect(body.error).toBe('not_found');
+ });
+});
+
+// ── 7. withdrawals — api/monetization/withdrawals.js ────────────────────────────
+
+describe('withdrawals endpoint', () => {
+ const SOL_ADDRESS = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+
+ // getAvailableBalance issues four queries: earned, pending/withdrawn, and the
+ // two split-adjustment lookups.
+ function queueBalance({ earned, pending = 0n, withdrawn = 0n }) {
+ sqlState.queue.push([{ earned }]);
+ sqlState.queue.push([{ pending, withdrawn }]);
+ sqlState.queue.push([{ amt: 0n }]);
+ sqlState.queue.push([{ amt: 0n }]);
+ }
+
+ it('returns 401 when unauthenticated', async () => {
+ const { status, body } = await invoke(withdrawalsHandler, {
+ method: 'GET',
+ url: '/api/monetization/withdrawals',
+ });
+
+ expect(status).toBe(401);
+ expect(body.error).toBe('unauthorized');
+ });
+
+ it('returns 400 on a malformed agent_id', async () => {
+ authState.session = { id: 'user-1' };
+
+ const { status, body } = await invoke(withdrawalsHandler, {
+ method: 'GET',
+ url: '/api/monetization/withdrawals?agent_id=not-a-uuid',
+ });
+
+ expect(status).toBe(400);
+ expect(body.error).toBe('validation_error');
+ });
+
+ it('rejects an unknown status filter instead of answering with an empty page', async () => {
+ authState.session = { id: 'user-1' };
+
+ const { status, body } = await invoke(withdrawalsHandler, {
+ method: 'GET',
+ url: '/api/monetization/withdrawals?status=bogus-status',
+ });
+
+ expect(status).toBe(400);
+ expect(body.error).toBe('validation_error');
+ expect(sqlState.calls).toHaveLength(0);
+ });
+
+ it('falls back to the default page when limit/offset are junk', async () => {
+ authState.session = { id: 'user-1' };
+
+ sqlState.queue.push([]); // withdrawal list
+ queueBalance({ earned: 0n });
+
+ const { status } = await invoke(withdrawalsHandler, {
+ method: 'GET',
+ url: '/api/monetization/withdrawals?limit=abc&offset=xyz',
+ });
+
+ expect(status).toBe(200);
+ // A NaN limit binds as NULL, which Postgres reads as "no limit" — the page
+ // size would silently become the whole table.
+ const list = sqlState.calls.find((c) => c.query.includes('agent_withdrawals'));
+ expect(list.values.slice(-2)).toEqual([20, 0]);
+ });
+
+ it('clamps an oversized limit to the maximum page', async () => {
+ authState.session = { id: 'user-1' };
+
+ sqlState.queue.push([]);
+ queueBalance({ earned: 0n });
+
+ await invoke(withdrawalsHandler, {
+ method: 'GET',
+ url: '/api/monetization/withdrawals?limit=5000',
+ });
+
+ const list = sqlState.calls.find((c) => c.query.includes('agent_withdrawals'));
+ expect(list.values.slice(-2)).toEqual([100, 0]);
+ });
+
+ it('lists withdrawals alongside the derived balance', async () => {
+ authState.session = { id: 'user-1' };
+
+ sqlState.queue.push([
+ {
+ id: 'wd-1', agent_id: 'agent-1', amount: 4_000_000n, currency_mint: USDC_MINT,
+ chain: 'solana', to_address: SOL_ADDRESS, status: 'pending', tx_signature: null,
+ error_message: null, created_at: '2026-06-18T00:00:00Z', updated_at: '2026-06-18T00:00:00Z',
+ },
+ ]);
+ queueBalance({ earned: 5_850_000n, pending: 4_000_000n });
+
+ const { status, body } = await invoke(withdrawalsHandler, {
+ method: 'GET',
+ url: '/api/monetization/withdrawals',
+ });
+
+ expect(status).toBe(200);
+ expect(body.withdrawals).toHaveLength(1);
+ expect(body.withdrawals[0]).toMatchObject({
+ amount_usdc: 4,
+ amount_atomic: 4_000_000,
+ status: 'pending',
+ destination_address: SOL_ADDRESS,
+ tx_hash: null,
+ });
+ expect(body.balance.available_usdc).toBe(1.85);
+ expect(body.balance.pending_usdc).toBe(4);
+ });
+
+ it('refuses a withdrawal before a payout wallet is configured', async () => {
+ const { agent, session } = createTestAgent();
+ authState.session = session;
+
+ sqlState.queue.push([{ id: agent.id, user_id: agent.user_id }]); // ownership
+ sqlState.queue.push([]); // no payout wallet
+
+ const { status, body } = await invoke(withdrawalsHandler, {
+ method: 'POST',
+ url: '/api/monetization/withdrawals',
+ body: { agent_id: agent.id, amount_usdc: 5 },
+ });
+
+ expect(status).toBe(422);
+ expect(body.error).toBe('no_payout_wallet');
+ });
+
+ it('refuses an amount under the 1 USDC minimum', async () => {
+ const { agent, session } = createTestAgent();
+ authState.session = session;
+
+ sqlState.queue.push([{ id: agent.id, user_id: agent.user_id }]);
+ sqlState.queue.push([{ address: SOL_ADDRESS, chain: 'solana', preferred_network: 'solana' }]);
+ queueBalance({ earned: 10_000_000n });
+
+ const { status, body } = await invoke(withdrawalsHandler, {
+ method: 'POST',
+ url: '/api/monetization/withdrawals',
+ body: { agent_id: agent.id, amount_usdc: 0.5 },
+ });
+
+ expect(status).toBe(422);
+ expect(body.error).toBe('below_minimum');
+ });
+
+ it('refuses an amount beyond the available balance', async () => {
+ const { agent, session } = createTestAgent();
+ authState.session = session;
+
+ sqlState.queue.push([{ id: agent.id, user_id: agent.user_id }]);
+ sqlState.queue.push([{ address: SOL_ADDRESS, chain: 'solana', preferred_network: 'solana' }]);
+ queueBalance({ earned: 2_000_000n });
+
+ const { status, body } = await invoke(withdrawalsHandler, {
+ method: 'POST',
+ url: '/api/monetization/withdrawals',
+ body: { agent_id: agent.id, amount_usdc: 100 },
+ });
+
+ expect(status).toBe(422);
+ expect(body.error).toBe('insufficient_balance');
+ });
+
+ it('reserves a pending withdrawal for the full available balance', async () => {
+ const { agent, session } = createTestAgent();
+ authState.session = session;
+
+ sqlState.queue.push([{ id: agent.id, user_id: agent.user_id }]);
+ sqlState.queue.push([{ address: SOL_ADDRESS, chain: 'solana', preferred_network: 'solana' }]);
+ queueBalance({ earned: 5_850_000n });
+ sqlState.queue.push([]); // pg_advisory_xact_lock
+ sqlState.queue.push([
+ {
+ id: 'wd-1', agent_id: agent.id, amount: 5_850_000n, currency_mint: USDC_MINT,
+ chain: 'solana', to_address: SOL_ADDRESS, status: 'pending', tx_signature: null,
+ created_at: '2026-06-18T00:00:00Z', updated_at: '2026-06-18T00:00:00Z',
+ },
+ ]);
+
+ // amount_usdc omitted → drain the whole available balance.
+ const { status, body } = await invoke(withdrawalsHandler, {
+ method: 'POST',
+ url: '/api/monetization/withdrawals',
+ body: { agent_id: agent.id },
+ });
+
+ expect(status).toBe(201);
+ expect(body.withdrawal.amount_atomic).toBe(5_850_000);
+ expect(body.withdrawal.status).toBe('pending');
+ expect(body.withdrawal.destination_address).toBe(SOL_ADDRESS);
+ expect(body.balance.available_usdc).toBe(0);
+ // The reservation is serialized behind an advisory lock, not a bare INSERT.
+ expect(sqlState.calls.some((c) => c.query.includes('pg_advisory_xact_lock'))).toBe(true);
+ });
+
+ it('turns a lost race for the same balance into a 422, not an over-withdrawal', async () => {
+ const { agent, session } = createTestAgent();
+ authState.session = session;
+
+ sqlState.queue.push([{ id: agent.id, user_id: agent.user_id }]);
+ sqlState.queue.push([{ address: SOL_ADDRESS, chain: 'solana', preferred_network: 'solana' }]);
+ queueBalance({ earned: 5_850_000n });
+ sqlState.queue.push([]); // pg_advisory_xact_lock
+ sqlState.queue.push([]); // conditional INSERT … SELECT inserted nothing
+
+ const { status, body } = await invoke(withdrawalsHandler, {
+ method: 'POST',
+ url: '/api/monetization/withdrawals',
+ body: { agent_id: agent.id, amount_usdc: 4 },
+ });
+
+ expect(status).toBe(422);
+ expect(body.error).toBe('insufficient_balance');
+ });
+
+ it("returns 403 against someone else's agent", async () => {
+ const { agent } = createTestAgent();
+ authState.session = { id: 'user-1' };
+
+ sqlState.queue.push([{ id: agent.id, user_id: 'a-different-user' }]);
+
+ const { status, body } = await invoke(withdrawalsHandler, {
+ method: 'POST',
+ url: '/api/monetization/withdrawals',
+ body: { agent_id: agent.id, amount_usdc: 5 },
+ });
+
+ expect(status).toBe(403);
+ expect(body.error).toBe('forbidden');
+ });
+});
diff --git a/tests/oracle/api-input-validation.test.js b/tests/oracle/api-input-validation.test.js
new file mode 100644
index 000000000..81fc85b39
--- /dev/null
+++ b/tests/oracle/api-input-validation.test.js
@@ -0,0 +1,205 @@
+// Input-validation contract for the Oracle read APIs.
+//
+// Every endpoint here takes caller-controlled params that flow straight into SQL
+// (`::timestamptz` casts, `limit`) or into string methods. Before this suite
+// each of those had a wrong answer for a plainly malformed input: a garbage
+// `?before=` 500'd, a garbage `?since=` opened an SSE stream that silently never
+// emitted an event, `?limit=abc` returned a 200 whose summary contradicted its
+// own empty action list, and `{"agent_id": 12345}` answered internal_error.
+// These tests pin the 4xx (or the safe fallback) so none of them can come back.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+vi.mock('../../api/_lib/http.js', async () => {
+ const actual = await vi.importActual('../../api/_lib/http.js');
+ return {
+ ...actual,
+ wrap: (fn) => fn,
+ cors: () => false,
+ method: () => true,
+ rateLimited: (res) => { res._rateLimited = true; },
+ json: (res, status, body) => { res._json = { status, body }; return res; },
+ error: (res, status, code, message) => {
+ res._json = { status, body: { error: code, error_description: message } };
+ return res;
+ },
+ readJson: async (req) => JSON.parse(req._rawBody),
+ };
+});
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: {
+ publicIp: vi.fn(async () => ({ success: true })),
+ mcpIp: vi.fn(async () => ({ success: true })),
+ oracleFollowIp: vi.fn(async () => ({ success: true })),
+ },
+ clientIp: () => '1.2.3.4',
+}));
+
+// One shared spy for every tagged-template read, so a test can assert a query
+// either ran or was never reached.
+const sqlCalls = [];
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: (...args) => { sqlCalls.push(args); return Promise.resolve([]); },
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+}));
+
+const storeCalls = { recentActions: [], actionsSummary: [] };
+vi.mock('../../api/_lib/oracle/store.js', () => ({
+ recentActions: (...args) => { storeCalls.recentActions.push(args); return Promise.resolve([]); },
+ actionsSummary: (...args) => {
+ storeCalls.actionsSummary.push(args);
+ return Promise.resolve({ total: 0, wins: 0, losses: 0, open: 0, win_rate: null });
+ },
+}));
+
+import { isoTimestamp } from '../../api/_lib/validate.js';
+import activity from '../../api/oracle/activity.js';
+import actionStream from '../../api/oracle/action-stream.js';
+import agentStats from '../../api/oracle/agent-stats.js';
+import follow from '../../api/oracle/follow.js';
+
+const AGENT_ID = '5e05f68f-eead-4ef9-b6b4-fc85ea73bbe9';
+
+function fakeRes() {
+ return {
+ statusCode: 200,
+ _headers: {},
+ _writeHeadCalls: 0,
+ setHeader(k, v) { this._headers[k.toLowerCase()] = v; },
+ getHeader(k) { return this._headers[k.toLowerCase()]; },
+ writeHead() { this._writeHeadCalls++; return this; },
+ flushHeaders() {},
+ write() { return true; },
+ end() { this.writableEnded = true; },
+ };
+}
+
+function fakeReq(url, { method = 'GET', body = null } = {}) {
+ return {
+ method,
+ url,
+ headers: { host: 'three.ws', 'content-type': 'application/json' },
+ _rawBody: body == null ? '' : JSON.stringify(body),
+ _handlers: {},
+ on(event, fn) { this._handlers[event] = fn; },
+ };
+}
+
+beforeEach(() => {
+ sqlCalls.length = 0;
+ storeCalls.recentActions.length = 0;
+ storeCalls.actionsSummary.length = 0;
+});
+
+describe('isoTimestamp', () => {
+ it('normalizes a parseable instant to ISO form', () => {
+ expect(isoTimestamp('2026-08-01T00:00:00Z')).toBe('2026-08-01T00:00:00.000Z');
+ expect(isoTimestamp(' 2026-08-01T00:00:00.000Z ')).toBe('2026-08-01T00:00:00.000Z');
+ });
+
+ it('rejects anything Postgres would refuse to cast', () => {
+ expect(isoTimestamp('lolnope')).toBeNull();
+ expect(isoTimestamp('')).toBeNull();
+ expect(isoTimestamp(' ')).toBeNull();
+ expect(isoTimestamp(null)).toBeNull();
+ expect(isoTimestamp(1786673136790)).toBeNull();
+ expect(isoTimestamp({})).toBeNull();
+ });
+});
+
+describe('GET /api/oracle/activity', () => {
+ it('400s a malformed `before` cursor instead of 500ing inside the query', async () => {
+ const res = fakeRes();
+ await activity(fakeReq('/api/oracle/activity?before=lolnope'), res);
+ expect(res._json.status).toBe(400);
+ expect(res._json.body.error).toBe('validation_error');
+ // The bad cursor must never have reached the database.
+ expect(sqlCalls).toHaveLength(0);
+ });
+
+ it('accepts a valid cursor and runs the feed query', async () => {
+ const res = fakeRes();
+ await activity(fakeReq('/api/oracle/activity?before=2026-08-01T00:00:00Z'), res);
+ expect(res._json.status).toBe(200);
+ expect(sqlCalls.length).toBeGreaterThan(0);
+ });
+});
+
+describe('GET /api/oracle/action-stream', () => {
+ it('400s a malformed `since` rather than opening a stream that never emits', async () => {
+ const res = fakeRes();
+ await actionStream(fakeReq('/api/oracle/action-stream?since=lolnope'), res);
+ expect(res._json.status).toBe(400);
+ expect(res._json.body.error).toBe('validation_error');
+ // The SSE headers must not have gone out: a 200 text/event-stream here is
+ // exactly the silent-stall failure this guards.
+ expect(res._writeHeadCalls).toBe(0);
+ });
+
+ it('opens the stream for a valid `since`', async () => {
+ const res = fakeRes();
+ const req = fakeReq('/api/oracle/action-stream?since=2026-08-01T00:00:00Z');
+ await actionStream(req, res);
+ expect(res._writeHeadCalls).toBe(1);
+ expect(res._json).toBeUndefined();
+ // The handler returns while its poll/ping/rotate timers are still armed for
+ // the next 90s. Fire the close handler the way a disconnecting client would
+ // so this test doesn't leave them running for the rest of the suite.
+ req._handlers.close();
+ expect(res.writableEnded).toBe(true);
+ });
+});
+
+describe('GET /api/oracle/agent-stats', () => {
+ it('falls back to the default limit when `limit` is unparseable', async () => {
+ const res = fakeRes();
+ await agentStats(fakeReq(`/api/oracle/agent-stats?agent_id=${AGENT_ID}&limit=abc`), res);
+ expect(res._json.status).toBe(200);
+ // NaN used to reach `limit NaN`, whose rejection the store swallowed into [].
+ expect(storeCalls.recentActions[0][2]).toBe(20);
+ });
+
+ it('honours and clamps an explicit limit', async () => {
+ const res = fakeRes();
+ await agentStats(fakeReq(`/api/oracle/agent-stats?agent_id=${AGENT_ID}&limit=999`), res);
+ expect(storeCalls.recentActions[0][2]).toBe(50);
+ });
+
+ it('400s a malformed agent_id', async () => {
+ const res = fakeRes();
+ await agentStats(fakeReq('/api/oracle/agent-stats?agent_id=not-a-uuid'), res);
+ expect(res._json.status).toBe(400);
+ expect(storeCalls.recentActions).toHaveLength(0);
+ });
+});
+
+describe('/api/oracle/follow', () => {
+ it('400s a non-string agent_id on POST instead of 500ing on .trim()', async () => {
+ const res = fakeRes();
+ await follow(fakeReq('/api/oracle/follow', { method: 'POST', body: { agent_id: 12345, chat_id: '12345' } }), res);
+ expect(res._json.status).toBe(400);
+ expect(res._json.body.error_description).toMatch(/agent_id/);
+ });
+
+ it('400s a non-string chat_id on POST', async () => {
+ const res = fakeRes();
+ await follow(fakeReq('/api/oracle/follow', { method: 'POST', body: { agent_id: AGENT_ID, chat_id: 12345 } }), res);
+ expect(res._json.status).toBe(400);
+ expect(res._json.body.error_description).toMatch(/chat_id/);
+ });
+
+ it('400s a non-string agent_id on DELETE', async () => {
+ const res = fakeRes();
+ await follow(fakeReq('/api/oracle/follow', { method: 'DELETE', body: { agent_id: 99, chat_id: '1' } }), res);
+ expect(res._json.status).toBe(400);
+ expect(res._json.body.error_description).toMatch(/agent_id/);
+ });
+
+ it('405s an unsupported verb', async () => {
+ const res = fakeRes();
+ await follow(fakeReq('/api/oracle/follow', { method: 'PUT', body: {} }), res);
+ expect(res._json.status).toBe(405);
+ });
+});
diff --git a/tests/pump-launch-og-card.test.js b/tests/pump-launch-og-card.test.js
new file mode 100644
index 000000000..223fa934d
--- /dev/null
+++ b/tests/pump-launch-og-card.test.js
@@ -0,0 +1,104 @@
+import { describe, it, expect } from 'vitest';
+import { renderCard } from '../api/pump/launch-og.js';
+
+// Guards the /launches/<mint> social card against three defects that shipped
+// silently because an SVG that renders is indistinguishable from an SVG that
+// renders the right numbers:
+// 1. the live market cap was read from a `market_cap_in_usd` key pump.fun
+// does not emit, so MKT CAP never appeared for a coin still on the curve;
+// 2. organic_score / bundle_score are 0..1 fractions in pump_coin_intel but
+// the gauge treated them as 0..100, drawing a 1 px bar labelled "0%";
+// 3. a fatal DB read had to degrade to a branded card, never a 5xx.
+
+const MINT = 'THREEsynthetic1111111111111111111111111111';
+
+function baseCard(overrides = {}) {
+ return {
+ name: 'Synthetic Launch',
+ symbol: 'SYN',
+ logoBase64: null,
+ qualityScore: 72,
+ category: 'meme',
+ isThreeWsLaunch: true,
+ intel: null,
+ outcome: null,
+ liveMcap: null,
+ ...overrides,
+ };
+}
+
+describe('launch-og renderCard', () => {
+ it('renders a well-formed 1200x630 SVG for the minimum viable card', () => {
+ const svg = renderCard(MINT, baseCard());
+ expect(svg.startsWith('<?xml version="1.0" encoding="UTF-8"?>')).toBe(true);
+ expect(svg).toContain('width="1200" height="630"');
+ expect(svg).toContain('Synthetic Launch');
+ expect(svg).toContain('$SYN');
+ // No enrichment supplied, so the optional blocks stay out of the card.
+ expect(svg).not.toContain('MKT CAP');
+ expect(svg).not.toContain('ORGANIC BUY');
+ });
+
+ it('draws the live market cap a coin on the curve reports', () => {
+ const svg = renderCard(MINT, baseCard({ liveMcap: 2_337_959 }));
+ expect(svg).toContain('MKT CAP');
+ expect(svg).toContain('$2.3M');
+ });
+
+ it('falls back to the recorded outcome market cap once a coin has an outcome', () => {
+ const svg = renderCard(MINT, baseCard({
+ liveMcap: null,
+ outcome: { graduated: true, ath_market_cap_usd: 84_000 },
+ }));
+ expect(svg).toContain('GRADUATED');
+ expect(svg).toContain('$84K');
+ });
+
+ it('scales the 0..1 organic and bundle fractions onto the percent gauge', () => {
+ const svg = renderCard(MINT, baseCard({
+ intel: { organic_score: 0.4279, bundle_score: 0.12, unique_buyers: 29 },
+ }));
+ // 42.79% of a 230 px bar, and the label reads the percentage, not the fraction.
+ expect(svg).toContain('>43%<');
+ expect(svg).toContain('width="98" height="8"');
+ expect(svg).toContain('>12%<');
+ expect(svg).toContain('UNIQUE BUYERS');
+ expect(svg).toContain('>29<');
+ // A clean launch keeps the amber bundle bar, not the red one.
+ expect(svg).toContain('#f59e0b');
+ });
+
+ it('flags a coordinated launch in red once bundle passes the 0.3 threshold', () => {
+ const svg = renderCard(MINT, baseCard({
+ intel: { organic_score: 0.05, bundle_score: 0.61 },
+ }));
+ expect(svg).toContain('>61%<');
+ expect(svg).toContain('#ef4444');
+ });
+
+ it('clamps a gauge score that exceeds its range instead of overflowing the bar', () => {
+ const svg = renderCard(MINT, baseCard({ intel: { organic_score: 4, bundle_score: 0 } }));
+ expect(svg).toContain('>100%<');
+ expect(svg).toContain('width="230" height="8"');
+ });
+
+ it('escapes coin metadata so a hostile name cannot inject SVG markup', () => {
+ const svg = renderCard(MINT, baseCard({ name: '<script>alert(1)</script>', symbol: 'a"b' }));
+ expect(svg).not.toContain('<script>');
+ expect(svg).toContain('&lt;script&gt;');
+ expect(svg).toContain('&quot;');
+ });
+
+ it('still renders a branded card when every enrichment read failed', () => {
+ const svg = renderCard(MINT, {
+ name: '', symbol: '', logoBase64: null, qualityScore: null, category: '',
+ isThreeWsLaunch: false, intel: null, outcome: null, liveMcap: null,
+ });
+ expect(svg).toContain('Unknown coin');
+ expect(svg).toContain('THREE.WS');
+ // Unknown quality reads as a placeholder, never as a fabricated score.
+ expect(svg).toContain('>-<');
+ expect(svg).not.toContain('undefined');
+ expect(svg).not.toContain('NaN');
+ });
+});
diff --git a/tests/pump-tx-program-guard.test.js b/tests/pump-tx-program-guard.test.js
index 8f4dda935..6ef6f0050 100644
--- a/tests/pump-tx-program-guard.test.js
+++ b/tests/pump-tx-program-guard.test.js
@@ -1,13 +1,21 @@
-// Unit tests for the launch-confirm program guard in api/_lib/pump.js.
+// Unit tests for the confirm-path program guards in api/_lib/pump.js.
//
// txInvokesPumpProgram() is what stops a confirmed tx that merely *references*
// a freshly-ground mint pubkey (a memo, a transfer) from being recorded in
-// pump_agent_mints as a real launch. The real module is imported (no vi.mock)
-// so we exercise the actual parsing + the real PUMP_PROGRAM_ID constant.
+// pump_agent_mints as a real launch, and txInvokesAgentPaymentsProgram() does
+// the same job for withdraw-confirm. The real module is imported (no vi.mock)
+// so we exercise the actual parsing + the real program-id constants.
import { describe, it, expect } from 'vitest';
-import { txProgramIds, txInvokesPumpProgram } from '../api/_lib/pump.js';
-import { PUMP_PROGRAM_ID } from '../api/_lib/solana/programs.js';
+import {
+ txProgramIds,
+ txInvokesPumpProgram,
+ txInvokesAgentPaymentsProgram,
+} from '../api/_lib/pump.js';
+import {
+ PUMP_PROGRAM_ID,
+ PUMP_AGENT_PAYMENTS_PROGRAM_ID,
+} from '../api/_lib/solana/programs.js';
const SYSTEM = '11111111111111111111111111111111';
const TOKEN = 'TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA';
@@ -68,3 +76,49 @@ describe('txInvokesPumpProgram', () => {
expect(txInvokesPumpProgram({})).toBe(false);
});
});
+
+describe('txInvokesAgentPaymentsProgram', () => {
+ it('true when the agent-payments program is a top-level instruction', () => {
+ const tx = {
+ transaction: {
+ message: { instructions: [{ programId: pk(PUMP_AGENT_PAYMENTS_PROGRAM_ID) }] },
+ },
+ };
+ expect(txInvokesAgentPaymentsProgram(tx)).toBe(true);
+ });
+
+ it('true when it is invoked via CPI (inner instruction)', () => {
+ const tx = {
+ transaction: { message: { instructions: [{ programId: SYSTEM }] } },
+ meta: {
+ innerInstructions: [
+ { index: 0, instructions: [{ programId: pk(PUMP_AGENT_PAYMENTS_PROGRAM_ID) }] },
+ ],
+ },
+ };
+ expect(txInvokesAgentPaymentsProgram(tx)).toBe(true);
+ });
+
+ it('false for a plain token transfer that merely touches the mint and authority', () => {
+ const tx = {
+ transaction: {
+ message: {
+ accountKeys: [{ pubkey: pk('3wsGroundMint1111111111111111111111') }],
+ instructions: [{ programId: TOKEN }],
+ },
+ },
+ meta: { innerInstructions: [] },
+ };
+ expect(txInvokesAgentPaymentsProgram(tx)).toBe(false);
+ });
+
+ it('false for the bonding-curve program (a launch is not a withdrawal)', () => {
+ const tx = { transaction: { message: { instructions: [{ programId: pk(PUMP_PROGRAM_ID) }] } } };
+ expect(txInvokesAgentPaymentsProgram(tx)).toBe(false);
+ });
+
+ it('false for malformed input', () => {
+ expect(txInvokesAgentPaymentsProgram(null)).toBe(false);
+ expect(txInvokesAgentPaymentsProgram({})).toBe(false);
+ });
+});