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.

39.0 KB
Raw Blame
// Unit + integration tests for the monetization service layer.
//
// The financial core of monetization lives in three places, none of which had
// direct coverage before this suite:
//
//   • api/_lib/fee.js         : platform fee split (calculateFee, getFeeBps)
//   • api/_lib/monetization.js: recordRevenueEvent (revenue attribution +
//                                fee/net split) and getAvailableBalance
//                                (withdrawable-balance aggregation)
//   • api/monetization/*.js   : the unified REST surface: prices.js (set/list
//                                skill prices) and revenue.js (creator sales
//                                aggregation)
//
// Money math is unforgiving, so every branch: validation, rounding, the
// owner/non-owner gate, and the earned − pending − withdrawn arithmetic: is
// exercised here. The DB client is mocked with a queue-driven `sql` stub
// (shared by the directly-called service functions and the HTTP handlers) so
// the logic is tested in isolation from Neon, exactly as Prompt 18 specifies.

import { describe, it, expect, beforeEach, vi } from 'vitest';
import { createTestAgent, createTestUser, invoke } from './_helpers/monetization.js';

// ── Mock state ────────────────────────────────────────────────────────────────

const authState = { session: null, bearer: null };
const sqlState = { queue: [], calls: [] };
const rlState = { success: true };

// ── Mocks ─────────────────────────────────────────────────────────────────────

vi.mock('../api/_lib/auth.js', () => ({
	getSessionUser: vi.fn(async () => authState.session),
	authenticateBearer: vi.fn(async () => authState.bearer),
	extractBearer: vi.fn(() => null),
}));

vi.mock('../api/_lib/db.js', () => {
	// Mirrors the real `sql` proxy: a tagged-template call receives the strings
	// array as the first arg; the function form receives a query string. Each
	// call records (query, values) for assertions and shifts the next queued
	// result, defaulting to [] so `const [row] = await sql\`…\`` never throws.
	const sql = vi.fn(async (strings, ...values) => {
		if (typeof strings === 'string') {
			sqlState.calls.push({ query: strings, values: values[0] ?? [] });
		} else {
			sqlState.calls.push({ query: strings.join('?'), values });
		}
		return sqlState.queue.length ? sqlState.queue.shift() : [];
	});
	sql.transaction = (queries) => Promise.all(queries);
	return { sql, isDbUnavailableError: () => false, isDbCapacityError: () => false };
});

vi.mock('../api/_lib/rate-limit.js', () => ({
	limits: {
		authIp: vi.fn(async () => ({ success: rlState.success })),
		authedReadIp: vi.fn(async () => ({ success: rlState.success })),
		publicIp: vi.fn(async () => ({ success: rlState.success })),
		pricingPerIp: vi.fn(async () => ({ success: rlState.success })),
		withdrawalPerUser: vi.fn(async () => ({ success: rlState.success })),
	},
	clientIp: vi.fn(() => '127.0.0.1'),
}));

vi.mock('../api/_lib/csrf.js', () => ({
	requireCsrf: vi.fn(async () => true),
	generateToken: vi.fn(async () => 'test-csrf-token'),
}));

// ── Imports under test (after mocks) ───────────────────────────────────────────

const { recordRevenueEvent, getAvailableBalance } = await import('../api/_lib/monetization.js');
const { calculateFee, getFeeBps } = await import('../api/_lib/fee.js');
const { default: pricesHandler } = await import('../api/monetization/prices.js');
const { default: walletHandler } = await import('../api/monetization/wallet.js');
const { default: withdrawalsHandler } = await import('../api/monetization/withdrawals.js');

const USDC_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';

// ── Reset between tests ─────────────────────────────────────────────────────────

beforeEach(() => {
	authState.session = null;
	authState.bearer = null;
	sqlState.queue = [];
	sqlState.calls = [];
	rlState.success = true;
});

// ── 1. Fee calculation (api/_lib/fee.js) ────────────────────────────────────────

describe('resolveAccessHours', () => {
	const pass = { time_pass_amount: '1000', time_pass_hours: 24, amount: '50000' };

	it('ignores the caller duration when the skill has a fixed time-pass price', async () => {
		const { resolveAccessHours } = await import('../api/_lib/services/MonetizationService.js');
		expect(resolveAccessHours(pass, 720, false)).toBe(24);
		expect(resolveAccessHours(pass, null, false)).toBe(24);
	});

	it('honors the caller duration only when no fixed pass price exists', async () => {
		const { resolveAccessHours } = await import('../api/_lib/services/MonetizationService.js');
		expect(resolveAccessHours({ amount: '50000' }, 48, false)).toBe(48);
		expect(resolveAccessHours(pass, 720, true)).toBeNull();
	});
});

describe('calculateFee', () => {
	it('exposes a sane default fee rate (250 bps = 2.5%)', () => {
		const bps = getFeeBps();
		expect(Number.isInteger(bps)).toBe(true);
		expect(bps).toBeGreaterThan(0);
		expect(bps).toBeLessThanOrEqual(10_000);
	});

	it('splits a round amount into platform fee and creator net', () => {
		const bps = getFeeBps();
		const { fee, net } = calculateFee(1_000_000);
		expect(fee).toBe(Math.floor((1_000_000 * bps) / 10_000));
		expect(net).toBe(1_000_000 - fee);
		// With the default 250 bps this is the 25_000 / 975_000 split the rest of
		// the monetization stack asserts against.
		if (bps === 250) {
			expect(fee).toBe(25_000);
			expect(net).toBe(975_000);
		}
	});

	it('floors the fee for amounts that do not divide evenly', () => {
		// 333 * 250 / 10_000 = 8.325 → floored to 8.
		const { fee, net } = calculateFee(333);
		expect(fee).toBe(Math.floor((333 * getFeeBps()) / 10_000));
		expect(Number.isInteger(fee)).toBe(true);
		expect(fee + net).toBe(333);
	});

	it('preserves the invariant fee + net === gross across a range', () => {
		for (const gross of [1, 7, 999, 1_000_000, 123_456_789]) {
			const { fee, net } = calculateFee(gross);
			expect(fee + net).toBe(gross);
			expect(fee).toBeGreaterThanOrEqual(0);
			expect(fee).toBeLessThanOrEqual(gross);
		}
	});

	it('returns a zero split for a zero amount', () => {
		expect(calculateFee(0)).toEqual({ fee: 0, net: 0 });
	});
});

// ── 2. recordRevenueEvent (api/_lib/monetization.js) ────────────────────────────

describe('recordRevenueEvent', () => {
	const baseEvent = {
		agentId: 'agent-uuid-1',
		skillName: 'answer-question',
		callerAddress: 'Payer1111111111111111111111111111111111111',
		amountUsdc: 1_000_000,
		network: 'solana',
		txHash: 'sig-abc',
		intentId: 'intent-xyz',
	};

	function findInsert() {
		return sqlState.calls.find((c) => c.query.includes('agent_revenue_events'));
	}

	it('records the gross amount with the correct fee/net split', async () => {
		sqlState.queue.push([{ id: 'rev-1', agent_id: baseEvent.agentId, skill: baseEvent.skillName }]);

		const row = await recordRevenueEvent(baseEvent);

		const insert = findInsert();
		expect(insert).toBeDefined();
		// VALUES order: agent_id, intent_id, skill, gross, fee, net, mint, chain, payer
		const [agentId, , skill, gross, fee, net, , chain, payer] = insert.values;
		expect(agentId).toBe(baseEvent.agentId);
		expect(skill).toBe(baseEvent.skillName);
		expect(gross).toBe(1_000_000);
		expect(fee).toBe(calculateFee(1_000_000).fee);
		expect(net).toBe(calculateFee(1_000_000).net);
		expect(fee + net).toBe(gross);
		expect(chain).toBe('solana');
		expect(payer).toBe(baseEvent.callerAddress);
		expect(row).toEqual({ id: 'rev-1', agent_id: baseEvent.agentId, skill: baseEvent.skillName });
	});

	it('defaults the currency mint to USDC when none is supplied', async () => {
		sqlState.queue.push([{ id: 'rev-2' }]);

		await recordRevenueEvent({ ...baseEvent, currencyMint: undefined });

		const insert = findInsert();
		expect(insert.values).toContain(USDC_MINT);
	});

	it('uses the explicit intentId as the intent reference', async () => {
		sqlState.queue.push([{ id: 'rev-3' }]);
		await recordRevenueEvent(baseEvent);
		expect(findInsert().values[1]).toBe('intent-xyz');
	});

	it('falls back to the txHash when no intentId is given', async () => {
		sqlState.queue.push([{ id: 'rev-4' }]);
		await recordRevenueEvent({ ...baseEvent, intentId: undefined });
		expect(findInsert().values[1]).toBe('sig-abc');
	});

	it('falls back to a unique direct_ key when neither intentId nor txHash is given', async () => {
		sqlState.queue.push([{ id: 'rev-5' }]);
		await recordRevenueEvent({ ...baseEvent, intentId: undefined, txHash: undefined });
		// intent_id is UNIQUE, so distinct direct credits must NOT collide on a
		// shared literal: each gets its own synthetic key.
		expect(findInsert().values[1]).toMatch(/^direct_[0-9a-f-]{36}$/);
	});

	it('rejects a non-positive amount before touching the database', async () => {
		await expect(recordRevenueEvent({ ...baseEvent, amountUsdc: 0 }))
			.rejects.toMatchObject({ status: 400 });
		await expect(recordRevenueEvent({ ...baseEvent, amountUsdc: -5 }))
			.rejects.toMatchObject({ status: 400 });
		expect(sqlState.calls).toHaveLength(0);
	});

	it('rejects a non-numeric amount', async () => {
		await expect(recordRevenueEvent({ ...baseEvent, amountUsdc: 'abc' }))
			.rejects.toMatchObject({ status: 400 });
		expect(sqlState.calls).toHaveLength(0);
	});

	it('rejects a missing agentId', async () => {
		await expect(recordRevenueEvent({ ...baseEvent, agentId: undefined }))
			.rejects.toThrow(/agentId/);
		expect(sqlState.calls).toHaveLength(0);
	});

	it('rejects a missing skillName', async () => {
		await expect(recordRevenueEvent({ ...baseEvent, skillName: undefined }))
			.rejects.toThrow(/skillName/);
		expect(sqlState.calls).toHaveLength(0);
	});
});

// ── 3. getAvailableBalance (api/_lib/monetization.js) ───────────────────────────

describe('getAvailableBalance', () => {
	function queueBalance({ earned, pending, withdrawn }) {
		sqlState.queue.push([{ earned }]); // revenue events sum
		sqlState.queue.push([{ pending, withdrawn }]); // withdrawals split
	}

	it('computes available = earned − pending − withdrawn', async () => {
		queueBalance({ earned: 5_000_000n, pending: 1_000_000n, withdrawn: 2_000_000n });

		const balance = await getAvailableBalance('user-1');

		expect(balance).toEqual({
			earned: 5_000_000,
			pending: 1_000_000,
			withdrawn: 2_000_000,
			available: 2_000_000,
		});
	});

	it('coerces bigint column sums to plain numbers', async () => {
		queueBalance({ earned: 10_000_000n, pending: 0n, withdrawn: 0n });

		const balance = await getAvailableBalance('user-1');

		expect(typeof balance.earned).toBe('number');
		expect(typeof balance.available).toBe('number');
		expect(balance.available).toBe(10_000_000);
	});

	it('clamps available at zero when withdrawals exceed earnings', async () => {
		queueBalance({ earned: 1_000_000n, pending: 0n, withdrawn: 3_000_000n });

		const balance = await getAvailableBalance('user-1');

		expect(balance.available).toBe(0); // never negative
		expect(balance.earned).toBe(1_000_000);
		expect(balance.withdrawn).toBe(3_000_000);
	});

	it('treats pending/processing withdrawals as reserved against the balance', async () => {
		queueBalance({ earned: 4_000_000n, pending: 4_000_000n, withdrawn: 0n });

		const balance = await getAvailableBalance('user-1');

		expect(balance.available).toBe(0);
		expect(balance.pending).toBe(4_000_000);
	});

	it('queries without a currency filter when no mint is given', async () => {
		queueBalance({ earned: 1n, pending: 0n, withdrawn: 0n });

		await getAvailableBalance('user-1');

		const earnedCall = sqlState.calls.find((c) => c.query.includes('agent_revenue_events'));
		// All-currencies branch binds only the userId.
		expect(earnedCall.values).toEqual(['user-1']);
	});

	it('binds the currency mint when a filter is supplied', async () => {
		queueBalance({ earned: 1n, pending: 0n, withdrawn: 0n });

		await getAvailableBalance('user-1', USDC_MINT);

		const earnedCall = sqlState.calls.find((c) => c.query.includes('agent_revenue_events'));
		const wdrawCall = sqlState.calls.find((c) => c.query.includes('agent_withdrawals'));
		expect(earnedCall.values).toEqual(['user-1', USDC_MINT]);
		expect(wdrawCall.values).toEqual(['user-1', USDC_MINT]);
	});
});

// ── 4. setSkillPrices: api/monetization/prices.js ──────────────────────────────

describe('prices endpoint (setSkillPrices)', () => {
	it('lets an owner set a new price and returns 201', async () => {
		const { agent, session } = createTestAgent();
		authState.session = session;

		sqlState.queue.push([{ id: agent.id, user_id: agent.user_id }]); // ownership
		sqlState.queue.push([]); // no existing price
		sqlState.queue.push([]); // upsert
		sqlState.queue.push([
			{
				id: 'price-1',
				skill: 'answer-question',
				currency_mint: USDC_MINT,
				chain: 'solana',
				amount: 50_000,
				is_active: true,
				created_at: '2026-06-18T00:00:00Z',
				updated_at: '2026-06-18T00:00:00Z',
			},
		]);

		const { status, body } = await invoke(pricesHandler, {
			method: 'PUT',
			url: '/api/monetization/prices',
			body: { agent_id: agent.id, skill_name: 'answer-question', price_usdc: 0.05 },
		});

		expect(status).toBe(201);
		expect(body.price.skill_name).toBe('answer-question');
		expect(body.price.amount_atomic).toBe(50_000);
		expect(body.price.price_usdc).toBe(0.05);
	});

	it('converts price_usdc to atomic units in the upsert (0.05 → 50000)', async () => {
		const { agent, session } = createTestAgent();
		authState.session = session;

		sqlState.queue.push([{ id: agent.id, user_id: agent.user_id }]);
		sqlState.queue.push([]);
		sqlState.queue.push([]);
		sqlState.queue.push([{ id: 'p', skill: 'echo', currency_mint: USDC_MINT, chain: 'solana', amount: 50_000, is_active: true }]);

		await invoke(pricesHandler, {
			method: 'PUT',
			url: '/api/monetization/prices',
			body: { agent_id: agent.id, skill_name: 'echo', price_usdc: 0.05 },
		});

		const upsert = sqlState.calls.find((c) => c.query.includes('ON CONFLICT'));
		expect(upsert).toBeDefined();
		expect(upsert.values).toContain(50_000); // amountAtomic = round(0.05 * 1e6)
	});

	it('returns 200 when updating an existing price', async () => {
		const { agent, session } = createTestAgent();
		authState.session = session;

		sqlState.queue.push([{ id: agent.id, user_id: agent.user_id }]); // ownership
		sqlState.queue.push([{ id: 'price-1' }]); // existing price → update path
		sqlState.queue.push([]); // upsert
		sqlState.queue.push([{ id: 'price-1', skill: 'echo', currency_mint: USDC_MINT, chain: 'solana', amount: 100_000, is_active: true }]);

		const { status } = await invoke(pricesHandler, {
			method: 'PUT',
			url: '/api/monetization/prices',
			body: { agent_id: agent.id, skill_name: 'echo', price_usdc: 0.1 },
		});

		expect(status).toBe(200);
	});

	it('blocks a non-owner with 403', async () => {
		const { agent } = createTestAgent();
		const { session: otherSession } = createTestUser();
		authState.session = otherSession;

		sqlState.queue.push([{ id: agent.id, user_id: agent.user_id }]); // owned by someone else

		const { status, body } = await invoke(pricesHandler, {
			method: 'PUT',
			url: '/api/monetization/prices',
			body: { agent_id: agent.id, skill_name: 'echo', price_usdc: 0.01 },
		});

		expect(status).toBe(403);
		expect(body.error).toBe('forbidden');
	});

	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(pricesHandler, {
			method: 'PUT',
			url: '/api/monetization/prices',
			body: { agent_id: agent.id, skill_name: 'echo', price_usdc: 0.01 },
		});

		expect(status).toBe(404);
		expect(body.error).toBe('not_found');
	});

	it('returns 401 when unauthenticated', async () => {
		const { agent } = createTestAgent();

		const { status, body } = await invoke(pricesHandler, {
			method: 'PUT',
			url: '/api/monetization/prices',
			body: { agent_id: agent.id, skill_name: 'echo', price_usdc: 0.01 },
		});

		expect(status).toBe(401);
		expect(body.error).toBe('unauthorized');
	});

	it('rejects a price below the minimum atomic unit with 400', async () => {
		const { agent, session } = createTestAgent();
		authState.session = session;

		// 0.0000004 USDC rounds to 0 atomic units, under MIN_PRICE_ATOMIC (1).
		const { status, body } = await invoke(pricesHandler, {
			method: 'PUT',
			url: '/api/monetization/prices',
			body: { agent_id: agent.id, skill_name: 'echo', price_usdc: 0.0000004 },
		});

		expect(status).toBe(400);
		expect(body.error).toBe('validation_error');
	});

	it('rejects a price above the ceiling with 400 rather than overflowing the column', async () => {
		const { agent, session } = createTestAgent();
		authState.session = session;

		// 1e30 USDC becomes 1e36 atomic units, far past the bigint `amount` column.
		// Without the ceiling this reached Postgres and came back as a 500.
		const { status, body } = await invoke(pricesHandler, {
			method: 'PUT',
			url: '/api/monetization/prices',
			body: { agent_id: agent.id, skill_name: 'echo', price_usdc: 1e30 },
		});

		expect(status).toBe(400);
		expect(body.error).toBe('validation_error');
		// The ownership lookup must not even have run: validation fails first.
		expect(sqlState.calls).toHaveLength(0);
	});

	it('rejects a non-finite price with 400', async () => {
		const { agent, session } = createTestAgent();
		authState.session = session;

		// JSON.parse('1e400') is Infinity, so a caller can put a non-finite number
		// on the wire even though JSON.stringify can never emit one.
		const { status, body } = await invoke(pricesHandler, {
			method: 'PUT',
			url: '/api/monetization/prices',
			body: `{"agent_id":"${agent.id}","skill_name":"echo","price_usdc":1e400}`,
		});

		expect(status).toBe(400);
		expect(body.error).toBe('validation_error');
	});

	it('rejects an invalid skill_name with a validation error', async () => {
		const { agent, session } = createTestAgent();
		authState.session = session;

		const { status, body } = await invoke(pricesHandler, {
			method: 'PUT',
			url: '/api/monetization/prices',
			body: { agent_id: agent.id, skill_name: 'has spaces!', price_usdc: 0.01 },
		});

		expect(status).toBe(400);
		expect(body.error).toBe('validation_error');
	});

	it('soft-deletes a price for the owner', async () => {
		const { agent, session } = createTestAgent();
		authState.session = session;

		sqlState.queue.push([{ id: agent.id, user_id: agent.user_id }]); // ownership
		sqlState.queue.push([{ id: 'price-1' }]); // UPDATE … RETURNING id

		const { status, body } = await invoke(pricesHandler, {
			method: 'DELETE',
			url: '/api/monetization/prices',
			body: { agent_id: agent.id, skill_name: 'echo' },
		});

		expect(status).toBe(200);
		expect(body.deleted).toBe(true);
		expect(body.skill_name).toBe('echo');
	});

	// The dashboard's del() helper (src/dashboard-next/api.js) sends no body and
	// no content-type, addressing the row with query parameters instead. Reading
	// the body alone answered every "Remove price" click with 415 and removed
	// nothing, so the query-string transport has to stay supported.
	it('soft-deletes a price addressed by query string with no request body', async () => {
		const { agent, session } = createTestAgent();
		authState.session = session;

		sqlState.queue.push([{ id: agent.id, user_id: agent.user_id }]); // ownership
		sqlState.queue.push([{ id: 'price-1' }]); // UPDATE … RETURNING id

		const { status, body } = await invoke(pricesHandler, {
			method: 'DELETE',
			url: `/api/monetization/prices?agent_id=${agent.id}&skill_name=echo`,
		});

		expect(status).toBe(200);
		expect(body.deleted).toBe(true);
		expect(body.skill_name).toBe('echo');
	});

	it('rejects a DELETE that names no agent in either transport', async () => {
		const { session } = createTestAgent();
		authState.session = session;

		const { status, body } = await invoke(pricesHandler, {
			method: 'DELETE',
			url: '/api/monetization/prices?skill_name=echo',
		});

		expect(status).toBe(400);
		expect(body.error).toBe('validation_error');
	});

	it('returns 404 when hard-deleting a price that does not exist', async () => {
		const { agent, session } = createTestAgent();
		authState.session = session;

		sqlState.queue.push([{ id: agent.id, user_id: agent.user_id }]); // ownership
		sqlState.queue.push([]); // DELETE … RETURNING id → nothing

		const { status, body } = await invoke(pricesHandler, {
			method: 'DELETE',
			url: '/api/monetization/prices',
			body: { agent_id: agent.id, skill_name: 'ghost', hard: true },
		});

		expect(status).toBe(404);
		expect(body.error).toBe('not_found');
	});

	it('lists active prices publicly via GET', async () => {
		const { agent } = createTestAgent();

		sqlState.queue.push([{ id: agent.id }]); // agent exists
		sqlState.queue.push([
			{ id: 'p1', skill: 'echo', currency_mint: USDC_MINT, chain: 'solana', amount: 1_000_000, is_active: true },
			{ id: 'p2', skill: 'summarize', currency_mint: USDC_MINT, chain: 'solana', amount: 2_500_000, is_active: true },
		]);

		const { status, body } = await invoke(pricesHandler, {
			method: 'GET',
			url: `/api/monetization/prices?agent_id=${agent.id}`,
		});

		expect(status).toBe(200);
		expect(body.prices).toHaveLength(2);
		expect(body.prices[0].price_usdc).toBe(1); // 1_000_000 atomic → 1 USDC
		expect(body.prices[1].amount_atomic).toBe(2_500_000);
	});

	it('returns 400 on GET without a UUID agent_id', async () => {
		const { status, body } = await invoke(pricesHandler, {
			method: 'GET',
			url: '/api/monetization/prices?agent_id=not-a-uuid',
		});

		expect(status).toBe(400);
		expect(body.error).toBe('validation_error');
	});

	it('returns 429 when the rate limit is exceeded', async () => {
		const { agent, session } = createTestAgent();
		authState.session = session;
		rlState.success = false;

		const { status, body } = await invoke(pricesHandler, {
			method: 'PUT',
			url: '/api/monetization/prices',
			body: { agent_id: agent.id, skill_name: 'echo', price_usdc: 0.01 },
		});

		expect(status).toBe(429);
		expect(body.error).toBe('rate_limited');
	});
});

// ── 5. 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', approved_at: '2026-01-01T00:00:00Z', effective_at: '2026-01-01T00:00:00Z' },
		]);

		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
		// The cooldown policy looks for a live wallet on each rail first: none,
		// so both addresses are first wallets and go live at once with no step-up.
		sqlState.queue.push([]); // no current solana payout wallet
		sqlState.queue.push([]); // no current evm payout wallet
		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('refuses to replace a live payout wallet without step-up, and says what it would replace', async () => {
		const { agent, session } = createTestAgent();
		authState.session = session;
		const CURRENT = 'THREEsynthetic1111111111111111111111111111111';

		sqlState.queue.push([{ id: agent.id, user_id: agent.user_id }]); // ownership
		sqlState.queue.push([{ id: 'w-old', agent_id: agent.id, address: CURRENT, chain: 'solana', is_default: true, approved_at: '2026-01-01T00:00:00Z', effective_at: '2026-01-01T00:00:00Z' }]);

		const { status, body } = await invoke(walletHandler, {
			method: 'PUT',
			url: '/api/monetization/wallet',
			body: { agent_id: agent.id, solana_address: SOL_ADDRESS },
		});

		expect(status).toBe(403);
		expect(body.error).toBe('step_up_required');
		expect(body.current_address).toBe(CURRENT);
		expect(body.cooldown_hours).toBe(24);
		expect(sqlState.calls.some((c) => c.query.includes('ON CONFLICT'))).toBe(false);
	});

	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');
	});
});

// ── 6. 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('pays out on Solana even when an EVM wallet was saved more recently', async () => {
		const { agent, session } = createTestAgent();
		const EVM_ADDRESS = '0x1111111111111111111111111111111111111111';
		authState.session = session;

		sqlState.queue.push([{ id: agent.id, user_id: agent.user_id }]);
		// Ordered newest-first, so the EVM row leads. Taking it would price the
		// withdrawal in Base USDC and strand the Solana balance at zero.
		sqlState.queue.push([
			{ address: EVM_ADDRESS, chain: 'base', preferred_network: 'solana' },
			{ address: SOL_ADDRESS, chain: 'solana', preferred_network: 'solana' },
		]);
		queueBalance({ earned: 5_000_000n });
		sqlState.queue.push([]); // advisory lock
		sqlState.queue.push([
			{
				id: 'wd-1', agent_id: agent.id, amount: 4_000_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',
			},
		]);

		const { status, body } = await invoke(withdrawalsHandler, {
			method: 'POST',
			url: '/api/monetization/withdrawals',
			body: { agent_id: agent.id, amount_usdc: 4 },
		});

		expect(status).toBe(201);
		expect(body.withdrawal.chain).toBe('solana');
		expect(body.withdrawal.destination_address).toBe(SOL_ADDRESS);
		expect(body.withdrawal.currency_mint).toBe(USDC_MINT);
	});

	it('refuses an explicit network the user has no wallet on, instead of paying out elsewhere', 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' }]);

		const { status, body } = await invoke(withdrawalsHandler, {
			method: 'POST',
			url: '/api/monetization/withdrawals',
			body: { agent_id: agent.id, amount_usdc: 5, network: 'base' },
		});

		expect(status).toBe(422);
		expect(body.error).toBe('no_payout_wallet');
	});

	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');
	});
});