Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(x402): resolve outbound agent spends against the Solana settlement itself
nirholas420a88d8847d
diff --git a/api/_lib/migrations/20261015110000_x402_outbound_resolved.sql b/api/_lib/migrations/20261015110000_x402_outbound_resolved.sqlnew file mode 100644index 000000000..25fc8fef2--- /dev/null+++ b/api/_lib/migrations/20261015110000_x402_outbound_resolved.sql@@ -0,0 +1,30 @@+-- Outbound receipts: chain-resolved enrichment for payment_session_executions.+--+-- payment_session_executions already records what the platform BELIEVES it+-- paid (amount_usdc, payer_address, payee_address as reported by the x402+-- settlement response). These columns hold what the resolver reads straight+-- off the transaction's token-balance diff instead: ground truth, independent+-- of whatever the settlement response claimed. Resolved lazily, on first view+-- of the Outbound receipts tab, then cached here so later views are free.+--+-- resolve_error records a terminal resolve failure (tx not found, tx failed,+-- no matching transfer) so a broken signature is not re-fetched on every page+-- load; resolved_at is null until a resolve attempt (success or error) ran.++alter table payment_session_executions+ add column if not exists resolved_payer text,+ add column if not exists resolved_payee text,+ add column if not exists resolved_mint text,+ add column if not exists resolved_amount_atomics numeric,+ add column if not exists resolved_decimals smallint,+ add column if not exists resolved_fee_lamports bigint,+ add column if not exists resolved_slot bigint,+ add column if not exists resolved_block_time bigint,+ add column if not exists resolved_at timestamptz,+ add column if not exists resolve_error text;++-- Outbound tab lists settled executions for a user, newest first, filterable+-- by resolve state (NULL resolved_at = "not yet resolved" = needs a lazy pass).+create index if not exists pse_user_settled_resolved+ on payment_session_executions (user_id, resolved_at, created_at desc)+ where status = 'settled';diff --git a/api/_lib/x402/outbound-receipts.js b/api/_lib/x402/outbound-receipts.jsnew file mode 100644index 000000000..ab712c5ca--- /dev/null+++ b/api/_lib/x402/outbound-receipts.js@@ -0,0 +1,169 @@+// Outbound receipts: what a three.ws-hosted agent spent at OTHER, external+// x402 merchants through a Payment Session (api/pay/session.js), enriched+// with the chain's own record of the settlement.+//+// payment_session_executions already stores what the settlement response+// CLAIMED (payer_address, payee_address, amount_usdc). This module resolves+// each settled, Solana-network execution's tx_hash against the chain itself+// (api/_lib/x402/solana-settlement.js) the first time anyone views it, then+// caches the resolved fields on the row so later views are free. Resolution+// is Solana-only for now (the home chain, see CLAUDE.md chain priority); a+// Base-network execution is listed using its reported fields, unresolved.++import { sql } from '../db.js';+import { atomicsToUsd, normalizeHost } from '../pay/policy.js';+import { resolveSettlement, SettlementResolveError } from './solana-settlement.js';++const RESOLVE_CONCURRENCY = 4;++async function mapLimit(items, limit, fn) {+ const out = new Array(items.length);+ let next = 0;+ const worker = async () => {+ while (next < items.length) {+ const i = next++;+ out[i] = await fn(items[i]);+ }+ };+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));+ return out;+}++/**+ * Resolve one row's settlement from chain and persist the result (success or+ * terminal error) so it is never re-fetched. Mutates nothing in the DB for a+ * row that is not eligible (non-Solana network, no tx_hash): those are left+ * for a future pass once/if they gain one.+ */+async function resolveAndCacheRow(row) {+ if (row.network !== 'solana' || !row.tx_hash) return row;+ try {+ const settlement = await resolveSettlement(row.tx_hash);+ const [updated] = await sql`+ UPDATE payment_session_executions+ SET resolved_payer = ${settlement.payer},+ resolved_payee = ${settlement.payee},+ resolved_mint = ${settlement.mint},+ resolved_amount_atomics = ${settlement.amountAtomics},+ resolved_decimals = ${settlement.decimals},+ resolved_fee_lamports = ${settlement.feeLamports},+ resolved_slot = ${settlement.slot},+ resolved_block_time = ${settlement.blockTime},+ resolved_at = now(),+ resolve_error = null,+ updated_at = now()+ WHERE id = ${row.id}+ RETURNING *+ `;+ return updated ?? row;+ } catch (err) {+ const code = err instanceof SettlementResolveError ? err.code : 'resolve_failed';+ const [updated] = await sql`+ UPDATE payment_session_executions+ SET resolved_at = now(),+ resolve_error = ${code},+ updated_at = now()+ WHERE id = ${row.id}+ RETURNING *+ `;+ return updated ?? row;+ }+}++function formatReceipt(row) {+ const resolved = row.resolved_at && !row.resolve_error+ ? {+ payer: row.resolved_payer,+ payee: row.resolved_payee,+ mint: row.resolved_mint,+ amountAtomics: row.resolved_amount_atomics != null ? String(row.resolved_amount_atomics) : null,+ decimals: row.resolved_decimals,+ feeLamports: row.resolved_fee_lamports != null ? Number(row.resolved_fee_lamports) : null,+ slot: row.resolved_slot != null ? Number(row.resolved_slot) : null,+ blockTime: row.resolved_block_time != null ? Number(row.resolved_block_time) : null,+ }+ : null;++ return {+ id: row.id,+ sessionId: row.session_id,+ endpointUrl: row.endpoint_url,+ endpointHost: row.endpoint_host,+ method: row.method,+ network: row.network,+ reportedAmountUsd: atomicsToUsd(row.amount_usdc),+ txHash: row.tx_hash,+ reportedPayer: row.payer_address,+ reportedPayee: row.payee_address,+ status: row.status,+ createdAt: row.created_at,+ resolved,+ resolveError: row.resolved_at && row.resolve_error ? row.resolve_error : null,+ resolvePending: row.network === 'solana' && Boolean(row.tx_hash) && !row.resolved_at,+ };+}++/**+ * List settled outbound spends for a user, newest first, lazily resolving+ * any Solana rows that have never been resolved before formatting them.+ *+ * @param {string} userId+ * @param {{ limit?: number, cursor?: string|null, network?: string|null, host?: string|null }} [opts]+ */+export async function listOutboundReceipts(userId, { limit = 20, cursor = null, network = null, host = null } = {}) {+ const lim = Math.min(Math.max(Math.floor(Number(limit)) || 20, 1), 100);+ const net = network === 'solana' || network === 'base' ? network : null;+ const hostFilter = host ? normalizeHost(host) : null;++ const rows = await sql`+ SELECT *+ FROM payment_session_executions+ WHERE user_id = ${userId}+ AND status = 'settled'+ AND (${net}::text IS NULL OR network = ${net})+ AND (${hostFilter}::text IS NULL OR endpoint_host = ${hostFilter})+ AND (${cursor}::timestamptz IS NULL OR created_at < ${cursor}::timestamptz)+ ORDER BY created_at DESC+ LIMIT ${lim + 1}+ `;++ const hasMore = rows.length > lim;+ const page = rows.slice(0, lim);++ const resolvedPage = await mapLimit(page, RESOLVE_CONCURRENCY, (row) =>+ row.resolved_at ? row : resolveAndCacheRow(row),+ );++ const receipts = resolvedPage.map(formatReceipt);+ return {+ receipts,+ nextCursor: hasMore ? page[page.length - 1].created_at : null,+ };+}++/**+ * Aggregate KPIs across every settled outbound spend for a user: reported+ * total spend, how many are chain-verified vs still pending resolution, and+ * how many distinct merchants were paid.+ */+export async function summarizeOutboundReceipts(userId) {+ const [stats] = await sql`+ SELECT+ count(*) AS total,+ coalesce(sum(amount_usdc), 0) AS total_amount_atomics,+ count(*) FILTER (WHERE resolved_at IS NOT NULL AND resolve_error IS NULL) AS verified,+ count(*) FILTER (WHERE network = 'solana' AND (resolved_at IS NULL OR resolve_error IS NOT NULL)) AS unverified,+ count(DISTINCT endpoint_host) AS unique_merchants+ FROM payment_session_executions+ WHERE user_id = ${userId}+ AND status = 'settled'+ `;++ return {+ total: Number(stats?.total ?? 0),+ totalSpendUsd: atomicsToUsd(stats?.total_amount_atomics ?? 0),+ verified: Number(stats?.verified ?? 0),+ unverified: Number(stats?.unverified ?? 0),+ uniqueMerchants: Number(stats?.unique_merchants ?? 0),+ };+}diff --git a/api/_lib/x402/solana-settlement.js b/api/_lib/x402/solana-settlement.jsnew file mode 100644index 000000000..46399808b--- /dev/null+++ b/api/_lib/x402/solana-settlement.js@@ -0,0 +1,159 @@+// Resolve a Solana settlement signature into payer, payee, mint, and amount+// straight from the transaction's token-balance diff, plus fee, slot and+// time. Ground truth for an x402 payment, independent of whatever the+// settlement response claimed when the payment session recorded it.+//+// Split into a pure parser (testable against recorded/synthetic transaction+// JSON, no network) and a thin async wrapper that fetches the transaction+// over RPC.++import { solanaConnection } from '../solana/connection.js';+import { SOLANA_USDC_MINT } from '../../payments/_config.js';++export class SettlementResolveError extends Error {+ constructor(code, message) {+ super(message);+ this.name = 'SettlementResolveError';+ this.code = code;+ }+}++// Mints whose ticker we know without a lookup. $THREE is the platform coin;+// USDC is the asset nearly every x402 settlement moves.+const KNOWN_MINT_SYMBOLS = {+ [SOLANA_USDC_MINT]: 'USDC',+ FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump: 'THREE',+};++/** Ticker for a known mint, or null when the mint isn't one we recognise. */+export function mintSymbol(mint) {+ return KNOWN_MINT_SYMBOLS[mint] || null;+}++function atomicsOf(entry) {+ const raw = entry?.uiTokenAmount?.amount;+ try {+ return BigInt(raw ?? '0');+ } catch {+ return 0n;+ }+}++/**+ * Per-owner, per-mint token balance deltas from a confirmed transaction's+ * `meta`. Positive = the owner received; negative = the owner sent. Several+ * token accounts belonging to the same owner+mint (legal, if rare) are+ * summed into one row.+ *+ * @param {{ preTokenBalances?: Array, postTokenBalances?: Array }} meta+ * @returns {Array<{ owner: string, mint: string, decimals: number, deltaAtomics: bigint }>}+ */+export function tokenBalanceDeltas(meta) {+ const byKey = new Map();+ const rowFor = (entry) => {+ const key = `${entry.owner}:${entry.mint}`;+ let row = byKey.get(key);+ if (!row) {+ row = { owner: entry.owner, mint: entry.mint, decimals: entry.uiTokenAmount?.decimals ?? 0, deltaAtomics: 0n };+ byKey.set(key, row);+ }+ return row;+ };+ for (const p of meta?.preTokenBalances || []) {+ if (!p?.owner || !p?.mint) continue;+ rowFor(p).deltaAtomics -= atomicsOf(p);+ }+ for (const q of meta?.postTokenBalances || []) {+ if (!q?.owner || !q?.mint) continue;+ const row = rowFor(q);+ row.deltaAtomics += atomicsOf(q);+ row.decimals = q.uiTokenAmount?.decimals ?? row.decimals;+ }+ return [...byKey.values()].filter((r) => r.deltaAtomics !== 0n);+}++/**+ * Parse an already-fetched `getTransaction()` result into a settlement+ * record. Pure: never touches the network, so it is unit-testable against+ * recorded or synthetic transaction JSON.+ *+ * A plain x402 settlement moves exactly one mint (USDC), so the common case+ * is unambiguous. A transaction that also moved other SPL mints in the same+ * instruction set (a swap leg, an unrelated transfer sharing the signature)+ * has no price oracle to compare an arbitrary mint's value against USDC's, so+ * rather than guess, this resolves the caller-expected settlement mint+ * (`opts.mint`, default USDC) specifically. Only when that mint moved neither+ * way, and exactly one other mint has a complete sender+receiver pair, does+ * it fall back to that one mint; with more than one candidate and no match on+ * the expected mint, it throws rather than pick arbitrarily.+ *+ * @param {object} tx getTransaction()'s result: { meta, transaction, slot, blockTime }+ * @param {{ signature: string, mint?: string }} ctx mint defaults to USDC+ */+export function parseSettlement(tx, { signature, mint: expectedMint = SOLANA_USDC_MINT }) {+ if (!tx) {+ throw new SettlementResolveError('tx_not_found', `Transaction ${signature} is not confirmed.`);+ }+ if (tx.meta?.err) {+ throw new SettlementResolveError('tx_failed', `Transaction ${signature} failed on-chain.`);+ }++ const deltas = tokenBalanceDeltas(tx.meta);+ if (!deltas.length) {+ throw new SettlementResolveError('no_token_transfer', `No SPL token balance change found in ${signature}.`);+ }++ const byMint = new Map();+ for (const d of deltas) {+ const list = byMint.get(d.mint) || [];+ list.push(d);+ byMint.set(d.mint, list);+ }++ const settlementsByMint = new Map();+ for (const [mint, list] of byMint) {+ const sent = list.filter((d) => d.deltaAtomics < 0n);+ const received = list.filter((d) => d.deltaAtomics > 0n);+ if (!sent.length || !received.length) continue;+ const payerRow = sent.reduce((a, b) => (a.deltaAtomics < b.deltaAtomics ? a : b));+ const payeeRow = received.reduce((a, b) => (a.deltaAtomics > b.deltaAtomics ? a : b));+ settlementsByMint.set(mint, { mint, payer: payerRow.owner, payee: payeeRow.owner, amountAtomics: payeeRow.deltaAtomics, decimals: payeeRow.decimals });+ }++ let best = settlementsByMint.get(expectedMint) || null;+ if (!best && settlementsByMint.size === 1) {+ best = settlementsByMint.values().next().value;+ }+ if (!best) {+ throw new SettlementResolveError('no_token_transfer', `No matching payer/payee token transfer found in ${signature}.`);+ }++ return {+ signature,+ network: 'solana',+ payer: best.payer,+ payee: best.payee,+ mint: best.mint,+ symbol: mintSymbol(best.mint),+ amountAtomics: best.amountAtomics.toString(),+ decimals: best.decimals,+ feeLamports: Number(tx.meta.fee ?? 0),+ slot: Number(tx.slot ?? 0),+ blockTime: typeof tx.blockTime === 'number' ? tx.blockTime : null,+ };+}++/**+ * Fetch a confirmed Solana transaction and resolve it into a settlement+ * record.+ *+ * @param {string} signature+ * @param {{ connection?: import('@solana/web3.js').Connection, mint?: string }} [opts]+ * `connection` injects one in tests (defaults to the shared mainnet+ * connection); `mint` is the expected settlement mint (defaults to USDC).+ */+export async function resolveSettlement(signature, { connection, mint } = {}) {+ const conn = connection || solanaConnection({ network: 'mainnet' });+ const tx = await conn.getTransaction(signature, { commitment: 'confirmed', maxSupportedTransactionVersion: 1 });+ return parseSettlement(tx, { signature, mint });+}diff --git a/api/x402/outbound-receipts.js b/api/x402/outbound-receipts.jsnew file mode 100644index 000000000..a42022d3c--- /dev/null+++ b/api/x402/outbound-receipts.js@@ -0,0 +1,57 @@+// GET /api/x402/outbound-receipts?network=<solana|base>&host=<endpoint-host>&cursor=<iso>&limit=<n>+//+// Outbound receipts: what the caller's agents spent at OTHER, external x402+// merchants while executing an Agent Payment Session (api/pay/session.js),+// enriched with what the Solana chain itself says settled (payer, payee,+// mint, amount, fee, slot, time), not just what the settlement response+// claimed. This is the counterpart to /api/x402/my-receipts (which answers+// "what did three.ws charge wallet X"); this endpoint answers "what did my+// agents spend elsewhere."+//+// Authentication: account session cookie, or a bearer token with wallet:write+// (the same credential that is allowed to see what a session spent, matching+// GET /api/pay/session/:id/executions). Read-only methods pass assertBearerMaySpend+// unconditionally, so a read-scoped key works too.++import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';+import { assertBearerMaySpend } from '../_lib/spend-scope.js';+import { cors, error, json, method, rateLimited, wrap } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { clampInt } from '../_lib/http-params.js';+import { listOutboundReceipts, summarizeOutboundReceipts } from '../_lib/x402/outbound-receipts.js';++async function resolveUser(req, res) {+ const session = await getSessionUser(req, res);+ if (session) return session;+ const bearer = assertBearerMaySpend(await authenticateBearer(extractBearer(req)), req);+ if (bearer) return { id: bearer.userId };+ return null;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const user = await resolveUser(req, res);+ if (!user) return error(res, 401, 'unauthorized', 'authentication required');++ const url = new URL(req.url, 'http://x');+ const network = url.searchParams.get('network') || null;+ const host = url.searchParams.get('host') || null;+ const rawCursor = url.searchParams.get('cursor');+ const cursor = rawCursor && Number.isFinite(Date.parse(rawCursor)) ? rawCursor : null;+ if (rawCursor && !cursor) {+ return error(res, 400, 'invalid_cursor', 'cursor must be an ISO 8601 timestamp');+ }+ const limit = clampInt(url.searchParams.get('limit'), { min: 1, max: 100, fallback: 20 });++ const [{ receipts, nextCursor }, summary] = await Promise.all([+ listOutboundReceipts(user.id, { limit, cursor, network, host }),+ summarizeOutboundReceipts(user.id),+ ]);++ return json(res, 200, { receipts, nextCursor, summary });+});diff --git a/tests/solana-settlement.test.js b/tests/solana-settlement.test.jsnew file mode 100644index 000000000..ad33a9a54--- /dev/null+++ b/tests/solana-settlement.test.js@@ -0,0 +1,279 @@+import { describe, it, expect, vi } from 'vitest';++const getTransactionMock = vi.fn();++vi.mock('../api/_lib/solana/connection.js', () => ({+ solanaConnection: () => ({ getTransaction: (...a) => getTransactionMock(...a) }),+}));++const {+ parseSettlement,+ tokenBalanceDeltas,+ mintSymbol,+ resolveSettlement,+ SettlementResolveError,+} = await import('../api/_lib/x402/solana-settlement.js');++const USDC_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+const SYNTH_MINT = 'THREEsynthetic1111111111111111111111111111';+const PAYER = 'PAYERsynthetic111111111111111111111111111';+const PAYEE = 'PAYEEsynthetic111111111111111111111111111';+const SIG = 'SYNTHETICsig1111111111111111111111111111111111111111111111111111111111111';++function balance(owner, mint, amount, decimals = 6) {+ return { owner, mint, uiTokenAmount: { amount: String(amount), decimals, uiAmount: Number(amount) / 10 ** decimals } };+}++function tx({ pre, post, err = null, fee = 5000, slot = 12345, blockTime = 1_700_000_000 }) {+ return { meta: { err, fee, preTokenBalances: pre, postTokenBalances: post }, slot, blockTime };+}++describe('tokenBalanceDeltas', () => {+ it('computes one delta per owner+mint from pre/post balances', () => {+ const deltas = tokenBalanceDeltas({+ preTokenBalances: [balance(PAYER, USDC_MINT, 5_000_000), balance(PAYEE, USDC_MINT, 0)],+ postTokenBalances: [balance(PAYER, USDC_MINT, 4_000_000), balance(PAYEE, USDC_MINT, 1_000_000)],+ });+ const byOwner = Object.fromEntries(deltas.map((d) => [d.owner, d.deltaAtomics]));+ expect(byOwner[PAYER]).toBe(-1_000_000n);+ expect(byOwner[PAYEE]).toBe(1_000_000n);+ });++ it('sums multiple token accounts for the same owner and mint', () => {+ const deltas = tokenBalanceDeltas({+ preTokenBalances: [balance(PAYER, USDC_MINT, 2_000_000), balance(PAYER, USDC_MINT, 3_000_000)],+ postTokenBalances: [balance(PAYER, USDC_MINT, 1_000_000), balance(PAYER, USDC_MINT, 3_000_000)],+ });+ expect(deltas).toHaveLength(1);+ expect(deltas[0].deltaAtomics).toBe(-1_000_000n);+ });++ it('drops owners whose net delta is zero', () => {+ const deltas = tokenBalanceDeltas({+ preTokenBalances: [balance(PAYER, USDC_MINT, 1_000_000)],+ postTokenBalances: [balance(PAYER, USDC_MINT, 1_000_000)],+ });+ expect(deltas).toHaveLength(0);+ });+});++describe('mintSymbol', () => {+ it('recognises USDC and $THREE', () => {+ expect(mintSymbol(USDC_MINT)).toBe('USDC');+ expect(mintSymbol(THREE_MINT)).toBe('THREE');+ });++ it('returns null for an unrecognised mint', () => {+ expect(mintSymbol(SYNTH_MINT)).toBeNull();+ });+});++describe('parseSettlement', () => {+ it('resolves payer, payee, mint, amount, fee, slot and time from a plain USDC settlement', () => {+ const result = parseSettlement(+ tx({+ pre: [balance(PAYER, USDC_MINT, 5_000_000), balance(PAYEE, USDC_MINT, 0)],+ post: [balance(PAYER, USDC_MINT, 4_000_000), balance(PAYEE, USDC_MINT, 1_000_000)],+ }),+ { signature: SIG },+ );+ expect(result).toEqual({+ signature: SIG,+ network: 'solana',+ payer: PAYER,+ payee: PAYEE,+ mint: USDC_MINT,+ symbol: 'USDC',+ amountAtomics: '1000000',+ decimals: 6,+ feeLamports: 5000,+ slot: 12345,+ blockTime: 1_700_000_000,+ });+ });++ it('picks the expected settlement mint (USDC) when a second, unrelated mint also moves', () => {+ // A swap-funded payment, or any transaction that bundles an incidental+ // transfer, can move a second SPL mint in the same signature. There is no+ // price oracle here to compare an arbitrary mint's value against USDC's+ // (raw atomics and UI-scaled amount are both just unit counts, not value),+ // so the resolver asks for the settlement mint it expects (USDC by+ // default) rather than guessing by magnitude.+ const result = parseSettlement(+ tx({+ pre: [+ balance(PAYER, USDC_MINT, 5_000_000),+ balance(PAYEE, USDC_MINT, 0),+ balance(PAYER, SYNTH_MINT, 1_000_000_000, 9),+ balance(PAYEE, SYNTH_MINT, 0, 9),+ ],+ post: [+ balance(PAYER, USDC_MINT, 4_000_000),+ balance(PAYEE, USDC_MINT, 1_000_000),+ balance(PAYER, SYNTH_MINT, 950_000_000, 9),+ balance(PAYEE, SYNTH_MINT, 50_000_000, 9),+ ],+ }),+ { signature: SIG },+ );+ expect(result.mint).toBe(USDC_MINT);+ expect(result.amountAtomics).toBe('1000000');+ });++ it('falls back to the one mint that moved when it is not the expected mint', () => {+ const result = parseSettlement(+ tx({+ pre: [balance(PAYER, SYNTH_MINT, 1_000_000_000, 9), balance(PAYEE, SYNTH_MINT, 0, 9)],+ post: [balance(PAYER, SYNTH_MINT, 950_000_000, 9), balance(PAYEE, SYNTH_MINT, 50_000_000, 9)],+ }),+ { signature: SIG },+ );+ expect(result.mint).toBe(SYNTH_MINT);+ expect(result.amountAtomics).toBe('50000000');+ });++ it('throws when several non-expected mints moved and none matches the expected mint', () => {+ const SYNTH_MINT_2 = 'OTHERsynthetic1111111111111111111111111111';+ try {+ parseSettlement(+ tx({+ pre: [+ balance(PAYER, SYNTH_MINT, 1_000_000_000, 9),+ balance(PAYEE, SYNTH_MINT, 0, 9),+ balance(PAYER, SYNTH_MINT_2, 1_000_000_000, 9),+ balance(PAYEE, SYNTH_MINT_2, 0, 9),+ ],+ post: [+ balance(PAYER, SYNTH_MINT, 950_000_000, 9),+ balance(PAYEE, SYNTH_MINT, 50_000_000, 9),+ balance(PAYER, SYNTH_MINT_2, 900_000_000, 9),+ balance(PAYEE, SYNTH_MINT_2, 100_000_000, 9),+ ],+ }),+ { signature: SIG },+ );+ throw new Error('expected a throw');+ } catch (e) {+ expect(e.code).toBe('no_token_transfer');+ }+ });++ it('resolves a non-USDC mint explicitly when the caller names it', () => {+ const result = parseSettlement(+ tx({+ pre: [balance(PAYER, THREE_MINT, 1_000_000_000, 6), balance(PAYEE, THREE_MINT, 0, 6)],+ post: [balance(PAYER, THREE_MINT, 900_000_000, 6), balance(PAYEE, THREE_MINT, 100_000_000, 6)],+ }),+ { signature: SIG, mint: THREE_MINT },+ );+ expect(result.mint).toBe(THREE_MINT);+ expect(result.symbol).toBe('THREE');+ expect(result.amountAtomics).toBe('100000000');+ });++ it('resolves a three-owner settlement shape (a USDC transfer alongside an unrelated fee-collector balance and a second mint)', () => {+ // Mirrors the real-world shape a facilitator-routed x402 settlement can+ // take: a fee collector's own USDC balance sits in the same transaction+ // without itself being the payer or payee, and an unrelated SPL mint+ // (e.g. a swap leftover) moves between the same two owners. The resolver+ // must still single out the USDC payer/payee pair. Synthetic accounts+ // throughout (per CLAUDE.md: no real third-party mint, wallet, or handle+ // in committed fixtures); verified separately against a live mainnet+ // signature via resolveSettlement() during manual QA, not committed here.+ const FEE_COLLECTOR = 'FEEsynthetic1111111111111111111111111111111';+ const MERCHANT = 'MERCHANTsynthetic111111111111111111111111111';+ const CUSTOMER = 'CUSTOMERsynthetic111111111111111111111111111';+ const OTHER_MINT = 'OTHERsynthetic22222222222222222222222222222';+ const result = parseSettlement(+ {+ meta: {+ err: null,+ fee: 5000,+ preTokenBalances: [+ balance(FEE_COLLECTOR, USDC_MINT, 33_586_654_975),+ balance(MERCHANT, OTHER_MINT, 12_576_312_270_994, 9),+ balance(MERCHANT, USDC_MINT, 73_251_888_166),+ balance(CUSTOMER, USDC_MINT, 5_394_299_230),+ balance(CUSTOMER, OTHER_MINT, 1_863_488_431_869, 9),+ ],+ postTokenBalances: [+ balance(FEE_COLLECTOR, USDC_MINT, 33_586_654_975),+ balance(MERCHANT, OTHER_MINT, 12_575_617_189_732, 9),+ balance(MERCHANT, USDC_MINT, 73_256_888_166),+ balance(CUSTOMER, USDC_MINT, 5_389_297_900),+ balance(CUSTOMER, OTHER_MINT, 1_864_183_513_131, 9),+ ],+ },+ slot: 457148215,+ blockTime: 1792048039,+ },+ { signature: SIG },+ );+ expect(result.mint).toBe(USDC_MINT);+ expect(result.payer).toBe(CUSTOMER);+ expect(result.payee).toBe(MERCHANT);+ expect(result.amountAtomics).toBe('5000000');+ expect(result.symbol).toBe('USDC');+ expect(result.slot).toBe(457148215);+ expect(result.blockTime).toBe(1792048039);+ });++ it('throws tx_failed for a transaction that failed on-chain', () => {+ expect(() => parseSettlement(tx({ pre: [], post: [], err: { InstructionError: [0, 'Custom'] } }), { signature: SIG })).toThrow(+ SettlementResolveError,+ );+ try {+ parseSettlement(tx({ pre: [], post: [], err: {} }), { signature: SIG });+ } catch (e) {+ expect(e.code).toBe('tx_failed');+ }+ });++ it('throws tx_not_found for a null transaction', () => {+ try {+ parseSettlement(null, { signature: SIG });+ throw new Error('expected a throw');+ } catch (e) {+ expect(e.code).toBe('tx_not_found');+ }+ });++ it('throws no_token_transfer when nothing moved', () => {+ try {+ parseSettlement(tx({ pre: [], post: [] }), { signature: SIG });+ throw new Error('expected a throw');+ } catch (e) {+ expect(e.code).toBe('no_token_transfer');+ }+ });++ it('throws no_token_transfer when balances changed but no owner both sent and received', () => {+ // Only one side moves (e.g. an airdrop-style mint with no counterparty debit).+ try {+ parseSettlement(+ tx({ pre: [balance(PAYEE, USDC_MINT, 0)], post: [balance(PAYEE, USDC_MINT, 1_000_000)] }),+ { signature: SIG },+ );+ throw new Error('expected a throw');+ } catch (e) {+ expect(e.code).toBe('no_token_transfer');+ }+ });+});++describe('resolveSettlement', () => {+ it('fetches the transaction and parses it', async () => {+ getTransactionMock.mockResolvedValueOnce(+ tx({+ pre: [balance(PAYER, USDC_MINT, 5_000_000), balance(PAYEE, USDC_MINT, 0)],+ post: [balance(PAYER, USDC_MINT, 4_000_000), balance(PAYEE, USDC_MINT, 1_000_000)],+ }),+ );+ const result = await resolveSettlement(SIG);+ expect(getTransactionMock).toHaveBeenCalledWith(SIG, { commitment: 'confirmed', maxSupportedTransactionVersion: 1 });+ expect(result.payer).toBe(PAYER);+ expect(result.payee).toBe(PAYEE);+ expect(result.amountAtomics).toBe('1000000');+ });+});diff --git a/tests/x402-outbound-receipts-endpoint.test.js b/tests/x402-outbound-receipts-endpoint.test.jsnew file mode 100644index 000000000..5baa3be3a--- /dev/null+++ b/tests/x402-outbound-receipts-endpoint.test.js@@ -0,0 +1,108 @@+// GET /api/x402/outbound-receipts: account-session (or wallet:write-bearer)+// read endpoint listing what the caller's agents spent at external x402+// merchants. Auth, query parsing, and the empty-state shape are the contract+// under test; the resolve/aggregate logic itself lives in+// api/_lib/x402/outbound-receipts.js and is covered there.+import { describe, it, expect, vi, beforeEach } from 'vitest';++const getSessionUserMock = vi.fn();+const authenticateBearerMock = vi.fn();+const extractBearerMock = vi.fn();+vi.mock('../api/_lib/auth.js', () => ({+ getSessionUser: (...a) => getSessionUserMock(...a),+ authenticateBearer: (...a) => authenticateBearerMock(...a),+ extractBearer: (...a) => extractBearerMock(...a),+}));++const authIpLimit = vi.fn();+vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: { authIp: (...a) => authIpLimit(...a) },+ clientIp: () => '127.0.0.1',+}));++const listOutboundReceiptsMock = vi.fn();+const summarizeOutboundReceiptsMock = vi.fn();+vi.mock('../api/_lib/x402/outbound-receipts.js', () => ({+ listOutboundReceipts: (...a) => listOutboundReceiptsMock(...a),+ summarizeOutboundReceipts: (...a) => summarizeOutboundReceiptsMock(...a),+}));++const { default: handler } = await import('../api/x402/outbound-receipts.js');++function mkReq({ method = 'GET', url = '/api/x402/outbound-receipts', headers = {} } = {}) {+ return { method, url, headers, on() {}, destroy() {} };+}+function mkRes() {+ return {+ statusCode: 200, headers: {}, body: undefined, writableEnded: false,+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },+ end(b) { this.body = b; this.writableEnded = true; },+ };+}+const parse = (res) => (res.body ? JSON.parse(res.body) : undefined);++beforeEach(() => {+ getSessionUserMock.mockReset().mockResolvedValue({ id: 'user-1' });+ authenticateBearerMock.mockReset().mockResolvedValue(null);+ extractBearerMock.mockReset().mockReturnValue(null);+ authIpLimit.mockReset().mockResolvedValue({ success: true, limit: 60, remaining: 59, reset: 0 });+ listOutboundReceiptsMock.mockReset().mockResolvedValue({ receipts: [], nextCursor: null });+ summarizeOutboundReceiptsMock.mockReset().mockResolvedValue({ total: 0, totalSpendUsd: 0, verified: 0, unverified: 0, uniqueMerchants: 0 });+});++describe('GET /api/x402/outbound-receipts', () => {+ it('rejects an unauthenticated caller', async () => {+ getSessionUserMock.mockResolvedValueOnce(null);+ const res = mkRes();+ await handler(mkReq(), res);+ expect(res.statusCode).toBe(401);+ });++ it('rejects a non-GET method', async () => {+ const res = mkRes();+ await handler(mkReq({ method: 'POST' }), res);+ expect(res.statusCode).toBe(405);+ });++ it('returns the designed empty state when there is nothing to show', async () => {+ const res = mkRes();+ await handler(mkReq(), res);+ expect(res.statusCode).toBe(200);+ const body = parse(res);+ expect(body.receipts).toEqual([]);+ expect(body.nextCursor).toBeNull();+ expect(body.summary.total).toBe(0);+ });++ it('passes network, host, cursor and a clamped limit through to the lib', async () => {+ const res = mkRes();+ await handler(+ mkReq({ url: '/api/x402/outbound-receipts?network=solana&host=example.test&cursor=2026-10-01T00:00:00.000Z&limit=500' }),+ res,+ );+ expect(res.statusCode).toBe(200);+ expect(listOutboundReceiptsMock).toHaveBeenCalledWith('user-1', {+ limit: 100,+ cursor: '2026-10-01T00:00:00.000Z',+ network: 'solana',+ host: 'example.test',+ });+ });++ it('rejects a cursor that is not a valid timestamp', async () => {+ const res = mkRes();+ await handler(mkReq({ url: '/api/x402/outbound-receipts?cursor=not-a-date' }), res);+ expect(res.statusCode).toBe(400);+ expect(parse(res).error).toBe('invalid_cursor');+ });++ it('accepts a wallet:write bearer when there is no session', async () => {+ getSessionUserMock.mockResolvedValueOnce(null);+ extractBearerMock.mockReturnValueOnce('tok');+ authenticateBearerMock.mockResolvedValueOnce({ userId: 'agent-1', scope: 'wallet:write' });+ const res = mkRes();+ await handler(mkReq(), res);+ expect(res.statusCode).toBe(200);+ expect(listOutboundReceiptsMock).toHaveBeenCalledWith('agent-1', expect.any(Object));+ });+});diff --git a/tests/x402-outbound-receipts.test.js b/tests/x402-outbound-receipts.test.jsnew file mode 100644index 000000000..ba1846199--- /dev/null+++ b/tests/x402-outbound-receipts.test.js@@ -0,0 +1,186 @@+// api/_lib/x402/outbound-receipts.js lists what a Payment Session spent at+// OTHER, external x402 merchants, lazily resolving each Solana settlement+// against chain truth on first view and caching the result. These tests+// cover: resolving an unresolved row and persisting it, skipping a row that+// is already resolved, tolerating a resolve failure without blocking the+// page, leaving Base-network rows unresolved, and the KPI aggregate.+import { describe, it, expect, vi, beforeEach } from 'vitest';++const sqlState = { calls: [], queue: [] };++vi.mock('../api/_lib/db.js', () => ({+ sql: vi.fn(async (strings, ...values) => {+ sqlState.calls.push({ query: strings.join('?'), values });+ return sqlState.queue.length ? sqlState.queue.shift() : [];+ }),+}));++const resolveSettlementMock = vi.fn();++vi.mock('../api/_lib/x402/solana-settlement.js', async () => {+ const actual = await vi.importActual('../api/_lib/x402/solana-settlement.js');+ return {+ ...actual,+ resolveSettlement: (...args) => resolveSettlementMock(...args),+ };+});++const { listOutboundReceipts, summarizeOutboundReceipts } = await import(+ '../api/_lib/x402/outbound-receipts.js'+);++const USER = 'user-1';+const MERCHANT = 'MERCHANTsynthetic11111111111111111111111111';+const CUSTOMER = 'CUSTOMERsynthetic1111111111111111111111111';+const USDC_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';++function executionRow(overrides = {}) {+ return {+ id: 'exec-1',+ session_id: 'session-1',+ user_id: USER,+ endpoint_url: 'https://example-merchant.test/api/paid',+ endpoint_host: 'example-merchant.test',+ method: 'GET',+ amount_usdc: '1000000',+ network: 'solana',+ tx_hash: 'SIGnature1111111111111111111111111111111111111111111111111111111111111',+ payer_address: CUSTOMER,+ payee_address: MERCHANT,+ status: 'settled',+ resolved_payer: null,+ resolved_payee: null,+ resolved_mint: null,+ resolved_amount_atomics: null,+ resolved_decimals: null,+ resolved_fee_lamports: null,+ resolved_slot: null,+ resolved_block_time: null,+ resolved_at: null,+ resolve_error: null,+ created_at: new Date('2026-10-15T00:00:00.000Z'),+ ...overrides,+ };+}++beforeEach(() => {+ sqlState.calls.length = 0;+ sqlState.queue.length = 0;+ resolveSettlementMock.mockReset();+});++describe('listOutboundReceipts', () => {+ it('resolves an unresolved Solana row from chain and persists the result', async () => {+ sqlState.queue.push([executionRow()]);+ resolveSettlementMock.mockResolvedValueOnce({+ payer: CUSTOMER,+ payee: MERCHANT,+ mint: USDC_MINT,+ symbol: 'USDC',+ amountAtomics: '1000000',+ decimals: 6,+ feeLamports: 5000,+ slot: 12345,+ blockTime: 1_700_000_000,+ });+ sqlState.queue.push([+ executionRow({+ resolved_payer: CUSTOMER,+ resolved_payee: MERCHANT,+ resolved_mint: USDC_MINT,+ resolved_amount_atomics: '1000000',+ resolved_decimals: 6,+ resolved_fee_lamports: 5000,+ resolved_slot: 12345,+ resolved_block_time: 1_700_000_000,+ resolved_at: new Date('2026-10-15T00:05:00.000Z'),+ }),+ ]);++ const { receipts, nextCursor } = await listOutboundReceipts(USER);+ expect(resolveSettlementMock).toHaveBeenCalledWith(executionRow().tx_hash);+ expect(receipts).toHaveLength(1);+ expect(receipts[0].resolved).toEqual({+ payer: CUSTOMER,+ payee: MERCHANT,+ mint: USDC_MINT,+ amountAtomics: '1000000',+ decimals: 6,+ feeLamports: 5000,+ slot: 12345,+ blockTime: 1_700_000_000,+ });+ expect(receipts[0].resolvePending).toBe(false);+ expect(nextCursor).toBeNull();++ const updateCall = sqlState.calls.find((c) => c.query.includes('UPDATE payment_session_executions') && c.query.includes('resolved_payer'));+ expect(updateCall).toBeTruthy();+ });++ it('does not re-resolve a row that was already resolved', async () => {+ sqlState.queue.push([+ executionRow({+ resolved_payer: CUSTOMER,+ resolved_payee: MERCHANT,+ resolved_mint: USDC_MINT,+ resolved_amount_atomics: '1000000',+ resolved_decimals: 6,+ resolved_fee_lamports: 5000,+ resolved_slot: 12345,+ resolved_block_time: 1_700_000_000,+ resolved_at: new Date('2026-10-15T00:05:00.000Z'),+ }),+ ]);++ const { receipts } = await listOutboundReceipts(USER);+ expect(resolveSettlementMock).not.toHaveBeenCalled();+ expect(receipts[0].resolved.mint).toBe(USDC_MINT);+ });++ it('records a terminal resolve error and still returns the row, unresolved', async () => {+ sqlState.queue.push([executionRow()]);+ resolveSettlementMock.mockRejectedValueOnce(Object.assign(new Error('nope'), { code: 'tx_not_found', name: 'SettlementResolveError' }));+ sqlState.queue.push([executionRow({ resolved_at: new Date('2026-10-15T00:05:00.000Z'), resolve_error: 'tx_not_found' })]);++ const { receipts } = await listOutboundReceipts(USER);+ expect(receipts[0].resolved).toBeNull();+ expect(receipts[0].resolveError).toBe('tx_not_found');+ expect(receipts[0].resolvePending).toBe(false);+ });++ it('leaves a Base-network row unresolved without calling the Solana resolver', async () => {+ sqlState.queue.push([+ executionRow({ network: 'base', tx_hash: '0xabc123', payer_address: '0xpayer', payee_address: '0xpayee' }),+ ]);++ const { receipts } = await listOutboundReceipts(USER);+ expect(resolveSettlementMock).not.toHaveBeenCalled();+ expect(receipts[0].resolved).toBeNull();+ expect(receipts[0].resolvePending).toBe(false);+ expect(receipts[0].reportedPayer).toBe('0xpayer');+ });++ it('returns an empty page without erroring when there is nothing to show', async () => {+ sqlState.queue.push([]);+ const { receipts, nextCursor } = await listOutboundReceipts(USER);+ expect(receipts).toEqual([]);+ expect(nextCursor).toBeNull();+ expect(resolveSettlementMock).not.toHaveBeenCalled();+ });+});++describe('summarizeOutboundReceipts', () => {+ it('maps the aggregate row into dollar figures and counts', async () => {+ sqlState.queue.push([+ { total: '3', total_amount_atomics: '15000000', verified: '2', unverified: '1', unique_merchants: '2' },+ ]);+ const summary = await summarizeOutboundReceipts(USER);+ expect(summary).toEqual({+ total: 3,+ totalSpendUsd: 15,+ verified: 2,+ unverified: 1,+ uniqueMerchants: 2,+ });+ });+});