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
security(stage,irl): prove a tip or a pay on-chain before it counts for anything
nirholas73bb063253eb
diff --git a/CLAUDE.md b/CLAUDE.mdindex c99163fd5..c7a785ec3 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -305,7 +305,7 @@ The whole build + submit + purge in one command: `npm run deploy:gcp:full`.- Frontend: vanilla JS modules + Vite (`npm run dev`, port 3000).- 3D: Three.js with glTF/GLB.- Backend touchpoints: serverless-style handlers in `api/`, workers in `workers/`.-- **Production runs on Google Cloud Run, NOT Vercel** (migrated 2026-07-07 after Vercel disabled the deployment). One container ([server/index.mjs](server/index.mjs)) serves the static frontend, the vercel.json route table, and all `api/**` handlers; the crons (103 as of 2026-08-02, see vercel.json) run on Cloud Scheduler. `vercel.json` is a LIVE config file: `server/index.mjs` reads its `routes` array on boot (split at the `{handle:"filesystem"}` marker into pre- and post-filesystem phases), and `scripts/create-gcp-scheduler.mjs` reads its `crons` array to sync Cloud Scheduler jobs. The server itself never reads `crons`. Never delete `vercel.json` as a leftover. GCP builds/deploys must pin the `three-ws-build@` (build) and `three-ws@` (runtime) service accounts; the project's default compute SA was deleted. Deploys: see the "Deploy runbook" section above.+- **Production runs on Google Cloud Run, NOT Vercel** (migrated 2026-07-07 after Vercel disabled the deployment). One container ([server/index.mjs](server/index.mjs)) serves the static frontend, the vercel.json route table, and all `api/**` handlers; the crons (104 as of 2026-08-06, see vercel.json) run on Cloud Scheduler. `vercel.json` is a LIVE config file: `server/index.mjs` reads its `routes` array on boot (split at the `{handle:"filesystem"}` marker into pre- and post-filesystem phases), and `scripts/create-gcp-scheduler.mjs` reads its `crons` array to sync Cloud Scheduler jobs. The server itself never reads `crons`. Never delete `vercel.json` as a leftover. GCP builds/deploys must pin the `three-ws-build@` (build) and `three-ws@` (runtime) service accounts; the project's default compute SA was deleted. Deploys: see the "Deploy runbook" section above.- **Env-var trap:** `vercel env pull` returns EMPTY for secret-type vars. Never trust a Vercel env export as complete. Production env lives on the Cloud Run service (`gcloud run services describe/update three-ws-api --region us-central1`).- Solana/agent SDKs in `sdk/`, `solana-agent-sdk/`, `agent-payments-sdk/`.- Real APIs in use: Pump.fun feed, Solana RPC, OpenAI/Anthropic via worker proxies. Never mock these.diff --git a/api/_lib/agent-payout-wallets.js b/api/_lib/agent-payout-wallets.jsnew file mode 100644index 000000000..18b810bf7--- /dev/null+++ b/api/_lib/agent-payout-wallets.js@@ -0,0 +1,34 @@+// Every address an agent can legitimately be paid at.+//+// A settlement recorded against an agent (an IRL pay, an x402 receipt) is only+// meaningful if the money actually reached that agent, which means knowing where+// "that agent" gets paid. Three sources, all real and all owner-controlled:+//+// • the payout addresses on its published paid services (agent_paid_services),+// which is where an x402 settlement for one of its skills actually lands,+// • its custodial EVM wallet (agent_identities.wallet_address), and+// • its custodial Solana wallet (meta.solana_address).+//+// An agent with none of these has no verifiable destination: callers decide what+// that means for them rather than getting a silent pass here.++import { sql } from './db.js';++export async function agentPayoutWallets(agentId) {+ if (!agentId) return [];+ const [identity] = await sql`+ SELECT wallet_address, meta FROM agent_identities+ WHERE id = ${agentId} AND deleted_at IS NULL LIMIT 1+ `.catch(() => []);+ const services = await sql`+ SELECT DISTINCT payout_address FROM agent_paid_services+ WHERE agent_id = ${agentId} AND archived_at IS NULL AND payout_address IS NOT NULL+ `.catch(() => []);++ const wallets = [+ identity?.meta?.solana_address,+ identity?.wallet_address,+ ...services.map((r) => r.payout_address),+ ];+ return [...new Set(wallets.filter((w) => typeof w === 'string' && w))];+}diff --git a/api/_lib/evm-payment-verify.js b/api/_lib/evm-payment-verify.jsindex b78218f00..4d645c123 100644--- a/api/_lib/evm-payment-verify.js+++ b/api/_lib/evm-payment-verify.js@@ -62,7 +62,11 @@ const TX_HASH_RE = /^0x[0-9a-fA-F]{64}$/;* @param {object} opts* @param {string} opts.txHash 0x-prefixed 32-byte tx hash from the buyer* @param {string} opts.chain stored chain string (e.g. 'base')- * @param {string} opts.recipient seller payout address (0x…)+ * @param {string|null} opts.recipient seller payout address (0x…). Pass null to+ * accept a transfer to ANY address: used only where the destination genuinely+ * is not knowable server-side (an x402 service whose payout address we do not+ * hold), so the check degrades to "this transaction is real, succeeded, and+ * moved at least this much USDC" instead of degrading to no check at all.* @param {string|bigint} opts.expectedAmount USDC atomics (6 decimals) required* @returns {Promise<{ status:'pending'|'match'|'mismatch', txHash?:string,* actualAmount?:string, from?:string, message?:string }>}@@ -76,11 +80,13 @@ export async function verifyEvmUsdcPayment({ txHash, chain, recipient, expectedAconst usdc = EVM_USDC[chainId];if (!usdc) return { status: 'mismatch', message: `no USDC contract known for chain ${chainId}` };- let to;- try {- to = getAddress(recipient);- } catch {- return { status: 'mismatch', message: 'seller payout address is not a valid EVM address' };+ let to = null;+ if (recipient != null) {+ try {+ to = getAddress(recipient);+ } catch {+ return { status: 'mismatch', message: 'seller payout address is not a valid EVM address' };+ }}const client = clientFor(chainId);@@ -120,13 +126,19 @@ export async function verifyEvmUsdcPayment({ txHash, chain, recipient, expectedAcontinue; // not a Transfer event}if (decoded.eventName !== 'Transfer') continue;- if (getAddress(decoded.args.to) !== to) continue;+ if (to !== null && getAddress(decoded.args.to) !== to) continue;total += decoded.args.value;from = from || decoded.args.from;}if (total === 0n) {- return { status: 'mismatch', txHash, message: 'no USDC transfer to the seller wallet found in this transaction' };+ return {+ status: 'mismatch',+ txHash,+ message: to === null+ ? 'no USDC transfer found in this transaction'+ : 'no USDC transfer to the seller wallet found in this transaction',+ };}const expected = BigInt(expectedAmount);if (total < expected) {diff --git a/api/_lib/migrations/20260806130000_settlement_verification.sql b/api/_lib/migrations/20260806130000_settlement_verification.sqlnew file mode 100644index 000000000..a7b93d168--- /dev/null+++ b/api/_lib/migrations/20260806130000_settlement_verification.sql@@ -0,0 +1,41 @@+-- Verified settlements: stage tips and IRL pays now prove themselves on-chain.+--+-- Both surfaces recorded a money event from a client-supplied signature after+-- checking only its SHAPE (a base58 / 0x regex), the mint allow-list, and a+-- positive amount. Nothing fetched the transaction, so a well-formed but+-- unrelated signature with a large amount minted a tip that never happened+-- (security review M4). The handlers now verify the transfer on-chain before the+-- row counts for anything.+--+-- verified_at is that proof: non-null means the chain showed us the transfer.+-- A row may exist with verified_at null when the transaction is real but not yet+-- visible to our RPC (a genuine payment must not be thrown away over lag); those+-- rows are excluded from every total, leaderboard, and notification until the+-- sweep in api/cron/settlement-verify.js promotes them, and are deleted when they+-- turn out to be unverifiable.+--+-- Backfill: every row that exists when this migration runs predates verification+-- and cannot be re-proved retroactively, so it is grandfathered as verified. The+-- deploy gate runs migrations before the new code is live, so no genuinely+-- pending row can exist yet at this point.++alter table if exists show_tips add column if not exists verified_at timestamptz;+alter table if exists show_tips add column if not exists verify_error text;+update show_tips set verified_at = created_at where verified_at is null;++-- The leaderboard and show totals read verified rows only.+create index if not exists show_tips_verified+ on show_tips (show_id, amount_atomic desc)+ where verified_at is not null;++-- The sweep's work queue: unverified rows, oldest first.+create index if not exists show_tips_unverified+ on show_tips (created_at)+ where verified_at is null;++alter table if exists irl_interactions add column if not exists verified_at timestamptz;+update irl_interactions set verified_at = created_at where type = 'pay' and verified_at is null;++create index if not exists irl_interactions_unverified+ on irl_interactions (created_at)+ where type = 'pay' and verified_at is null;diff --git a/api/_lib/settlement-verify.js b/api/_lib/settlement-verify.jsnew file mode 100644index 000000000..51b6d5a89--- /dev/null+++ b/api/_lib/settlement-verify.js@@ -0,0 +1,158 @@+// Did this settlement actually happen, on-chain, to the right wallet?+//+// Several surfaces record a money event from a signature the CLIENT hands us: a+// stage tip, an IRL "someone paid your agent" tap. Until the 2026-08-06 security+// review (M4) those paths checked only the SHAPE of the signature (a base58 or+// 0x-hash regex), the mint allow-list, and a positive amount. Nothing fetched the+// transaction, so a well-formed but unrelated signature with a large amount+// recorded a tip that never happened: leaderboard and social fraud on a surface+// whose whole promise is "never trusts a client-asserted tip without a verifiable+// settlement".+//+// This module is that verification, shared so the two surfaces cannot drift:+//+// • Solana (base58 signature): fetch the parsed transaction and sum the SPL+// balance delta for `mint` credited to any recipient wallet. Robust to an+// associated token account created inside the same transaction, and to the+// payer bundling several transfers.+// • EVM (0x tx hash): delegate to verifyEvmUsdcPayment, which already handles+// receipt status, confirmations, and Transfer-log decoding for USDC on Base.+//+// Three outcomes, and the difference matters:+// match the funds moved; record it.+// pending the chain has not shown us this transaction yet (RPC lag, not yet+// confirmed). The money may well be real, so callers hold the record+// rather than discarding a genuine payment.+// mismatch it is not there, it failed, or it paid too little / the wrong+// wallet. Never record.++import { TOKEN_MINT, TOKEN_DECIMALS } from './token/config.js';+import { verifyEvmUsdcPayment } from './evm-payment-verify.js';++export const EVM_TX_RE = /^0x[0-9a-fA-F]{64}$/;+export const SOL_SIG_RE = /^[1-9A-HJ-NP-Za-km-z]{43,88}$/;++// $THREE, the only coin this platform promotes, plus USDC, the sole other asset+// the existing pay paths settle in. Kept in lockstep with stage-split.js.+export const THREE_MINT = TOKEN_MINT;+export const USDC_SOLANA = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';+export const USDC_BASE = '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913';++export const THREE_ATOMIC_DECIMALS = Number(TOKEN_DECIMALS) || 6;++function isEvmMint(mint) {+ return typeof mint === 'string' && mint.toLowerCase() === USDC_BASE;+}++// Solana native-SOL transfers are not a settlement asset here (every allowed mint+// is an SPL token or an ERC-20), so a Solana verification is always a token+// balance-delta check.+async function verifySolana({ signature, mint, amountAtomic, recipients, network, anyRecipient }) {+ const { solanaConnection } = await import('./agent-pumpfun.js');+ const cluster = String(network || '').toLowerCase().includes('devnet') ? 'devnet' : 'mainnet';+ let tx;+ try {+ tx = await solanaConnection(cluster).getParsedTransaction(signature, {+ maxSupportedTransactionVersion: 0,+ commitment: 'confirmed',+ });+ } catch {+ return { status: 'pending', reason: 'could not reach the chain to verify this settlement' };+ }+ if (!tx) return { status: 'pending', reason: 'the settlement is not confirmed on-chain yet' };+ if (tx.meta?.err) return { status: 'mismatch', reason: 'the settlement transaction failed on-chain' };++ const owners = new Set(recipients);+ const pre = tx.meta?.preTokenBalances || [];+ const post = tx.meta?.postTokenBalances || [];+ let credited = 0n;+ for (const p of post) {+ if (p.mint !== mint) continue;+ if (!anyRecipient && !owners.has(p.owner)) continue;+ const before = pre.find((x) => x.accountIndex === p.accountIndex);+ const delta = BigInt(p.uiTokenAmount?.amount ?? '0') - BigInt(before?.uiTokenAmount?.amount ?? '0');+ // With no known destination, only credits count: summing the payer's own+ // negative delta back in would net a real transfer to zero.+ if (anyRecipient && delta <= 0n) continue;+ credited += delta;+ }+ if (credited <= 0n) {+ return { status: 'mismatch', reason: 'this transaction moved nothing to the recipient wallet' };+ }+ if (credited < BigInt(amountAtomic)) {+ return { status: 'mismatch', credited: credited.toString(), reason: 'the amount claimed is larger than what the transaction actually paid' };+ }+ return { status: 'match', credited: credited.toString() };+}++async function verifyEvm({ signature, amountAtomic, recipients, network, anyRecipient }) {+ const chain = String(network || '').toLowerCase().includes('sepolia') ? 'base-sepolia' : 'base';+ if (anyRecipient) {+ const res = await verifyEvmUsdcPayment({+ txHash: signature, chain, recipient: null, expectedAmount: BigInt(amountAtomic),+ });+ if (res.status === 'match') return { status: 'match', credited: res.actualAmount };+ if (res.status === 'pending') return { status: 'pending', reason: 'the settlement is not confirmed on-chain yet' };+ return { status: 'mismatch', reason: res.message || 'this transaction did not move the amount claimed' };+ }+ // Any one of the recipient wallets satisfying the amount is a match: a surface+ // may legitimately hold both an agent wallet and its owner's payout address.+ let lastReason = 'no USDC transfer to the recipient wallet found in this transaction';+ for (const recipient of recipients) {+ if (!/^0x[0-9a-fA-F]{40}$/.test(recipient || '')) continue;+ const res = await verifyEvmUsdcPayment({+ txHash: signature, chain, recipient, expectedAmount: BigInt(amountAtomic),+ });+ if (res.status === 'match') return { status: 'match', credited: res.actualAmount };+ if (res.status === 'pending') return { status: 'pending', reason: 'the settlement is not confirmed on-chain yet' };+ lastReason = res.message || lastReason;+ }+ return { status: 'mismatch', reason: lastReason };+}++/**+ * Verify that `signature` really moved at least `amountAtomic` of `mint` to one of+ * `recipients`.+ *+ * @param {object} a+ * @param {string} a.signature base58 Solana signature or 0x EVM tx hash+ * @param {string} a.mint the settlement asset ($THREE or USDC)+ * @param {bigint|number|string} a.amountAtomic atomic units the caller claims+ * @param {string[]} a.recipients wallets that may legitimately receive it+ * @param {string} [a.network] network hint from the caller+ * @param {boolean} [a.allowAnyRecipient] when the destination is genuinely not+ * knowable server-side (an x402 service whose payout address we do not hold),+ * accept a transfer of the right asset and size to anyone. Strictly stronger+ * than the shape-only check it replaces, and never used where a payout wallet+ * IS on record.+ * @returns {Promise<{status:'match'|'pending'|'mismatch', credited?:string, reason?:string}>}+ */+export async function verifySettlement({ signature, mint, amountAtomic, recipients, network, allowAnyRecipient = false }) {+ const sig = typeof signature === 'string' ? signature.trim() : '';+ const wallets = [...new Set((recipients || []).filter((r) => typeof r === 'string' && r))];+ const anyRecipient = !wallets.length && allowAnyRecipient;+ if (!wallets.length && !anyRecipient) {+ return { status: 'mismatch', reason: 'this agent has no payout wallet on record, so a payment to it cannot be verified' };+ }+ let amount;+ try {+ amount = BigInt(amountAtomic);+ } catch {+ return { status: 'mismatch', reason: 'amount must be an integer in atomic units' };+ }+ if (amount <= 0n) return { status: 'mismatch', reason: 'amount must be positive' };++ if (EVM_TX_RE.test(sig)) {+ if (!isEvmMint(mint)) {+ return { status: 'mismatch', reason: 'an EVM transaction hash can only settle USDC on Base' };+ }+ return verifyEvm({ signature: sig, amountAtomic: amount, recipients: wallets, network, anyRecipient });+ }+ if (SOL_SIG_RE.test(sig)) {+ if (isEvmMint(mint)) {+ return { status: 'mismatch', reason: 'a Solana signature cannot settle an EVM asset' };+ }+ return verifySolana({ signature: sig, mint, amountAtomic: amount, recipients: wallets, network, anyRecipient });+ }+ return { status: 'mismatch', reason: 'not a valid on-chain settlement signature' };+}diff --git a/api/_lib/stage-wallets.js b/api/_lib/stage-wallets.jsnew file mode 100644index 000000000..093322855--- /dev/null+++ b/api/_lib/stage-wallets.js@@ -0,0 +1,22 @@+// Where a stage host can legitimately be paid.+//+// The tip UI is handed the host agent's Solana address as the transfer target+// (api/stage/index.js readHostWallet), so that address is the destination a real+// tip credits. The agent's EVM wallet rides along because the platform's pay path+// also accepts USDC on Base, and a settlement there lands on the EVM side.+//+// One place, so the endpoint that TELLS a tipper where to send and the endpoint+// that VERIFIES where it went can never disagree about which wallets count.++import { sql } from './db.js';++export async function hostPayoutWallets(agentId) {+ if (!agentId) return [];+ const [row] = await sql`+ SELECT wallet_address, meta FROM agent_identities+ WHERE id = ${agentId} AND deleted_at IS NULL LIMIT 1+ `;+ if (!row) return [];+ const wallets = [row.meta?.solana_address, row.wallet_address];+ return [...new Set(wallets.filter((w) => typeof w === 'string' && w))];+}diff --git a/api/cron/settlement-verify.js b/api/cron/settlement-verify.jsnew file mode 100644index 000000000..a27335478--- /dev/null+++ b/api/cron/settlement-verify.js@@ -0,0 +1,122 @@+// Settlement sweep: resolve every quarantined money row against the chain.+//+// Stage tips and IRL pays are verified on-chain at write time (security review+// M4). When our RPC has not yet seen a transaction the handler keeps the row with+// verified_at null rather than discarding what may be a real payment: the row+// counts for nothing, notifies nobody, and appears on no leaderboard.+//+// This tick is what resolves those rows without the client having to come back:+//+// match → promote. The tip joins its show's total and leaderboard.+// mismatch → discard. Nothing was paid, so nothing should persist; a stage tip+// keeps a verify_error breadcrumb for one grace period before the+// row is deleted, so a support question has something to read.+// pending → leave it. Retried next tick, until GRACE_MINUTES is up, after+// which a settlement that has never appeared is treated as fiction.+//+// Idempotent and swarm-safe: promotion flips verified_at from null in a+// conditional UPDATE, so overlapping ticks cannot double-count a tip.++import { json, method, wrapCron } from '../_lib/http.js';+import { sql } from '../_lib/db.js';+import { requireCron } from '../_lib/cron-auth.js';+import { verifySettlement } from '../_lib/settlement-verify.js';+import { promoteTip } from '../stage/tip.js';+import { hostPayoutWallets } from '../_lib/stage-wallets.js';+import { agentPayoutWallets } from '../_lib/agent-payout-wallets.js';++export const maxDuration = 60;++// How long a settlement gets to show up before we call it fiction. Solana+// finality is seconds and Base is ~2s blocks plus a confirmation buffer, so an+// hour is generous for RPC lag, a reorg, or a provider outage.+const GRACE_MINUTES = 60;+// Bound the batch so a tick stays well inside maxDuration; the next one picks up+// the rest.+const BATCH = 40;++async function sweepStageTips() {+ const rows = await sql`+ SELECT t.id, t.show_id, t.stage_id, t.amount_atomic, t.currency_mint, t.settlement_sig,+ t.network, t.created_at, s.agent_id+ FROM show_tips t+ JOIN stages s ON s.id = t.stage_id+ WHERE t.verified_at IS NULL+ ORDER BY t.created_at ASC+ LIMIT ${BATCH}+ `;+ let promoted = 0; let discarded = 0; let stillPending = 0;+ for (const row of rows) {+ const recipients = await hostPayoutWallets(row.agent_id);+ const proof = await verifySettlement({+ signature: row.settlement_sig,+ mint: row.currency_mint,+ amountAtomic: BigInt(row.amount_atomic),+ recipients,+ network: row.network,+ });+ if (proof.status === 'match') {+ if (await promoteTip({ tipId: row.id, showId: row.show_id, amount: Number(row.amount_atomic) })) promoted++;+ continue;+ }+ const expired = Date.now() - new Date(row.created_at).getTime() > GRACE_MINUTES * 60_000;+ if (proof.status === 'mismatch' || expired) {+ await sql`DELETE FROM show_tips WHERE id = ${row.id} AND verified_at IS NULL`;+ discarded++;+ console.warn('[settlement-verify] discarded an unprovable tip', {+ tipId: row.id, stageId: row.stage_id, reason: proof.reason || 'never appeared on-chain',+ });+ continue;+ }+ stillPending++;+ }+ return { scanned: rows.length, promoted, discarded, pending: stillPending };+}++async function sweepIrlPays() {+ const rows = await sql`+ SELECT id, agent_id, amount, currency_mint, payload, created_at+ FROM irl_interactions+ WHERE type = 'pay' AND verified_at IS NULL+ ORDER BY created_at ASC+ LIMIT ${BATCH}+ `.catch(() => []);+ let promoted = 0; let discarded = 0; let stillPending = 0;+ for (const row of rows) {+ const recipients = await agentPayoutWallets(row.agent_id);+ const proof = await verifySettlement({+ signature: row.payload?.signature,+ mint: row.currency_mint,+ amountAtomic: Math.round(Number(row.amount) || 0),+ recipients,+ network: row.payload?.network,+ allowAnyRecipient: recipients.length === 0,+ });+ if (proof.status === 'match') {+ await sql`UPDATE irl_interactions SET verified_at = now() WHERE id = ${row.id} AND verified_at IS NULL`;+ promoted++;+ continue;+ }+ const expired = Date.now() - new Date(row.created_at).getTime() > GRACE_MINUTES * 60_000;+ if (proof.status === 'mismatch' || expired) {+ await sql`DELETE FROM irl_interactions WHERE id = ${row.id} AND verified_at IS NULL`;+ discarded++;+ continue;+ }+ stillPending++;+ }+ return { scanned: rows.length, promoted, discarded, pending: stillPending };+}++export default wrapCron(async (req, res) => {+ if (!method(req, res, ['GET', 'POST'])) return;+ if (!requireCron(req, res)) return;++ const t0 = Date.now();+ // One failing lane must not strand the other: both run, both report.+ const [tips, pays] = await Promise.all([+ sweepStageTips().catch((err) => ({ error: err?.message || String(err) })),+ sweepIrlPays().catch((err) => ({ error: err?.message || String(err) })),+ ]);+ return json(res, 200, { ok: true, tips, pays, took_ms: Date.now() - t0 });+});diff --git a/api/irl/interactions.js b/api/irl/interactions.jsindex fe3e22d78..b0642b147 100644--- a/api/irl/interactions.js+++ b/api/irl/interactions.js@@ -45,6 +45,8 @@ import { sendOpsAlert } from '../_lib/alerts.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { readDeviceToken } from '../_lib/irl-auth.js';import { isUuid } from '../_lib/validate.js';+import { verifySettlement } from '../_lib/settlement-verify.js';+import { agentPayoutWallets } from '../_lib/agent-payout-wallets.js';// view | tap — passive/active sighting of the agent. message — a note left for// the owner. pay — an x402 settlement against the agent (see PAY note below).@@ -60,16 +62,21 @@ const VIEW_DEDUPE_MS = 5 * 60 * 1000; // collapse repeat views from one deviceconst MAX_MESSAGE_LEN = 280;// A `pay` is the one caller-asserted type that names money, so it is NOT trusted-// blindly (the original guard against forged "someone paid your agent" rows). A-// pay is only recorded when it carries a settlement proof we can sanity-check:+// blindly. A pay is recorded only when it carries a settlement we can PROVE:// 1. a well-formed on-chain signature (0x… EVM tx hash, or base58 Solana sig),-// 2. a currency mint that is $THREE or USDC — the only coins this platform-// references; anything else is rejected outright, and-// 3. global de-dupe by signature so one settlement can be logged exactly once.-// Pays surface ONLY in the owner's private inbox (never publicly), and the write-// is rate-limited + deduped, so the residual abuse surface is a forger spamming-// their own inbox. Full on-chain attribution (recipient/amount match) is layered-// on by the B3 settlement path, which owns the seller payout + price context.+// 2. a currency mint that is $THREE or USDC, the only coins this platform+// references; anything else is rejected outright,+// 3. global de-dupe by signature so one settlement is logged exactly once, and+// 4. on-chain verification (security review M4): the transaction must exist,+// have succeeded, and have moved at least the amount claimed. When the pin's+// agent has payout wallets on record (its paid-service payout addresses, its+// custodial wallets) the transfer must have credited one of them. When it has+// none, the destination genuinely is not knowable server-side, since an x402+// service can pay out anywhere, so the check degrades to "this transaction is+// real and moved this much of this asset" rather than to no check at all.+// A pay whose settlement is not yet visible to our RPC is recorded with+// verified_at null: it counts for nothing and notifies nobody until the sweep in+// api/cron/settlement-verify.js proves or discards it.const EVM_TX_RE = /^0x[0-9a-fA-F]{64}$/;const SOL_SIG_RE = /^[1-9A-HJ-NP-Za-km-z]{43,88}$/;const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';@@ -181,6 +188,10 @@ async function runMigrations() {await sql`ALTER TABLE irl_interactions ADD COLUMN IF NOT EXISTS device_type TEXT DEFAULT 'phone'`;// One settlement → one pay row. Indexed for the de-dupe lookup on insert.await sql`CREATE INDEX IF NOT EXISTS irl_interactions_paysig ON irl_interactions ((payload->>'signature')) WHERE type = 'pay'`;+ // On-chain proof for a pay (M4). Null on a pay means "not proved yet": the row+ // is inert until the settlement sweep promotes it. Never backfilled here; the+ // migration owns grandfathering the rows that predate verification.+ await sql`ALTER TABLE irl_interactions ADD COLUMN IF NOT EXISTS verified_at TIMESTAMPTZ`;}export default wrap(async (req, res) => {@@ -263,6 +274,7 @@ export default wrap(async (req, res) => {payload.from = 'owner';if (replyToRaw) payload.replyTo = replyToRaw;}+ let payVerifiedAt = null;if (type === 'pay') {const sig = payload.signature ?? body.signature ?? null;const mint = body.currencyMint ?? payload.currencyMint ?? null;@@ -274,6 +286,9 @@ export default wrap(async (req, res) => {}const amt = Number(body.amount);amount = Number.isFinite(amt) && amt > 0 ? amt : null;+ if (amount == null) {+ return json(res, 400, { error: 'pay requires the amount actually settled, in atomic units' });+ }currencyMint = mint;payload = { ...payload, signature: sig };if (body.network) payload.network = String(body.network).slice(0, 32);@@ -284,6 +299,24 @@ export default wrap(async (req, res) => {LIMIT 1`;if (dupe) return json(res, 200, { ok: true, deduped: true, id: dupe.id });++ // Prove the settlement before it becomes an earnings row.+ const recipients = await agentPayoutWallets(pin.agent_id);+ const proof = await verifySettlement({+ signature: sig,+ mint,+ amountAtomic: Math.round(amount),+ recipients,+ network: payload.network,+ allowAnyRecipient: recipients.length === 0,+ });+ if (proof.status === 'mismatch') {+ return json(res, 402, {+ error: 'settlement_unverified',+ message: proof.reason || 'that settlement could not be verified on-chain',+ });+ }+ if (proof.status === 'match') payVerifiedAt = new Date().toISOString();}// An owner reply is authored by the owner, so it lands already-seen — it must@@ -298,7 +331,7 @@ export default wrap(async (req, res) => {const [row] = await sql`INSERT INTO irl_interactions(pin_id, agent_id, type, message, viewer_user_id, viewer_device, lat, lng,- amount, currency_mint, payload, seen_at, device_type)+ amount, currency_mint, payload, seen_at, device_type, verified_at)VALUES (${pinId},${pin.agent_id ?? null},@@ -312,7 +345,8 @@ export default wrap(async (req, res) => {${currencyMint},${payloadJson}::jsonb,${seenAt},- ${deviceType}+ ${deviceType},+ ${payVerifiedAt})RETURNING id, type, created_at`;@@ -353,6 +387,16 @@ export default wrap(async (req, res) => {notified = true;}}+ } else if (type === 'pay' && !payVerifiedAt) {+ // Real money may be in flight; our RPC just has not seen it. The row is+ // kept and stays inert (no notification, no ops alert) until the sweep+ // proves it, so a lagging read never turns into a false "you got paid".+ return json(res, 202, {+ ok: true,+ pending: true,+ interaction: row,+ message: 'settlement not visible on-chain yet, this pay counts as soon as it is',+ });} else if ((type === 'pay' || type === 'message') && pin.user_id) {// High-signal visitor events notify the owner: in-app always (the dashboard// inbox + the global nav bell), plus an optional Telegram ping for a pay.@@ -410,7 +454,7 @@ export default wrap(async (req, res) => {SELECTix.id, ix.pin_id, ix.agent_id, ix.type, ix.message,ix.lat, ix.lng, ix.seen_at, ix.created_at,- ix.amount, ix.currency_mint, ix.payload, ix.device_type,+ ix.amount, ix.currency_mint, ix.payload, ix.device_type, ix.verified_at,p.avatar_name, p.captionFROM irl_interactions ixJOIN irl_pins p ON p.id = ix.pin_id@@ -423,7 +467,7 @@ export default wrap(async (req, res) => {SELECTix.id, ix.pin_id, ix.agent_id, ix.type, ix.message,ix.lat, ix.lng, ix.seen_at, ix.created_at,- ix.amount, ix.currency_mint, ix.payload, ix.device_type,+ ix.amount, ix.currency_mint, ix.payload, ix.device_type, ix.verified_at,p.avatar_name, p.captionFROM irl_interactions ixJOIN irl_pins p ON p.id = ix.pin_iddiff --git a/api/stage/index.js b/api/stage/index.jsindex 3cc190191..845dcb707 100644--- a/api/stage/index.js+++ b/api/stage/index.js@@ -85,9 +85,18 @@ async function ensureTables() {settlement_sig TEXT NOT NULL,network TEXT,message TEXT,+ verified_at TIMESTAMPTZ,+ verify_error TEXT,created_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`;+ // Live databases predate the verification columns (migration+ // 20260806130000_settlement_verification.sql adds them there, with the+ // grandfathering backfill). These ALTERs only cover a database that has never+ // run migrations; they must never backfill, or a genuinely pending tip would be+ // promoted without proof.+ await sql`ALTER TABLE show_tips ADD COLUMN IF NOT EXISTS verified_at TIMESTAMPTZ`;+ await sql`ALTER TABLE show_tips ADD COLUMN IF NOT EXISTS verify_error TEXT`;// One settlement → one tip row. The unique index is the idempotency guarantee// the tip endpoint leans on (ON CONFLICT DO NOTHING).await sql`CREATE UNIQUE INDEX IF NOT EXISTS show_tips_sig ON show_tips (settlement_sig)`;@@ -107,6 +116,8 @@ async function readHostWallet(agentId) {// Aggregate the per-tipper leaderboard for a show, highest total first.async function showLeaderboard(showId, limit = 10) {if (!showId) return [];+ // Verified tips only: a tip whose settlement has not been proved on-chain is+ // quarantined and must never reach a public leaderboard.const rows = await sql`SELECTCOALESCE(tipper_label, 'someone') AS label,@@ -114,7 +125,7 @@ async function showLeaderboard(showId, limit = 10) {COUNT(*)::int AS count,MIN(created_at) AS first_atFROM show_tips- WHERE show_id = ${showId}+ WHERE show_id = ${showId} AND verified_at IS NOT NULLGROUP BY COALESCE(tipper_label, 'someone')ORDER BY total DESC, first_at ASCLIMIT ${limit}diff --git a/api/stage/tip.js b/api/stage/tip.jsindex 9af8e3cbe..1050a6c5e 100644--- a/api/stage/tip.js+++ b/api/stage/tip.js@@ -5,7 +5,12 @@* already allows it) directly to the host agent's wallet on-chain, then POSTs the* settlement signature here. This endpoint:* 1. validates the settlement signature + the $THREE/USDC mint + the atomic- * amount (mirrors api/irl/interactions.js' pay discipline),+ * amount, then VERIFIES the transfer on-chain: the referenced transaction+ * must really have credited the host's wallet with at least the amount+ * claimed. Shape validation alone (what this did before the 2026-08-06+ * security review, M4) let anyone POST a well-formed but unrelated signature+ * with a huge amount and buy the top of the leaderboard plus a host+ * shout-out for free,* 2. is IDEMPOTENT per signature — one settlement records exactly one tip row* (a unique index + ON CONFLICT DO NOTHING is the guarantee, so a client* retry returns the existing row, never a double-credit),@@ -33,6 +38,8 @@ import { insertNotification } from '../_lib/notify.js';import { sendOpsAlert } from '../_lib/alerts.js';import { validateTipPayload, splitTip, tipExplorerUrl } from '../_lib/stage-split.js';import { notifyStageRoom } from '../_lib/stage-bridge.js';+import { verifySettlement } from '../_lib/settlement-verify.js';+import { hostPayoutWallets } from '../_lib/stage-wallets.js';const MAX_MESSAGE = 140;// A tip is "loud" when it clears 10k $THREE (6 decimals) — worth a Telegram ping.@@ -91,38 +98,81 @@ export default wrap(async (req, res) => {const network = valid.network;const message = cleanMessage(body.message);+ // Prove it. The host's own payout wallets are the only acceptable destination+ // (they are what the tip UI is handed as the transfer target), and the+ // transaction must have credited at least the amount claimed.+ const recipients = await hostPayoutWallets(stage.agent_id);+ const proof = await verifySettlement({+ signature: valid.signature,+ mint: valid.mint,+ amountAtomic: valid.amount,+ recipients,+ network,+ });+ if (proof.status === 'mismatch') {+ return json(res, 402, {+ error: 'settlement_unverified',+ message: proof.reason || 'that settlement does not pay this host',+ });+ }+ const verified = proof.status === 'match';+// Idempotent insert: the unique index on settlement_sig makes a retry a no-op.// A returned row means this is the FIRST time we've seen this settlement.+ // An unverified row is quarantined: it counts for nothing until the chain+ // catches up (see promoteTip / api/cron/settlement-verify.js).const [row] = await sql`INSERT INTO show_tips(show_id, stage_id, tipper_user_id, tipper_label, amount_atomic, currency_mint,- host_credit_atomic, venue_cut_atomic, settlement_sig, network, message)+ host_credit_atomic, venue_cut_atomic, settlement_sig, network, message, verified_at)VALUES (${show.id}, ${stageId}, ${session?.id ?? null}, ${label},${valid.amount}, ${valid.mint}, ${hostCredit}, ${venueCut},- ${valid.signature}, ${network}, ${message}+ ${valid.signature}, ${network}, ${message}, ${verified ? new Date().toISOString() : null})ON CONFLICT (settlement_sig) DO NOTHINGRETURNING id, amount_atomic, host_credit_atomic, venue_cut_atomic, created_at`;if (!row) {- // Already recorded — hand back the original so the client is idempotent too.+ // Already recorded. If that row is still quarantined and the chain has now+ // shown us the transfer, promote it here: a re-POST is the client's own+ // retry path and must not need the sweep to run first.const [existing] = await sql`- SELECT id, amount_atomic, host_credit_atomic, venue_cut_atomic+ SELECT id, amount_atomic, host_credit_atomic, venue_cut_atomic, verified_atFROM show_tips WHERE settlement_sig = ${valid.signature} LIMIT 1`;- return json(res, 200, { ok: true, deduped: true, tip: shapeTip(existing) });+ if (existing && !existing.verified_at && verified) {+ await promoteTip({ tipId: existing.id, showId: show.id, amount: valid.amount });+ }+ return json(res, 200, {+ ok: true,+ deduped: true,+ pending: !!existing && !existing.verified_at && !verified,+ tip: shapeTip(existing),+ });+ }++ const explorer = tipExplorerUrl(valid.signature, network);++ if (!verified) {+ // Real money may well be in flight; the RPC just has not caught up. Keep the+ // row, count nothing, and tell the client so it can retry or poll.+ return json(res, 202, {+ ok: true,+ pending: true,+ message: 'settlement not visible on-chain yet, this tip counts as soon as it is',+ tip: shapeTip(row),+ explorer,+ });}// Roll the show total (the row is already written, so a failed bump is logged,- // never fatal — the per-tip rows remain the source of truth for the leaderboard).+ // never fatal: the per-tip rows remain the source of truth for the leaderboard).sql`UPDATE shows SET total_tips_atomic = total_tips_atomic + ${valid.amount}, tip_count = tip_count + 1WHERE id = ${show.id}`.catch((err) => console.warn('[stage/tip] show total bump failed', { showId: show.id, reason: err?.message }));- const explorer = tipExplorerUrl(valid.signature, network);-// Notify the owner (in-app bell always; Telegram for a loud one).if (stage.owner_user_id) {insertNotification(stage.owner_user_id, 'stage_tip', {@@ -177,10 +227,11 @@ async function handleGet(req, res) {ORDER BY (ended_at IS NULL) DESC, started_at DESC LIMIT 1`;if (!show) return json(res, 200, { leaderboard: [], totalTipsAtomic: 0, tipCount: 0 });+ // Verified tips only: a quarantined row must never reach a public total.const rows = await sql`SELECT COALESCE(tipper_label, 'someone') AS label,SUM(amount_atomic)::numeric AS total, COUNT(*)::int AS count, MIN(created_at) AS first_at- FROM show_tips WHERE show_id = ${show.id}+ FROM show_tips WHERE show_id = ${show.id} AND verified_at IS NOT NULLGROUP BY COALESCE(tipper_label, 'someone')ORDER BY total DESC, first_at ASC LIMIT 10`;@@ -191,6 +242,23 @@ async function handleGet(req, res) {}, { 'cache-control': 'no-store' });}+// Mark a quarantined tip verified and roll it into the show total, exactly once.+// The conditional UPDATE is the guard: whoever flips verified_at from null owns+// the total bump, so the client retry and the sweep can both call this safely.+export async function promoteTip({ tipId, showId, amount }) {+ const [claimed] = await sql`+ UPDATE show_tips SET verified_at = now(), verify_error = NULL+ WHERE id = ${tipId} AND verified_at IS NULL+ RETURNING id+ `;+ if (!claimed) return false;+ await sql`+ UPDATE shows SET total_tips_atomic = total_tips_atomic + ${amount}, tip_count = tip_count + 1+ WHERE id = ${showId}+ `.catch((err) => console.warn('[stage/tip] show total bump failed', { showId, reason: err?.message }));+ return true;+}+function tipperLabel(session, tipperName) {if (session?.display_name) return cleanLabel(session.display_name);if (session?.email) return cleanLabel(session.email.split('@')[0]);diff --git a/docs/irl.md b/docs/irl.mdindex 6861c6323..2caa77cc2 100644--- a/docs/irl.md+++ b/docs/irl.md@@ -57,6 +57,16 @@ Tapping an agent opens its inspect card:- **leave a message** that lands in the owner's IRL feed- **view profile** to open its full agent page+A recorded pay has to prove itself. The client posts the settlement signature the+x402 receipt carried, and the server fetches that transaction before the row+becomes an earnings event: it must have succeeded and moved at least the amount+claimed, and when the agent has payout wallets on record (its paid-service payout+addresses, its custodial wallets) the transfer must have credited one of them. An+unprovable signature is refused with `402 settlement_unverified`. A settlement our+RPC has not caught up with yet is kept but inert (no owner notification, no ops+ping) until the `*/5` sweep in `api/cron/settlement-verify.js` proves it, or+deletes it after an hour of never appearing.+### Share a placementThe **Share** button captures your camera feed and the placed agent as one photo, then, if you're the one who placed the pin, turns it into a permanent link at `three.ws/irl/s/<token>` instead of a bare file. Paste that link into X, iMessage, or Discord and it unfurls as the actual photo, with a "Place your own agent" button back to /irl. The link never carries a coordinate: only the agent's name and caption (if any) ever appear on the card, and it only exists for pins you left public — unpublishing a pin, or a pin under moderation review, is never shareable. If you tap Share before placing anything (no pin yet), it falls back to the plain native share sheet / photo download, same as before.diff --git a/docs/stage.md b/docs/stage.mdindex 6b156ef90..6c21504d7 100644--- a/docs/stage.md+++ b/docs/stage.md@@ -88,10 +88,11 @@ The client transfers $THREE (6 decimals) directly to the host agent's wallet onThe endpoint ([`api/stage/tip.js`](../api/stage/tip.js)) then:1. **Validates before it trusts.** The settlement signature must match a real shape (a Solana base58 signature or an EVM transaction hash), the mint must be on the allow-list (`$THREE`, plus the stablecoin settlement mints the platform's existing pay path already accepts, all defined in [`api/_lib/stage-split.js`](../api/_lib/stage-split.js)), and the amount must be a positive safe integer in atomic units. No settlement proof, no row.-2. **Requires a live show.** A tip with no open show is refused with a 409 and an explanation, so a tip can never land outside a ledger.-3. **Deduplicates by signature.** A unique index on the settlement signature plus `ON CONFLICT DO NOTHING` is the idempotency guarantee: one settlement records exactly one tip, and a client retry gets the original row back with `deduped: true` rather than a double credit.-4. **Computes the accounting split.** The full amount already landed in the host wallet on-chain; the split records what is owed onward to the venue per the stage's policy. It is integer-only, and the venue cut is floored so the host absorbs the rounding remainder. The host credit and the venue cut always sum to exactly the original amount, which the unit suite asserts across a fuzz range. Value is never minted out of rounding.-5. **Pushes it to the room** over the signed internal bridge, so the host pre-empts its next beat and shouts the tipper out within about a second. This step is best-effort on purpose: the money already settled on-chain and is already recorded, so a missed push loses the in-room flourish, never funds.+2. **Proves the transfer on-chain.** Shape is not proof. [`api/_lib/settlement-verify.js`](../api/_lib/settlement-verify.js) fetches the referenced transaction and requires that it succeeded and credited one of the host agent's own payout wallets with at least the amount claimed. A signature that pays someone else, pays less, or does not exist is refused with `402 settlement_unverified` and records nothing. When our RPC simply has not caught up yet, the tip is kept but quarantined (`verified_at` null): it joins no total, no leaderboard, and no notification until it is proved, either by the client re-posting (the POST is idempotent, and the /stage client retries for a few seconds) or by the `*/5` sweep in [`api/cron/settlement-verify.js`](../api/cron/settlement-verify.js), which promotes what the chain confirms and deletes what never appears within an hour.+3. **Requires a live show.** A tip with no open show is refused with a 409 and an explanation, so a tip can never land outside a ledger.+4. **Deduplicates by signature.** A unique index on the settlement signature plus `ON CONFLICT DO NOTHING` is the idempotency guarantee: one settlement records exactly one tip, and a client retry gets the original row back with `deduped: true` rather than a double credit.+5. **Computes the accounting split.** The full amount already landed in the host wallet on-chain; the split records what is owed onward to the venue per the stage's policy. It is integer-only, and the venue cut is floored so the host absorbs the rounding remainder. The host credit and the venue cut always sum to exactly the original amount, which the unit suite asserts across a fuzz range. Value is never minted out of rounding.+6. **Pushes it to the room** over the signed internal bridge, so the host pre-empts its next beat and shouts the tipper out within about a second. This step is best-effort on purpose: the money already settled on-chain and is already recorded, so a missed push loses the in-room flourish, never funds.In the room, the tip is ranked, the leaderboard is resynced, the ticker broadcasts it with a block-explorer deep link, and a tip of 50,000 $THREE or more promotes that audience member to the VIP front row. A tip that takes the top spot is announced as a new top tipper.diff --git a/src/stage.js b/src/stage.jsindex c710918c7..67dca5af6 100644--- a/src/stage.js+++ b/src/stage.js@@ -370,22 +370,42 @@ class VenueController {onStage: (s) => this.tipStatus(tipStageLabel(s), 'warn'),});this.tipStatus('Recording your tip…', 'warn');- const res = await apiFetch('/api/stage/tip', {- method: 'POST',- allowAnonymous: true,- headers: { 'content-type': 'application/json' },- body: JSON.stringify({- stageId: this.stageId,- signature: settle.signature,- currencyMint: THREE_MINT,- amount: Math.round(amount * 10 ** THREE_DECIMALS),- message: msg,- network: 'solana',- tipperSession: this.net?.sessionId || null,- }),+ const body = JSON.stringify({+ stageId: this.stageId,+ signature: settle.signature,+ currencyMint: THREE_MINT,+ amount: Math.round(amount * 10 ** THREE_DECIMALS),+ message: msg,+ network: 'solana',+ tipperSession: this.net?.sessionId || null,});- const out = await res.json().catch(() => ({}));- if (!res.ok) throw new Error(out.error || 'could not record tip');+ const post = async () => {+ const res = await apiFetch('/api/stage/tip', {+ method: 'POST',+ allowAnonymous: true,+ headers: { 'content-type': 'application/json' },+ body,+ });+ const out = await res.json().catch(() => ({}));+ if (!res.ok) throw new Error(out.message || out.error || 'could not record tip');+ return out;+ };+ // The server verifies the transfer on-chain before the tip counts. Our+ // own RPC can lag the one that confirmed the transfer by a few seconds,+ // in which case it holds the tip and answers `pending`. The POST is+ // idempotent, so re-posting is the retry: the tip lands the moment the+ // chain shows it.+ let out = await post();+ for (let attempt = 0; out.pending && attempt < 4; attempt++) {+ this.tipStatus('Confirming on-chain…', 'warn');+ await new Promise((r) => setTimeout(r, 3000));+ out = await post();+ }+ if (out.pending) {+ this.tipStatus('Sent. It will appear on the leaderboard once the network confirms it.', 'warn');+ this.els.tipMsg.value = '';+ return;+ }this.tipStatus(`Tipped ${amount.toLocaleString()} $THREE 🎉`, 'ok');this.els.tipMsg.value = '';} catch (err) {diff --git a/tests/settlement-verify.test.js b/tests/settlement-verify.test.jsnew file mode 100644index 000000000..0caa96225--- /dev/null+++ b/tests/settlement-verify.test.js@@ -0,0 +1,78 @@+// Settlement verification (security review M4): a stage tip and an IRL pay are+// recorded from a client-supplied signature, so the signature has to prove+// itself. Before this, only its SHAPE was checked, which meant a well-formed but+// unrelated signature with a huge amount bought the top of a stage leaderboard.+//+// These cases cover every branch that decides an outcome WITHOUT touching an RPC:+// the shape gate, the chain/asset agreement, the amount gate, and the+// no-known-destination rule. The on-chain paths are exercised against the live+// chains by the sweep, not mocked into a fake "verified" here.++import { describe, it, expect } from 'vitest';+import { verifySettlement, USDC_BASE, THREE_MINT } from '../api/_lib/settlement-verify.js';++const SOL_SIG = '5'.repeat(64); // base58, in the 43-88 char signature range+const EVM_TX = `0x${'a'.repeat(64)}`;+const SOL_WALLET = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+const EVM_WALLET = `0x${'b'.repeat(40)}`;++describe('verifySettlement: rejects before it ever asks a chain', () => {+ it('rejects a signature that is neither a Solana sig nor an EVM tx hash', async () => {+ const r = await verifySettlement({+ signature: 'not-a-signature', mint: THREE_MINT, amountAtomic: 1n, recipients: [SOL_WALLET],+ });+ expect(r.status).toBe('mismatch');+ expect(r.reason).toMatch(/settlement signature/i);+ });++ it('rejects an empty signature', async () => {+ const r = await verifySettlement({ signature: '', mint: THREE_MINT, amountAtomic: 1n, recipients: [SOL_WALLET] });+ expect(r.status).toBe('mismatch');+ });++ it('rejects a non-positive amount', async () => {+ const r = await verifySettlement({ signature: SOL_SIG, mint: THREE_MINT, amountAtomic: 0n, recipients: [SOL_WALLET] });+ expect(r.status).toBe('mismatch');+ expect(r.reason).toMatch(/positive/i);+ });++ it('rejects a non-integer amount', async () => {+ const r = await verifySettlement({ signature: SOL_SIG, mint: THREE_MINT, amountAtomic: 1.5, recipients: [SOL_WALLET] });+ expect(r.status).toBe('mismatch');+ expect(r.reason).toMatch(/atomic units/i);+ });++ it('refuses to settle an EVM asset with a Solana signature', async () => {+ const r = await verifySettlement({ signature: SOL_SIG, mint: USDC_BASE, amountAtomic: 1n, recipients: [EVM_WALLET] });+ expect(r.status).toBe('mismatch');+ expect(r.reason).toMatch(/cannot settle an EVM asset/i);+ });++ it('refuses to settle a Solana asset with an EVM tx hash', async () => {+ const r = await verifySettlement({ signature: EVM_TX, mint: THREE_MINT, amountAtomic: 1n, recipients: [EVM_WALLET] });+ expect(r.status).toBe('mismatch');+ expect(r.reason).toMatch(/only settle USDC on Base/i);+ });++ it('refuses to verify against an agent with no payout wallet on record', async () => {+ const r = await verifySettlement({ signature: SOL_SIG, mint: THREE_MINT, amountAtomic: 1n, recipients: [] });+ expect(r.status).toBe('mismatch');+ expect(r.reason).toMatch(/no payout wallet/i);+ });++ it('does not fall back to any-recipient unless the caller opted in', async () => {+ const strict = await verifySettlement({ signature: SOL_SIG, mint: THREE_MINT, amountAtomic: 1n, recipients: [null, ''] });+ expect(strict.status).toBe('mismatch');+ expect(strict.reason).toMatch(/no payout wallet/i);+ });++ it('ignores blank recipients when deciding whether a destination is known', async () => {+ const r = await verifySettlement({+ signature: 'still-not-a-signature', mint: THREE_MINT, amountAtomic: 1n,+ recipients: ['', null, undefined], allowAnyRecipient: true,+ });+ // Opted in, so the missing destination is not the objection: the shape is.+ expect(r.status).toBe('mismatch');+ expect(r.reason).toMatch(/settlement signature/i);+ });+});diff --git a/vercel.json b/vercel.jsonindex 31ed8c7de..56ea44f8c 100644--- a/vercel.json+++ b/vercel.json@@ -5654,6 +5654,10 @@"path": "/api/cron/irl-reap","schedule": "17 * * * *"},+ {+ "path": "/api/cron/settlement-verify",+ "schedule": "*/5 * * * *"+ },{"path": "/api/cron/expire-pending-purchases","schedule": "*/5 * * * *"