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.

feat: implement full audit trail and breach monitoring for economy funding wallet

nirholas28cd869794eb
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bc0e2e198..ca59c74d5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,10 @@
Public history for [three.ws](https://three.ws), newest first. New pages come from `added` dates in data/pages.json; everything else is curated in data/changelog.json. Also available as [JSON](https://three.ws/changelog.json) and [RSS](https://three.ws/changelog.xml), live at [three.ws/changelog](https://three.ws/changelog).
+## 2026-07-03
+
+- **Full audit trail + breach monitoring on the economy's funding wallet** — The master wallet that fuels the platform's autonomous economy now keeps a tamper-evident accounting book of every move it makes. Each SOL transfer is recorded with the engine it funded, the amount, the on-chain signature, the running balance, and the US-dollar value at the moment of the transfer — cryptographically hash-chained so no past entry can be altered or deleted without detection. A monitor runs every 30 minutes and checks three things: that the book hasn't been tampered with, that every transfer we recorded really happened on-chain, and — most importantly — that no SOL ever left the wallet without a matching record, which is the tell-tale sign of a stolen key. Anything off raises an immediate operator alert and lands on the finance-integrity board. There's also a one-command accounting export (CSV or JSON, with running balance and dollar totals) for bookkeeping and review. `[security, infra, docs]`
+
## 2026-07-02
- **Agent wallet creation and vanity addresses restored** — Creating an agent's custodial Solana wallet — including grinding a custom vanity address — was failing with a server error. The platform's dedicated at-rest encryption key had gone missing from the production environment, and the wallet layer correctly refuses to encrypt a new custodial key without it rather than fall back to a weaker key. The key is restored, and the encryption layer now also keeps wallets written under the older key readable after a key change, so wallet creation, vanity addresses, and withdrawals all work again. No funds were ever at risk or moved. (`/vanity-wallet`) `[fix, security]`
diff --git a/STRUCTURE.md b/STRUCTURE.md
index 594ba3650..16496d5d5 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -41,6 +41,7 @@ bottom.
| SNS naming + pay-by-name | [api/sns.js](api/sns.js), [api/sns-subdomain.js](api/sns-subdomain.js), [api/threews/subdomain.js](api/threews/subdomain.js), [api/x402/pay-by-name.js](api/x402/pay-by-name.js), [src/solana/sns-subdomain.js](src/solana/sns-subdomain.js), [pages/threews-claim.html](pages/threews-claim.html) | In-repo | `*.threews.sol` subdomain mint, x402 payments addressed by name. Env: `THREEWS_SOL_PARENT_SECRET_BASE58`. See [SNS_PARTNERSHIP_PROPOSAL.md](docs/internal/SNS_PARTNERSHIP_PROPOSAL.md) |
| Self-hosted x402 facilitator + ring economy | [api/x402-facilitator/[action].js](api/x402-facilitator/[action].js), [api/_lib/x402/self-facilitator.js](api/_lib/x402/self-facilitator.js), [api/x402/ring-settle.js](api/x402/ring-settle.js), [api/_lib/x402/pipelines/ring-rebalance.js](api/_lib/x402/pipelines/ring-rebalance.js), [api/x402-ring.js](api/x402-ring.js), [scripts/x402-ring-setup.mjs](scripts/x402-ring-setup.mjs) | In-repo (off by default) | Closed-loop agent-to-agent x402: platform wallets pay platform endpoints, settled in-house (no external facilitator). Fee-minimized, SOL-floor guarded, internal-labeled. Env: `X402_SELF_FACILITATOR_ENABLED`, `X402_FEE_PAYER_SECRET_BASE58`, `X402_TREASURY_SECRET_BASE58`. See [docs/x402-ring-economy.md](docs/x402-ring-economy.md) |
| Economy funding root (master wallet) | [api/_lib/economy-master.js](api/_lib/economy-master.js), cron [api/cron/treasury-topup.js](api/cron/treasury-topup.js), registry [api/_lib/solana-signers.js](api/_lib/solana-signers.js) | In-repo (inert until keyed) | One master wallet (`WwwuGbq…T3WwW`, `ECONOMY_MASTER_SECRET_BASE58`) auto-tops-up every other Solana engine below its floor. Funder-only — never trades/settles; reserve/per-engine/per-run guarded; allowlisted to registry wallets; fee-minimized. See [docs/economy-master.md](docs/economy-master.md) + [SOLANA-SIGNERS.md](tasks/onchain-deployment/SOLANA-SIGNERS.md) |
+| Economy master audit ledger + breach monitor | ledger [api/_lib/economy-ledger.js](api/_lib/economy-ledger.js) ([schema](api/_lib/migrations/20260702010000_economy_master_ledger.sql)), reconcile cron [api/cron/economy-reconcile.js](api/cron/economy-reconcile.js), export [scripts/economy-ledger-export.mjs](scripts/economy-ledger-export.mjs) | In-repo | Tamper-evident (SHA-256 hash-chained) accounting book of every SOL movement from the master, with running balance + USD-at-transfer-time. The reconcile cron checks it every 30 min for tamper, unrecorded on-chain outbound (breach/key-compromise), and on-chain integrity; findings land in `payment_reconciliation`. Accounting CSV/JSON export. See [docs/economy-master.md](docs/economy-master.md#audit-accounting--breach-monitoring) |
## npm workspaces
diff --git a/api/_lib/migrations/20260702100000_treasury_ledger.sql b/api/_lib/migrations/20260702100000_treasury_ledger.sql
deleted file mode 100644
index 09d3c6baa..000000000
--- a/api/_lib/migrations/20260702100000_treasury_ledger.sql
+++ /dev/null
@@ -1,65 +0,0 @@
--- Treasury Ledger — the durable, append-only accounting + audit record for every
--- SOL movement the economy master wallet (api/_lib/economy-master.js) makes.
---
--- WHY: the treasury-topup cron auto-refills engine signers from the ONE master
--- (Www…WwW). That moves real money on a schedule. Telegram alerts + an ephemeral
--- HTTP response are not an accounting record: you cannot reconcile a month, prove
--- to a regulator/auditor where funds went, or detect a breach after the fact.
--- This table is that record — one row per transfer/skip/reject, plus a `summary`
--- row per sweep carrying the before/after master balance, the caps in force, the
--- reconciliation result, and a tamper-evident hash chain over the summary rows.
---
--- Ground truth is still the chain: every `transfer` row carries the on-chain
--- `tx_signature`, independently verifiable on Solscan forever. This table is the
--- queryable index over that truth plus the off-chain context (which run, which
--- caps, which reconciliation) the chain does not hold.
---
--- APPEND-ONLY: our code only ever INSERTs. Rows are never updated. The
--- prev_hash/row_hash chain over `summary` rows makes any retroactive edit or
--- deletion detectable (a broken link). Consumers: api/cron/treasury-topup.js
--- (writer), api/ops/treasury-ledger.js (owner/accounting reader + CSV export).
-
-create table if not exists treasury_ledger (
- id bigserial primary key,
- ts timestamptz not null default now(),
- -- Groups every row emitted by one sweep run.
- sweep_id uuid not null,
- -- Monotonic sweep counter; orders the hash chain deterministically.
- seq bigint not null default 0,
- -- 'transfer' | 'skip' | 'reject' | 'summary'
- kind text not null,
- master text not null,
- network text not null default 'mainnet',
- -- Line rows (transfer/skip/reject): which engine and how much.
- engine_name text,
- engine_pubkey text,
- amount_lamports bigint,
- amount_sol numeric(20,9),
- -- funded | failed | rejected | skipped | ok | breach
- status text not null,
- reason text,
- tx_signature text,
- -- Summary rows only: the run's balances, caps, and reconciliation.
- master_sol_before numeric(20,9),
- master_sol_after numeric(20,9),
- spent_sol numeric(20,9),
- reserve_sol numeric(20,9),
- per_topup_max_sol numeric(20,9),
- run_cap_sol numeric(20,9),
- expected_after_sol numeric(20,9),
- -- Breach signal: SOL that left the master beyond what this cron sent (fees
- -- excluded). Non-zero means the master key moved funds out of band.
- unexplained_sol numeric(20,9),
- breach boolean not null default false,
- -- Provenance: the deployed commit that produced this row.
- git_sha text,
- -- Tamper-evident chain over summary rows (sha256(prev_hash || canonical row)).
- prev_hash text,
- row_hash text,
- meta jsonb not null default '{}'::jsonb
-);
-
-create index if not exists treasury_ledger_ts on treasury_ledger (ts desc);
-create index if not exists treasury_ledger_sweep on treasury_ledger (sweep_id);
-create index if not exists treasury_ledger_engine on treasury_ledger (engine_name, ts desc);
-create index if not exists treasury_ledger_breach on treasury_ledger (breach) where breach = true;
diff --git a/api/_lib/treasury-ledger.js b/api/_lib/treasury-ledger.js
deleted file mode 100644
index 28179ca30..000000000
--- a/api/_lib/treasury-ledger.js
+++ /dev/null
@@ -1,417 +0,0 @@
-// @ts-check
-// api/_lib/treasury-ledger.js
-//
-// Durable accounting + audit trail for the economy master wallet's SOL movements.
-// The treasury-topup cron calls recordSweep() after every sweep; this module
-// persists one row per transfer/skip/reject plus a `summary` row per run into the
-// append-only treasury_ledger table (migration 20260702100000_treasury_ledger.sql),
-// computes the reconciliation, flags breaches, and chains the summary rows with a
-// tamper-evident hash so a retroactive edit or deletion is detectable.
-//
-// Ground truth is the chain: every transfer row carries its on-chain signature.
-// This table is the queryable index + the off-chain context (run, caps, balances)
-// an auditor needs and the blockchain does not hold.
-//
-// Nothing here ever throws into the cron's money path: a DB failure degrades to a
-// logged warning, never a lost or double transfer (the transfers already landed
-// on-chain before we record them).
-
-import { createHash } from 'node:crypto';
-import { sql } from './db.js';
-
-const LAMPORTS_PER_SOL = 1_000_000_000;
-
-// Per-transfer fee headroom used by reconciliation. A System transfer with the
-// priority fee sendSol sets costs ~5k lamports base + a few hundred priority;
-// 0.00002 SOL (20k lamports) is a generous ceiling that never false-positives a
-// breach on ordinary fees while still catching any real out-of-band outflow.
-const PER_TX_FEE_SOL = 0.00002;
-// Reconciliation slack for rounding/RPC balance jitter (lamport-scale).
-const RECONCILE_EPSILON_SOL = 0.00001;
-
-function round(n) {
- return Math.round(Number(n) * 1e9) / 1e9;
-}
-
-/**
- * Belt-and-suspenders: create the ledger table if the migration hasn't run yet,
- * so the writer works on a fresh environment. Mirrors the pattern other
- * autonomous pipelines use. Safe to call on every sweep (idempotent DDL).
- */
-export async function ensureLedgerTable() {
- await sql`
- create table if not exists treasury_ledger (
- id bigserial primary key,
- ts timestamptz not null default now(),
- sweep_id uuid not null,
- seq bigint not null default 0,
- kind text not null,
- master text not null,
- network text not null default 'mainnet',
- engine_name text,
- engine_pubkey text,
- amount_lamports bigint,
- amount_sol numeric(20,9),
- status text not null,
- reason text,
- tx_signature text,
- master_sol_before numeric(20,9),
- master_sol_after numeric(20,9),
- spent_sol numeric(20,9),
- reserve_sol numeric(20,9),
- per_topup_max_sol numeric(20,9),
- run_cap_sol numeric(20,9),
- expected_after_sol numeric(20,9),
- unexplained_sol numeric(20,9),
- breach boolean not null default false,
- git_sha text,
- prev_hash text,
- row_hash text,
- meta jsonb not null default '{}'::jsonb
- )
- `;
- await sql`create index if not exists treasury_ledger_ts on treasury_ledger (ts desc)`;
- await sql`create index if not exists treasury_ledger_sweep on treasury_ledger (sweep_id)`;
- await sql`create index if not exists treasury_ledger_engine on treasury_ledger (engine_name, ts desc)`;
-}
-
-/**
- * Reconcile a sweep against on-chain reality. PURE — no I/O — so the breach logic
- * is unit-tested exhaustively.
- *
- * Two independent breach signals, both meaning "the master lost SOL this cron did
- * NOT send" (i.e. the key was used out of band — the exact regulatory/compromise
- * condition to catch):
- * • unexplained — within this run: (before − after) exceeded our sends + fees.
- * • interRunDrop — between runs: this run started below where the last run ended
- * (the master can only gain between runs via a deposit; a drop
- * is unaccounted outflow).
- *
- * @param {object} p
- * @param {number} p.masterBefore master SOL at sweep start
- * @param {number} p.masterAfter master SOL after the transfers landed
- * @param {number} p.spentSol SOL this sweep actually transferred out
- * @param {number} p.fundedCount number of transfers (for the fee allowance)
- * @param {number|null} [p.prevAfter] previous sweep's recorded master_sol_after
- * @returns {{ expectedAfterSol:number, unexplainedSol:number, interRunDropSol:number, breach:boolean, reasons:string[] }}
- */
-export function reconcile({ masterBefore, masterAfter, spentSol, fundedCount, prevAfter = null }) {
- const feeAllowance = Math.max(0, fundedCount) * PER_TX_FEE_SOL;
- const expectedAfterSol = round(masterBefore - spentSol - feeAllowance);
-
- // Positive = more SOL left than we sent (+fees). Negative = the master gained
- // mid-sweep (a deposit) — never a breach.
- const observedOutflow = masterBefore - masterAfter;
- const unexplainedSol = round(Math.max(0, observedOutflow - spentSol - feeAllowance - RECONCILE_EPSILON_SOL));
-
- let interRunDropSol = 0;
- if (prevAfter != null && Number.isFinite(prevAfter)) {
- interRunDropSol = round(Math.max(0, prevAfter - masterBefore - RECONCILE_EPSILON_SOL));
- }
-
- const reasons = [];
- if (unexplainedSol > 0) reasons.push('unexplained_outflow');
- if (interRunDropSol > 0) reasons.push('inter_run_drop');
-
- return { expectedAfterSol, unexplainedSol, interRunDropSol, breach: reasons.length > 0, reasons };
-}
-
-/**
- * Canonical, order-stable serialization of a summary row's material fields.
- * Feeds the hash chain — must be deterministic and cover everything an auditor
- * would care was not altered (balances, caps, and every transfer's amount+sig).
- * @param {object} s
- * @returns {string}
- */
-export function canonicalSummary(s) {
- const transfers = (s.transfers || []).map((t) => [t.name, t.pubkey, t.amountLamports, t.signature, t.status]);
- return JSON.stringify([
- s.sweepId,
- s.seq,
- s.master,
- s.network,
- round(s.masterBefore),
- round(s.masterAfter),
- round(s.spentSol),
- round(s.reserveSol),
- round(s.perTopupMaxSol),
- round(s.runCapSol),
- round(s.expectedAfterSol),
- round(s.unexplainedSol),
- !!s.breach,
- s.gitSha || null,
- transfers,
- ]);
-}
-
-/** sha256(prevHash || canonical) as hex — the tamper-evident link. */
-export function hashRow(prevHash, canonical) {
- return createHash('sha256').update(String(prevHash || '')).update('\n').update(canonical).digest('hex');
-}
-
-/**
- * Persist one sweep: every transfer/skip/reject line + a chained summary row.
- * Never throws into the caller — a DB error is logged and swallowed (the money
- * already moved on-chain; losing the record is bad, but must not trigger a retry
- * that could double-send). Returns the summary's audit fields for alerting.
- *
- * @param {object} p
- * @param {string} p.sweepId uuid grouping this run's rows
- * @param {string} p.master master pubkey (base58)
- * @param {'mainnet'|'devnet'} p.network
- * @param {number} p.masterBefore
- * @param {number} p.masterAfter
- * @param {number} p.spentSol
- * @param {number} p.reserveSol
- * @param {number} p.perTopupMaxSol
- * @param {number} p.runCapSol
- * @param {Array<{name:string,pubkey:string,sol:number,signature:string}>} p.funded
- * @param {Array<{name:string,pubkey:string,sol:number,reason:string}>} p.failed
- * @param {Array<{name:string,reason:string}>} p.skipped
- * @param {Array<{name:string,pubkey:string,reason:string}>} p.rejected
- * @returns {Promise<{ ok:boolean, sweepId:string, breach:boolean, unexplainedSol:number, interRunDropSol:number, reasons:string[], seq:number, rowHash:string|null }>}
- */
-export async function recordSweep(p) {
- const gitSha = process.env.VERCEL_GIT_COMMIT_SHA || null;
- const funded = p.funded || [];
- const failed = p.failed || [];
- const skipped = p.skipped || [];
- const rejected = p.rejected || [];
-
- // Previous summary → seq + prev_hash (the chain head). One cron instance runs
- // at a time, so this read-then-write is not racy in practice.
- let prevSeq = 0;
- let prevHash = '';
- let prevAfter = null;
- try {
- const [prev] = await sql`
- select seq, row_hash, master_sol_after
- from treasury_ledger
- where kind = 'summary' and master = ${p.master}
- order by seq desc, id desc
- limit 1
- `;
- if (prev) {
- prevSeq = Number(prev.seq) || 0;
- prevHash = prev.row_hash || '';
- prevAfter = prev.master_sol_after != null ? Number(prev.master_sol_after) : null;
- }
- } catch {
- /* first-ever sweep, or table absent until ensureLedgerTable ran */
- }
- const seq = prevSeq + 1;
-
- const rec = reconcile({
- masterBefore: p.masterBefore,
- masterAfter: p.masterAfter,
- spentSol: p.spentSol,
- fundedCount: funded.length,
- prevAfter,
- });
-
- const transfers = funded.map((f) => ({
- name: f.name,
- pubkey: f.pubkey,
- amountLamports: Math.round(f.sol * LAMPORTS_PER_SOL),
- signature: f.signature,
- status: 'funded',
- }));
- const rowHash = hashRow(
- prevHash,
- canonicalSummary({
- sweepId: p.sweepId,
- seq,
- master: p.master,
- network: p.network,
- masterBefore: p.masterBefore,
- masterAfter: p.masterAfter,
- spentSol: p.spentSol,
- reserveSol: p.reserveSol,
- perTopupMaxSol: p.perTopupMaxSol,
- runCapSol: p.runCapSol,
- expectedAfterSol: rec.expectedAfterSol,
- unexplainedSol: rec.unexplainedSol,
- breach: rec.breach,
- gitSha,
- transfers,
- }),
- );
-
- try {
- // Line rows: transfers, then failed, then rejected, then skipped.
- for (const f of funded) {
- await sql`
- insert into treasury_ledger
- (sweep_id, seq, kind, master, network, engine_name, engine_pubkey, amount_lamports, amount_sol, status, tx_signature, git_sha)
- values (${p.sweepId}, ${seq}, 'transfer', ${p.master}, ${p.network}, ${f.name}, ${f.pubkey},
- ${Math.round(f.sol * LAMPORTS_PER_SOL)}, ${round(f.sol)}, 'funded', ${f.signature}, ${gitSha})
- `;
- }
- for (const f of failed) {
- await sql`
- insert into treasury_ledger
- (sweep_id, seq, kind, master, network, engine_name, engine_pubkey, amount_lamports, amount_sol, status, reason, git_sha)
- values (${p.sweepId}, ${seq}, 'transfer', ${p.master}, ${p.network}, ${f.name}, ${f.pubkey},
- ${Math.round((f.sol || 0) * LAMPORTS_PER_SOL)}, ${round(f.sol || 0)}, 'failed', ${f.reason || 'send_failed'}, ${gitSha})
- `;
- }
- for (const r of rejected) {
- await sql`
- insert into treasury_ledger
- (sweep_id, seq, kind, master, network, engine_name, engine_pubkey, status, reason, git_sha)
- values (${p.sweepId}, ${seq}, 'reject', ${p.master}, ${p.network}, ${r.name}, ${r.pubkey}, 'rejected', ${r.reason}, ${gitSha})
- `;
- }
- for (const s of skipped) {
- await sql`
- insert into treasury_ledger
- (sweep_id, seq, kind, master, network, engine_name, status, reason, git_sha)
- values (${p.sweepId}, ${seq}, 'skip', ${p.master}, ${p.network}, ${s.name}, 'skipped', ${s.reason}, ${gitSha})
- `;
- }
- // Summary row (chained) last, so its hash can cover the transfers above.
- await sql`
- insert into treasury_ledger
- (sweep_id, seq, kind, master, network, status, reason,
- master_sol_before, master_sol_after, spent_sol, reserve_sol, per_topup_max_sol, run_cap_sol,
- expected_after_sol, unexplained_sol, breach, git_sha, prev_hash, row_hash, meta)
- values (${p.sweepId}, ${seq}, 'summary', ${p.master}, ${p.network},
- ${rec.breach ? 'breach' : 'ok'}, ${rec.reasons.join(',') || null},
- ${round(p.masterBefore)}, ${round(p.masterAfter)}, ${round(p.spentSol)},
- ${round(p.reserveSol)}, ${round(p.perTopupMaxSol)}, ${round(p.runCapSol)},
- ${rec.expectedAfterSol}, ${rec.unexplainedSol}, ${rec.breach}, ${gitSha}, ${prevHash || null}, ${rowHash},
- ${JSON.stringify({ interRunDropSol: rec.interRunDropSol, funded: funded.length, failed: failed.length, skipped: skipped.length, rejected: rejected.length })}::jsonb)
- `;
- } catch (e) {
- console.warn('[treasury-ledger] persist failed:', e?.message || e);
- return { ok: false, sweepId: p.sweepId, breach: rec.breach, unexplainedSol: rec.unexplainedSol, interRunDropSol: rec.interRunDropSol, reasons: rec.reasons, seq, rowHash: null };
- }
-
- return { ok: true, sweepId: p.sweepId, breach: rec.breach, unexplainedSol: rec.unexplainedSol, interRunDropSol: rec.interRunDropSol, reasons: rec.reasons, seq, rowHash };
-}
-
-/**
- * Read recent ledger rows for the owner/accounting endpoint. Cursor by id
- * (descending, strictly-less-than) for stable pagination.
- * @param {object} [opts]
- * @param {number} [opts.limit]
- * @param {number|null} [opts.beforeId]
- * @param {string|null} [opts.engine] filter to one engine_name
- * @param {boolean} [opts.breachOnly]
- * @param {string|null} [opts.kind] e.g. 'transfer' | 'summary'
- * @returns {Promise<Array<object>>}
- */
-export async function getLedger({ limit = 100, beforeId = null, engine = null, breachOnly = false, kind = null } = {}) {
- const lim = Math.min(1000, Math.max(1, Number(limit) || 100));
- const rows = await sql`
- select * from treasury_ledger
- where (${beforeId}::bigint is null or id < ${beforeId})
- and (${engine}::text is null or engine_name = ${engine})
- and (${kind}::text is null or kind = ${kind})
- and (${breachOnly} = false or breach = true)
- order by id desc
- limit ${lim}
- `;
- return rows;
-}
-
-/**
- * Accounting rollup since a timestamp: total moved, per-engine totals, breach
- * count. Reads only `transfer`/`summary` rows.
- * @param {object} [opts]
- * @param {string|null} [opts.since] ISO timestamp; null = all time
- * @returns {Promise<{ since:string|null, total_sol:number, transfers:number, breaches:number, per_engine:Array<{engine:string,sol:number,count:number}> }>}
- */
-export async function reconcileTotals({ since = null } = {}) {
- const [tot] = await sql`
- select
- coalesce(sum(amount_sol) filter (where kind = 'transfer' and status = 'funded'), 0)::float8 as total_sol,
- count(*) filter (where kind = 'transfer' and status = 'funded') as transfers,
- count(*) filter (where kind = 'summary' and breach = true) as breaches
- from treasury_ledger
- where (${since}::timestamptz is null or ts >= ${since})
- `;
- const perEngine = await sql`
- select engine_name as engine,
- coalesce(sum(amount_sol), 0)::float8 as sol,
- count(*) as count
- from treasury_ledger
- where kind = 'transfer' and status = 'funded'
- and (${since}::timestamptz is null or ts >= ${since})
- group by engine_name
- order by sol desc
- `;
- return {
- since,
- total_sol: round(tot?.total_sol || 0),
- transfers: Number(tot?.transfers || 0),
- breaches: Number(tot?.breaches || 0),
- per_engine: perEngine.map((r) => ({ engine: r.engine, sol: round(r.sol), count: Number(r.count) })),
- };
-}
-
-/**
- * Re-derive the summary hash chain and report the first broken link, if any —
- * the tamper check for the audit endpoint. Verifies both each row's own hash and
- * that each links to its predecessor.
- * @param {number} [limit] most recent N summaries to verify
- * @returns {Promise<{ ok:boolean, checked:number, brokenAt:number|null, reason:string|null }>}
- */
-export async function verifyChain(limit = 500) {
- const rows = await sql`
- select sweep_id, seq, master, network, master_sol_before, master_sol_after, spent_sol,
- reserve_sol, per_topup_max_sol, run_cap_sol, expected_after_sol, unexplained_sol,
- breach, git_sha, prev_hash, row_hash
- from treasury_ledger
- where kind = 'summary'
- order by seq asc
- limit ${Math.min(5000, Math.max(1, limit))}
- `;
- let prevHash = '';
- let checked = 0;
- for (const r of rows) {
- // Rebuild the transfer list this summary covered from its line rows.
- const lines = await sql`
- select engine_name, engine_pubkey, amount_lamports, tx_signature, status
- from treasury_ledger
- where sweep_id = ${r.sweep_id} and kind = 'transfer' and status = 'funded'
- order by id asc
- `;
- const transfers = lines.map((l) => ({
- name: l.engine_name,
- pubkey: l.engine_pubkey,
- amountLamports: l.amount_lamports != null ? Number(l.amount_lamports) : null,
- signature: l.tx_signature,
- status: 'funded',
- }));
- const canonical = canonicalSummary({
- sweepId: r.sweep_id,
- seq: Number(r.seq),
- master: r.master,
- network: r.network,
- masterBefore: Number(r.master_sol_before),
- masterAfter: Number(r.master_sol_after),
- spentSol: Number(r.spent_sol),
- reserveSol: Number(r.reserve_sol),
- perTopupMaxSol: Number(r.per_topup_max_sol),
- runCapSol: Number(r.run_cap_sol),
- expectedAfterSol: Number(r.expected_after_sol),
- unexplainedSol: Number(r.unexplained_sol),
- breach: r.breach,
- gitSha: r.git_sha,
- transfers,
- });
- const expected = hashRow(prevHash, canonical);
- if ((r.prev_hash || '') !== (prevHash || '')) {
- return { ok: false, checked, brokenAt: Number(r.seq), reason: 'prev_hash_mismatch' };
- }
- if (r.row_hash !== expected) {
- return { ok: false, checked, brokenAt: Number(r.seq), reason: 'row_hash_mismatch' };
- }
- prevHash = r.row_hash;
- checked++;
- }
- return { ok: true, checked, brokenAt: null, reason: null };
-}
-
-export { LAMPORTS_PER_SOL, PER_TX_FEE_SOL, RECONCILE_EPSILON_SOL };
diff --git a/api/_lib/x402/revenue-reconciliation.js b/api/_lib/x402/revenue-reconciliation.js
index 38564fb04..4bc184c94 100644
--- a/api/_lib/x402/revenue-reconciliation.js
+++ b/api/_lib/x402/revenue-reconciliation.js
@@ -41,6 +41,7 @@ import { randomUUID } from 'node:crypto';
import { sql } from '../db.js';
import { env } from '../env.js';
import { logger } from '../usage.js';
+import { sendOpsAlert } from '../alerts.js';
import { solanaConnection } from '../solana/connection.js';
import {
payX402, bootstrapSolanaContext, fetchWithTimeout,
@@ -371,6 +372,27 @@ export async function run(ctx = {}) {
// lives in payment_reconciliation.
summary.flagged_sample = flagged.slice(0, 20);
+ // Page ops on any settlement whose books disagree with the chain. "Recorded
+ // revenue ≠ on-chain reality" is the single most regulatory-relevant signal a
+ // financial ledger can produce, and until now it was written to
+ // payment_reconciliation and never surfaced. Best-effort; the signature keys on
+ // the discrepancy counts so a stable state de-dupes (1/hr) while any change or a
+ // worsening count always re-fires. Never blocks the run.
+ if (summary.discrepancies > 0) {
+ const { missing_onchain, failed_onchain, missing_signature } = summary;
+ await sendOpsAlert(
+ `x402 reconciliation: ${summary.discrepancies} discrepanc${summary.discrepancies === 1 ? 'y' : 'ies'} of ${summary.checked} settlements`,
+ [
+ `missing_onchain=${missing_onchain} — DB marked settled but no tx on-chain`,
+ `failed_onchain=${failed_onchain} — on-chain tx reverted`,
+ `missing_signature=${missing_signature} — settled row carries no tx signature`,
+ `sample: ${flagged.slice(0, 5).map((f) => `${f.source}:${f.ref}[${f.status}]`).join(', ') || '—'}`,
+ `full set: SELECT * FROM payment_reconciliation WHERE reconciled = false`,
+ ].join('\n'),
+ { signature: `reconcile-discrepancy:${missing_onchain}:${failed_onchain}:${missing_signature}` },
+ ).catch(() => {});
+ }
+
const durationMs = Date.now() - t0;
const success = statusOk || records.length > 0;
const errorMsg = success ? null : (statusErr || 'reconcile_no_data');
diff --git a/api/cron/economy-reconcile.js b/api/cron/economy-reconcile.js
new file mode 100644
index 000000000..d593d2f87
--- /dev/null
+++ b/api/cron/economy-reconcile.js
@@ -0,0 +1,282 @@
+// @ts-check
+// GET /api/cron/economy-reconcile — financial-integrity + breach monitor for the
+// economy master funding wallet (api/_lib/economy-master.js).
+//
+// Runs every 30 min and answers three questions a regulator, an accountant, and
+// an incident responder each ask:
+//
+// 1. TAMPER — is the accounting ledger intact? verifyChain() recomputes the
+// hash chain; a broken link or a seq gap means a historical row was edited
+// or deleted. → CRITICAL alert.
+// 2. BREACH — did any SOL leave the master that our books did NOT record? It
+// pulls the master's real on-chain transaction history and flags every
+// outbound debit whose signature is absent from the ledger. An unrecorded
+// outbound is the key-compromise signal: someone moved funds outside our
+// system. → CRITICAL alert.
+// 3. INTEGRITY — does every transfer our books CLAIM actually exist on-chain
+// and succeed? Missing/failed signatures mean a fabricated or lost record.
+//
+// Every non-reconciled finding is upserted into the shared `payment_reconciliation`
+// table (source `economy_master_*`), so it surfaces on the existing ops
+// financial-integrity board alongside x402 revenue discrepancies. Read-only
+// on-chain — it never moves funds.
+
+import { error, json, method, wrapCron } from '../_lib/http.js';
+import { env } from '../_lib/env.js';
+import { constantTimeEquals } from '../_lib/crypto.js';
+import { sendOpsAlert } from '../_lib/alerts.js';
+import { withDbRetry } from '../_lib/db-retry.js';
+import { sql } from '../_lib/db.js';
+import { ECONOMY_MASTER_ADDRESS, RESERVE_SOL } from '../_lib/economy-master.js';
+import { verifyChain } from '../_lib/economy-ledger.js';
+import { getSolBalance } from '../_lib/avatar-wallet.js';
+
+// How many recent on-chain signatures to scan per run, and how far back to
+// re-verify our own recorded transfers. A low-activity funder makes both cheap.
+const SIG_SCAN_LIMIT = 200;
+const LEDGER_VERIFY_WINDOW_HOURS = 72;
+// Net debit below this (SOL) on an unrecorded tx is treated as fee noise, not a
+// drain — a real unauthorized transfer moves far more than a signature fee.
+const OUTBOUND_FEE_FLOOR_SOL = 0.0005;
+const LAMPORTS_PER_SOL = 1_000_000_000;
+
+function requireCron(req, res) {
+ const secret = process.env.CRON_SECRET || env.CRON_SECRET;
+ if (!secret) {
+ error(res, 503, 'not_configured', 'CRON_SECRET unset');
+ return false;
+ }
+ const auth = req.headers['authorization'] || '';
+ const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';
+ if (!constantTimeEquals(presented, secret)) {
+ error(res, 401, 'unauthorized', 'invalid cron secret');
+ return false;
+ }
+ return true;
+}
+
+async function upsertVerdict({ source, sourceRef, txSig, network, amountAtomic, dbStatus, chainStatus, reconciled, discrepancy, detail, runId }) {
+ try {
+ await withDbRetry(() => sql`
+ INSERT INTO payment_reconciliation
+ (source, source_ref, tx_signature, network, amount_atomic,
+ db_status, chain_status, reconciled, discrepancy, detail, run_id, checked_at)
+ VALUES
+ (${source}, ${sourceRef}, ${txSig}, ${network}, ${amountAtomic},
+ ${dbStatus}, ${chainStatus}, ${reconciled}, ${discrepancy},
+ ${detail ? JSON.stringify(detail) : null}, ${runId}, now())
+ ON CONFLICT (source, source_ref) DO UPDATE SET
+ tx_signature = EXCLUDED.tx_signature,
+ network = EXCLUDED.network,
+ amount_atomic = EXCLUDED.amount_atomic,
+ db_status = EXCLUDED.db_status,
+ chain_status = EXCLUDED.chain_status,
+ reconciled = EXCLUDED.reconciled,
+ discrepancy = EXCLUDED.discrepancy,
+ detail = EXCLUDED.detail,
+ run_id = EXCLUDED.run_id,
+ checked_at = now()
+ `);
+ } catch (err) {
+ console.warn('[economy-reconcile] upsert failed', { source, sourceRef, message: err?.message });
+ }
+}
+
+/** Distinct master wallets present in the ledger, falling back to the canonical. */
+async function ledgerMasters() {
+ try {
+ const rows = await withDbRetry(() => sql`
+ SELECT DISTINCT master_pubkey FROM economy_master_ledger
+ `);
+ const set = new Set(rows.map((r) => r.master_pubkey).filter(Boolean));
+ set.add(ECONOMY_MASTER_ADDRESS);
+ return [...set];
+ } catch {
+ return [ECONOMY_MASTER_ADDRESS];
+ }
+}
+
+async function ledgerSignatures(masterPubkey) {
+ const rows = await withDbRetry(() => sql`
+ SELECT DISTINCT tx_signature FROM economy_master_ledger
+ WHERE master_pubkey = ${masterPubkey} AND tx_signature IS NOT NULL
+ `);
+ return new Set(rows.map((r) => r.tx_signature));
+}
+
+async function recentLedgerTransfers(masterPubkey) {
+ return withDbRetry(() => sql`
+ SELECT seq, tx_signature, lamports FROM economy_master_ledger
+ WHERE master_pubkey = ${masterPubkey}
+ AND event = 'transfer' AND tx_signature IS NOT NULL
+ AND ts >= now() - (${LEDGER_VERIFY_WINDOW_HOURS} || ' hours')::interval
+ ORDER BY seq DESC LIMIT 500
+ `);
+}
+
+/** Net lamports the master LOST in a parsed tx (>0 ⇒ debit). null if unreadable. */
+function masterNetDebit(tx, masterPubkey) {
+ const msg = tx?.transaction?.message;
+ const meta = tx?.meta;
+ if (!msg || !meta || !Array.isArray(meta.preBalances) || !Array.isArray(meta.postBalances)) return null;
+ const keys = (msg.accountKeys || []).map((k) => (typeof k === 'string' ? k : k?.pubkey?.toString?.() || k?.toString?.()));
+ const idx = keys.findIndex((k) => k === masterPubkey);
+ if (idx < 0) return null;
+ const pre = meta.preBalances[idx];
+ const post = meta.postBalances[idx];
+ if (typeof pre !== 'number' || typeof post !== 'number') return null;
+ return pre - post; // lamports lost
+}
+
+async function reconcileMaster(conn, masterPubkey, runId) {
+ const findings = [];
+ const summary = { master: masterPubkey, scanned_onchain: 0, unrecorded_outbound: 0, ledger_transfers_checked: 0, missing_onchain: 0, failed_onchain: 0 };
+
+ // 1. TAMPER — verify the hash chain.
+ let chain;
+ try {
+ chain = await verifyChain(masterPubkey);
+ } catch (e) {
+ chain = { ok: true, count: 0, note: `verify_skipped:${e?.message}` };
+ }
+ summary.ledger_rows = chain.count;
+ summary.chain_ok = chain.ok;
+ if (chain.ok === false) {
+ const where = chain.brokenAtSeq != null ? `broken at seq ${chain.brokenAtSeq}` : `missing row before seq ${chain.gapAtSeq}`;
+ findings.push({ kind: 'tamper', detail: where });
+ await upsertVerdict({
+ source: 'economy_master_chain', sourceRef: masterPubkey, txSig: null, network: 'mainnet',
+ amountAtomic: null, dbStatus: 'chain_intact', chainStatus: 'chain_broken', reconciled: false,
+ discrepancy: where, detail: chain, runId,
+ });
+ await sendOpsAlert(
+ `🚨 Economy ledger tamper detected`,
+ `The economy master accounting chain for ${masterPubkey} failed integrity: ${where}. A historical ledger row was edited or deleted. Freeze changes and investigate before trusting the books.`,
+ { signature: `economy-tamper:${masterPubkey}:${chain.brokenAtSeq ?? chain.gapAtSeq}` },
+ );
+ }
+
+ // 2. BREACH — every on-chain outbound must be in the ledger.
+ const recorded = await ledgerSignatures(masterPubkey);
+ let sigInfos = [];
+ try {
+ const { PublicKey } = await import('@solana/web3.js');
+ sigInfos = await conn.getSignaturesForAddress(new PublicKey(masterPubkey), { limit: SIG_SCAN_LIMIT });
+ } catch (e) {
+ summary.onchain_scan_error = e?.message || 'sig_fetch_failed';
+ }
+ summary.scanned_onchain = sigInfos.length;
+ for (const info of sigInfos) {
+ const sig = info.signature;
+ if (recorded.has(sig)) continue; // matched to a book entry — fine
+ if (info.err) continue; // a failed tx moved nothing
+ let tx = null;
+ try {
+ tx = await conn.getParsedTransaction(sig, { maxSupportedTransactionVersion: 0 });
+ } catch {
+ /* unreadable — skip; a later run retries */
+ }
+ const debitLamports = tx ? masterNetDebit(tx, masterPubkey) : null;
+ if (debitLamports == null) continue;
+ if (debitLamports > OUTBOUND_FEE_FLOOR_SOL * LAMPORTS_PER_SOL) {
+ // An outbound debit we never recorded. This is the breach signal.
+ summary.unrecorded_outbound += 1;
+ findings.push({ kind: 'unrecorded_outbound', sig, sol: debitLamports / LAMPORTS_PER_SOL });
+ await upsertVerdict({
+ source: 'economy_master_onchain', sourceRef: sig, txSig: sig, network: 'mainnet',
+ amountAtomic: debitLamports, dbStatus: 'not_in_ledger', chainStatus: 'unrecorded_outbound',
+ reconciled: false, discrepancy: `master debited ${(debitLamports / LAMPORTS_PER_SOL).toFixed(6)} SOL with no ledger row`,
+ detail: { blockTime: info.blockTime ?? null, slot: info.slot ?? null }, runId,
+ });
+ await sendOpsAlert(
+ `🚨 Unrecorded SOL leaving the economy master`,
+ `${(debitLamports / LAMPORTS_PER_SOL).toFixed(6)} SOL left ${masterPubkey} in tx ${sig} with NO ledger entry. If the treasury-topup cron did not make this transfer, the key is compromised — rotate ECONOMY_MASTER_SECRET_BASE58 and move remaining funds now. https://solscan.io/tx/${sig}`,
+ { signature: `economy-breach:${sig}` },
+ );
+ }
+ }
+
+ // 3. INTEGRITY — every recorded transfer must exist + succeed on-chain.
+ const transfers = await recentLedgerTransfers(masterPubkey);
+ summary.ledger_transfers_checked = transfers.length;
+ if (transfers.length) {
+ const sigs = transfers.map((t) => t.tx_signature);
+ let statuses = new Map();
+ try {
+ const { value } = await conn.getSignatureStatuses(sigs, { searchTransactionHistory: true });
+ sigs.forEach((s, j) => statuses.set(s, value?.[j] ?? null));
+ } catch (e) {
+ summary.status_error = e?.message || 'status_fetch_failed';
+ }
+ for (const t of transfers) {
+ const st = statuses.get(t.tx_signature);
+ if (st === undefined) continue; // RPC gap — do not flag on our own failure
+ let chainStatus = null;
+ if (st === null) chainStatus = 'missing_onchain';
+ else if (st.err) chainStatus = 'failed_onchain';
+ if (!chainStatus) continue;
+ summary[chainStatus] += 1;
+ findings.push({ kind: chainStatus, sig: t.tx_signature });
+ await upsertVerdict({
+ source: 'economy_master_ledger', sourceRef: `${masterPubkey}:${t.seq}`, txSig: t.tx_signature, network: 'mainnet',
+ amountAtomic: t.lamports ?? null, dbStatus: 'recorded_transfer', chainStatus, reconciled: false,
+ discrepancy: chainStatus === 'missing_onchain' ? 'ledger transfer not found on-chain' : 'ledger transfer reverted on-chain',
+ detail: { seq: Number(t.seq) }, runId,
+ });
+ }
+ }
+
+ // Balance-below-reserve is a fund-safety warning (engines will stall).
+ try {
+ const { PublicKey } = await import('@solana/web3.js');
+ const { sol } = await getSolBalance(conn, new PublicKey(masterPubkey));
+ summary.master_sol = sol;
+ if (sol < RESERVE_SOL) {
+ findings.push({ kind: 'below_reserve', sol });
+ await sendOpsAlert(
+ `⛽ Economy master below reserve`,
+ `${masterPubkey} holds ${sol.toFixed(4)} SOL, under the ${RESERVE_SOL} SOL reserve floor. Engines cannot be topped up until it is funded.`,
+ { signature: `economy-below-reserve:${masterPubkey}:${Math.floor(Date.now() / 86_400_000)}` },
+ );
+ }
+ } catch (e) {
+ summary.balance_error = e?.message || 'balance_failed';
+ }
+
+ return { summary, findings };
+}
+
+export default wrapCron(async (req, res) => {
+ if (!method(req, res, ['GET', 'POST'])) return;
+ if (!requireCron(req, res)) return;
+
+ const runId = (await import('node:crypto')).randomUUID();
+ const rpcUrl = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
+ const { solanaConnection } = await import('../_lib/solana/connection.js');
+ const conn = solanaConnection({ url: rpcUrl, network: 'mainnet', commitment: 'confirmed' });
+
+ const masters = await ledgerMasters();
+ const results = [];
+ let breaches = 0;
+ let tampers = 0;
+ for (const m of masters) {
+ try {
+ const r = await reconcileMaster(conn, m, runId);
+ results.push(r.summary);
+ breaches += r.findings.filter((f) => f.kind === 'unrecorded_outbound').length;
+ tampers += r.findings.filter((f) => f.kind === 'tamper').length;
+ } catch (e) {
+ results.push({ master: m, error: e?.message || 'reconcile_failed' });
+ }
+ }
+
+ return json(res, 200, {
+ ok: true,
+ run_id: runId,
+ rpc: rpcUrl,
+ masters: masters.length,
+ breaches,
+ tampers,
+ results,
+ });
+});
diff --git a/data/changelog.json b/data/changelog.json
index f392d5f8d..fa47dd1e8 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,16 @@
{
"$comment": "Curated changelog entries for three.ws \u2014 the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-07-03",
+ "title": "Full audit trail + breach monitoring on the economy's funding wallet",
+ "summary": "The master wallet that fuels the platform's autonomous economy now keeps a tamper-evident accounting book of every move it makes. Each SOL transfer is recorded with the engine it funded, the amount, the on-chain signature, the running balance, and the US-dollar value at the moment of the transfer — cryptographically hash-chained so no past entry can be altered or deleted without detection. A monitor runs every 30 minutes and checks three things: that the book hasn't been tampered with, that every transfer we recorded really happened on-chain, and — most importantly — that no SOL ever left the wallet without a matching record, which is the tell-tale sign of a stolen key. Anything off raises an immediate operator alert and lands on the finance-integrity board. There's also a one-command accounting export (CSV or JSON, with running balance and dollar totals) for bookkeeping and review.",
+ "tags": [
+ "security",
+ "infra",
+ "docs"
+ ]
+ },
{
"date": "2026-07-02",
"title": "Coin pages now have a live price chart, and every coin across the site links to them",
diff --git a/docs/economy-master.md b/docs/economy-master.md
index bd14f9a15..62bf670c5 100644
--- a/docs/economy-master.md
+++ b/docs/economy-master.md
@@ -107,6 +107,99 @@ The JSON response reports `configured`, `master_sol`, `funded`, `failed`,
`skipped`, `rejected`, and `spent_sol`. A non-empty `rejected` array means an
off-registry target reached the sweep and was blocked — investigate the caller.
+## Audit, accounting & breach monitoring
+
+This is real money, so every movement is recorded to a durable, tamper-evident
+book and independently reconciled against the chain. Three moving parts:
+
+### 1. The ledger — the financial book of record
+
+Every sweep appends a hash-chained batch of rows to the `economy_master_ledger`
+table via [`api/_lib/economy-ledger.js`](../api/_lib/economy-ledger.js):
+
+- one **`transfer`** row per SOL movement — the engine it funded, the target
+ pubkey, the amount, the confirmed **tx signature**, the **running balance**
+ after the move, and the **USD value at the instant of the transfer** (SOL/USD is
+ captured at write time via [`sol-price.js`](../api/_lib/sol-price.js), so an
+ accountant reads the dollar value as of the transfer, not as of report time);
+- a **`failed`** row per attempted transfer that errored, with the reason;
+- a **`blocked`** row per target the allowlist refused (`not_in_registry` /
+ `is_master`) — the on-chain evidence that the leak guard fired;
+- a **`sweep`** heartbeat row every run, even a no-op, so there is a continuous
+ "we checked this wallet every 30 minutes" trail.
+
+**Tamper-evidence.** Each row carries `prev_hash` + `entry_hash`, a SHA-256 hash
+chain: `entry_hash = sha256(seq | ts | master | event | target | lamports |
+signature | resulting-balance | prev_hash)`. The head commits the entire history,
+so editing or deleting *any* historical row (to hide a transfer, change an amount,
+or swap a recipient) breaks the chain from that row forward. The break is
+detectable and located to the exact `seq`. Schema:
+[`migrations/20260702010000_economy_master_ledger.sql`](../api/_lib/migrations/20260702010000_economy_master_ledger.sql).
+
+### 2. The reconcile / breach monitor
+
+[`api/cron/economy-reconcile.js`](../api/cron/economy-reconcile.js) runs every 30
+minutes and answers the three questions an auditor, an accountant, and an incident
+responder each ask:
+
+| Check | What it does | On failure |
+|---|---|---|
+| **Tamper** | `verifyChain()` recomputes the whole hash chain | 🚨 CRITICAL ops alert; row in `payment_reconciliation` (`source=economy_master_chain`) |
+| **Breach** | Pulls the master's real on-chain history and flags any **outbound debit whose signature is not in the ledger** | 🚨 CRITICAL alert — *unrecorded SOL leaving the master is the key-compromise signal*; verdict `chain_status=unrecorded_outbound` |
+| **Integrity** | Confirms every recorded `transfer` signature exists and succeeded on-chain | verdict `missing_onchain` / `failed_onchain` — a fabricated or lost record |
+| **Reserve** | Master balance below `ECONOMY_MASTER_RESERVE_SOL` | ⛽ fund-safety alert |
+
+Non-reconciled findings are upserted into the **shared** `payment_reconciliation`
+table (the same finance-integrity surface x402 revenue reconciliation writes to),
+so `WHERE reconciled = false` on the ops board shows master discrepancies next to
+everything else. The monitor is **read-only on-chain** — it never moves funds.
+
+### 3. Accounting export
+
+[`scripts/economy-ledger-export.mjs`](../scripts/economy-ledger-export.mjs) emits
+the ledger as CSV (default) or JSON with the running balance and USD valuation, and
+can re-verify the chain first:
+
+```bash
+# CSV of July, into a file for the accountant:
+node scripts/economy-ledger-export.mjs --from 2026-07-01 --to 2026-07-31 > july.csv
+
+# JSON with window totals (SOL out + USD out):
+node scripts/economy-ledger-export.mjs --event transfer --format json
+
+# Verify tamper-evidence before exporting (non-zero exit if the chain is broken):
+node scripts/economy-ledger-export.mjs --verify
+```
+
+Needs `DATABASE_URL`. Never prints secrets.
+
+### Breach-response runbook
+
+**On a `🚨 Unrecorded SOL leaving the economy master` alert:**
+1. Open the linked Solscan tx. If it is *not* a `treasury-topup` transfer to a
+ registry engine, treat the key as compromised.
+2. **Rotate immediately** — generate a new master keypair, set
+ `ECONOMY_MASTER_SECRET_BASE58` + `ECONOMY_MASTER_ADDRESS` to it, and redeploy so
+ the compromised key is no longer loaded.
+3. **Sweep remaining funds** from the old master to the new one (or cold storage)
+ before the attacker drains more.
+4. Reconcile: the ledger's last good `entry_hash` and the on-chain history bound
+ exactly what was authorized vs. stolen.
+
+**On a `🚨 Economy ledger tamper detected` alert:**
+1. Do not trust the DB books until resolved — the chain says a row was altered.
+2. Export with `--verify` to get the exact broken `seq`.
+3. Compare the on-chain transaction history against the ledger around that `seq`
+ to reconstruct the true record; restore from backup / re-derive from chain.
+
+### Retention
+
+`economy_master_ledger` is append-only and **must not** be pruned by the
+`db-retention` cron — it is the accounting record. It is tiny (a few dozen rows per
+day) so it does not contribute to storage pressure. The chain head may be anchored
+on-chain (same mechanism as [`ledger-anchor.js`](../api/_lib/ledger-anchor.js)) for
+a third-party-verifiable timestamp of the books.
+
## Known gaps & runbook (as of 2026-07-02)
The master is configured and funded, but the tree it feeds is only partly wired:
diff --git a/docs/financial-controls.md b/docs/financial-controls.md
new file mode 100644
index 000000000..200786ceb
--- /dev/null
+++ b/docs/financial-controls.md
@@ -0,0 +1,235 @@
+# Financial controls & audit register
+
+three.ws moves **real money** (USDC, SOL, $THREE) on behalf of users and agents.
+This document is the audit-grade control register: for every money flow it records
+**where it is logged, whether that record is immutable and idempotent, whether the
+on-chain transaction is captured, whether it is reconciled against the chain, and
+how long it is retained** — plus the monitoring/breach controls around it and the
+open gaps ranked by accounting/regulatory risk.
+
+It is a companion to the [money map](money-map.md) (who receives what) and the
+[Solana signers runbook](../tasks/onchain-deployment/SOLANA-SIGNERS.md) (the
+wallets). Keep it in sync with the code — every row cites its source.
+
+> **Status of this register:** the platform's logging is strong for a few flows
+> (credit deposits, marketplace sales, labor settlement) and has material gaps in
+> others (unlogged treasury transfers, fire-and-forget revenue writes, Redis-only
+> payout ledgers). The [gap register](#gap-register) tracks each with a severity
+> and a fix. Do not treat any flow as audit-complete until its gaps are closed.
+
+---
+
+## 1. The financial ledgers
+
+Each row: the flow, its ledger table + key columns, whether the on-chain tx
+signature is persisted, whether the record is append-only, its idempotency guard,
+and whether it is reconciled against the chain.
+
+| Flow | Ledger table (key columns) | tx sig? | Append-only | Idempotency | Chain-reconciled |
+| ---- | -------------------------- | ------- | ----------- | ----------- | ---------------- |
+| x402 settlements (main revenue) | `x402_audit_log` (`event_type, payer, network, amount_atomics, asset, tx_hash, settlement_status, …`) | ✅ | by convention* | Redis proof-hash slot (app-layer) | ❌ **no** |
+| Signed receipts | `x402_receipts` (`payer, resource_url, receipt jsonb, transaction`) | ⚠️ often NULL (`includeTxHash` default false) | by convention | ❌ none | n/a (EIP-712 verifiable) |
+| Club tips → dancer payouts | `club_tips` (`ticket_id UNIQUE, dancer, amount_atomics, paid_tx`) → `club_payouts` (`tx, swept_tip_count`) | ✅ | payouts ✅; tips mutable | `ticket_id UNIQUE` + claim-before-send | ❌ |
+| Club cover charges | **none** (only `x402_audit_log`) | — | — | — | ❌ |
+| Cosmetic sales + creator split | `cosmetic_sales` (`price_usdc_atomics, creator_cut_atomics, payout_tx, payout_status`, `UNIQUE(account,cosmetic_id)`) | ✅ | sale once; payout fields mutable | `UNIQUE(account,cosmetic_id)` | ❌ |
+| Marketplace skill sale + fee | `skill_purchases` (`tx_signature UNIQUE`, `platform_fee_amount`) + `agent_revenue_events` (`gross/fee/net`) | ✅ | revenue events ✅ | `tx_signature UNIQUE` | ❌ |
+| Labor escrow (fund/settle/payout/refund) | `agent_bounties`, `agent_jobs` (`settle_key UNIQUE, settlement_sig, royalty_sig, refund_sig`) + custody ledger | ✅ | mutable status; single-shot | `settle_key UNIQUE` + atomic claim | ❌ |
+| $THREE buyback | `three_buyback_runs` (`usdc_spent_atomics, three_bought_atomics, buy_signature, sweep_signature`) | ✅ | ✅ (one row/run) | ❌ **no unique key** | ❌ |
+| Coin buyback / distribute | `pump_buyback_runs`, `pump_distribute_runs` (`tx_signature, status`) | ✅ | mutable status | ❌ **no unique key** | ❌ |
+| Withdrawals | `agent_withdrawals` (`amount, currency_mint, chain, to_address, tx_signature, status`) | ✅ | mutable status | ⚠️ claim-CAS only; **no on-chain-send idempotency** | ❌ |
+| Treasury top-up / economy master | **NONE** — only an ops-alert string + ephemeral cron response | ⚠️ in alert text only | ❌ not persisted | ❌ | ❌ |
+| Autonomous x402 loop | `x402_autonomous_log` (`tx_signature, amount_atomic, success`) | ✅ | ✅ | ❌ no unique on sig | ✅ **yes** |
+| Inbound agent payments | `agent_payment_intents` (`amount, currency_mint, tx_signature, status`) | ✅ | mutable status | tx-unique index | ✅ **yes** |
+| a2a mandate settlements | **no durable ledger** — mandate is an unstored JWS; cap in Redis (`INCRBY`) with per-replica memory fallback | ❌ | ❌ | Redis atomic (bypassable w/o Upstash) | ❌ |
+| Credit deposits | `credit_ledger` (`amount_usd, balance_after, tx_signature, idempotency_key UNIQUE`) — balance+ledger in one CTE | ✅ | ✅ | `idempotency_key UNIQUE` + finalized-only | on finalized tx |
+| Subscriptions | `subscription_checkouts` (`reference UNIQUE, amount, platform_fee_amount, tx_signature`) | ✅ | mutable status | `reference UNIQUE` + payment-idempotency | ❌ |
+| Vanity bounty payouts | **Redis / in-memory** (`vanity-bounty-store.js`) — not Postgres | ⚠️ in Redis only | ❌ (memory fallback loses on restart) | Redis CAS | ❌ |
+
+\* **"By convention"** means the code never issues UPDATE/DELETE on the table, but
+there is **no DB-level enforcement** (no trigger, no revoked grant) — so
+immutability is not guaranteed against a bug, a migration, or a compromised
+credential. This applies to *every* table above, including those designed as
+immutable (`credit_ledger`, `agent_revenue_events`, `three_buyback_runs`).
+
+**Reference-grade flows** (idempotent + tx-sig + append-only): **credit deposits**,
+**marketplace skill purchases**, **labor settlement**. New money flows should copy
+their pattern — a `UNIQUE` idempotency key on the on-chain signature, an
+append-only ledger row, and balance+ledger written atomically.
+
+---
+
+## 2. Reconciliation coverage
+
+Only two books are automatically verified against the chain, by
+[`revenue-reconciliation.js`](../api/_lib/x402/revenue-reconciliation.js) (daily,
+7-day / 250-row window, driven by the `x402-autonomous-loop` cron):
+
+- ✅ `x402_autonomous_log` (outbound autonomous spend)
+- ✅ `agent_payment_intents` (inbound user→agent revenue)
+
+**NOT reconciled against the chain:** `x402_audit_log` (the main revenue ledger),
+`club_payouts`, `cosmetic_sales`, `agent_jobs`, `agent_withdrawals`,
+`three_buyback_runs`, treasury top-ups, and vanity payouts.
+
+Two blind spots default a record to `reconciled=true` without verifying it:
+**EVM/Base** settlements (`skipped_non_solana`) and **RPC failures** (`unknown`).
+A network-wide RPC outage, or all-EVM revenue, would show zero discrepancies while
+nothing was actually checked.
+
+**As of this register**, discrepancies now page ops: when the reconciler finds any
+`missing_onchain` / `failed_onchain` / `missing_signature` record it fires
+`sendOpsAlert` (previously the verdict was written to `payment_reconciliation` and
+never surfaced). The full open set is always queryable:
+
+```sql
+SELECT * FROM payment_reconciliation WHERE reconciled = false ORDER BY checked_at DESC;
+```
+
+---
+
+## 3. Monitoring & breach controls
+
+**Alerting** — [`sendOpsAlert`](../api/_lib/alerts.js) is **Telegram-only**
+(`TELEGRAM_BOT_TOKEN` + `TELEGRAM_ALERTS_CHAT_ID`); a no-op if unset, swallows
+delivery failures, and **self-throttles at 20 alerts/hour**. There is no
+email/Slack/PagerDuty fallback and no alert-on-alerting-down.
+
+**Balance watchdogs** — `relayer-balance-check` (6h) alerts on any signer's SOL
+below its `minSol` floor; `treasury-topup` (30 min) auto-refills from the economy
+master and alerts when the master can't cover or an off-registry target is
+rejected. **Both read native SOL only — no USDC balance watchdog exists.**
+
+**Spend controls** — x402 buyer caps (`X402_MAX_PER_CALL/HOUR/DAY_ATOMIC`, Redis
+reserve-first), autonomous-loop daily cap (default $5), pumpfun spend-policy
+(`daily_sol_cap` default 5), agent-wallet bridge caps, a2a mandate budget, labor
+escrow. **Cross-path USD caps (`agent-trade-guards.js` `daily_usd`/`per_tx_usd`)
+default to `null` = uncapped** — an agent whose owner never set limits has no USD
+ceiling.
+
+**Kill switches** — per-agent wallet freeze (`spend_limits.frozen`, instant,
+auto-set by the anomaly engine), per-agent/strategy `kill_switch`, worker global
+kills (`SNIPER_/ORACLE_/MM_/ORDERS_GLOBAL_KILL` — **env flags, need a redeploy**),
+`CIRCULATION_ENABLED`, dead-man switch.
+
+**Breach detection** — `wallet-anomaly.js` scores outbound transfers (size,
+velocity, first-time destination) and **auto-freezes** the wallet, but notifies
+only the **wallet owner, never platform ops** (`sendOpsAlert` is not called), and
+**does not cover the treasury / economy-master / coin-creator custodial signers**.
+There is no detection of a signer key used from an unexpected host/IP.
+
+**Tamper-evidence** — `custody-attest` (6h) Merkle-anchors custodial wallet
+balances on-chain. The revenue/tips/hires ledgers have **no hash-chain, signature,
+or anchor**.
+
+---
+
+## 4. Retention
+
+| Table(s) | Deleted by | Window | Financial-record risk |
+| -------- | ---------- | ------ | --------------------- |
+| `x402_audit_log`, `x402_receipts`, `club_tips/payouts`, `cosmetic_sales`, `agent_*`, `credit_ledger`, payout/run tables | **nothing** | ∞ | none (safe) |
+| `audit_log` (generic action log) | `audit-log-cleanup` (daily) | **365 days, hardcoded** | ⚠️ likely below statutory (5–7 yr) retention; no archive before delete |
+| `siwx_payments` (access grants) | `siwx-gc` (daily) | 7 days post-expiry | low (money record survives elsewhere; entitlement history lost) |
+| pump-intel firehose | `db-retention` (15 min) | `PUMP_INTEL_RETENTION_DAYS` (14, floor 3) | none — valve never touches money tables |
+
+**Storage fragility:** financial tables share one **512 MB Neon branch** with a
+~60 MB/day intel firehose. The pressure valve protects money data *by omission
+only*; at the cap **all financial/audit writes fail** (audit writes already
+fail-fast at 3 s), silently losing *new* records. Money data is not isolated onto a
+separate branch/DB, and there is no dead-letter for dropped writes.
+
+---
+
+## 5. Accounting export
+
+There is **no consolidated, admin-authenticated, all-flows ledger export** and no
+cost side, so **a full P&L / cash-flow cannot be produced today**. What exists:
+
+- `api/x402-revenue.js?view=export` → CSV, **x402 settlements only**.
+- `api/x402/analytics.js?report=revenue` → JSON, x402 only, **net is an estimate**
+ (gross − count × avg gas), not actual per-tx fees.
+- `api/billing/invoices.js?format=csv` → per-user metered usage, owner-scoped only.
+- `api/x402/my-receipts.js` → a buyer's own signed receipts.
+
+Club tips, hires, skill purchases, metered `token_payments`, buybacks, payouts, and
+withdrawals have **no unified export**.
+
+---
+
+## Gap register
+
+Ranked by accounting/regulatory risk. Each is a tracked remediation item.
+
+### P0 — must fix (unlogged or double-pay risk)
+1. **Treasury top-up / economy-master transfers are unlogged.** Real SOL moves with
+ no durable record — only an ops-alert string. *Fix: append-only
+ `treasury_transfers` table (from, to, lamports, signature, run_id, ts) written in
+ `economy-master.js` `sendSol`.* ⚠️ `economy-master.js` is under active
+ development by another workstream — coordinate before editing.
+2. **x402 revenue writes are fire-and-forget and drop under DB load.** On-chain
+ settled USDC can be absent from `x402_audit_log`, under-reporting revenue. *Fix:
+ make the settle-path audit write awaited/durable with a dead-letter, and add a
+ `UNIQUE(tx_hash)` idempotency constraint.*
+3. **Withdrawals lack on-chain-send idempotency.** Broadcast-then-throw marks
+ `failed` while funds may have left → double-pay on retry. *Fix: persist an
+ idempotency key / pre-send intent and check chain before re-issuing.*
+
+### P1
+4. **Vanity bounty payout ledger is Redis/in-memory** (lost on restart w/o Upstash).
+ *Fix: mirror payouts/refunds to an append-only Postgres table.*
+5. **a2a mandate settlements have no durable per-tx ledger**; the spend cap's memory
+ fallback allows cross-replica overspend without Upstash. *Fix: persist mandates +
+ settlements; make the cap Postgres- or Redis-authoritative (no memory fallback in
+ prod).*
+6. **Signed receipts lack an idempotency key and usually omit the tx hash.** *Fix:
+ `UNIQUE(payer, resource_url, transaction)` + default `includeTxHash=true`.*
+7. **Main revenue ledger is not chain-reconciled and has no tamper-evidence.** *Fix:
+ extend reconciliation to `x402_audit_log`; hash-chain or periodically
+ Merkle-anchor it (reuse `custody-proof.js`).*
+8. **No consolidated P&L / all-flows export.** *Fix: an admin-auth endpoint that
+ unions every ledger into one dated cash-flow CSV, with the cost side.*
+9. **Custodial-signer drains don't page ops and aren't anomaly-scored.** *Fix: extend
+ `wallet-anomaly` (or a balance-delta monitor) to treasury/master/coin signers and
+ route to `sendOpsAlert`.*
+
+### P2
+10. **Buyback/distribute run tables and `x402_autonomous_log` lack idempotency keys.**
+11. **No DB-level immutability** on any ledger — add append-only enforcement
+ (revoke UPDATE/DELETE, or triggers) to the truly-append-only tables
+ (`x402_audit_log`, `credit_ledger`, `agent_revenue_events`, `three_buyback_runs`).
+12. **`audit_log` hard-deleted at 365 days** — make the window configurable and
+ archive to cold storage before delete.
+13. **Reconciliation blind spots** (EVM/RPC-miss default to reconciled); **no USDC
+ balance watchdog**; **alerting is single-channel + self-throttling**; **global
+ kill switches need a redeploy** (add a runtime halt flag).
+14. **Financial data shares the storage-capped Neon branch** — isolate money/audit
+ tables onto their own branch/DB so an intel-firehose cap can't drop financial
+ writes.
+
+### Done
+- ✅ **Reconciliation discrepancies now page ops** (`revenue-reconciliation.js`) —
+ was detected-but-silent (G1/R1).
+
+---
+
+## Operating procedures
+
+- **Daily:** review `SELECT * FROM payment_reconciliation WHERE reconciled = false`
+ and clear or escalate every row. An alert here means recorded revenue disagrees
+ with the chain — treat as a financial incident until explained.
+- **On a breach/anomaly alert:** freeze the affected wallet(s)
+ (`spend_limits.frozen`), and for a signer-key concern rotate the key
+ ([Solana signers runbook](../tasks/onchain-deployment/SOLANA-SIGNERS.md)) and
+ re-run `check-relayer-balances.mjs` to confirm balances.
+- **Before adding a paid flow:** it is not done until it writes an append-only
+ ledger row with the on-chain signature and a `UNIQUE` idempotency key, and is
+ added to this register and the [money map](money-map.md).
+
+---
+
+## Related
+
+- [Money map](money-map.md) — who receives each payment.
+- [x402 revenue & receipts](x402-revenue.md) — the x402 recording detail.
+- [x402 endpoints](x402-endpoints.md) — the paid endpoint catalog.
+- [Solana signers runbook](../tasks/onchain-deployment/SOLANA-SIGNERS.md) — the wallets + funding.
diff --git a/docs/money-map.md b/docs/money-map.md
index 922d4c6af..8849fe967 100644
--- a/docs/money-map.md
+++ b/docs/money-map.md
@@ -155,6 +155,7 @@ recurring payout crons that forward the flows above:
## Related
+- [Financial controls & audit register](financial-controls.md) — every ledger's integrity, reconciliation, retention, monitoring, and the ranked gap list.
- [x402 endpoints](x402-endpoints.md) — the paid endpoint catalog and price overrides.
- [x402 revenue & receipts](x402-revenue.md) — where settlements are recorded.
- [x402 ring economy](x402-ring-economy.md) — the internal recirculation loop.
diff --git a/public/changelog.json b/public/changelog.json
index 96f58a9ae..5757818d1 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,11 +1,23 @@
{
- "generated_at": "2026-07-02T23:53:40.916Z",
+ "generated_at": "2026-07-03T00:09:38.457Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
"url": "https://three.ws"
},
"entries": [
+ {
+ "date": "2026-07-03",
+ "type": "update",
+ "title": "Full audit trail + breach monitoring on the economy's funding wallet",
+ "summary": "The master wallet that fuels the platform's autonomous economy now keeps a tamper-evident accounting book of every move it makes. Each SOL transfer is recorded with the engine it funded, the amount, the on-chain signature, the running balance, and the US-dollar value at the moment of the transfer — cryptographically hash-chained so no past entry can be altered or deleted without detection. A monitor runs every 30 minutes and checks three things: that the book hasn't been tampered with, that every transfer we recorded really happened on-chain, and — most importantly — that no SOL ever left the wallet without a matching record, which is the tell-tale sign of a stolen key. Anything off raises an immediate operator alert and lands on the finance-integrity board. There's also a one-command accounting export (CSV or JSON, with running balance and dollar totals) for bookkeeping and review.",
+ "link": null,
+ "tags": [
+ "security",
+ "infra",
+ "docs"
+ ]
+ },
{
"date": "2026-07-02",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 8655866cc..d220f6f0f 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -6,6 +6,14 @@
<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/>
<description>What's new on three.ws — features, improvements, and releases, newest first.</description>
<language>en</language>
+ <item>
+ <title>Full audit trail + breach monitoring on the economy's funding wallet</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-07-03:Full audit trail + breach monitoring on the economy's funding wallet</guid>
+ <pubDate>Fri, 03 Jul 2026 12:00:00 GMT</pubDate>
+ <category>security</category>
+ <description>The master wallet that fuels the platform's autonomous economy now keeps a tamper-evident accounting book of every move it makes. Each SOL transfer is recorded with the engine it funded, the amount, the on-chain signature, the running balance, and the US-dollar value at the moment of the transfer — cryptographically hash-chained so no past entry can be altered or deleted without detection. A monitor runs every 30 minutes and checks three things: that the book hasn't been tampered with, that every transfer we recorded really happened on-chain, and — most importantly — that no SOL ever left the wallet without a matching record, which is the tell-tale sign of a stolen key. Anything off raises an immediate operator alert and lands on the finance-integrity board. There's also a one-command accounting export (CSV or JSON, with running balance and dollar totals) for bookkeeping and review.</description>
+ </item>
<item>
<title>Agent wallet creation and vanity addresses restored</title>
<link>https://three.ws/vanity-wallet</link>
diff --git a/public/features.json b/public/features.json
index 883385ec3..8c3547326 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-02T23:53:40.892Z",
+ "generated_at": "2026-07-03T00:09:38.424Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/scripts/economy-ledger-export.mjs b/scripts/economy-ledger-export.mjs
new file mode 100644
index 000000000..4e093acab
--- /dev/null
+++ b/scripts/economy-ledger-export.mjs
@@ -0,0 +1,103 @@
+#!/usr/bin/env node
+// scripts/economy-ledger-export.mjs
+//
+// Accounting export for the economy master funding wallet's tamper-evident ledger
+// (api/_lib/economy-master.js → economy_master_ledger). Emits every recorded money
+// event over a window as CSV (default) or JSON, with the running balance and the
+// USD value captured at the instant of each transfer — the record an accountant or
+// auditor reads. Optionally re-verifies the hash chain first.
+//
+// Auth: reads DATABASE_URL from the environment (Neon). Never prints secrets.
+//
+// Usage:
+// node scripts/economy-ledger-export.mjs # all rows, CSV
+// node scripts/economy-ledger-export.mjs --from 2026-07-01 --to 2026-07-31
+// node scripts/economy-ledger-export.mjs --event transfer --format json
+// node scripts/economy-ledger-export.mjs --verify # check chain integrity
+// node scripts/economy-ledger-export.mjs --from 2026-07-01 > july.csv
+
+import { readLedger, verifyChain } from '../api/_lib/economy-ledger.js';
+
+const DEFAULT_MASTER = 'WwwuGbqHrwF5RG89KhUbmRWEvjnRH9k5kVM5p7T3WwW';
+
+function parseArgs(argv) {
+ const a = { format: 'csv', master: process.env.ECONOMY_MASTER_ADDRESS || DEFAULT_MASTER, from: null, to: null, event: null, verify: false };
+ for (let i = 2; i < argv.length; i++) {
+ const k = argv[i];
+ if (k === '--verify') a.verify = true;
+ else if (k === '--format') a.format = argv[++i];
+ else if (k === '--master') a.master = argv[++i];
+ else if (k === '--from') a.from = argv[++i];
+ else if (k === '--to') a.to = argv[++i];
+ else if (k === '--event') a.event = argv[++i];
+ else if (k === '--help' || k === '-h') { printHelp(); process.exit(0); }
+ }
+ return a;
+}
+
+function printHelp() {
+ console.log('Usage: node scripts/economy-ledger-export.mjs [--from DATE] [--to DATE] [--event transfer|failed|blocked|sweep] [--master ADDR] [--format csv|json] [--verify]');
+}
+
+const CSV_COLS = [
+ 'seq', 'ts', 'event', 'target_name', 'target_pubkey', 'lamports', 'sol',
+ 'sol_usd', 'usd_value', 'tx_signature', 'reason', 'master_sol_before',
+ 'master_sol_after', 'run_id', 'entry_hash',
+];
+
+function csvCell(v) {
+ if (v == null) return '';
+ const s = String(v);
+ return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
+}
+
+async function main() {
+ if (!process.env.DATABASE_URL) {
+ console.error('DATABASE_URL is not set. Export it or add it to .env.local.');
+ process.exit(1);
+ }
+ const args = parseArgs(process.argv);
+
+ if (args.verify) {
+ const v = await verifyChain(args.master);
+ if (v.ok) {
+ console.error(`✓ chain intact — ${v.count} rows, head seq ${v.headSeq}, head hash ${String(v.headHash).slice(0, 16)}…`);
+ } else {
+ const where = v.brokenAtSeq != null ? `broken at seq ${v.brokenAtSeq}` : `gap before seq ${v.gapAtSeq}`;
+ console.error(`✗ CHAIN INTEGRITY FAILURE — ${where}. The ledger has been altered.`);
+ process.exit(2);
+ }
+ }
+
+ const rows = await readLedger({ masterPubkey: args.master, from: args.from, to: args.to, event: args.event });
+
+ // Accounting totals over the window (transfers only are real money out).
+ let outSol = 0;
+ let outUsd = 0;
+ for (const r of rows) {
+ if (r.event === 'transfer') {
+ outSol += Number(r.sol || 0);
+ outUsd += Number(r.usd_value || 0);
+ }
+ }
+
+ if (args.format === 'json') {
+ process.stdout.write(JSON.stringify({
+ master: args.master,
+ from: args.from,
+ to: args.to,
+ rows,
+ totals: { transfers: rows.filter((r) => r.event === 'transfer').length, sol_out: outSol, usd_out: outUsd },
+ }, null, 2) + '\n');
+ } else {
+ process.stdout.write(CSV_COLS.join(',') + '\n');
+ for (const r of rows) process.stdout.write(CSV_COLS.map((c) => csvCell(r[c])).join(',') + '\n');
+ }
+
+ console.error(`\n${rows.length} rows · ${outSol.toFixed(6)} SOL out ($${outUsd.toFixed(2)}) · master ${args.master}`);
+}
+
+main().catch((e) => {
+ console.error('export failed:', e?.message || e);
+ process.exit(1);
+});
diff --git a/src/agora/agora-world.js b/src/agora/agora-world.js
index bd8f87724..202f4c5d4 100644
--- a/src/agora/agora-world.js
+++ b/src/agora/agora-world.js
@@ -388,11 +388,20 @@ async function main() {
if (enterBtn) { enterBtn.disabled = true; enterBtn.textContent = 'Entering…'; }
try {
const { mountPlayerMode } = await import('./player-mode.js');
- playerMode = await mountPlayerMode({
+ const mounted = await mountPlayerMode({
scene, camera, population, buildingBoxes,
getCameraYaw: () => cityCamera.yaw,
openPassport: (id) => openPassport(id, null),
});
+ // The mount awaits a module import + an avatar GLB (seconds). If the page
+ // was torn down during that window (pagehide → disposeWorld already ran,
+ // once), nothing would ever dispose this layer — its socket + global
+ // listeners + HUD would outlive the world. Tear it down here instead.
+ if (disposed) {
+ try { mounted.dispose(); } catch { /* best-effort */ }
+ return;
+ }
+ playerMode = mounted;
focusGoal = null;
if (enterBtn) {
enterBtn.disabled = false;
diff --git a/src/agora/player-mode.js b/src/agora/player-mode.js
index 11d1c92ec..2b372ed9c 100644
--- a/src/agora/player-mode.js
+++ b/src/agora/player-mode.js
@@ -263,9 +263,18 @@ class RemotePlayers {
}
}
- dispose() {
+ // Drop every remote (freeing rigs + bubbles). Used on a reconnect: while the
+ // socket was down, peers may have left without a `remove` event (walk-net's
+ // _closeRoom drops all listeners), so on rejoin their entries would linger as
+ // motionless ghosts. Clearing here lets onAdd repopulate only who's actually
+ // present. The object stays usable — the map is simply emptied.
+ clear() {
for (const id of [...this._byId.keys()]) this.remove(id);
}
+
+ dispose() {
+ this.clear();
+ }
}
const _v = new THREE.Vector3();
@@ -366,11 +375,17 @@ export async function mountPlayerMode(ctx) {
const remotes = new RemotePlayers(scene, bubbles);
const net = new WalkNet({ name, avatar: avatarUrl, room: 'agora_world' });
const presenceText = presence.querySelector('.agora-p-presence-text');
+ let wasOnline = false; // tracks online→down transitions so we clear ghosts once
function renderPresence() {
const state = net.status === 'online' ? 'online'
: net.status === 'connecting' ? 'connecting'
: net.status === 'unavailable' ? 'solo'
: 'offline';
+ // Left the live room (drop / reconnect): peers may have departed during the
+ // gap with no `remove` event, so drop every remote now. onAdd repopulates
+ // only who's actually present when the socket comes back — no ghost avatars.
+ if (wasOnline && state !== 'online') remotes.clear();
+ wasOnline = state === 'online';
presence.dataset.state = state;
if (state === 'online') {
const n = remotes.count + 1;
diff --git a/tests/economy-ledger.test.js b/tests/economy-ledger.test.js
new file mode 100644
index 000000000..9a725e113
--- /dev/null
+++ b/tests/economy-ledger.test.js
@@ -0,0 +1,110 @@
+// Pure-logic tests for the economy master accounting ledger
+// (api/_lib/economy-ledger.js): row construction from a sweep result, the running
+// balance, USD valuation, and the SHA-256 hash chain's tamper-evidence. No DB.
+import { test } from 'vitest';
+import assert from 'node:assert/strict';
+import { buildSweepRows, hashEntry } from '../api/_lib/economy-ledger.js';
+
+const MASTER = 'WwwuGbqHrwF5RG89KhUbmRWEvjnRH9k5kVM5p7T3WwW';
+
+function sampleResult() {
+ return {
+ configured: true,
+ master: MASTER,
+ masterSol: 10,
+ reserveSol: 1,
+ spendableSol: 9,
+ funded: [
+ { name: 'a2a-payer', pubkey: 'AAA', sol: 0.5, signature: 'sigA' },
+ { name: 'club-treasury', pubkey: 'BBB', sol: 0.25, signature: 'sigB' },
+ ],
+ failed: [{ name: 'launcher', pubkey: 'CCC', sol: 0.5, reason: 'blockhash_expired' }],
+ rejected: [{ name: 'evil', pubkey: 'EVIL', reason: 'not_in_registry' }],
+ skipped: [{ name: 'hair', reason: 'below_dust_threshold' }],
+ spentSol: 0.75,
+ };
+}
+
+test('buildSweepRows: one row per transfer/failed/blocked + a sweep summary', () => {
+ const rows = buildSweepRows({ masterPubkey: MASTER, result: sampleResult(), solUsd: 200, now: 1_000_000 });
+ assert.equal(rows.filter((r) => r.event === 'transfer').length, 2);
+ assert.equal(rows.filter((r) => r.event === 'failed').length, 1);
+ assert.equal(rows.filter((r) => r.event === 'blocked').length, 1);
+ assert.equal(rows.filter((r) => r.event === 'sweep').length, 1);
+});
+
+test('running balance decrements across transfers; sweep row holds the final', () => {
+ const rows = buildSweepRows({ masterPubkey: MASTER, result: sampleResult(), solUsd: 200, now: 1_000_000 });
+ const transfers = rows.filter((r) => r.event === 'transfer');
+ assert.equal(transfers[0].master_sol_before, 10);
+ assert.equal(transfers[0].master_sol_after, 9.5); // 10 - 0.5
+ assert.equal(transfers[1].master_sol_after, 9.25); // 9.5 - 0.25
+ const sweep = rows.find((r) => r.event === 'sweep');
+ assert.equal(sweep.master_sol_after, 9.25);
+ assert.equal(sweep.detail.spent_sol, 0.75);
+});
+
+test('USD valuation is captured at the transfer instant', () => {
+ const rows = buildSweepRows({ masterPubkey: MASTER, result: sampleResult(), solUsd: 200, now: 1_000_000 });
+ const t = rows.find((r) => r.event === 'transfer');
+ assert.equal(t.sol_usd, 200);
+ assert.equal(t.usd_value, 100); // 0.5 SOL × $200
+});
+
+test('an unpriced sweep (solUsd 0) records null valuations, not a guess', () => {
+ const rows = buildSweepRows({ masterPubkey: MASTER, result: sampleResult(), solUsd: 0, now: 1 });
+ const t = rows.find((r) => r.event === 'transfer');
+ assert.equal(t.sol_usd, null);
+ assert.equal(t.usd_value, null);
+});
+
+test('a no-op sweep still writes the heartbeat summary row', () => {
+ const rows = buildSweepRows({
+ masterPubkey: MASTER,
+ result: { configured: true, master: MASTER, masterSol: 5, funded: [], failed: [], rejected: [], skipped: [], spentSol: 0 },
+ solUsd: 100,
+ now: 1,
+ });
+ assert.equal(rows.length, 1);
+ assert.equal(rows[0].event, 'sweep');
+});
+
+// Simulate recordSweep's chaining, then assert tamper-evidence.
+function chain(rows, startSeq = 0, startHash = '') {
+ let prevHash = startHash;
+ let seq = startSeq;
+ return rows.map((r) => {
+ const row = { ...r, seq: ++seq, prev_hash: prevHash };
+ row.entry_hash = hashEntry(prevHash, row);
+ prevHash = row.entry_hash;
+ return row;
+ });
+}
+
+test('hash chain: each entry_hash recomputes from the row + prev_hash', () => {
+ const built = buildSweepRows({ masterPubkey: MASTER, result: sampleResult(), solUsd: 200, now: 1_000_000 });
+ const chained = chain(built);
+ let prev = '';
+ for (const row of chained) {
+ assert.equal(row.prev_hash, prev);
+ assert.equal(hashEntry(prev, row), row.entry_hash); // reproducible
+ prev = row.entry_hash;
+ }
+});
+
+test('tamper: editing a recorded amount breaks the chain from that row on', () => {
+ const built = buildSweepRows({ masterPubkey: MASTER, result: sampleResult(), solUsd: 200, now: 1_000_000 });
+ const chained = chain(built);
+ const victim = chained.find((r) => r.event === 'transfer');
+ // Attacker rewrites the resulting balance to hide a drain.
+ const tampered = { ...victim, master_sol_after: 9.9 };
+ assert.notEqual(hashEntry(tampered.prev_hash, tampered), victim.entry_hash);
+});
+
+test('tamper: swapping the recipient of a transfer is detectable', () => {
+ const built = buildSweepRows({ masterPubkey: MASTER, result: sampleResult(), solUsd: 200, now: 1_000_000 });
+ const chained = chain(built);
+ const victim = chained.find((r) => r.event === 'transfer');
+ const tampered = { ...victim, target_pubkey: 'ATTACKER_WALLET' };
+ assert.notEqual(hashEntry(tampered.prev_hash, tampered), victim.entry_hash);
+});
diff --git a/vercel.json b/vercel.json
index 40821786c..25f89f529 100644
--- a/vercel.json
+++ b/vercel.json
@@ -15,6 +15,9 @@
"api/cron/treasury-topup.js": {
"maxDuration": 120
},
+ "api/cron/economy-reconcile.js": {
+ "maxDuration": 300
+ },
"{api/strategies,api/cron/payment-session-sweep,api/cron/three-market-refresh}.js": {
"maxDuration": 30
},
@@ -4909,6 +4912,10 @@
{
"path": "/api/cron/treasury-topup",
"schedule": "*/30 * * * *"
+ },
+ {
+ "path": "/api/cron/economy-reconcile",
+ "schedule": "*/30 * * * *"
}
]
}