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
fix(economy): give the treasury sweepback a dry-run mode and unmask the tripwire's silent column mismatch
nirholas03d54dc8796f
diff --git a/api/_lib/economy-sweepback.js b/api/_lib/economy-sweepback.jsindex d15db5300..a0280b325 100644--- a/api/_lib/economy-sweepback.js+++ b/api/_lib/economy-sweepback.js@@ -94,7 +94,7 @@ export function planSweepback(targets, opts = {}) {* @param {'mainnet'|'devnet'} args.network* @returns {Promise<{ swept: Array<{mint:string,amount:string,decimals:number,signature:string}>, failed: Array<{mint:string,reason:string}> }>}*/-async function sweepTokenBalances({ connection, owner, network }) {+async function sweepTokenBalances({ connection, owner, network, dryRun = false }) {const { PublicKey } = await import('@solana/web3.js');const {TOKEN_PROGRAM_ID,@@ -139,6 +139,12 @@ async function sweepTokenBalances({ connection, owner, network }) {for (let i = 0; i < holdings.length; i += TOKEN_ACCOUNTS_PER_TX) {const chunk = holdings.slice(i, i + TOKEN_ACCOUNTS_PER_TX);+ if (dryRun) {+ for (const h of chunk) {+ swept.push({ mint: h.mint, amount: h.amount.toString(), decimals: h.decimals, signature: null, dryRun: true });+ }+ continue;+ }const instructions = [];for (const h of chunk) {const mint = new PublicKey(h.mint);@@ -176,9 +182,10 @@ async function sweepTokenBalances({ connection, owner, network }) {* @param {'excess'|'drain'} [args.mode]* @param {boolean} [args.includeTokens]* @param {'mainnet'|'devnet'} [args.network]+ * @param {boolean} [args.dryRun] plan only: same reads, same guards, no sends* @returns {Promise<object>}*/-export async function sweepBack({ connection, mode = 'excess', includeTokens = true, network = 'mainnet' }) {+export async function sweepBack({ connection, mode = 'excess', includeTokens = true, network = 'mainnet', dryRun = false }) {const { PublicKey } = await import('@solana/web3.js');const master = ECONOMY_MASTER_ADDRESS;@@ -238,7 +245,7 @@ export async function sweepBack({ connection, mode = 'excess', includeTokens = t// (buyback USDC, withdrawal SPL float, NFT collection) keeps them; a// drain takes all.if (includeTokens && (mode === 'drain' || !wallet.holdsTokens)) {- const tokens = await sweepTokenBalances({ connection, owner: wallet.keypair, network });+ const tokens = await sweepTokenBalances({ connection, owner: wallet.keypair, network, dryRun });for (const t of tokens.swept) sweptTokens.push({ name, pubkey: wallet.pubkey, ...t });for (const f of tokens.failed) failed.push({ name, pubkey: wallet.pubkey, sol: null, reason: `token ${f.mint}: ${f.reason}` });}@@ -256,6 +263,10 @@ export async function sweepBack({ connection, mode = 'excess', includeTokens = t);skipped.push(...planSkipped);for (const step of plan) {+ if (dryRun) {+ sweptSol.push({ name: step.name, pubkey: step.pubkey, sol: step.sol, signature: null, dryRun: true });+ continue;+ }try {const signature = await sendSol({connection,@@ -281,6 +292,7 @@ export async function sweepBack({ connection, mode = 'excess', includeTokens = treturn {mode,+ dryRun,master,masterSolBefore,masterSolAfter,diff --git a/api/_lib/financial-tripwire.js b/api/_lib/financial-tripwire.jsindex 376090a81..6b47de408 100644--- a/api/_lib/financial-tripwire.js+++ b/api/_lib/financial-tripwire.js@@ -86,7 +86,12 @@ export async function lastActivityMs(table, tsColumn = 'created_at') {const rows = await sql(`SELECT extract(epoch from max(${tsColumn})) * 1000 AS ms FROM ${table}`);const ms = rows?.[0]?.ms;return ms != null ? Number(ms) : null;- } catch {- return null; // table absent / empty → treat as no activity on record+ } catch (err) {+ // A missing table legitimately means "nothing has happened yet", but a typo'd+ // column name produces the same null and turns the tripwire into a permanent+ // false "enabled but SILENT" alarm. Say so in the logs so the next mismatch+ // is one grep away instead of an alert nobody can explain.+ console.warn('[tripwire] last-activity read failed', { table, column: tsColumn, message: err?.message });+ return null;}}diff --git a/api/cron/treasury-sweepback.js b/api/cron/treasury-sweepback.jsindex fbde13e7d..98582db06 100644--- a/api/cron/treasury-sweepback.js+++ b/api/cron/treasury-sweepback.js@@ -17,6 +17,10 @@// every reclaimed rent lamport, all SOL minus fee headroom. Engines are left// unfunded until the next topup, so this is for decommission or emergency// recovery and requires the explicit confirm token.+// • ?dry=1 (either mode) is plan only. Same balance reads, same alias merging+// and floor math, but nothing is signed or sent, no ledger row is written and+// no alert fires. It is the only way to inspect what a sweep would consolidate+// without moving money, and the mirror of treasury-topup's own ?dry=1.//// Every movement lands in the tamper-evident economy_master_ledger as `inflow`// / `inflow_token` rows chained onto the same history the topup writes.@@ -27,7 +31,6 @@import { randomUUID } from 'node:crypto';import { error, json, method, wrapCron } from '../_lib/http.js';-import { env } from '../_lib/env.js';import { sendOpsAlert } from '../_lib/alerts.js';import { sweepBack } from '../_lib/economy-sweepback.js';import { ECONOMY_MASTER_ADDRESS } from '../_lib/economy-master.js';@@ -41,10 +44,13 @@ export default wrapCron(async (req, res) => {const url = new URL(req.url || '/', 'https://internal');const mode = url.searchParams.get('mode') === 'drain' ? 'drain' : 'excess';const includeTokens = url.searchParams.get('tokens') !== '0';+ // Plan-only inspection. Deliberately checked BEFORE the drain guard below so an+ // operator can preview a drain without holding the confirm token.+ const dryRun = /^(1|true)$/i.test(url.searchParams.get('dry') || '');// A drain empties every engine — never something a schedule or a stray GET// should be able to do. Require the explicit method + confirm token.- if (mode === 'drain' && (req.method !== 'POST' || url.searchParams.get('confirm') !== 'drain')) {+ if (mode === 'drain' && !dryRun && (req.method !== 'POST' || url.searchParams.get('confirm') !== 'drain')) {return error(res, 400, 'confirm_required', 'a full drain needs POST with ?mode=drain&confirm=drain');}@@ -52,7 +58,26 @@ export default wrapCron(async (req, res) => {const { solanaConnection } = await import('../_lib/solana/connection.js');const connection = solanaConnection({ url: rpcUrl, network: 'mainnet', commitment: 'confirmed' });- const result = await sweepBack({ connection, mode, includeTokens, network: 'mainnet' });+ const result = await sweepBack({ connection, mode, includeTokens, network: 'mainnet', dryRun });++ // A plan moved nothing, so there is nothing to book and nobody to page. Return+ // the plan verbatim: same shape as a real run, with every entry flagged dryRun.+ if (dryRun) {+ return json(res, 200, {+ ok: true,+ dry_run: true,+ rpc: rpcUrl,+ mode,+ master: result.master,+ master_sol_before: result.masterSolBefore,+ would_sweep_sol: result.sweptSol,+ would_sweep_tokens: result.sweptTokens,+ would_receive_sol: result.receivedSol,+ failed: result.failed,+ skipped: result.skipped,+ read_errors: result.readErrors,+ });+ }// Book every movement onto the master's hash chain. Same contract as the// topup: a dropped write never fails the response, but real money movingdiff --git a/api/cron/wallets-leak-scan.js b/api/cron/wallets-leak-scan.jsindex 2b247bef1..995feceaf 100644--- a/api/cron/wallets-leak-scan.js+++ b/api/cron/wallets-leak-scan.js@@ -15,7 +15,7 @@// never moves funds, CRON_SECRET-authed, bounded (≤100 sigs/wallet/run).import { randomUUID } from 'node:crypto';-import { error, json, method, wrapCron } from '../_lib/http.js';+import { json, method, wrapCron } from '../_lib/http.js';import { env } from '../_lib/env.js';import { sql } from '../_lib/db.js';import { sendOpsAlert } from '../_lib/alerts.js';@@ -226,7 +226,12 @@ export default wrapCron(async (req, res) => {// loop that DRIVES it (pipelines + tick), which should never be idle when on.const now = Date.now();const autoConfigured = String(env.X402_AUTONOMOUS_ENABLED ?? '').toLowerCase() !== 'false';- const autoLast = await lastActivityMs('x402_autonomous_log', 'created_at');+ // The log's timestamp column is `ts` (see the CREATE TABLE in+ // x402-autonomous-loop.js). Naming a column that does not exist made+ // lastActivityMs swallow the SQL error and answer null, so the tripwire read a+ // loop with half a million rows and activity seconds old as "no activity on+ // record" and alerted "enabled but SILENT" on every run.+ const autoLast = await lastActivityMs('x402_autonomous_log', 'ts');const tripwire = await runTripwire({subsystem: 'x402_autonomous_loop', configured: autoConfigured,lastActivityMs: autoLast, windowMinutes: 60, now, runId,diff --git a/docs/economy-master.md b/docs/economy-master.mdindex f225aaf5c..d079a3031 100644--- a/docs/economy-master.md+++ b/docs/economy-master.md@@ -98,6 +98,26 @@ every lamport cycles master → engines → work → master:rejects a transfer that would leave a wallet below rent exemption). Engines areleft unfunded until the next topup — use it to decommission the fleet orrecover everything to the root in one call.+- **Dry run (either mode).** Append `?dry=1` to plan without moving anything:+ the same balance reads, alias merging, and floor math run, then every entry+ comes back flagged `dryRun` with a `null` signature. Nothing is signed or+ broadcast, no ledger row is written, and no alert fires. A dry drain does not+ need the `confirm=drain` token, because a preview cannot empty anything:++ ```bash+ # what would the scheduled 6-hourly sweep consolidate right now?+ curl -s -H "Authorization: Bearer $CRON_SECRET" \+ 'https://three.ws/api/cron/treasury-sweepback?dry=1' | jq .would_sweep_sol++ # and what would a full drain pull back, tokens included?+ curl -s -H "Authorization: Bearer $CRON_SECRET" \+ 'https://three.ws/api/cron/treasury-sweepback?mode=drain&dry=1' | jq+ ```++ This is the mirror of the topup's own `?dry=1`, and it is what makes the+ return leg inspectable (and testable, see+ [`tests/cron-sweepback-dryrun.test.js`](../tests/cron-sweepback-dryrun.test.js))+ without moving real mainnet SOL.The destination lock is the mirror of the topup allowlist: the only recipient inthe module is the `ECONOMY_MASTER_ADDRESS` constant — not a parameter — so nodiff --git a/tests/cron-sweepback-dryrun.test.js b/tests/cron-sweepback-dryrun.test.jsnew file mode 100644index 000000000..2f5a06d07--- /dev/null+++ b/tests/cron-sweepback-dryrun.test.js@@ -0,0 +1,98 @@+// The consolidation sweep's plan-only mode (api/_lib/economy-sweepback.js).+//+// treasury-sweepback moves real mainnet SOL and, unlike its mirror+// treasury-topup, had no way to be inspected or exercised without doing so: the+// only reachable branches were the auth gate and the drain confirm guard. ?dry=1+// closes that, and the property that makes it worth anything is negative: a dry+// sweep must read balances, apply the same floors, and then sign and broadcast+// NOTHING. These tests assert exactly that by mocking the two send paths and+// failing if either is ever reached.+import { test, expect, vi, beforeEach } from 'vitest';+import { Keypair } from '@solana/web3.js';++const sendSol = vi.fn(async () => 'live-signature');+const submitProtected = vi.fn(async () => ({ signature: 'live-token-signature' }));++const ENGINE = Keypair.generate();++vi.mock('../api/_lib/solana-signers.js', () => ({+ SOLANA_SIGNERS: [{ name: 'test-engine', minSol: 0.1, refillTo: 0.3, network: 'mainnet', holdsTokens: false }],+ loadSignerKeypair: async () => ({ keypair: ENGINE, configured: true, decodeError: null }),+}));+vi.mock('../api/_lib/avatar-wallet.js', () => ({+ sendSol: (...args) => sendSol(...args),+ LAMPORTS_PER_SOL: 1_000_000_000,+}));+vi.mock('../api/_lib/execution-engine.js', () => ({+ submitProtected: (...args) => submitProtected(...args),+}));++const { sweepBack } = await import('../api/_lib/economy-sweepback.js');++// One idle engine holding `engineSol` against a 0.3 float, plus one SPL balance+// worth consolidating. Everything a real sweep would act on is present.+function connectionWith({ engineSol = 2 }) {+ return {+ getBalance: async () => Math.round(engineSol * 1_000_000_000),+ getParsedTokenAccountsByOwner: async () => ({+ value: [+ {+ pubkey: Keypair.generate().publicKey,+ account: {+ data: {+ parsed: {+ info: {+ mint: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',+ tokenAmount: { amount: '1250000', decimals: 6 },+ },+ },+ },+ },+ },+ ],+ }),+ };+}++beforeEach(() => {+ sendSol.mockClear();+ submitProtected.mockClear();+});++test('a dry sweep plans the SOL move without signing or sending it', async () => {+ const result = await sweepBack({ connection: connectionWith({ engineSol: 2 }), network: 'mainnet', dryRun: true });++ expect(sendSol).not.toHaveBeenCalled();+ expect(result.dryRun).toBe(true);+ // 2 SOL against a 0.3 float leaves 1.7 above it.+ expect(result.sweptSol).toHaveLength(1);+ expect(result.sweptSol[0]).toMatchObject({ sol: 1.7, signature: null, dryRun: true });+ expect(result.receivedSol).toBe(1.7);+});++test('a dry sweep plans the token move without broadcasting it', async () => {+ const result = await sweepBack({ connection: connectionWith({ engineSol: 2 }), network: 'mainnet', dryRun: true });++ expect(submitProtected).not.toHaveBeenCalled();+ // Both SPL programs are walked, so the same holding is planned once per program.+ expect(result.sweptTokens.length).toBeGreaterThan(0);+ for (const t of result.sweptTokens) {+ expect(t).toMatchObject({ amount: '1250000', decimals: 6, signature: null, dryRun: true });+ }+});++test('a dry sweep still applies the float, so an engine at its floor is skipped', async () => {+ const result = await sweepBack({ connection: connectionWith({ engineSol: 0.25 }), network: 'mainnet', dryRun: true });++ expect(sendSol).not.toHaveBeenCalled();+ expect(result.sweptSol).toHaveLength(0);+ expect(result.skipped.map((s) => s.reason)).toContain('at_or_below_float');+});++test('the default (non-dry) sweep still sends, so dry mode is opt-in only', async () => {+ const result = await sweepBack({ connection: connectionWith({ engineSol: 2 }), network: 'mainnet' });++ expect(sendSol).toHaveBeenCalledTimes(1);+ expect(result.dryRun).toBe(false);+ expect(result.sweptSol[0]).toMatchObject({ sol: 1.7, signature: 'live-signature' });+});