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 TTS input guards, trades feed, trading scan, and vault guards

nirholas6ddb4c7b8e9b
diff --git a/tests/api-user-wallet-x402-guards.test.js b/tests/api-user-wallet-x402-guards.test.js
index 17c38ea8e..949082881 100644
--- a/tests/api-user-wallet-x402-guards.test.js
+++ b/tests/api-user-wallet-x402-guards.test.js
@@ -25,11 +25,12 @@ const AGENT_ID = '11111111-1111-4111-8111-111111111111';
// Synthetic, deliberately: these cases assert address handling only, so a real
// third-party account would add a claim we do not mean.
const MASTER_WALLET = '7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU';
+const MASTER_EVM = '0x1111111111111111111111111111111111111111';
const AGENT_WALLET = 'GDfnEsia2WLAW5t8yx2X5j2mkfA74i5kK8vY6C4nGRQe';
const authState = { session: { id: USER_ID } };
const csrfState = { ok: true };
-const sqlState = { queue: [] };
+const sqlState = { queue: [], calls: [] };
const rpcState = { sigLimit: null, balanceLamports: 5_000_000n, tokenAmount: '2500000', destAtaExists: true };
const keysState = { calls: [], createThrows: null };
@@ -38,7 +39,14 @@ vi.mock('../api/_lib/auth.js', () => ({
}));
vi.mock('../api/_lib/db.js', () => ({
- sql: vi.fn(async () => (sqlState.queue.length ? sqlState.queue.shift() : [])),
+ // The bootstrap DDL in wallet/index.js runs before the reads a case primes,
+ // so it must not eat a queued result. Everything else answers in order.
+ sql: vi.fn(async (strings, ...values) => {
+ const text = Array.isArray(strings) ? strings.join(' ? ') : String(strings);
+ sqlState.calls.push({ text, values });
+ if (/CREATE TABLE/i.test(text)) return [];
+ return sqlState.queue.length ? sqlState.queue.shift() : [];
+ }),
isDbUnavailableError: () => false,
isDbCapacityError: () => false,
isStoragePressured: async () => ({ pressured: false }),
@@ -75,8 +83,38 @@ vi.mock('../api/_lib/agent-wallet.js', () => ({
recoverSolanaAgentKeypair: vi.fn(async () => {
throw new Error('test reached key recovery: no case here may sign');
}),
+ generateSolanaAgentWallet: vi.fn(async () => ({
+ address: MASTER_WALLET,
+ encrypted_secret: 'enc-sol',
+ })),
+ generateAgentWallet: vi.fn(async () => ({
+ address: MASTER_EVM,
+ encrypted_key: 'enc-evm',
+ })),
+ getSolanaAddressBalances: vi.fn(async () => ({
+ native: 0.42,
+ total_usd: 63,
+ tokens: [{ mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', uiAmount: 12.5 }],
+ })),
+}));
+
+vi.mock('../api/_lib/evm/rpc.js', () => ({
+ evmFallbackProvider: vi.fn(async () => ({
+ call: vi.fn(async () => '0x' + (7_000_000).toString(16).padStart(64, '0')),
+ })),
}));
+vi.mock('../api/_lib/provider-keys.js', async () => {
+ const actual = await vi.importActual('../api/_lib/provider-keys.js');
+ return {
+ BYOK_PROVIDERS: actual.BYOK_PROVIDERS,
+ // The real one needs JWT_SECRET. What matters at this boundary is that a
+ // value is encrypted before it reaches the column and a null deletes the
+ // entry, not which cipher ran.
+ encryptProviderKey: vi.fn(async (v) => `enc(${v})`),
+ };
+});
+
const connection = {
getBalance: vi.fn(async () => Number(rpcState.balanceLamports)),
getMinimumBalanceForRentExemption: vi.fn(async () => 2_039_280),
@@ -124,6 +162,8 @@ vi.mock('../api/_lib/aws-marketplace-bridge.js', () => ({
const subscriptionsHandler = (await import('../api/user/x402-subscriptions.js')).default;
const fundAgentHandler = (await import('../api/user/wallet/fund-agent.js')).default;
const historyHandler = (await import('../api/user/wallet/history.js')).default;
+const walletHandler = (await import('../api/user/wallet/index.js')).default;
+const providerKeysHandler = (await import('../api/user/provider-keys.js')).default;
function makeReq({ method, url, body = null }) {
const raw = body === null ? null : JSON.stringify(body);
@@ -168,6 +208,7 @@ beforeEach(() => {
authState.session = { id: USER_ID };
csrfState.ok = true;
sqlState.queue = [];
+ sqlState.calls = [];
keysState.calls = [];
keysState.createThrows = null;
rpcState.sigLimit = null;
@@ -335,3 +376,127 @@ describe('wallet/history: limit clamping', () => {
expect(body.history).toEqual([]);
});
});
+
+// The two suites below cover the success paths a local curl cannot reach:
+// both need JWT_SECRET to derive an encryption key, and this worktree's env
+// carries only the QA login and DATABASE_URL. Creating a real master wallet
+// under a throwaway key would write an undecryptable row into the shared
+// production database, so the coverage lives here instead.
+describe('wallet index: create and read', () => {
+ it('creates a master wallet and reports it as new', async () => {
+ sqlState.queue.push([]); // no existing wallet
+ sqlState.queue.push([{ solana_address: MASTER_WALLET, evm_address: MASTER_EVM, created_at: '2026-08-15T00:00:00Z' }]);
+ const { status, body } = await call(walletHandler, {
+ method: 'POST',
+ url: '/api/user/wallet',
+ body: {},
+ });
+ expect(status).toBe(201);
+ expect(body.wallet.created).toBe(true);
+ expect(body.wallet.solana_address).toBe(MASTER_WALLET);
+ expect(body.wallet.evm_address).toBe(MASTER_EVM);
+ });
+
+ it('is idempotent: a second create returns the existing wallet, not a new one', async () => {
+ sqlState.queue.push([{ solana_address: MASTER_WALLET, evm_address: MASTER_EVM, created_at: '2026-08-15T00:00:00Z' }]);
+ const { status, body } = await call(walletHandler, {
+ method: 'POST',
+ url: '/api/user/wallet',
+ body: {},
+ });
+ expect(status).toBe(200);
+ expect(body.wallet.created).toBe(false);
+ expect(sqlState.calls.some((c) => /INSERT INTO master_wallets/i.test(c.text))).toBe(false);
+ });
+
+ it('refuses a create with no CSRF token', async () => {
+ csrfState.ok = false;
+ const { status } = await call(walletHandler, { method: 'POST', url: '/api/user/wallet', body: {} });
+ expect(status).toBe(403);
+ expect(sqlState.calls.some((c) => /INSERT INTO master_wallets/i.test(c.text))).toBe(false);
+ });
+
+ it('reads live balances and totals SOL value with EVM USDC', async () => {
+ sqlState.queue.push([{ solana_address: MASTER_WALLET, evm_address: MASTER_EVM, created_at: '2026-08-15T00:00:00Z' }]);
+ const { status, body } = await call(walletHandler, { method: 'GET', url: '/api/user/wallet' });
+ expect(status).toBe(200);
+ expect(body.wallet.balances).toEqual({
+ sol: 0.42,
+ sol_usdc: 12.5,
+ evm_usdc: 7,
+ total_usd: 70,
+ });
+ });
+
+ it('answers a null wallet rather than 404 for a user who has none', async () => {
+ sqlState.queue.push([]);
+ const { status, body } = await call(walletHandler, { method: 'GET', url: '/api/user/wallet' });
+ expect(status).toBe(200);
+ expect(body.wallet).toBeNull();
+ });
+});
+
+describe('provider-keys: set, clear, and what never leaves', () => {
+ it('reports which keys are set and never the values', async () => {
+ sqlState.queue.push([{ provider_keys: { openai: 'enc(sk-live)' } }]);
+ const { status, body } = await call(providerKeysHandler, { method: 'GET', url: '/api/user/provider-keys' });
+ expect(status).toBe(200);
+ expect(body.keys.openai).toEqual({ set: true });
+ expect(body.keys.anthropic).toEqual({ set: false });
+ expect(res_body_has_secret(body)).toBe(false);
+ });
+
+ it('encrypts a new value before it reaches the column', async () => {
+ sqlState.queue.push([{ provider_keys: {} }]);
+ const { status, body } = await call(providerKeysHandler, {
+ method: 'PATCH',
+ url: '/api/user/provider-keys',
+ body: { openai: ' sk-plaintext ' },
+ });
+ expect(status).toBe(200);
+ expect(body.keys.openai).toEqual({ set: true });
+ const update = sqlState.calls.find((c) => /UPDATE users SET provider_keys/i.test(c.text));
+ expect(update.values[0]).toBe(JSON.stringify({ openai: 'enc(sk-plaintext)' }));
+ });
+
+ it('deletes the entry when a provider is set to null', async () => {
+ sqlState.queue.push([{ provider_keys: { openai: 'enc(sk-old)', grok: 'enc(xai-old)' } }]);
+ const { status, body } = await call(providerKeysHandler, {
+ method: 'PATCH',
+ url: '/api/user/provider-keys',
+ body: { openai: null },
+ });
+ expect(status).toBe(200);
+ expect(body.keys.openai).toEqual({ set: false });
+ expect(body.keys.grok).toEqual({ set: true });
+ const update = sqlState.calls.find((c) => /UPDATE users SET provider_keys/i.test(c.text));
+ expect(JSON.parse(update.values[0])).toEqual({ grok: 'enc(xai-old)' });
+ });
+
+ it('rejects a non-string value with a 400 naming the field', async () => {
+ const { status, body } = await call(providerKeysHandler, {
+ method: 'PATCH',
+ url: '/api/user/provider-keys',
+ body: { openai: 123 },
+ });
+ expect(status).toBe(400);
+ expect(body.error).toBe('validation_error');
+ expect(body.error_description).toContain('openai');
+ });
+
+ it('refuses a write with no CSRF token', async () => {
+ csrfState.ok = false;
+ const { status } = await call(providerKeysHandler, {
+ method: 'PATCH',
+ url: '/api/user/provider-keys',
+ body: { openai: 'sk-plaintext' },
+ });
+ expect(status).toBe(403);
+ expect(sqlState.calls.some((c) => /UPDATE users SET provider_keys/i.test(c.text))).toBe(false);
+ });
+});
+
+// The GET contract is that a stored ciphertext never appears in the response.
+function res_body_has_secret(body) {
+ return JSON.stringify(body).includes('enc(');
+}
diff --git a/tests/api/gcp-budget-alert.test.js b/tests/api/gcp-budget-alert.test.js
index 1b427510c..92a07b689 100644
--- a/tests/api/gcp-budget-alert.test.js
+++ b/tests/api/gcp-budget-alert.test.js
@@ -16,6 +16,10 @@ vi.mock('../../api/_lib/zauth.js', () => ({ instrument: () => null, drain: async
vi.mock('../../api/_lib/env.js', () => ({ env: { APP_ORIGIN: 'http://localhost:3000' } }));
const { default: handler } = await import('../../api/webhooks/gcp-budget-alert.js');
+// The REAL severity classifier, not the mock: the alert title is the only input
+// that decides whether ops sees a budget crossing as critical or as a warning,
+// so the test has to run the classifier that ships.
+const { severityOf } = await vi.importActual('../../api/_lib/alerts.js');
function pubsubBody(notification) {
const data = Buffer.from(JSON.stringify(notification), 'utf8').toString('base64');
@@ -107,6 +111,51 @@ describe('gcp-budget-alert webhook', () => {
expect(sendOpsAlert).not.toHaveBeenCalled();
});
+ it('files a 90% crossing as critical, not as routine burn-down noise', async () => {
+ await invoke({
+ token: 'secret',
+ body: pubsubBody({
+ budgetDisplayName: 'gcp-credits program',
+ alertThresholdExceeded: 0.9,
+ costAmount: 90000,
+ budgetAmount: 100000,
+ }),
+ });
+ const [title] = sendOpsAlert.mock.calls[0];
+ // alerts.js severityOf() reads the emoji: 🚨 is what makes this `critical`.
+ // Any other marker files a near-exhausted grant next to routine warnings.
+ expect(severityOf(title)).toBe('critical');
+ });
+
+ it('keeps a 25% crossing at warn severity', async () => {
+ await invoke({
+ token: 'secret',
+ body: pubsubBody({
+ budgetDisplayName: 'gcp-credits program',
+ alertThresholdExceeded: 0.25,
+ costAmount: 25000,
+ budgetAmount: 100000,
+ }),
+ });
+ const [title] = sendOpsAlert.mock.calls[0];
+ expect(severityOf(title)).toBe('warn');
+ });
+
+ it('renders a zero budget without emitting a broken percentage', async () => {
+ const { status } = await invoke({
+ token: 'secret',
+ body: pubsubBody({
+ budgetDisplayName: 'misconfigured budget',
+ alertThresholdExceeded: 0.5,
+ costAmount: 5,
+ budgetAmount: 0,
+ }),
+ });
+ expect(status).toBe(200);
+ const [, detail] = sendOpsAlert.mock.calls[0];
+ expect(detail).toContain('(n/a)');
+ });
+
it('acks a verification ping with no decodable data', async () => {
const { status, body } = await invoke({ token: 'secret', body: JSON.stringify({ message: { messageId: 'x' } }) });
expect(status).toBe(200);
diff --git a/tests/api/tts-input-guards.test.js b/tests/api/tts-input-guards.test.js
new file mode 100644
index 000000000..15e0ac47d
--- /dev/null
+++ b/tests/api/tts-input-guards.test.js
@@ -0,0 +1,413 @@
+// A caller's bad input has to come back as the caller's error, before any money
+// moves. Three places in the TTS surface used to break that:
+//
+// 1. GET /api/tts/catalog answered 200 with an empty catalog for a provider id
+// that does not exist, so a typo and a lane that is genuinely down looked
+// identical to the picker.
+// 2. POST /api/tts/synthesize handed an unrecognized voiceId straight to the
+// router, which swaps in the lane default. The caller got a 200, somebody
+// else's voice, and (on a metered lane) a charge, with nothing in the
+// response saying a substitution had happened. A well-formed-but-nonexistent
+// id instead burned an upstream round trip and came back 502.
+// 3. POST /api/tts/eleven-clone read out whether this server has an ElevenLabs
+// key before it checked who was asking, so a signed-out caller could probe
+// the deployment's configuration.
+//
+// Transport-layer stubs only (global fetch, the R2 and credit boundaries). No
+// live synthesis, no live credit ledger.
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { Readable } from 'node:stream';
+
+const authState = vi.hoisted(() => ({ user: null }));
+const creditState = vi.hoisted(() => ({ charges: [], refunds: [] }));
+
+vi.mock('../../api/_lib/auth.js', () => ({
+ getSessionUser: async () => authState.user,
+ authenticateBearer: async () => null,
+ extractBearer: () => null,
+}));
+
+// R2 stands in for "no cached clip": a miss on both head and write keeps the
+// handler on the path this file is about.
+vi.mock('../../api/_lib/r2.js', () => ({
+ headObject: async () => {
+ throw new Error('no such key');
+ },
+ getObjectBuffer: async () => {
+ throw new Error('no such key');
+ },
+ putObject: async () => ({}),
+}));
+
+// api/tts/eleven.js only touches the database on the agent-voice lane, which no
+// test here exercises; the stub exists so importing the handler does not need a
+// live connection.
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: async () => [],
+}));
+
+vi.mock('../../api/_lib/credits.js', () => ({
+ chargeCreditsForAction: async (args) => {
+ creditState.charges.push(args);
+ return { chargedUsd: 0.0001 };
+ },
+ refundCredits: async (args) => {
+ creditState.refunds.push(args);
+ return { refundedUsd: 0.0001 };
+ },
+}));
+
+const ORIGINAL_FETCH = globalThis.fetch;
+const ENV_KEYS = ['OPENAI_API_KEY', 'ELEVENLABS_API_KEY', 'NVIDIA_API_KEY'];
+const ORIGINAL_ENV = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]]));
+
+// Shaped exactly like Microsoft's published voice list, so the real
+// normalizer in api/_lib/tts-edge.js runs over it.
+const EDGE_LIST = [
+ {
+ Name: 'Microsoft Server Speech Text to Speech Voice (en-US, AriaNeural)',
+ ShortName: 'en-US-AriaNeural',
+ Gender: 'Female',
+ Locale: 'en-US',
+ FriendlyName: 'Microsoft Aria Online (Natural) - English (United States)',
+ VoiceTag: { ContentCategories: ['News'], VoicePersonalities: ['Positive'] },
+ },
+ {
+ Name: 'Microsoft Server Speech Text to Speech Voice (en-GB, RyanNeural)',
+ ShortName: 'en-GB-RyanNeural',
+ Gender: 'Male',
+ Locale: 'en-GB',
+ FriendlyName: 'Microsoft Ryan Online (Natural) - English (United Kingdom)',
+ VoiceTag: { ContentCategories: ['General'], VoicePersonalities: ['Friendly'] },
+ },
+];
+
+const OPENAI_MP3 = Buffer.from('openai-mp3-fixture');
+const ELEVEN_MP3 = Buffer.from('eleven-mp3-fixture');
+
+let edgeListCalls = 0;
+let openaiCalls = [];
+
+function stubFetch({ edgeList = EDGE_LIST, edgeStatus = 200, elevenStatus = 200 } = {}) {
+ globalThis.fetch = vi.fn(async (url, opts = {}) => {
+ const u = String(url);
+ if (u.includes('voices/list')) {
+ edgeListCalls += 1;
+ if (edgeStatus !== 200) return new Response('nope', { status: edgeStatus });
+ return new Response(JSON.stringify(edgeList), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ });
+ }
+ if (u.includes('api.openai.com')) {
+ openaiCalls.push(JSON.parse(opts.body));
+ return new Response(OPENAI_MP3, {
+ status: 200,
+ headers: { 'content-type': 'audio/mpeg' },
+ });
+ }
+ if (u.includes('api.elevenlabs.io')) {
+ if (elevenStatus !== 200) {
+ // The shape ElevenLabs actually returns for an id it does not have.
+ return new Response(
+ JSON.stringify({
+ detail: {
+ status: 'voice_not_found',
+ message: "An invalid ID has been received: 'ghost-voice'.",
+ },
+ }),
+ { status: elevenStatus, headers: { 'content-type': 'application/json' } },
+ );
+ }
+ return new Response(ELEVEN_MP3, {
+ status: 200,
+ headers: { 'content-type': 'audio/mpeg' },
+ });
+ }
+ throw new Error(`unexpected fetch in test: ${u}`);
+ });
+}
+
+let ipCounter = 0;
+let userCounter = 0;
+
+function makeReq({ method = 'POST', url = '/api/tts/synthesize', body = null, headers = {} } = {}) {
+ const buf = body === null ? Buffer.alloc(0) : Buffer.from(JSON.stringify(body));
+ const req = Readable.from([buf]);
+ req.method = method;
+ req.url = url;
+ req.headers = {
+ 'content-type': 'application/json',
+ 'content-length': String(buf.length),
+ // A fresh IP and a fresh user id per request so the in-memory limiters
+ // never trip across this file.
+ 'x-forwarded-for': `10.1.0.${++ipCounter}, 35.191.0.1`,
+ ...headers,
+ };
+ return req;
+}
+
+function makeRes() {
+ const chunks = [];
+ return {
+ statusCode: 200,
+ _h: {},
+ writableEnded: false,
+ headersSent: false,
+ setHeader(k, v) {
+ this._h[k.toLowerCase()] = v;
+ },
+ getHeader(k) {
+ return this._h[k.toLowerCase()];
+ },
+ write(c) {
+ chunks.push(Buffer.from(c));
+ },
+ end(c) {
+ if (c) chunks.push(Buffer.from(c));
+ this.writableEnded = true;
+ },
+ body() {
+ return Buffer.concat(chunks);
+ },
+ json() {
+ return JSON.parse(this.body().toString('utf8'));
+ },
+ };
+}
+
+async function call(modulePath, reqOpts) {
+ const handler = (await import(modulePath)).default;
+ const res = makeRes();
+ await handler(makeReq(reqOpts), res);
+ return res;
+}
+
+function signIn() {
+ authState.user = { id: `11111111-0000-4000-8000-00000000${String(++userCounter).padStart(4, '0')}` };
+ return authState.user;
+}
+
+beforeEach(() => {
+ authState.user = null;
+ creditState.charges.length = 0;
+ creditState.refunds.length = 0;
+ openaiCalls = [];
+ edgeListCalls = 0;
+ for (const k of ENV_KEYS) delete process.env[k];
+ stubFetch();
+});
+
+afterEach(() => {
+ globalThis.fetch = ORIGINAL_FETCH;
+ for (const k of ENV_KEYS) {
+ if (ORIGINAL_ENV[k] === undefined) delete process.env[k];
+ else process.env[k] = ORIGINAL_ENV[k];
+ }
+});
+
+describe('isKnownVoice (api/_lib/voice-providers.js)', () => {
+ it('accepts an id the lane actually publishes and rejects one it does not', async () => {
+ const { isKnownVoice } = await import('../../api/_lib/voice-providers.js');
+ expect(await isKnownVoice('edge', 'en-GB-RyanNeural')).toBe(true);
+ expect(await isKnownVoice('edge', 'zz-ZZ-NopeNeural')).toBe(false);
+ expect(await isKnownVoice('edge', 'not a voice at all')).toBe(false);
+ });
+
+ it('treats an omitted voiceId as "use the lane default"', async () => {
+ const { isKnownVoice } = await import('../../api/_lib/voice-providers.js');
+ for (const p of ['edge', 'gemini', 'nvidia', 'openai', 'elevenlabs']) {
+ expect(await isKnownVoice(p, '')).toBe(true);
+ expect(await isKnownVoice(p, undefined)).toBe(true);
+ }
+ });
+
+ it('checks the closed-vocabulary lanes against their own catalog', async () => {
+ const { isKnownVoice, listProviderVoices } = await import(
+ '../../api/_lib/voice-providers.js'
+ );
+ for (const p of ['gemini', 'nvidia', 'openai']) {
+ const [first] = await listProviderVoices(p);
+ expect(await isKnownVoice(p, first.id)).toBe(true);
+ expect(await isKnownVoice(p, 'totally-not-real')).toBe(false);
+ }
+ });
+
+ it('leaves the per-account ElevenLabs catalog to upstream', async () => {
+ const { isKnownVoice } = await import('../../api/_lib/voice-providers.js');
+ // Voices are cloned and added to an account at runtime, so a local list
+ // would reject ids that are genuinely valid a second later.
+ expect(await isKnownVoice('elevenlabs', 'a-voice-only-this-account-has')).toBe(true);
+ });
+
+ it('fails open when the lane catalog cannot be fetched', async () => {
+ // A Microsoft outage must not turn every Edge request into a 400.
+ vi.resetModules();
+ stubFetch({ edgeStatus: 503 });
+ const { isKnownVoice } = await import('../../api/_lib/voice-providers.js');
+ expect(await isKnownVoice('edge', 'en-US-AriaNeural')).toBe(true);
+ });
+});
+
+describe('POST /api/tts/synthesize voiceId guard', () => {
+ it('rejects a voice the lane does not have instead of silently substituting one', async () => {
+ const res = await call('../../api/tts/synthesize.js', {
+ body: { provider: 'edge', voiceId: 'zz-ZZ-NopeNeural', text: 'hello' },
+ });
+ expect(res.statusCode).toBe(400);
+ const body = res.json();
+ expect(body.error).toBe('validation_error');
+ expect(body.error_description).toContain('zz-ZZ-NopeNeural');
+ expect(body.error_description).toContain('/api/tts/catalog?provider=edge');
+ });
+
+ it('never charges for a rejected voice', async () => {
+ process.env.OPENAI_API_KEY = 'sk-test-openai';
+ signIn();
+ const res = await call('../../api/tts/synthesize.js', {
+ body: { provider: 'openai', voiceId: 'not-an-openai-voice', text: 'hello' },
+ });
+ expect(res.statusCode).toBe(400);
+ expect(creditState.charges).toEqual([]);
+ expect(openaiCalls).toEqual([]);
+ });
+
+ it('still renders, and still meters, a voice the lane does have', async () => {
+ process.env.OPENAI_API_KEY = 'sk-test-openai';
+ signIn();
+ const res = await call('../../api/tts/synthesize.js', {
+ body: { provider: 'openai', voiceId: 'nova', text: 'hello' },
+ });
+ expect(res.statusCode).toBe(200);
+ expect(res.getHeader('x-tts-billing')).toBe('credits');
+ expect(res.getHeader('x-tts-voice')).toBe('nova');
+ expect(openaiCalls).toHaveLength(1);
+ expect(openaiCalls[0].voice).toBe('nova');
+ expect(creditState.charges).toHaveLength(1);
+ expect(creditState.refunds).toEqual([]);
+ });
+
+ it('lets an omitted voiceId through to the lane default', async () => {
+ process.env.OPENAI_API_KEY = 'sk-test-openai';
+ signIn();
+ const res = await call('../../api/tts/synthesize.js', {
+ body: { provider: 'openai', text: 'hello' },
+ });
+ expect(res.statusCode).toBe(200);
+ expect(openaiCalls).toHaveLength(1);
+ expect(res.getHeader('x-tts-voice')).toBe(openaiCalls[0].voice);
+ });
+
+ it('rejects an unknown provider before it looks at the voice', async () => {
+ const res = await call('../../api/tts/synthesize.js', {
+ body: { provider: 'nope', voiceId: 'x', text: 'hello' },
+ });
+ expect(res.statusCode).toBe(400);
+ expect(res.json().error_description).toContain('nope');
+ });
+});
+
+describe('GET /api/tts/catalog provider guard', () => {
+ it('rejects a provider id that does not exist', async () => {
+ const res = await call('../../api/tts/catalog.js', {
+ method: 'GET',
+ url: '/api/tts/catalog?provider=bogus',
+ });
+ expect(res.statusCode).toBe(400);
+ const body = res.json();
+ expect(body.error).toBe('validation_error');
+ expect(body.error_description).toContain('bogus');
+ // The message names the lanes that do exist, so the caller can fix it.
+ expect(body.error_description).toContain('edge');
+ });
+
+ it('serves the lane for a provider id that does exist', async () => {
+ const res = await call('../../api/tts/catalog.js', {
+ method: 'GET',
+ url: '/api/tts/catalog?provider=edge',
+ });
+ expect(res.statusCode).toBe(200);
+ const body = res.json();
+ expect(body.counts.edge).toBe(EDGE_LIST.length);
+ expect(body.voices.map((v) => v.id)).toEqual(EDGE_LIST.map((v) => v.ShortName));
+ });
+
+ it('treats a blank provider param as "every lane"', async () => {
+ const res = await call('../../api/tts/catalog.js', {
+ method: 'GET',
+ url: '/api/tts/catalog?provider=',
+ });
+ expect(res.statusCode).toBe(200);
+ expect(res.json().total).toBe(EDGE_LIST.length);
+ });
+});
+
+describe('an unknown ElevenLabs voice is the caller\'s error, not the platform\'s', () => {
+ it('POST /api/tts/eleven answers 4xx and refunds, instead of blaming itself with a 502', async () => {
+ vi.resetModules();
+ stubFetch({ elevenStatus: 400 });
+ process.env.ELEVENLABS_API_KEY = 'xi-platform-key';
+ signIn();
+ const res = await call('../../api/tts/eleven.js', {
+ url: '/api/tts/eleven',
+ body: { voiceId: 'ghost-voice', text: 'hello' },
+ });
+ expect(res.statusCode).toBe(400);
+ expect(res.json().error).toBe('validation_error');
+ expect(res.json().error_description).toContain('ghost-voice');
+ // Charged before the upstream call, so a failed clip has to be given back.
+ expect(creditState.charges).toHaveLength(1);
+ expect(creditState.refunds).toHaveLength(1);
+ });
+
+ it('POST /api/tts/eleven still reports a genuine upstream fault as 502', async () => {
+ vi.resetModules();
+ stubFetch({ elevenStatus: 500 });
+ process.env.ELEVENLABS_API_KEY = 'xi-platform-key';
+ signIn();
+ const res = await call('../../api/tts/eleven.js', {
+ url: '/api/tts/eleven',
+ body: { voiceId: 'ghost-voice', text: 'hello' },
+ });
+ expect(res.statusCode).toBe(502);
+ expect(res.json().error).toBe('upstream_error');
+ expect(creditState.refunds).toHaveLength(1);
+ });
+
+ it('synthesizeVoice tags a 404 as invalid_argument so the router can answer 4xx', async () => {
+ vi.resetModules();
+ stubFetch({ elevenStatus: 404 });
+ const { synthesizeVoice } = await import('../../api/_lib/voice-providers.js');
+ await expect(
+ synthesizeVoice({
+ provider: 'elevenlabs',
+ text: 'hello',
+ voiceId: 'ghost-voice',
+ elevenKey: 'xi-user-key',
+ }),
+ ).rejects.toMatchObject({ code: 'invalid_argument' });
+ });
+});
+
+describe('POST /api/tts/eleven-clone auth ordering', () => {
+ it('answers 401 to a signed-out caller rather than reporting the key state', async () => {
+ process.env.ELEVENLABS_API_KEY = 'xi-platform-key';
+ const res = await call('../../api/tts/eleven-clone.js', {
+ url: '/api/tts/eleven-clone',
+ body: {},
+ headers: { 'content-type': 'multipart/form-data; boundary=abc' },
+ });
+ expect(res.statusCode).toBe(401);
+ expect(res.json().error).toBe('unauthorized');
+ });
+
+ it('answers 401 the same way when the server has no key at all', async () => {
+ const res = await call('../../api/tts/eleven-clone.js', {
+ url: '/api/tts/eleven-clone',
+ body: {},
+ headers: { 'content-type': 'multipart/form-data; boundary=abc' },
+ });
+ expect(res.statusCode).toBe(401);
+ });
+});
diff --git a/tests/trades-feed.test.js b/tests/trades-feed.test.js
new file mode 100644
index 000000000..bac341be2
--- /dev/null
+++ b/tests/trades-feed.test.js
@@ -0,0 +1,240 @@
+// Contract for GET /api/trades/feed, the public feed of notable closed exits.
+//
+// This is the platform's top-of-funnel surface, so every wrong answer here is a
+// wrong answer in public. Four of them shipped at once:
+// - `min_pnl_pct=0` was rewritten to 10 by a `Number(x) || 10` default, so the
+// oracle coin drawer, which passes 0 to mean "every trade on this coin",
+// silently only ever saw the winners above 10%.
+// - `multiple` was exit/entry, but a position that took initials first rewrites
+// its cost basis and books only the closing leg's proceeds, so the feed
+// rendered "0.56x" beside "+88%" on the same row.
+// - A malformed `cursor` slipped past a prefix regex into a `::timestamptz`
+// cast, and a malformed `mint` was dropped, answering a coin-scoped request
+// with the whole platform feed.
+// - A blanket `.catch(() => [])` turned any database fault into a 200 with an
+// empty feed: no error, no alert, just a platform that looks like it has
+// never had a profitable trade.
+
+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, headers = {}) => { res._json = { status, body, headers }; return res; },
+ error: (res, status, code, message) => {
+ res._json = { status, body: { error: code, error_description: message } };
+ return res;
+ },
+ };
+});
+
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ limits: { publicIp: vi.fn(async () => ({ success: true })) },
+ clientIp: () => '1.2.3.4',
+}));
+
+// Every tagged-template read lands here. The handler builds three small SQL
+// fragments (window / cursor / mint) before the feed query itself, so tests pick
+// the main query out by the table it reads rather than by call index.
+const sqlCalls = [];
+let feedRows = [];
+let feedError = null;
+vi.mock('../api/_lib/db.js', () => ({
+ sql: (strings, ...values) => {
+ sqlCalls.push({ text: strings.join('?'), values });
+ if (!strings.join('').includes('agent_sniper_positions pos')) return Promise.resolve([]);
+ return feedError ? Promise.reject(feedError) : Promise.resolve(feedRows);
+ },
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+}));
+
+import feed from '../api/trades/feed.js';
+
+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+const AGENT_ID = '0846c27e-6258-4859-bc1c-3148d59951c5';
+
+// A position that took initials before its final exit: the basis left on the row
+// is the moon bag's, the exit is the closing leg only, and the realized numbers
+// are cumulative across both legs. Shape lifted from a live mainnet row.
+function partialExitRow(overrides = {}) {
+ return {
+ id: 'c6ad1e50-3fcb-4d4a-9a19-2a4a0b7bbf16',
+ mint: THREE_MINT,
+ symbol: 'THREE',
+ name: 'three.ws',
+ network: 'mainnet',
+ status: 'closed',
+ exit_reason: 'trailing_stop',
+ realized_pnl_lamports: '2339513',
+ realized_pnl_pct: '87.93654170563242',
+ entry_quote_lamports: '2660456',
+ exit_quote_lamports: '1487868',
+ buy_sig: 'buysig',
+ sell_sig: 'sellsig',
+ opened_at: '2026-08-15T00:14:15.507Z',
+ closed_at: '2026-08-15T00:15:13.750Z',
+ hold_seconds: 58,
+ agent_id: AGENT_ID,
+ agent_name: 'Moe Money AI',
+ agent_avatar: null,
+ agent_image: null,
+ oracle_score: null,
+ oracle_tier: null,
+ oracle_category: null,
+ image_uri: null,
+ copier_count: '3',
+ ...overrides,
+ };
+}
+
+function fakeRes() {
+ return {
+ statusCode: 200,
+ _headers: {},
+ setHeader(k, v) { this._headers[k.toLowerCase()] = v; },
+ getHeader(k) { return this._headers[k.toLowerCase()]; },
+ end() { this.writableEnded = true; },
+ };
+}
+
+function fakeReq(url) {
+ return { method: 'GET', url, headers: { host: 'three.ws' } };
+}
+
+function mainQuery() {
+ return sqlCalls.find((c) => c.text.includes('agent_sniper_positions pos'));
+}
+
+beforeEach(() => {
+ sqlCalls.length = 0;
+ feedRows = [];
+ feedError = null;
+});
+
+describe('GET /api/trades/feed', () => {
+ it('shapes a closed position into a feed item with real trader and coin context', async () => {
+ feedRows = [partialExitRow()];
+ const res = fakeRes();
+ await feed(fakeReq('/api/trades/feed?window=all&limit=40'), res);
+
+ expect(res._json.status).toBe(200);
+ const { body } = res._json;
+ expect(body.count).toBe(1);
+ expect(body.window).toBe('all');
+ const item = body.items[0];
+ expect(item.mint).toBe(THREE_MINT);
+ expect(item.symbol).toBe('THREE');
+ expect(item.agent_id).toBe(AGENT_ID);
+ expect(item.agent_name).toBe('Moe Money AI');
+ expect(item.copier_count).toBe(3);
+ expect(item.entry_sol).toBeCloseTo(0.002660456, 9);
+ expect(item.realized_pnl_sol).toBeCloseTo(0.002339513, 9);
+ expect(item.realized_pnl_pct).toBeCloseTo(87.93654, 4);
+ expect(item.hold_seconds).toBe(58);
+ expect(item.closed_at).toBe('2026-08-15T00:15:13.750Z');
+ // A short page does not advertise another one.
+ expect(body.next_cursor).toBeNull();
+ });
+
+ it('derives `multiple` from the cumulative pct so it cannot contradict the pnl', async () => {
+ feedRows = [partialExitRow()];
+ const res = fakeRes();
+ await feed(fakeReq('/api/trades/feed?window=all'), res);
+
+ const item = res._json.body.items[0];
+ // exit/entry on this row is 0.56, which is the closing leg alone. The
+ // position returned +87.9%, so the honest multiple is 1.88.
+ expect(item.multiple).toBe(1.88);
+ expect(item.multiple).toBeGreaterThan(1);
+ expect(item.exit_sol / item.entry_sol).toBeLessThan(1);
+ });
+
+ it('honors an explicit min_pnl_pct=0 instead of defaulting it back to 10', async () => {
+ const res = fakeRes();
+ await feed(fakeReq('/api/trades/feed?window=all&min_pnl_pct=0'), res);
+
+ expect(res._json.body.min_pnl_pct).toBe(0);
+ // The floor the query actually filtered on, not just the echoed field.
+ expect(mainQuery().values).toContain(0);
+ });
+
+ it('still defaults min_pnl_pct to 10 when it is absent or unparseable', async () => {
+ for (const qs of ['', '&min_pnl_pct=', '&min_pnl_pct=abc']) {
+ sqlCalls.length = 0;
+ const res = fakeRes();
+ await feed(fakeReq(`/api/trades/feed?window=all${qs}`), res);
+ expect(res._json.body.min_pnl_pct).toBe(10);
+ expect(mainQuery().values).toContain(10);
+ }
+ });
+
+ it('400s a malformed cursor instead of letting the timestamptz cast reject', async () => {
+ const res = fakeRes();
+ await feed(fakeReq('/api/trades/feed?cursor=2020-01-01Tgarbage'), 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(mainQuery()).toBeUndefined();
+ });
+
+ it('400s a malformed mint rather than answering with the whole platform feed', async () => {
+ feedRows = [partialExitRow()];
+ const res = fakeRes();
+ await feed(fakeReq('/api/trades/feed?mint=not-a-base58-mint'), res);
+
+ expect(res._json.status).toBe(400);
+ expect(res._json.body.error).toBe('validation_error');
+ expect(mainQuery()).toBeUndefined();
+ });
+
+ it('scopes a valid mint to that coin and drops the time window', async () => {
+ feedRows = [partialExitRow()];
+ const res = fakeRes();
+ await feed(fakeReq(`/api/trades/feed?window=24h&mint=${THREE_MINT}`), res);
+
+ expect(res._json.status).toBe(200);
+ expect(res._json.body.mint).toBe(THREE_MINT);
+ expect(res._json.body.window).toBe('all');
+ // The mint reaches SQL through its own fragment, and no window fragment is
+ // built alongside it.
+ expect(sqlCalls.find((c) => c.text.includes('pos.mint =')).values).toContain(THREE_MINT);
+ expect(sqlCalls.some((c) => c.text.includes('now() -'))).toBe(false);
+ });
+
+ it('excludes deleted agents and null exit timestamps from the public feed', async () => {
+ const res = fakeRes();
+ await feed(fakeReq('/api/trades/feed?window=all'), res);
+
+ const text = mainQuery().text;
+ expect(text).toContain('ai.deleted_at is null');
+ expect(text).toContain('pos.closed_at is not null');
+ // A stable tiebreaker, or the cursor walks a nondeterministic order.
+ expect(text).toContain('order by pos.closed_at desc, pos.id desc');
+ });
+
+ it('advertises a cursor only when the page is full', async () => {
+ feedRows = [partialExitRow(), partialExitRow({ id: 'b', closed_at: '2026-08-14T00:00:00.000Z' })];
+ const res = fakeRes();
+ await feed(fakeReq('/api/trades/feed?window=all&limit=2'), res);
+
+ expect(res._json.body.count).toBe(2);
+ expect(res._json.body.next_cursor).toBe('2026-08-14T00:00:00.000Z');
+ });
+
+ it('lets a database fault reach the error boundary instead of serving an empty feed', async () => {
+ feedError = new Error('connection terminated unexpectedly');
+ const res = fakeRes();
+
+ await expect(feed(fakeReq('/api/trades/feed?window=all'), res)).rejects.toThrow(/connection terminated/);
+ // The old `.catch(() => [])` answered 200 with count 0 here, which reads as
+ // "no agent has ever turned a profit" and fires no alert.
+ expect(res._json).toBeUndefined();
+ });
+});
diff --git a/tests/trading-scan-endpoint.test.js b/tests/trading-scan-endpoint.test.js
new file mode 100644
index 000000000..3b09a3043
--- /dev/null
+++ b/tests/trading-scan-endpoint.test.js
@@ -0,0 +1,294 @@
+// POST /api/trading/scan: the Trading Brain's assisted "what would my agent buy
+// right now?" preview.
+//
+// The launch feed, the on-chain quote, the firewall, and the RPC connection are
+// mocked; the entry gate (api/_lib/strategy-schema.js) is the real one, because
+// the whole point of the endpoint is that the owner sees exactly what the
+// autonomous runner would act on. Covered here: auth + ownership gating, input
+// validation, the devnet honesty note, a mainnet success path that carries a real
+// quote and firewall verdict per candidate, and the three regressions that made
+// this handler worth auditing:
+//
+// 1. an owner-writable meta.solana_address that is not a valid pubkey used to
+// throw out of the handler and surface as a 500;
+// 2. a creator-gated rule paid for a live creator lookup on every launch in the
+// feed page, including ones already rejected on age or market cap;
+// 3. `scanned` reported the feed page size even though the loop stops early at
+// MAX_PRICED matches.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { Readable } from 'node:stream';
+
+const AGENT_ID = '11111111-2222-4333-8444-555555555555';
+const OWNER_ID = 'owner-1';
+const AGENT_ADDR = '3Bx1x2kzFqPVDqQxfCVJUmqB7B9ZBRRQ4h6sBLKKTBiN';
+// Coin-agnostic synthetic mints: this endpoint scans whatever the live feed
+// returns and promotes nothing. $THREE remains the only coin three.ws promotes.
+const MINT_A = 'THREEsynthetic1111111111111111111111111AAAA';
+const MINT_B = 'THREEsynthetic1111111111111111111111111BBBB';
+
+const sqlState = { agent: null };
+vi.mock('../api/_lib/db.js', () => ({
+ sql: vi.fn(async () => (sqlState.agent ? [sqlState.agent] : [])),
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+}));
+
+const authState = { session: { id: OWNER_ID }, bearer: null };
+vi.mock('../api/_lib/auth.js', () => ({
+ getSessionUser: vi.fn(async () => authState.session),
+ authenticateBearer: vi.fn(async () => authState.bearer),
+ extractBearer: vi.fn(() => null),
+}));
+
+const rlState = { ip: { success: true }, owner: { success: true } };
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ limits: {
+ authedReadIp: vi.fn(async () => rlState.ip),
+ tradingScan: vi.fn(async () => rlState.owner),
+ },
+ clientIp: () => '127.0.0.1',
+}));
+
+const feedState = { launches: [], throws: false, creatorCalls: [] };
+vi.mock('../api/_lib/pump-launch-feed.js', () => ({
+ recentPumpLaunches: vi.fn(async () => {
+ if (feedState.throws) throw new Error('feed down');
+ return feedState.launches;
+ }),
+ enrichCreatorStats: vi.fn(async (launch) => {
+ feedState.creatorCalls.push(launch.mint);
+ launch.creator_launches = 1;
+ launch.creator_graduated = 1;
+ return launch;
+ }),
+}));
+
+const quoteState = { throwsFor: new Set() };
+vi.mock('../api/agents/solana-trade.js', () => ({
+ quoteTrade: vi.fn(async ({ mintStr }) => {
+ if (quoteState.throwsFor.has(mintStr)) throw new Error('no curve for this mint');
+ return {
+ outUi: 1234.5,
+ priceImpactPct: 0.42,
+ venue: 'bonding_curve',
+ minOutAtomics: '1172775000',
+ decimals: 6,
+ inAtomics: '100000000',
+ };
+ }),
+}));
+
+const firewallState = { seenPayers: [] };
+vi.mock('../api/_lib/trade-firewall.js', () => ({
+ assessTradeSafety: vi.fn(async ({ payer }) => {
+ firewallState.seenPayers.push(payer ?? null);
+ return { verdict: 'allow', score: 100, simulated: true, reasons: ['ok'] };
+ }),
+}));
+
+vi.mock('../api/_lib/agent-pumpfun.js', () => ({
+ solanaConnection: vi.fn(() => ({})),
+}));
+
+const handler = (await import('../api/trading/scan.js')).default;
+
+function mockRes() {
+ return {
+ statusCode: 200,
+ _headers: {},
+ _body: '',
+ setHeader(k, v) { this._headers[k.toLowerCase()] = v; },
+ getHeader(k) { return this._headers[k.toLowerCase()]; },
+ end(b) { this._body = b || ''; },
+ get headersSent() { return false; },
+ get writableEnded() { return false; },
+ get json() { try { return JSON.parse(this._body); } catch { return null; } },
+ };
+}
+
+function mockReq({ method = 'POST', body = null } = {}) {
+ const chunks = body != null ? [Buffer.from(JSON.stringify(body))] : [];
+ const r = Readable.from(chunks);
+ r.method = method;
+ r.url = '/api/trading/scan';
+ r.headers = { origin: 'http://localhost:3000', 'content-type': 'application/json' };
+ return r;
+}
+
+async function scan(body) {
+ const res = mockRes();
+ await handler(mockReq({ body }), res);
+ return res;
+}
+
+// A launch the default rule accepts: fresh, quoted in SOL, with socials.
+function freshLaunch(mint, over = {}) {
+ return {
+ mint,
+ name: 'Synthetic Test Launch',
+ symbol: 'SYNTH',
+ created_at: Date.now() - 60_000,
+ market_cap_usd: 5_000,
+ liquidity_sol: 12,
+ creator: `creator-of-${mint}`,
+ twitter: 'https://x.com/example',
+ ...over,
+ };
+}
+
+beforeEach(() => {
+ sqlState.agent = { id: AGENT_ID, user_id: OWNER_ID, meta: { solana_address: AGENT_ADDR } };
+ authState.session = { id: OWNER_ID };
+ authState.bearer = null;
+ rlState.ip = { success: true };
+ rlState.owner = { success: true };
+ feedState.launches = [];
+ feedState.throws = false;
+ feedState.creatorCalls = [];
+ quoteState.throwsFor = new Set();
+ firewallState.seenPayers = [];
+});
+
+describe('POST /api/trading/scan gating', () => {
+ it('rejects an anonymous caller with 401', async () => {
+ authState.session = null;
+ const res = await scan({ agent_id: AGENT_ID });
+ expect(res.statusCode).toBe(401);
+ expect(res.json.error).toBe('unauthorized');
+ });
+
+ it('rejects a non-POST method with 405', async () => {
+ const res = mockRes();
+ await handler(mockReq({ method: 'GET' }), res);
+ expect(res.statusCode).toBe(405);
+ });
+
+ it('rejects a missing or malformed agent_id with a structured 400', async () => {
+ for (const body of [{}, { agent_id: 'not-a-uuid' }, { agent_id: 42 }]) {
+ const res = await scan(body);
+ expect(res.statusCode).toBe(400);
+ expect(res.json.error).toBe('validation_error');
+ }
+ });
+
+ it("404s on an agent the caller does not own", async () => {
+ sqlState.agent = null;
+ const res = await scan({ agent_id: AGENT_ID });
+ expect(res.statusCode).toBe(404);
+ expect(res.json.error).toBe('not_found');
+ });
+
+ it('applies a per-owner ceiling on top of the per-IP bucket', async () => {
+ rlState.owner = { success: false, limit: 30, remaining: 0, reset: Date.now() + 1000 };
+ const res = await scan({ agent_id: AGENT_ID });
+ expect(res.statusCode).toBe(429);
+ // The feed must not be touched once the owner bucket is empty.
+ expect(feedState.creatorCalls).toEqual([]);
+ });
+
+ it('502s with a recoverable message when the live feed is unreachable', async () => {
+ feedState.throws = true;
+ const res = await scan({ agent_id: AGENT_ID });
+ expect(res.statusCode).toBe(502);
+ expect(res.json.error).toBe('feed_unavailable');
+ expect(res.json.error_description).toMatch(/try again/i);
+ });
+});
+
+describe('POST /api/trading/scan results', () => {
+ it('is honest that live scanning is mainnet-only instead of returning an empty list', async () => {
+ const res = await scan({ agent_id: AGENT_ID, config: { network: 'devnet' } });
+ expect(res.statusCode).toBe(200);
+ expect(res.json.data.network).toBe('devnet');
+ expect(res.json.data.candidates).toEqual([]);
+ expect(res.json.data.note).toMatch(/mainnet only/i);
+ });
+
+ it('prices each match with a real quote and firewall verdict', async () => {
+ feedState.launches = [freshLaunch(MINT_A)];
+ const res = await scan({ agent_id: AGENT_ID, config: {} });
+ expect(res.statusCode).toBe(200);
+ const { data } = res.json;
+ expect(data.matched).toBe(1);
+ const [cand] = data.candidates;
+ expect(cand.mint).toBe(MINT_A);
+ expect(cand.quote).toMatchObject({ venue: 'bonding_curve', out_ui: 1234.5, price_impact_pct: 0.42 });
+ expect(cand.firewall).toMatchObject({ verdict: 'allow', score: 100, simulated: true });
+ expect(cand.has_socials).toBe(true);
+ expect(cand.amount_sol).toBe(data.amount_sol);
+ expect(firewallState.seenPayers).toEqual([AGENT_ADDR]);
+ });
+
+ it('marks an unquotable coin as such rather than dropping or faking it', async () => {
+ quoteState.throwsFor = new Set([MINT_A]);
+ feedState.launches = [freshLaunch(MINT_A)];
+ const res = await scan({ agent_id: AGENT_ID, config: {} });
+ const [cand] = res.json.data.candidates;
+ expect(cand.quote).toBeNull();
+ expect(cand.firewall.verdict).toBe('warn');
+ expect(cand.firewall.reasons[0]).toMatch(/could not quote/i);
+ });
+
+ it('reports the launches it actually examined, not the size of the feed page', async () => {
+ // Ten matchable launches, but the loop stops at MAX_PRICED (6) because each
+ // match costs a quote plus a firewall simulation. Claiming ten were scanned
+ // would overstate the work behind the answer.
+ feedState.launches = Array.from({ length: 10 }, (_, i) => freshLaunch(`${MINT_A}${i}`));
+ const res = await scan({ agent_id: AGENT_ID, config: {} });
+ expect(res.json.data.matched).toBe(6);
+ expect(res.json.data.scanned).toBe(6);
+ expect(res.json.data.feed_size).toBe(10);
+ });
+
+ it('examines the whole feed page when fewer than MAX_PRICED launches match', async () => {
+ feedState.launches = [
+ freshLaunch(MINT_A),
+ freshLaunch(MINT_B, { created_at: Date.now() - 7 * 24 * 3600 * 1000 }),
+ ];
+ const res = await scan({ agent_id: AGENT_ID, config: {} });
+ expect(res.json.data.scanned).toBe(2);
+ expect(res.json.data.feed_size).toBe(2);
+ expect(res.json.data.matched).toBe(1);
+ });
+
+ it('does not 500 when the agent wallet address on the row is unparsable', async () => {
+ // meta.solana_address is owner-writable through PATCH /api/agents/:id.
+ sqlState.agent = { id: AGENT_ID, user_id: OWNER_ID, meta: { solana_address: 'not a pubkey' } };
+ feedState.launches = [freshLaunch(MINT_A)];
+ const res = await scan({ agent_id: AGENT_ID, config: {} });
+ expect(res.statusCode).toBe(200);
+ expect(res.json.data.matched).toBe(1);
+ // The firewall owns pubkey resolution and downgrades a bad one to a skip.
+ expect(firewallState.seenPayers).toEqual(['not a pubkey']);
+ });
+});
+
+describe('POST /api/trading/scan creator-stat lookups', () => {
+ const creatorRule = { entry: { min_creator_graduated: 1 } };
+
+ it('buys a creator lookup only for launches the rest of the rule already likes', async () => {
+ feedState.launches = [
+ freshLaunch(MINT_A),
+ // Rejected on age long before the creator gate can matter.
+ freshLaunch(MINT_B, { created_at: Date.now() - 7 * 24 * 3600 * 1000 }),
+ ];
+ const res = await scan({ agent_id: AGENT_ID, config: creatorRule });
+ expect(res.statusCode).toBe(200);
+ expect(feedState.creatorCalls).toEqual([MINT_A]);
+ expect(res.json.data.matched).toBe(1);
+ });
+
+ it('never looks a creator up when the rule does not gate on creator stats', async () => {
+ feedState.launches = [freshLaunch(MINT_A)];
+ await scan({ agent_id: AGENT_ID, config: {} });
+ expect(feedState.creatorCalls).toEqual([]);
+ });
+
+ it('re-checks the gate after enrichment and drops a creator that still fails', async () => {
+ feedState.launches = [freshLaunch(MINT_A)];
+ const res = await scan({ agent_id: AGENT_ID, config: { entry: { min_creator_graduated: 5 } } });
+ expect(feedState.creatorCalls).toEqual([MINT_A]);
+ expect(res.json.data.matched).toBe(0);
+ });
+});
diff --git a/tests/vault-accounting.test.js b/tests/vault-accounting.test.js
index 7a532537a..6d043ba5a 100644
--- a/tests/vault-accounting.test.js
+++ b/tests/vault-accounting.test.js
@@ -4,6 +4,7 @@ import {
sharesRedeemableNow, drawdownBps, isDrawdownBreached, depositExceedsCap,
tradeExceedsPerTrade, tradeExceedsDailyBudget, nextPeak, roiBps,
usdcToAtomics, atomicsToUsdc, SHARE_PRICE_SCALE,
+ parseAmountInput, clampTermBps, TERM_BOUNDS,
} from '../api/_lib/vault-accounting.js';
const USDC = 1_000_000n; // 1 USDC in atomics
@@ -286,3 +287,37 @@ describe('end-to-end lifecycle conservation', () => {
expect(vaultBalance).toBeGreaterThanOrEqual(0n);
});
});
+
+describe('parseAmountInput (the HTTP boundary guard)', () => {
+ it('accepts the shapes a real caller sends', () => {
+ expect(parseAmountInput('2500000')).toBe(2_500_000n);
+ expect(parseAmountInput(2_500_000)).toBe(2_500_000n);
+ expect(parseAmountInput(2_500_000n)).toBe(2_500_000n);
+ expect(parseAmountInput(' 2500000 ')).toBe(2_500_000n);
+ expect(parseAmountInput('0')).toBe(0n);
+ // A decimal tail truncates down, never up into funds that aren't there.
+ expect(parseAmountInput('2500000.99')).toBe(2_500_000n);
+ });
+
+ it('returns null for anything BigInt() would throw on, so the handler can answer 400', () => {
+ for (const bad of ['abc', '', ' ', '1e6', '0x10', '1,000', '-5', -5, NaN, Infinity, null, undefined, {}, [], true]) {
+ expect(parseAmountInput(bad)).toBeNull();
+ }
+ });
+});
+
+describe('clampTermBps', () => {
+ it('clamps into the term bound and rounds to a whole bps', () => {
+ expect(clampTermBps(9999, TERM_BOUNDS.performanceFeeBps)).toBe(5000);
+ expect(clampTermBps(-1, TERM_BOUNDS.performanceFeeBps)).toBe(0);
+ expect(clampTermBps(1234.6, TERM_BOUNDS.performanceFeeBps)).toBe(1235);
+ expect(clampTermBps(0, TERM_BOUNDS.maxDrawdownBps)).toBe(100);
+ expect(clampTermBps(99_999, TERM_BOUNDS.maxDrawdownBps)).toBe(9000);
+ });
+
+ it('returns null (never NaN) for a value that is not a number', () => {
+ expect(clampTermBps('abc', TERM_BOUNDS.performanceFeeBps)).toBeNull();
+ expect(clampTermBps(NaN, TERM_BOUNDS.maxDrawdownBps)).toBeNull();
+ expect(clampTermBps(Infinity, TERM_BOUNDS.maxDrawdownBps)).toBeNull();
+ });
+});
diff --git a/tests/vaults-api-guards.test.js b/tests/vaults-api-guards.test.js
new file mode 100644
index 000000000..19c8ba20d
--- /dev/null
+++ b/tests/vaults-api-guards.test.js
@@ -0,0 +1,257 @@
+// The /api/vaults write routes take caller-supplied ids and amounts and hand them
+// straight to a uuid column or to BigInt(). Before this file, a single malformed
+// field ("vaultId":"not-a-uuid", "shares":"abc") raised a NeonDbError / SyntaxError
+// that the wrapper turned into a 500 with a support ref, on four separate routes;
+// a non-uuid agentId leaked the raw Postgres code 22P02 back to the caller as the
+// error code. These tests pin the boundary: malformed input answers 4xx JSON, the
+// good path still reaches the settlement layer untouched, and the owner's terms
+// PATCH can never write a NaN into an integer column.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const VAULT = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
+const AGENT = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';
+const USER = 'cccccccc-cccc-4ccc-8ccc-cccccccccccc';
+const MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+
+const authWriteMock = vi.fn();
+const resolveUserIdMock = vi.fn();
+const loadOwnedAgentMock = vi.fn();
+vi.mock('../api/_lib/vault-auth.js', () => ({
+ authWrite: (...a) => authWriteMock(...a),
+ resolveUserId: (...a) => resolveUserIdMock(...a),
+ loadOwnedAgent: (...a) => loadOwnedAgentMock(...a),
+ loadAgent: vi.fn(async () => ({ id: AGENT, name: 'Anchor', description: null, image: null })),
+ assertReputationVerified: vi.fn(async () => true),
+ traderBadge: vi.fn(async () => null),
+}));
+
+const getVaultMock = vi.fn();
+const updateVaultTermsMock = vi.fn();
+vi.mock('../api/_lib/vault-store.js', () => ({
+ getVault: (...a) => getVaultMock(...a),
+ updateVaultTerms: (...a) => updateVaultTermsMock(...a),
+ recordVaultEvent: vi.fn(async () => ({})),
+ getOpenPositions: vi.fn(async () => []),
+ getBacker: vi.fn(async () => null),
+ listBackers: vi.fn(async () => []),
+ setVaultStatus: vi.fn(async () => ({})),
+ createVault: vi.fn(async () => ({ id: VAULT })),
+ listVaults: vi.fn(async () => []),
+ listBackedVaults: vi.fn(async () => []),
+}));
+
+const depositToVaultMock = vi.fn(async () => ({ status: 'settled', shares: '1' }));
+const redeemFromVaultMock = vi.fn(async () => ({ status: 'settled', net_atomics: '1' }));
+const claimVaultFeesMock = vi.fn(async () => ({ status: 'settled', atomics: '1' }));
+vi.mock('../api/_lib/vault-transfer.js', () => ({
+ depositToVault: (...a) => depositToVaultMock(...a),
+ redeemFromVault: (...a) => redeemFromVaultMock(...a),
+ claimVaultFees: (...a) => claimVaultFeesMock(...a),
+}));
+
+const vaultTradeMock = vi.fn(async () => ({ status: 'filled', signature: 'sig' }));
+vi.mock('../api/_lib/vault-trade.js', () => ({ vaultTrade: (...a) => vaultTradeMock(...a) }));
+
+vi.mock('../api/_lib/vault-wallet.js', () => ({
+ generateVaultWallet: vi.fn(async () => ({ address: 'Vau1t', encrypted_secret: 'enc' })),
+ computeVaultNav: vi.fn(async () => ({ navAtomics: 0n, freeAtomics: 0n, usdcAtomics: 0n, priced: true, positions: [] })),
+}));
+
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ limits: { tradePerUser: vi.fn(async () => ({ success: true, reset: 1_000 })) },
+ clientIp: () => '203.0.113.9',
+}));
+
+const { default: depositHandler } = await import('../api/vaults/deposit.js');
+const { default: redeemHandler } = await import('../api/vaults/redeem.js');
+const { default: tradeHandler } = await import('../api/vaults/trade.js');
+const { default: claimFeesHandler } = await import('../api/vaults/claim-fees.js');
+const { default: vaultsHandler } = await import('../api/vaults/index.js');
+const { default: vaultDetailHandler } = await import('../api/vaults/[id].js');
+
+function mkReq({ method = 'POST', url = '/api/vaults', body = null, headers = {} } = {}) {
+ 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;
+ if (body == null) queueMicrotask(() => cb());
+ }
+ },
+ destroy() {},
+ };
+}
+function mkRes() {
+ return {
+ statusCode: 200, headers: {}, body: undefined, writableEnded: false, headersSent: false,
+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
+ end(b) { this.body = b; this.writableEnded = true; this.headersSent = true; },
+ };
+}
+const parse = (res) => (res.body ? JSON.parse(res.body) : undefined);
+
+async function call(handler, req) {
+ const res = mkRes();
+ await handler(req, res);
+ return { res, out: parse(res) };
+}
+
+const OPEN_VAULT = {
+ id: VAULT, agent_id: AGENT, owner_user_id: USER, network: 'mainnet', status: 'open',
+ performance_fee_bps: 1000, max_drawdown_bps: 2500, per_backer_cap_atomics: null,
+ max_per_trade_atomics: '5000000', daily_budget_atomics: '50000000',
+ total_shares: '0', peak_share_price_e6: '1000000', accrued_fee_atomics: '0',
+ halt_reason: null, paused_at: null, created_at: new Date('2026-08-01T00:00:00Z'),
+ vault_address: 'Vau1t',
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ authWriteMock.mockResolvedValue({ userId: USER, session: false });
+ resolveUserIdMock.mockResolvedValue({ userId: USER, session: false });
+ loadOwnedAgentMock.mockResolvedValue({
+ id: AGENT, user_id: USER, name: 'Anchor',
+ meta: { solana_address: 'Ag3nt', encrypted_solana_secret: 'enc' },
+ });
+ getVaultMock.mockResolvedValue(OPEN_VAULT);
+ // The real store returns a row whose numeric(40,0) columns are plain strings,
+ // so the handler's JSON response never sees a BigInt.
+ updateVaultTermsMock.mockImplementation(async (_id, patch) => ({
+ ...OPEN_VAULT,
+ performance_fee_bps: patch.performanceFeeBps ?? OPEN_VAULT.performance_fee_bps,
+ max_drawdown_bps: patch.maxDrawdownBps ?? OPEN_VAULT.max_drawdown_bps,
+ max_per_trade_atomics: String(patch.maxPerTradeAtomics ?? OPEN_VAULT.max_per_trade_atomics),
+ daily_budget_atomics: String(patch.dailyBudgetAtomics ?? OPEN_VAULT.daily_budget_atomics),
+ }));
+});
+
+describe('malformed ids never reach a uuid column', () => {
+ it('POST /api/vaults/deposit rejects a non-uuid vaultId and backerAgentId with 400', async () => {
+ const a = await call(depositHandler, mkReq({ url: '/api/vaults/deposit', body: { vaultId: 'not-a-uuid', backerAgentId: AGENT, usdc: 1 } }));
+ expect(a.res.statusCode).toBe(400);
+ expect(a.out.error).toBe('validation_error');
+
+ const b = await call(depositHandler, mkReq({ url: '/api/vaults/deposit', body: { vaultId: VAULT, backerAgentId: 'nope', usdc: 1 } }));
+ expect(b.res.statusCode).toBe(400);
+ expect(b.out.error).toBe('validation_error');
+
+ expect(getVaultMock).not.toHaveBeenCalled();
+ expect(depositToVaultMock).not.toHaveBeenCalled();
+ });
+
+ it('POST /api/vaults/redeem rejects a non-uuid vaultId with 400', async () => {
+ const { res, out } = await call(redeemHandler, mkReq({ url: '/api/vaults/redeem', body: { vaultId: 'not-a-uuid' } }));
+ expect(res.statusCode).toBe(400);
+ expect(out.error).toBe('validation_error');
+ expect(redeemFromVaultMock).not.toHaveBeenCalled();
+ });
+
+ it('POST /api/vaults/trade rejects a non-uuid vaultId and a non-address mint with 400', async () => {
+ const a = await call(tradeHandler, mkReq({ url: '/api/vaults/trade', body: { vaultId: 'not-a-uuid', side: 'buy', mint: MINT, usdc: 1 } }));
+ expect(a.res.statusCode).toBe(400);
+
+ const b = await call(tradeHandler, mkReq({ url: '/api/vaults/trade', body: { vaultId: VAULT, side: 'buy', mint: 'x', usdc: 1 } }));
+ expect(b.res.statusCode).toBe(400);
+ expect(b.out.error_description).toMatch(/mint/);
+ expect(vaultTradeMock).not.toHaveBeenCalled();
+ });
+
+ it('POST /api/vaults/claim-fees rejects a non-uuid vaultId and toAgentId with 400', async () => {
+ const a = await call(claimFeesHandler, mkReq({ url: '/api/vaults/claim-fees', body: { vaultId: 'not-a-uuid', toAgentId: AGENT } }));
+ expect(a.res.statusCode).toBe(400);
+ const b = await call(claimFeesHandler, mkReq({ url: '/api/vaults/claim-fees', body: { vaultId: VAULT, toAgentId: 'nope' } }));
+ expect(b.res.statusCode).toBe(400);
+ expect(claimVaultFeesMock).not.toHaveBeenCalled();
+ });
+
+ it('POST /api/vaults rejects a non-uuid agentId instead of leaking the Postgres 22P02 code', async () => {
+ const { res, out } = await call(vaultsHandler, mkReq({ body: { agentId: 'nope', maxPerTradeUsdc: 1, dailyBudgetUsdc: 2 } }));
+ expect(res.statusCode).toBe(400);
+ expect(out.error).toBe('validation_error');
+ expect(loadOwnedAgentMock).not.toHaveBeenCalled();
+ });
+});
+
+describe('caller-supplied amounts are parsed at the boundary', () => {
+ it('rejects a non-numeric shares value instead of throwing inside BigInt()', async () => {
+ const { res, out } = await call(redeemHandler, mkReq({ url: '/api/vaults/redeem', body: { vaultId: VAULT, shares: 'abc' } }));
+ expect(res.statusCode).toBe(400);
+ expect(out.error_description).toMatch(/shares/);
+ expect(redeemFromVaultMock).not.toHaveBeenCalled();
+ });
+
+ it('rejects a non-numeric sell amount on a vault the caller really owns', async () => {
+ const { res, out } = await call(tradeHandler, mkReq({ url: '/api/vaults/trade', body: { vaultId: VAULT, side: 'sell', mint: MINT, amount: 'abc' } }));
+ expect(res.statusCode).toBe(400);
+ expect(out.error_description).toMatch(/amount/);
+ expect(vaultTradeMock).not.toHaveBeenCalled();
+ });
+
+ it('passes a real redemption through untouched: "max" stays max, a number stays exact', async () => {
+ await call(redeemHandler, mkReq({ url: '/api/vaults/redeem', body: { vaultId: VAULT } }));
+ expect(redeemFromVaultMock).toHaveBeenLastCalledWith(expect.objectContaining({ vaultId: VAULT, userId: USER, shares: 'max' }));
+
+ await call(redeemHandler, mkReq({ url: '/api/vaults/redeem', body: { vaultId: VAULT, shares: '2500000' } }));
+ expect(redeemFromVaultMock).toHaveBeenLastCalledWith(expect.objectContaining({ shares: '2500000' }));
+ });
+
+ it('passes a real sell through as an exact BigInt of raw token units', async () => {
+ const { res } = await call(tradeHandler, mkReq({ url: '/api/vaults/trade', body: { vaultId: VAULT, side: 'sell', mint: MINT, amount: '123456789' } }));
+ expect(res.statusCode).toBe(200);
+ expect(vaultTradeMock).toHaveBeenLastCalledWith(expect.objectContaining({ side: 'sell', mint: MINT, amountRaw: 123456789n }));
+ });
+});
+
+describe('PATCH /api/vaults/:id terms', () => {
+ const patchReq = (body) => mkReq({ method: 'PATCH', url: `/api/vaults/${VAULT}`, body });
+
+ it('refuses a non-numeric bps term instead of writing NaN into an integer column', async () => {
+ const a = await call(vaultDetailHandler, patchReq({ action: 'terms', performanceFeeBps: 'abc' }));
+ expect(a.res.statusCode).toBe(400);
+ const b = await call(vaultDetailHandler, patchReq({ action: 'terms', maxDrawdownBps: 'abc' }));
+ expect(b.res.statusCode).toBe(400);
+ expect(updateVaultTermsMock).not.toHaveBeenCalled();
+ });
+
+ it('refuses a non-positive spend term rather than silently ignoring it', async () => {
+ const { res, out } = await call(vaultDetailHandler, patchReq({ action: 'terms', maxPerTradeUsdc: -5 }));
+ expect(res.statusCode).toBe(400);
+ expect(out.error_description).toMatch(/maxPerTradeUsdc/);
+ expect(updateVaultTermsMock).not.toHaveBeenCalled();
+ });
+
+ it('refuses a per-trade ceiling above the daily budget, counting the terms already stored', async () => {
+ // Stored budget is 50 USDC; a 60 USDC per-trade ceiling would let one trade
+ // blow the whole day's limit.
+ const { res } = await call(vaultDetailHandler, patchReq({ action: 'terms', maxPerTradeUsdc: 60 }));
+ expect(res.statusCode).toBe(400);
+ expect(updateVaultTermsMock).not.toHaveBeenCalled();
+ });
+
+ it('clamps a legal-but-extreme fee into bounds and applies it', async () => {
+ const { res } = await call(vaultDetailHandler, patchReq({ action: 'terms', performanceFeeBps: 9999 }));
+ expect(res.statusCode).toBe(200);
+ expect(updateVaultTermsMock).toHaveBeenCalledWith(VAULT, expect.objectContaining({ performanceFeeBps: 5000 }));
+ });
+
+ it('applies a matched per-trade + daily budget raise', async () => {
+ const { res } = await call(vaultDetailHandler, patchReq({ action: 'terms', maxPerTradeUsdc: 60, dailyBudgetUsdc: 600 }));
+ expect(res.statusCode).toBe(200);
+ expect(updateVaultTermsMock).toHaveBeenCalledWith(VAULT, expect.objectContaining({
+ maxPerTradeAtomics: 60_000_000n, dailyBudgetAtomics: 600_000_000n,
+ }));
+ });
+
+ it('answers 404 for a malformed vault id in the path, never a database error', async () => {
+ const { res, out } = await call(vaultDetailHandler, mkReq({ method: 'PATCH', url: '/api/vaults/not-a-uuid', body: { action: 'pause' } }));
+ expect(res.statusCode).toBe(404);
+ expect(out.error).toBe('not_found');
+ expect(getVaultMock).not.toHaveBeenCalled();
+ });
+});