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.

Add live-state audit report for x402 ring economy and unit tests for ring config logic

nrpo804800031508
diff --git a/api/_lib/migrations/2026-07-03-x402-ring-agents.sql b/api/_lib/migrations/2026-07-03-x402-ring-agents.sql
new file mode 100644
index 000000000..c006ee456
--- /dev/null
+++ b/api/_lib/migrations/2026-07-03-x402-ring-agents.sql
@@ -0,0 +1,31 @@
+-- 2026-07-03-x402-ring-agents.sql
+--
+-- Platform agents as real buyers in the x402 ring (Task 09).
+--
+-- The closed-loop economy stops being "a cron paying itself" once the buyers are
+-- named, custodial-walleted platform agents. This migration adds the ONE piece of
+-- durable schema that turns anonymous ring traffic into an attributable
+-- agent-to-agent economy: an `agent_id` column on the per-call settlement log so
+-- the dashboard can show WHICH agent bought WHAT.
+--
+-- x402_autonomous_log.agent_id — the buying agent_identities.id for a purchase
+-- driven by a roster persona (NULL for the
+-- generic seed-wallet volume/health traffic that
+-- predates the agent roster). Indexed for the
+-- per-agent attribution panel (Task 10).
+--
+-- Roster wallets themselves are registered in the EXISTING x402_ring_wallets table
+-- (role='agent') by the provisioning path — no new table. That keeps them inside
+-- ringAllowedAddresses() (Task 06) and the ring verify script (Task 03)
+-- automatically, since both read x402_ring_wallets.
+
+ALTER TABLE x402_autonomous_log ADD COLUMN IF NOT EXISTS agent_id uuid;
+
+CREATE INDEX IF NOT EXISTS x402_autonomous_log_agent_ts
+ ON x402_autonomous_log (agent_id, ts DESC);
+
+-- role='agent' is a new VALUE in the existing x402_ring_wallets.role column
+-- (payer | treasury | sponsor | agent). No constraint change is required — the
+-- column is free-text — but document the widened vocabulary here for the reader.
+COMMENT ON COLUMN x402_ring_wallets.role IS
+ 'payer | treasury | sponsor | agent — agent rows are custodial roster wallets that buy inside the ring (Task 09).';
diff --git a/api/_lib/migrations/20260703000000_x402_fee_audit.sql b/api/_lib/migrations/20260703000000_x402_fee_audit.sql
new file mode 100644
index 000000000..a63ade92c
--- /dev/null
+++ b/api/_lib/migrations/20260703000000_x402_fee_audit.sql
@@ -0,0 +1,44 @@
+-- 20260703000000_x402_fee_audit.sql
+--
+-- Fee audit rollup for the closed-loop x402 ring economy.
+--
+-- The ring's operating rule is "the lowest fees ALWAYS". The Fee Audit + ATA
+-- Rent Reclaim pipeline (api/_lib/x402/autonomous-registry.js → fee-audit,
+-- implemented in api/_lib/x402/pipelines/fee-audit.js) runs nightly, sums the
+-- REAL chain-read settlement fees for the day from x402_self_facilitator_log
+-- (fee_lamports comes from getParsedTransaction().meta.fee, not an estimate)
+-- plus the settlement + volume counts from x402_autonomous_log, and upserts one
+-- row per day here. It also reclaims ATA rent by closing zero-balance non-role
+-- ATAs, accumulating the reclaimed lamports + close count onto the same row.
+--
+-- Two efficiency numbers are the point of this table:
+-- lamports_per_settlement — real SOL fee burned per settled payment. At the
+-- 1-signature self-pay floor this is ~5,000; the
+-- pipeline alerts above 1.5× (7,500).
+-- sol_per_100_usd — SOL burned per $100 of gross ring volume, the
+-- headline "cost of moving a dollar" number.
+--
+-- The pipeline also creates this lazily (ensureSchema), so this migration is
+-- belt-and-suspenders for environments that run db:migrate.
+--
+-- Downstream consumer: GET /api/x402-ring exposes the two efficiency metrics
+-- (computed live from the same logs); this table is the durable daily history a
+-- dashboard charts and the acceptance run reads.
+
+CREATE TABLE IF NOT EXISTS x402_fee_audit (
+ day date PRIMARY KEY,
+ settlements bigint NOT NULL DEFAULT 0,
+ gross_volume_atomic numeric NOT NULL DEFAULT 0,
+ fees_lamports numeric NOT NULL DEFAULT 0,
+ lamports_per_settlement numeric,
+ sol_per_100_usd numeric,
+ budget_lamports numeric,
+ above_floor boolean NOT NULL DEFAULT false,
+ over_budget boolean NOT NULL DEFAULT false,
+ ata_closed_count int NOT NULL DEFAULT 0,
+ ata_rent_reclaimed_lamports numeric NOT NULL DEFAULT 0,
+ run_id uuid,
+ updated_at timestamptz NOT NULL DEFAULT now()
+);
+
+CREATE INDEX IF NOT EXISTS x402_fee_audit_day_desc ON x402_fee_audit (day DESC);
diff --git a/api/_lib/x402/autonomous-registry.js b/api/_lib/x402/autonomous-registry.js
index 795ce921d..821591a31 100644
--- a/api/_lib/x402/autonomous-registry.js
+++ b/api/_lib/x402/autonomous-registry.js
@@ -45,6 +45,7 @@ import { run as tokenIntelPreSnipeGate } from './pipelines/token-intel-gate.js';
import { run as sniperIntelEnrich } from './pipelines/sniper-intel-enrich.js';
import { run as volumeBootstrapLoop } from './pipelines/volume-bootstrap-loop.js';
import { run as ringRebalance } from './pipelines/ring-rebalance.js';
+import { run as feeAudit } from './pipelines/fee-audit.js';
import { run as liveFeedSeeder } from './pipelines/live-feed-seeder.js';
import { run as feeCalculationValidator } from './pipelines/fee-calculation-validator.js';
import { run as crossChainCostComparison } from './pipelines/cross-chain-cost.js';
@@ -2681,6 +2682,34 @@ const SELF_ENDPOINTS = [
run: (ctx) => ringRebalance(ctx),
},
+ // ── Fee Audit + ATA Rent Reclaim ─────────────────────────────────────────────
+ // Nightly enforcement of the ring's "lowest fees always" rule. Sums the real
+ // chain-read settlement fees for the day (x402_self_facilitator_log +
+ // x402_autonomous_log), derives lamports-per-settlement and SOL-per-$100 of
+ // volume, upserts one row into x402_fee_audit, and raises an ops alert when
+ // per-settlement fee drifts above 1.5× the 1-sig floor (7,500 lamports) or the
+ // daily burn exceeds X402_RING_DAILY_FEE_BUDGET_LAMPORTS (default 0.05 SOL).
+ // The same run reclaims ATA rent: it closes any zero-balance, non-role USDC
+ // ATA owned by a ring wallet (owner-signed, rent → owner, capped 5/run) — the
+ // safety selection is a pure, unit-tested function that never returns a funded
+ // or active role ATA. Audit + reclaim only — returns amountAtomic:0, never a
+ // spend, so it never consumes the daily cap. Value sink: x402_fee_audit
+ // (per-day). Downstream: GET /api/x402-ring exposes the two efficiency metrics.
+ {
+ id: 'fee-audit',
+ name: 'Fee Audit + ATA Rent Reclaim',
+ // path is informational — run() reads the fee logs and closes empty ATAs itself.
+ path: '/api/x402-ring',
+ method: 'GET',
+ body: null,
+ cooldown_s: 86400, // nightly
+ priority: 22,
+ pipeline: 'self',
+ enabled: true,
+ run: (ctx) => feeAudit(ctx),
+ extractSignal: null,
+ },
+
// ── Live Payment Feed Seeder (USE-025) ─────────────────────────────────────
// Keeps the homepage "live payment feed" (the /pay page, the in-world
// jumbotron and the exchange NPCs — all polling GET /api/x402-pay?feed=1)
diff --git a/api/_lib/x402/pipelines/fee-audit.js b/api/_lib/x402/pipelines/fee-audit.js
new file mode 100644
index 000000000..a5c8cfd2b
--- /dev/null
+++ b/api/_lib/x402/pipelines/fee-audit.js
@@ -0,0 +1,497 @@
+// api/_lib/x402/pipelines/fee-audit.js
+//
+// Fee Audit + ATA Rent Reclaim — autonomous pipeline (self/fee-audit).
+//
+// The owner's rule is "the lowest fees ALWAYS". This nightly pipeline is the
+// continuous enforcement of that rule: it measures the REAL SOL burned per
+// settlement and per $100 of ring volume, alarms when either drifts above
+// budget, and reclaims the one-time ATA rent the ring locks up over time.
+//
+// Two jobs, one run:
+//
+// 1. FEE ROLLUP (measurement). Sums the real, chain-read fees the self-hosted
+// facilitator logged for the day (x402_self_facilitator_log.fee_lamports —
+// populated from getParsedTransaction().meta.fee, not an estimate) plus the
+// settlement + volume counts from both the facilitator log and the
+// autonomous loop log. Derives lamports-per-settlement and SOL-per-$100 of
+// gross volume, upserts one row per day into x402_fee_audit, and raises an
+// ops alert when lamports-per-settlement exceeds 1.5× the 1-signature floor
+// (7,500 lamports) or the daily burn exceeds X402_RING_DAILY_FEE_BUDGET_
+// LAMPORTS (default 0.05 SOL). Those are the two ways the fee floor slips:
+// a per-tx regression (someone flipped off self-pay, or a priority fee
+// crept up) or runaway volume burning more SOL than budgeted.
+//
+// 2. ATA RENT RECLAIM (recovery). Every new receiver ATA the ring creates
+// locks 2,039,280 lamports of rent — one-time, but reclaimable by closing
+// the account once it is empty. This job enumerates the USDC token accounts
+// owned by the ring's role wallets and closes any that are (a) zero-balance
+// AND (b) not one of the three ACTIVE role ATAs (payer / treasury / sponsor
+// canonical USDC ATAs). Closing returns the rent to the owner wallet. It is
+// owner-signed, idempotent (a closed account simply no longer appears),
+// capped at 5 closes/run, and NEVER touches an account with a balance or an
+// active role ATA — the safety invariant selectClosableAtas() enforces and
+// the tests hammer before any live run.
+//
+// Value sink: x402_fee_audit (one row per day, upserted). Downstream consumer:
+// GET /api/x402-ring exposes fees.lamports_per_settlement and fees.sol_per_100_usd
+// read from the same live logs, and the acceptance run reads the measured
+// efficiency from here.
+//
+// No mocks. The rollup reads real settled-fee rows; the reclaim enumerates real
+// on-chain token accounts and closes empty ones with a real transaction.
+
+import { randomUUID } from 'node:crypto';
+import bs58 from 'bs58';
+import {
+ PublicKey, Keypair, TransactionMessage, VersionedTransaction, ComputeBudgetProgram,
+} from '@solana/web3.js';
+import {
+ getAssociatedTokenAddressSync, createCloseAccountInstruction,
+ TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
+} from '@solana/spl-token';
+
+import { sql as defaultSql } from '../../db.js';
+import { env } from '../../env.js';
+import { logger } from '../../usage.js';
+import { solanaConnection } from '../../solana/connection.js';
+import { sendOpsAlert } from '../../alerts.js';
+import { loadSeedKeypair, USDC_MINT, SIGNATURE_FEE_LAMPORTS, RING_CU_LIMIT, ringPriorityMicrolamports } from '../pay.js';
+
+const log = logger('x402-fee-audit');
+
+// One-time ATA rent (lamports) reclaimed per closed account. Matches the
+// facilitator's ATA_RENT_LAMPORTS — the same rent the create locked up.
+export const ATA_RENT_LAMPORTS = 2_039_280;
+
+// The 1-signature self-pay floor. lamports-per-settlement above 1.5× this is a
+// fee-floor regression worth an alert.
+const ONE_SIG_FLOOR_LAMPORTS = SIGNATURE_FEE_LAMPORTS; // 5000
+const PER_SETTLEMENT_ALERT_LAMPORTS = Math.round(ONE_SIG_FLOOR_LAMPORTS * 1.5); // 7500
+
+// Daily SOL-burn budget for the whole ring. Default 0.05 SOL. Above this the
+// day's burn is over budget regardless of per-tx efficiency (too much volume).
+function dailyFeeBudgetLamports() {
+ return Number(process.env.X402_RING_DAILY_FEE_BUDGET_LAMPORTS || 50_000_000);
+}
+
+// Max ATA closes per run — bounds the reclaim so one run can never fan out an
+// unbounded number of close transactions.
+const MAX_CLOSES_PER_RUN = 5;
+
+function loadKp(b58) {
+ const raw = bs58.decode(b58);
+ if (raw.length !== 64) throw new Error(`keypair expected 64 bytes, got ${raw.length}`);
+ return Keypair.fromSecretKey(raw);
+}
+
+// ── Pure: fee-efficiency math ────────────────────────────────────────────────
+// Given the day's real settled fee total, settlement count, and gross USDC
+// volume (atomic), derive the two efficiency numbers plus the alert verdicts.
+// Pure and total — the rollup and the tests both reason about this one function.
+export function computeFeeEfficiency({
+ feesLamports = 0,
+ settlements = 0,
+ grossVolumeAtomic = 0,
+ budgetLamports = 50_000_000,
+}) {
+ const fees = Number(feesLamports) || 0;
+ const n = Number(settlements) || 0;
+ const grossUsd = (Number(grossVolumeAtomic) || 0) / 1e6;
+ const lamportsPerSettlement = n > 0 ? Math.round(fees / n) : null;
+ const solBurned = fees / 1e9;
+ // SOL burned per $100 of gross volume. Null when there is no volume to
+ // normalize against (avoids a divide-by-zero that would read as "free").
+ const solPer100Usd = grossUsd > 0
+ ? Number(((solBurned / grossUsd) * 100).toFixed(9))
+ : null;
+ const aboveFloor = lamportsPerSettlement != null
+ && lamportsPerSettlement > PER_SETTLEMENT_ALERT_LAMPORTS;
+ const overBudget = fees > Number(budgetLamports);
+ return {
+ fees_lamports: fees,
+ settlements: n,
+ gross_volume_atomic: Number(grossVolumeAtomic) || 0,
+ gross_volume_usd: Number(grossUsd.toFixed(6)),
+ lamports_per_settlement: lamportsPerSettlement,
+ sol_burned: Number(solBurned.toFixed(9)),
+ sol_per_100_usd: solPer100Usd,
+ budget_lamports: Number(budgetLamports),
+ above_floor: aboveFloor,
+ over_budget: overBudget,
+ per_settlement_alert_lamports: PER_SETTLEMENT_ALERT_LAMPORTS,
+ };
+}
+
+// ── Pure: which role ATAs are active and must NEVER be closed ────────────────
+// The canonical USDC ATA for each configured ring role wallet. These hold (or
+// are meant to hold) the ring's live float — closing one would break settlement.
+// Returns a Set of base58 ATA addresses.
+export function activeRoleAtas({ mint, owners }) {
+ const set = new Set();
+ if (!mint) return set;
+ const mintPk = new PublicKey(mint);
+ for (const owner of owners) {
+ if (!owner) continue;
+ try {
+ const ownerPk = owner instanceof PublicKey ? owner : new PublicKey(owner);
+ const ata = getAssociatedTokenAddressSync(
+ mintPk, ownerPk, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,
+ );
+ set.add(ata.toBase58());
+ } catch { /* skip an unparseable owner */ }
+ }
+ return set;
+}
+
+// ── Pure: SAFETY-CRITICAL — pick which ATAs are closable ─────────────────────
+// Given enumerated USDC token accounts (each { pubkey, amount, mint }) and the
+// set of active role ATAs, return ONLY the ones safe to close: exact USDC mint,
+// zero balance, and NOT an active role ATA — capped. Every exclusion is defended
+// by a unit test. A non-zero balance or a role ATA is NEVER returned, no matter
+// the cap. This is the invariant the whole reclaim rests on.
+export function selectClosableAtas({ accounts, activeAtaSet, mint, cap = MAX_CLOSES_PER_RUN }) {
+ const out = [];
+ for (const acc of accounts || []) {
+ if (out.length >= cap) break;
+ if (!acc || !acc.pubkey) continue;
+ // Wrong mint → never touch (defensive; the enumerator already filters).
+ if (mint && acc.mint && acc.mint !== mint) continue;
+ // Active role ATA → the ring's live float. Never close.
+ if (activeAtaSet.has(acc.pubkey)) continue;
+ // Any balance → funded account. Never close (would burn the tokens).
+ const amount = BigInt(acc.amount ?? 0n);
+ if (amount !== 0n) continue;
+ out.push(acc.pubkey);
+ }
+ return out;
+}
+
+// One-time DDL guard per warm instance (mirrors the loop's ensureSchema idiom).
+let _schemaReady = false;
+async function ensureSchema(sql) {
+ if (_schemaReady) return;
+ await sql`
+ CREATE TABLE IF NOT EXISTS x402_fee_audit (
+ day date PRIMARY KEY,
+ settlements bigint NOT NULL DEFAULT 0,
+ gross_volume_atomic numeric NOT NULL DEFAULT 0,
+ fees_lamports numeric NOT NULL DEFAULT 0,
+ lamports_per_settlement numeric,
+ sol_per_100_usd numeric,
+ budget_lamports numeric,
+ above_floor boolean NOT NULL DEFAULT false,
+ over_budget boolean NOT NULL DEFAULT false,
+ ata_closed_count int NOT NULL DEFAULT 0,
+ ata_rent_reclaimed_lamports numeric NOT NULL DEFAULT 0,
+ run_id uuid,
+ updated_at timestamptz NOT NULL DEFAULT now()
+ )
+ `;
+ _schemaReady = true;
+}
+
+// Sum the day's real settled fees + settlement/volume counts. Fees come ONLY
+// from the facilitator log (the sole place a real chain-read fee is recorded);
+// the autonomous log contributes its successful paid calls to the settlement +
+// volume totals so the efficiency number reflects the full ring, not just the
+// self-facilitator lane.
+async function readDailyTotals(sql) {
+ const [fac] = await sql`
+ SELECT count(*)::bigint AS settlements,
+ COALESCE(sum(fee_lamports), 0)::numeric AS fees_lamports,
+ COALESCE(sum(amount_atomic), 0)::numeric AS gross_atomic
+ FROM x402_self_facilitator_log
+ WHERE action = 'settle' AND ok = true
+ AND ts >= date_trunc('day', now())
+ `;
+ // Autonomous loop paid calls today (successful, non-zero spend). These add to
+ // the settlement + volume denominators; their on-chain fee — when settled by
+ // our own facilitator — is already counted in the facilitator sum above, so
+ // we deliberately do NOT add a second fee figure here.
+ const [auto] = await sql`
+ SELECT count(*)::bigint AS settlements,
+ COALESCE(sum(amount_atomic), 0)::numeric AS gross_atomic
+ FROM x402_autonomous_log
+ WHERE success = true AND amount_atomic > 0
+ AND ts >= date_trunc('day', now())
+ `;
+ return {
+ feesLamports: Number(fac?.fees_lamports || 0),
+ facSettlements: Number(fac?.settlements || 0),
+ facGrossAtomic: Number(fac?.gross_atomic || 0),
+ autoSettlements: Number(auto?.settlements || 0),
+ autoGrossAtomic: Number(auto?.gross_atomic || 0),
+ };
+}
+
+// Enumerate the ring's USDC token accounts, one owner at a time. Returns
+// { owner, ownerKp, pubkey, amount, mint } rows — every USDC account each role
+// wallet owns, with its live balance. Best-effort per owner: an RPC hiccup on
+// one owner skips that owner, never the whole reclaim.
+async function enumerateRingUsdcAccounts(conn, mint, roleWallets) {
+ const rows = [];
+ const mintPk = new PublicKey(mint);
+ for (const { role, kp } of roleWallets) {
+ try {
+ const res = await conn.getParsedTokenAccountsByOwner(kp.publicKey, { mint: mintPk });
+ for (const { pubkey, account } of res.value) {
+ const info = account?.data?.parsed?.info;
+ const amount = BigInt(info?.tokenAmount?.amount ?? '0');
+ rows.push({
+ role,
+ ownerKp: kp,
+ owner: kp.publicKey.toBase58(),
+ pubkey: pubkey.toBase58(),
+ amount,
+ mint,
+ });
+ }
+ } catch (err) {
+ log.warn('enumerate_owner_failed', { role, message: err?.message });
+ }
+ }
+ return rows;
+}
+
+async function confirmSignature(conn, signature, timeoutMs = 30_000) {
+ const deadline = Date.now() + timeoutMs;
+ for (;;) {
+ const { value } = await conn.getSignatureStatuses([signature]);
+ const st = value?.[0];
+ if (st) {
+ if (st.err) return { confirmed: false, err: JSON.stringify(st.err) };
+ if (st.confirmationStatus === 'confirmed' || st.confirmationStatus === 'finalized') {
+ return { confirmed: true };
+ }
+ }
+ if (Date.now() > deadline) return { confirmed: false, err: 'confirm_timeout' };
+ await new Promise((r) => setTimeout(r, 1200));
+ }
+}
+
+// Close one empty ATA, owner-signed, rent → owner. Returns the signature or an
+// error string. The owner is BOTH the fee payer and the close authority, so the
+// tx is 1 signature; rent lands back in the owner's SOL balance.
+async function closeEmptyAta(conn, { ownerKp, pubkey }) {
+ const account = new PublicKey(pubkey);
+ const owner = ownerKp.publicKey;
+ const { blockhash } = await conn.getLatestBlockhash('confirmed');
+ const ixs = [
+ ComputeBudgetProgram.setComputeUnitLimit({ units: RING_CU_LIMIT }),
+ ComputeBudgetProgram.setComputeUnitPrice({ microLamports: ringPriorityMicrolamports(0) }),
+ // closeAccount: [account, destination(rent), authority]. Destination =
+ // owner → the reclaimed rent returns to the wallet that funded it.
+ createCloseAccountInstruction(account, owner, owner, [], TOKEN_PROGRAM_ID),
+ ];
+ const msg = new TransactionMessage({
+ payerKey: owner,
+ recentBlockhash: blockhash,
+ instructions: ixs,
+ }).compileToV0Message();
+ const vtx = new VersionedTransaction(msg);
+ vtx.sign([ownerKp]);
+ let signature;
+ try {
+ signature = await conn.sendRawTransaction(vtx.serialize(), { skipPreflight: false, maxRetries: 5 });
+ } catch (err) {
+ return { ok: false, error: `close_broadcast_failed:${String(err?.message || err).slice(0, 160)}` };
+ }
+ const conf = await confirmSignature(conn, signature);
+ if (!conf.confirmed) return { ok: false, error: `close_not_confirmed:${conf.err}`, signature };
+ return { ok: true, signature };
+}
+
+// Resolve the ring's role wallets we can sign for (needed to close their empty
+// ATAs). Payer + treasury + sponsor, each only if its secret is configured.
+function resolveRoleWallets() {
+ const wallets = [];
+ try { wallets.push({ role: 'payer', kp: loadSeedKeypair() }); } catch { /* payer unset */ }
+ const treasurySecret = process.env.X402_TREASURY_SECRET_BASE58;
+ if (treasurySecret) {
+ try { wallets.push({ role: 'treasury', kp: loadKp(treasurySecret) }); } catch { /* bad key */ }
+ }
+ const sponsorSecret = process.env.X402_FEE_PAYER_SECRET_BASE58;
+ if (sponsorSecret) {
+ try { wallets.push({ role: 'sponsor', kp: loadKp(sponsorSecret) }); } catch { /* bad key */ }
+ }
+ return wallets;
+}
+
+/**
+ * Run the fee audit + ATA rent reclaim. Conforms to the run()-style registry
+ * contract. All ctx fields optional for a standalone/manual run.
+ *
+ * @param {object} ctx { sql, conn, redis, runId, dryRun }
+ * dryRun — enumerate + select closable ATAs but broadcast nothing (used by the
+ * acceptance run to prove the reclaim's safety selection without spend).
+ * @returns the aggregate the loop records to x402_autonomous_log.
+ */
+export async function run(ctx = {}) {
+ const runId = ctx.runId || randomUUID();
+ const sql = ctx.sql || defaultSql;
+ const dryRun = ctx.dryRun === true;
+
+ if (!USDC_MINT) {
+ return { success: false, amountAtomic: 0, skipped: true, note: 'usdc_mint_unset' };
+ }
+
+ // ── 1. Fee rollup ─────────────────────────────────────────────────────────
+ let eff = null;
+ try {
+ await ensureSchema(sql);
+ const totals = await readDailyTotals(sql);
+ const settlements = totals.facSettlements + totals.autoSettlements;
+ const grossVolumeAtomic = totals.facGrossAtomic + totals.autoGrossAtomic;
+ eff = computeFeeEfficiency({
+ feesLamports: totals.feesLamports,
+ settlements,
+ grossVolumeAtomic,
+ budgetLamports: dailyFeeBudgetLamports(),
+ });
+ } catch (err) {
+ log.warn('fee_rollup_failed', { message: err?.message });
+ }
+
+ // ── 2. ATA rent reclaim ─────────────────────────────────────────────────────
+ let closedCount = 0;
+ let reclaimedLamports = 0;
+ const closedSigs = [];
+ const selected = [];
+ let reclaimNote = 'no_role_wallets';
+ try {
+ const roleWallets = resolveRoleWallets();
+ if (roleWallets.length > 0) {
+ const conn = ctx.conn || solanaConnection({ url: env.SOLANA_RPC_URL, commitment: 'confirmed' });
+ // The three active role ATAs — the canonical USDC ATA of each role
+ // wallet AND the advertised treasury/sponsor pubkeys (a role wallet
+ // might be configured only by pubkey, no secret).
+ const activeOwners = [
+ ...roleWallets.map((w) => w.kp.publicKey),
+ env.X402_PAY_TO_SOLANA || null,
+ env.X402_FEE_PAYER_SOLANA || null,
+ ];
+ const activeAtaSet = activeRoleAtas({ mint: USDC_MINT, owners: activeOwners });
+
+ const accounts = await enumerateRingUsdcAccounts(conn, USDC_MINT, roleWallets);
+ const closablePubkeys = selectClosableAtas({
+ accounts, activeAtaSet, mint: USDC_MINT, cap: MAX_CLOSES_PER_RUN,
+ });
+ // Map selected pubkeys back to their owner keypair for signing.
+ const byPubkey = new Map(accounts.map((a) => [a.pubkey, a]));
+ for (const pk of closablePubkeys) selected.push(byPubkey.get(pk));
+
+ if (dryRun) {
+ reclaimNote = `dry_run_selected:${selected.length}`;
+ log.info('fee_audit_dry_run', {
+ run_id: runId,
+ enumerated: accounts.length,
+ active_role_atas: activeAtaSet.size,
+ closable: selected.map((s) => ({ role: s.role, ata: s.pubkey })),
+ });
+ } else {
+ for (const acc of selected) {
+ const res = await closeEmptyAta(conn, acc);
+ if (res.ok) {
+ closedCount += 1;
+ reclaimedLamports += ATA_RENT_LAMPORTS;
+ closedSigs.push(res.signature);
+ log.info('ata_rent_reclaimed', {
+ run_id: runId, role: acc.role, ata: acc.pubkey, tx: res.signature,
+ });
+ } else {
+ log.warn('ata_close_failed', { role: acc.role, ata: acc.pubkey, error: res.error });
+ }
+ }
+ reclaimNote = `closed:${closedCount}`;
+ }
+ }
+ } catch (err) {
+ log.warn('ata_reclaim_failed', { message: err?.message });
+ reclaimNote = `reclaim_error:${err?.message}`;
+ }
+
+ // ── 3. Persist the day's audit row (upsert) ──────────────────────────────────
+ if (eff) {
+ try {
+ await sql`
+ INSERT INTO x402_fee_audit
+ (day, settlements, gross_volume_atomic, fees_lamports,
+ lamports_per_settlement, sol_per_100_usd, budget_lamports,
+ above_floor, over_budget, ata_closed_count,
+ ata_rent_reclaimed_lamports, run_id, updated_at)
+ VALUES
+ (date_trunc('day', now()), ${eff.settlements}, ${eff.gross_volume_atomic},
+ ${eff.fees_lamports}, ${eff.lamports_per_settlement}, ${eff.sol_per_100_usd},
+ ${eff.budget_lamports}, ${eff.above_floor}, ${eff.over_budget},
+ ${closedCount}, ${reclaimedLamports}, ${runId}, now())
+ ON CONFLICT (day) DO UPDATE SET
+ settlements = EXCLUDED.settlements,
+ gross_volume_atomic = EXCLUDED.gross_volume_atomic,
+ fees_lamports = EXCLUDED.fees_lamports,
+ lamports_per_settlement = EXCLUDED.lamports_per_settlement,
+ sol_per_100_usd = EXCLUDED.sol_per_100_usd,
+ budget_lamports = EXCLUDED.budget_lamports,
+ above_floor = EXCLUDED.above_floor,
+ over_budget = EXCLUDED.over_budget,
+ ata_closed_count = x402_fee_audit.ata_closed_count + EXCLUDED.ata_closed_count,
+ ata_rent_reclaimed_lamports = x402_fee_audit.ata_rent_reclaimed_lamports + EXCLUDED.ata_rent_reclaimed_lamports,
+ run_id = EXCLUDED.run_id,
+ updated_at = now()
+ `;
+ } catch (err) {
+ log.warn('fee_audit_upsert_failed', { message: err?.message });
+ }
+ }
+
+ // ── 4. Alert on fee-floor drift ──────────────────────────────────────────────
+ if (eff && (eff.above_floor || eff.over_budget)) {
+ const reasons = [];
+ if (eff.above_floor) {
+ reasons.push(
+ `lamports/settlement ${eff.lamports_per_settlement} > ${eff.per_settlement_alert_lamports} (1.5× the 1-sig floor)`,
+ );
+ }
+ if (eff.over_budget) {
+ reasons.push(
+ `daily burn ${eff.sol_burned} SOL > budget ${(eff.budget_lamports / 1e9).toFixed(4)} SOL`,
+ );
+ }
+ await sendOpsAlert(
+ 'x402 ring fee floor drift',
+ `${reasons.join('; ')}. settlements=${eff.settlements}, ` +
+ `gross=$${eff.gross_volume_usd}, sol/$100=${eff.sol_per_100_usd}`,
+ { signature: 'x402-fee-audit-drift' },
+ ).catch(() => {});
+ log.warn('fee_floor_drift', { run_id: runId, ...eff });
+ }
+
+ const note = eff
+ ? `settlements=${eff.settlements} lamports/settle=${eff.lamports_per_settlement} ` +
+ `sol/$100=${eff.sol_per_100_usd} ${reclaimNote}`
+ : `rollup_unavailable ${reclaimNote}`;
+
+ return {
+ success: true,
+ amountAtomic: 0, // audit + reclaim — never a spend
+ txSig: closedSigs[0] || null,
+ signalData: eff ? { ...eff, ata_closed_count: closedCount, ata_rent_reclaimed_lamports: reclaimedLamports } : null,
+ valueExtracted: {
+ fees: eff,
+ reclaim: {
+ dry_run: dryRun,
+ selected: selected.map((s) => ({ role: s?.role, ata: s?.pubkey })),
+ closed_count: closedCount,
+ reclaimed_lamports: reclaimedLamports,
+ signatures: closedSigs,
+ },
+ },
+ note,
+ };
+}
+
+export const FEE_AUDIT = Object.freeze({
+ perSettlementAlertLamports: PER_SETTLEMENT_ALERT_LAMPORTS,
+ oneSigFloorLamports: ONE_SIG_FLOOR_LAMPORTS,
+ maxClosesPerRun: MAX_CLOSES_PER_RUN,
+ ataRentLamports: ATA_RENT_LAMPORTS,
+});
diff --git a/api/_lib/x402/pipelines/volume-shared.js b/api/_lib/x402/pipelines/volume-shared.js
new file mode 100644
index 000000000..015829ce9
--- /dev/null
+++ b/api/_lib/x402/pipelines/volume-shared.js
@@ -0,0 +1,276 @@
+// api/_lib/x402/pipelines/volume-shared.js
+//
+// Shared plumbing for the ring's paid-traffic drivers. Both the 5-minute volume
+// bootstrap loop (volume-bootstrap-loop.js) and the per-minute ring tick
+// (api/cron/x402-ring-tick.js) settle real USDC across the SAME internal
+// catalog, record to the SAME per-call log, and roll up the SAME per-endpoint
+// ledger. This module is that single source of truth so there is exactly one
+// payment-recording path, not two that drift.
+//
+// Nothing here mints, prices, or moves money — it is the catalog + the two
+// durable sinks (x402_autonomous_log rows and the x402_volume_metrics ledger).
+// The payment itself is always payX402 (../pay.js); callers own budget/cadence.
+
+import { USDC_MINT } from '../pay.js';
+
+export const ASSET = USDC_MINT || 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+
+// Self-imposed per-run USDC budget (atomics, 6dp) for the 5-minute volume loop.
+// Bounds a single tick on top of the loop's daily cap so one run can't drain the
+// day. Raised from the original $0.05 to ACCOMMODATE the ring-settle price this
+// catalog rotates ($1.00 default, X402_PRICE_RING_SETTLE) — at $0.05 the
+// flagship ring-settle call was silently skipped every cycle (cap_would_exceed).
+// The pair is documented in .env.example; validateRingConfig() flags a
+// price > cap contradiction, and payX402 warns loudly if one is ever hit.
+// Default $1.10 = 1_100_000 (ring-settle $1.00 + headroom for the cheap calls a
+// window sweeps alongside it). The loop's daily cap still bounds total spend.
+export const VOLUME_PER_RUN_CAP_ATOMIC = Math.max(
+ 0,
+ Number(process.env.X402_VOLUME_PER_RUN_CAP_ATOMIC || 1_100_000),
+);
+
+// How many endpoints the 5-minute volume loop sweeps per run (cursor advances by
+// this each tick). With the catalog below a batch of 4 covers the full set in
+// ~3 runs.
+export const VOLUME_BATCH_PER_RUN = Math.max(
+ 1,
+ Number(process.env.X402_VOLUME_BATCH_PER_RUN || 4),
+);
+
+// The canonical catalog of paid self x402 endpoints the ring drivers round-robin.
+// Each body is a proven, harmless canary payload (mirrors the per-endpoint health
+// entries in autonomous-registry.js) so every sweep call is a valid paid request.
+// INTERNAL paths only — the ring never pays anything outside three.ws; this list
+// is hardcoded and X402_EXTERNAL_ENABLED has no effect on it. To add an endpoint
+// to ring volume, add it here — the cursor, the metrics ledger, and the
+// per-minute tick pick it up automatically. The drivers themselves are never
+// listed (they are not HTTP endpoints; no self-recursion).
+export const VOLUME_ENDPOINTS = [
+ // Ring-settle is the price-configurable, INTERNAL settlement primitive — the
+ // fee-optimal way to carry volume (fewer, larger payments). The per-minute
+ // ring tick fires it every Nth tick; the volume loop rotates it too. Its price
+ // (X402_PRICE_RING_SETTLE, default $1.00) must fit the applicable per-run cap
+ // or it is skipped — the caps default high enough to fit it. See
+ // api/x402/ring-settle.js.
+ { key: 'ring-settle', name: 'Ring Settlement', path: '/api/x402/ring-settle', method: 'POST', body: { note: 'ring-cycle' } },
+ { key: 'dance-tip', name: 'Dance Tip', path: '/api/x402/dance-tip', method: 'POST', body: { dancer: '1', dance: 'hiphop' } },
+ { key: 'crypto-intel', name: 'Crypto Intel', path: '/api/x402/crypto-intel', method: 'POST', body: { topic: 'solana' } },
+ { key: 'three-intel', name: '$THREE Signal Feed', path: '/api/x402/three-intel', method: 'POST', body: {} },
+ { key: 'token-intel', name: 'Token Intel', path: '/api/x402/token-intel', method: 'POST', body: { mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', network: 'mainnet' } },
+ { key: 'fact-check', name: 'Fact Check', path: '/api/x402/fact-check', method: 'POST', body: { claim: 'The sky is blue' } },
+ { key: 'symbol-availability', name: 'Symbol Availability', path: '/api/x402/symbol-availability', method: 'POST', body: { symbol: 'HEALTH' } },
+ { key: 'pay-by-name', name: 'Pay By Name', path: '/api/x402/pay-by-name?name=threews.sol', method: 'GET', body: null },
+ { key: 'skill-marketplace', name: 'Skill Marketplace', path: '/api/x402/skill-marketplace', method: 'GET', body: null },
+ { key: 'agent-reputation', name: 'Agent Reputation', path: '/api/x402/agent-reputation', method: 'GET', body: null },
+ { key: 'club-cover', name: 'Club Cover Charge', path: '/api/x402/club-cover', method: 'POST', body: { club: 'canary_test' } },
+ { key: 'cosmetic-purchase', name: 'Cosmetic Purchase', path: '/api/x402/cosmetic-purchase', method: 'POST', body: { item: 'canary_test', quantity: 1, _health_check: true } },
+];
+
+// The ring-settle catalog entry (the periodic large volume carrier).
+export const RING_SETTLE_ENDPOINT = VOLUME_ENDPOINTS.find((e) => e.key === 'ring-settle');
+// Everything else — the cheap tips/services that dominate the per-minute count.
+export const CHEAP_ENDPOINTS = VOLUME_ENDPOINTS.filter((e) => e.key !== 'ring-settle');
+
+// Reserve the next window of `batch` endpoint indices, advancing a cursor
+// atomically. Redis INCRBY gives a stable rotation across warm instances; the
+// in-memory counter is the single-process fallback. `cursorKey` scopes the
+// rotation so the volume loop and the ring tick keep independent cursors.
+const _memCursors = new Map();
+export async function reserveWindow(redis, batch, len, cursorKey = 'x402:auto:volume:cursor') {
+ let end;
+ if (redis) {
+ try {
+ end = Number(await redis.incrby(cursorKey, batch));
+ } catch {
+ end = (_memCursors.get(cursorKey) || 0) + batch;
+ _memCursors.set(cursorKey, end);
+ }
+ } else {
+ end = (_memCursors.get(cursorKey) || 0) + batch;
+ _memCursors.set(cursorKey, end);
+ }
+ const start = end - batch;
+ const out = [];
+ for (let i = 0; i < batch; i++) out.push(((start + i) % len + len) % len);
+ return out;
+}
+
+// One-time DDL guard per warm instance. Both drivers call this before recording.
+let _schemaReady = false;
+export async function ensureVolumeSchema(sql) {
+ if (_schemaReady) return;
+ // Per-endpoint cumulative volume ledger. PRIMARY KEY endpoint_key → one row
+ // per paid endpoint, accumulated across every sweep (loop AND tick).
+ await sql`
+ CREATE TABLE IF NOT EXISTS x402_volume_metrics (
+ endpoint_key text PRIMARY KEY,
+ service_name text,
+ endpoint_path text,
+ network text NOT NULL DEFAULT 'solana:mainnet',
+ asset text,
+ call_count bigint NOT NULL DEFAULT 0,
+ success_count bigint NOT NULL DEFAULT 0,
+ fail_count bigint NOT NULL DEFAULT 0,
+ total_spent_atomic bigint NOT NULL DEFAULT 0,
+ last_amount_atomic bigint NOT NULL DEFAULT 0,
+ last_success boolean,
+ last_status int,
+ last_tx_signature text,
+ last_error text,
+ last_run_id uuid,
+ first_called_at timestamptz DEFAULT now(),
+ last_called_at timestamptz DEFAULT now()
+ )
+ `;
+ await sql`CREATE INDEX IF NOT EXISTS x402_volume_metrics_last_called ON x402_volume_metrics (last_called_at DESC)`;
+ // The autonomous log predates value_extracted; ensure the column exists
+ // (idempotent — shared with other pipelines).
+ await sql`ALTER TABLE x402_autonomous_log ADD COLUMN IF NOT EXISTS value_extracted jsonb`;
+ _schemaReady = true;
+}
+
+// Compact, generic liveness summary of a paid response — keeps the log row small
+// while still proving the endpoint returned something usable.
+export function summarizeResponse(body) {
+ if (body == null) return { ok: false, shape: 'empty' };
+ if (typeof body === 'string') return { ok: body.length > 0, shape: 'text', length: body.length };
+ if (Array.isArray(body)) return { ok: body.length > 0, shape: 'array', length: body.length };
+ if (typeof body === 'object') {
+ const keys = Object.keys(body);
+ return { ok: keys.length > 0 && !body.error, shape: 'object', keys: keys.slice(0, 12) };
+ }
+ return { ok: true, shape: typeof body };
+}
+
+// Upsert the per-endpoint volume ledger and return the resulting cumulative row.
+// Wrapped by the caller so a DB fault is logged, never fatal.
+export async function upsertVolumeMetric(sql, ep, { amountAtomic, txSig, success, status, errorMsg, runId }) {
+ const rows = await sql`
+ INSERT INTO x402_volume_metrics
+ (endpoint_key, service_name, endpoint_path, network, asset,
+ call_count, success_count, fail_count, total_spent_atomic,
+ last_amount_atomic, last_success, last_status, last_tx_signature,
+ last_error, last_run_id, first_called_at, last_called_at)
+ VALUES
+ (${ep.key}, ${ep.name}, ${ep.path}, ${'solana:mainnet'}, ${ASSET},
+ ${1}, ${success ? 1 : 0}, ${success ? 0 : 1}, ${amountAtomic || 0},
+ ${amountAtomic || 0}, ${success}, ${status ?? null}, ${txSig || null},
+ ${errorMsg || null}, ${runId}, now(), now())
+ ON CONFLICT (endpoint_key) DO UPDATE SET
+ service_name = EXCLUDED.service_name,
+ endpoint_path = EXCLUDED.endpoint_path,
+ asset = EXCLUDED.asset,
+ call_count = x402_volume_metrics.call_count + 1,
+ success_count = x402_volume_metrics.success_count + ${success ? 1 : 0},
+ fail_count = x402_volume_metrics.fail_count + ${success ? 0 : 1},
+ total_spent_atomic = x402_volume_metrics.total_spent_atomic + ${amountAtomic || 0},
+ last_amount_atomic = EXCLUDED.last_amount_atomic,
+ last_success = EXCLUDED.last_success,
+ last_status = EXCLUDED.last_status,
+ last_tx_signature = EXCLUDED.last_tx_signature,
+ last_error = EXCLUDED.last_error,
+ last_run_id = EXCLUDED.last_run_id,
+ last_called_at = now()
+ RETURNING call_count, success_count, fail_count, total_spent_atomic
+ `;
+ return rows[0] || null;
+}
+
+// Per-call row into x402_autonomous_log. `pipeline` tags the driver ('volume' or
+// 'ring-tick') so each driver's spend can be summed independently — this is what
+// keeps the ring tick's daily budget separate from the volume loop's.
+export async function recordVolumeCall(sql, runId, ep, {
+ endpointUrl, amountAtomic, txSig, responseData, durationMs, success, errorMsg, valueExtracted,
+ pipeline = 'volume', namePrefix = 'Volume',
+}, log) {
+ try {
+ await sql`
+ INSERT INTO x402_autonomous_log
+ (run_id, endpoint_type, service_name, endpoint_url,
+ network, amount_atomic, asset, tx_signature,
+ response_data, value_extracted, duration_ms, success, error_msg, pipeline)
+ VALUES
+ (${runId}, ${'self'}, ${`${namePrefix}: ${ep.name}`}, ${endpointUrl},
+ ${'solana:mainnet'}, ${amountAtomic || 0}, ${ASSET}, ${txSig || null},
+ ${responseData ? JSON.stringify(responseData) : null},
+ ${valueExtracted ? JSON.stringify(valueExtracted) : null},
+ ${durationMs || 0}, ${success}, ${errorMsg || null}, ${pipeline})
+ `;
+ } catch (err) {
+ log?.warn?.('volume_call_log_insert_failed', { endpoint: ep.key, pipeline, message: err?.message });
+ }
+}
+
+// Settle one catalog endpoint through payX402, roll it into the ledger, and
+// record the per-call log row. Returns the payX402 result plus the resolved
+// endpoint URL. This is the ONE place a ring driver pays + records a single
+// endpoint, so the loop and the tick never diverge. `payFn` is injectable for
+// tests; production passes payX402.
+export async function settleAndRecord({
+ sql, runId, ep, origin, remaining, ctx, pipeline, namePrefix, payFn, log,
+}) {
+ const endpointUrl = `${origin}${ep.path}`;
+ const t0 = Date.now();
+
+ let result;
+ try {
+ result = await payFn({
+ url: endpointUrl,
+ method: ep.method || 'POST',
+ body: ep.body,
+ buyer: ctx.buyer,
+ conn: ctx.conn,
+ blockhash: ctx.blockhash,
+ mintInfo: ctx.mintInfo,
+ remainingCap: remaining,
+ });
+ } catch (err) {
+ result = { success: false, paid: false, amountAtomic: 0, txSig: null, status: 0, responseBody: null, errorMsg: err?.message || 'fetch_failed' };
+ }
+
+ // Only PAID amounts count toward spend accounting; a skipped/failed call
+ // settled nothing, so its recorded amount is 0 (keeps SUM(amount_atomic) an
+ // honest spend total for the daily-cap query).
+ const paidAmount = result.paid ? (result.amountAtomic || 0) : 0;
+
+ let metric = null;
+ try {
+ metric = await upsertVolumeMetric(sql, ep, {
+ amountAtomic: paidAmount,
+ txSig: result.txSig,
+ success: result.success,
+ status: result.status,
+ errorMsg: result.errorMsg,
+ runId,
+ });
+ } catch (err) {
+ log?.warn?.('volume_metric_upsert_failed', { endpoint: ep.key, message: err?.message });
+ }
+
+ const valueExtracted = {
+ endpoint_key: ep.key,
+ paid: result.paid === true,
+ amount_atomic: paidAmount,
+ liveness: summarizeResponse(result.responseBody),
+ ...(metric ? {
+ cumulative_calls: Number(metric.call_count),
+ cumulative_success: Number(metric.success_count),
+ cumulative_spent_atomic: Number(metric.total_spent_atomic),
+ } : {}),
+ };
+
+ await recordVolumeCall(sql, runId, ep, {
+ endpointUrl,
+ amountAtomic: paidAmount,
+ txSig: result.txSig,
+ responseData: { status: result.status, liveness: valueExtracted.liveness },
+ durationMs: Date.now() - t0,
+ success: result.success,
+ errorMsg: result.errorMsg,
+ valueExtracted,
+ pipeline,
+ namePrefix,
+ }, log);
+
+ return { result, endpointUrl, paidAmount };
+}
diff --git a/api/_lib/x402/wallet-balance-monitor.js b/api/_lib/x402/wallet-balance-monitor.js
index 4791b7afa..1596ce1ad 100644
--- a/api/_lib/x402/wallet-balance-monitor.js
+++ b/api/_lib/x402/wallet-balance-monitor.js
@@ -152,6 +152,162 @@ async function writeRedisState(redis, sample) {
}
}
+// Read a wallet's live SOL balance (lamports) — null on any RPC failure so a
+// transient RPC hiccup never fabricates a false breach.
+async function readSol(conn, ownerB58) {
+ try {
+ return await conn.getBalance(new (await pk())(ownerB58), 'confirmed');
+ } catch {
+ return null;
+ }
+}
+
+// Read a wallet's live USDC balance (atomic) — null on RPC failure, 0 when the
+// ATA does not exist yet (a real "empty" state, not an error).
+async function readUsdc(conn, ownerB58) {
+ if (!USDC_MINT) return null;
+ try {
+ const spl = await import('@solana/spl-token');
+ const PublicKey = await pk();
+ const ata = spl.getAssociatedTokenAddressSync(
+ new PublicKey(USDC_MINT), new PublicKey(ownerB58), false,
+ spl.TOKEN_PROGRAM_ID, spl.ASSOCIATED_TOKEN_PROGRAM_ID,
+ );
+ try {
+ return Number((await spl.getAccount(conn, ata)).amount);
+ } catch {
+ return 0; // no ATA = zero USDC, a real balance
+ }
+ } catch {
+ return null; // spl-token unavailable — USDC unknown, don't fabricate a breach
+ }
+}
+
+let _PublicKey = null;
+async function pk() {
+ if (!_PublicKey) ({ PublicKey: _PublicKey } = await import('@solana/web3.js'));
+ return _PublicKey;
+}
+
+// Resolve the three ring wallet addresses from env, exactly as production does:
+// treasury = X402_PAY_TO_SOLANA, sponsor = X402_FEE_PAYER_SOLANA, payer = the
+// seed keypair's pubkey (loadSeedKeypair). Any role whose env is unset is
+// reported as unconfigured, never guessed.
+function resolveRingAddresses() {
+ let payer = null;
+ try {
+ payer = loadSeedKeypair().publicKey.toBase58();
+ } catch { /* payer key not configured in this env */ }
+ return {
+ payer,
+ treasury: env.X402_PAY_TO_SOLANA || null,
+ sponsor: env.X402_FEE_PAYER_SOLANA || null,
+ };
+}
+
+/**
+ * Check the three ring wallets against their role-appropriate floors and raise
+ * an ops alert on any breach. Reads balances live on-chain (no funds moved).
+ * Best-effort: an unresolved address or dead RPC is reported, never thrown.
+ *
+ * @param {object} ctx — { redis } optional, for the cheap-read snapshot.
+ * @returns {Promise<{ configured: boolean, wallets: object[], breaches: string[] }>}
+ */
+export async function checkRingWallets(ctx = {}) {
+ const redis = ctx.redis || null;
+ const addrs = resolveRingAddresses();
+ const anyConfigured = Boolean(addrs.payer || addrs.treasury || addrs.sponsor);
+ if (!anyConfigured) {
+ return { configured: false, wallets: [], breaches: [] };
+ }
+
+ let conn;
+ try {
+ conn = solanaConnection({ url: env.SOLANA_RPC_URL, commitment: 'confirmed' });
+ } catch (err) {
+ log.warn('ring_balance_conn_failed', { message: err?.message });
+ return { configured: true, wallets: [], breaches: [], error: 'rpc_unavailable' };
+ }
+
+ // Per-role floor spec. Treasury is intentionally floor-free (it fills + gets
+ // swept). SOL floors apply to sponsor always and to payer in self-pay mode.
+ const selfPay = String(process.env.X402_RING_SELF_PAY || env.X402_RING_SELF_PAY || '').toLowerCase() === 'true';
+ const specs = [
+ { role: 'sponsor', address: addrs.sponsor, solFloor: RING_SOL_FLOOR_LAMPORTS, usdcFloor: null },
+ { role: 'payer', address: addrs.payer, solFloor: selfPay ? RING_SOL_FLOOR_LAMPORTS : null, usdcFloor: RING_PAYER_USDC_FLOOR_ATOMIC },
+ { role: 'treasury', address: addrs.treasury, solFloor: null, usdcFloor: null },
+ ];
+
+ const wallets = [];
+ const breaches = [];
+ for (const spec of specs) {
+ if (!spec.address) {
+ wallets.push({ role: spec.role, address: null, configured: false });
+ continue;
+ }
+ const lamports = await readSol(conn, spec.address);
+ const usdcAtomic = spec.usdcFloor != null || spec.role === 'payer' || spec.role === 'treasury'
+ ? await readUsdc(conn, spec.address)
+ : null;
+ const solLow = spec.solFloor != null && lamports != null && lamports < spec.solFloor;
+ const usdcLow = spec.usdcFloor != null && usdcAtomic != null && usdcAtomic < spec.usdcFloor;
+
+ const entry = {
+ role: spec.role,
+ address: spec.address,
+ configured: true,
+ sol: lamports != null ? lamports / LAMPORTS_PER_SOL : null,
+ usdc: usdcAtomic != null ? usdcAtomic / 1e6 : null,
+ sol_floor: spec.solFloor != null ? spec.solFloor / LAMPORTS_PER_SOL : null,
+ usdc_floor: spec.usdcFloor != null ? spec.usdcFloor / 1e6 : null,
+ sol_low: solLow,
+ usdc_low: usdcLow,
+ };
+ wallets.push(entry);
+
+ if (solLow) {
+ breaches.push(`${spec.role} SOL ${entry.sol.toFixed(4)} < floor ${entry.sol_floor.toFixed(4)}`);
+ await sendOpsAlert(
+ `⛽ x402 ring ${spec.role} low on SOL`,
+ `${spec.role} ${spec.address} holds ${entry.sol.toFixed(4)} SOL, below the ${entry.sol_floor.toFixed(4)} SOL floor. ` +
+ `Below the facilitator's ${(SPONSOR_SOL_FLOOR_LAMPORTS / LAMPORTS_PER_SOL).toFixed(4)} SOL hard floor settlement is refused and the ring halts. ` +
+ `The economy master's treasury-topup cron refills registry signers automatically; fund it or the ${spec.role} directly.`,
+ { signature: `x402-ring-sol-low:${spec.address}` },
+ );
+ }
+ if (usdcLow) {
+ breaches.push(`${spec.role} USDC ${entry.usdc.toFixed(2)} < floor ${entry.usdc_floor.toFixed(2)}`);
+ await sendOpsAlert(
+ `💵 x402 ring ${spec.role} low on USDC float`,
+ `${spec.role} ${spec.address} holds $${entry.usdc.toFixed(2)} USDC, below the $${entry.usdc_floor.toFixed(2)} float floor. ` +
+ `The daily volume cap can no longer be fully funded — top up the payer's USDC float.`,
+ { signature: `x402-ring-usdc-low:${spec.address}` },
+ );
+ }
+ }
+
+ // Cheap consumer snapshot (dashboard / health) — mirrors the seed-wallet key.
+ if (redis) {
+ try {
+ await redis.set(REDIS_RING_KEY, JSON.stringify({
+ ts: new Date().toISOString(), wallets, breaches,
+ }), { ex: ALERT_TTL_SECONDS });
+ } catch (err) {
+ log.warn('ring_balance_redis_write_failed', { message: err?.message });
+ }
+ }
+
+ if (breaches.length) {
+ log.warn('x402_ring_wallet_breach', { breaches });
+ } else {
+ log.info('x402_ring_wallets_ok', {
+ wallets: wallets.filter((w) => w.configured).map((w) => `${w.role}:${w.sol?.toFixed?.(3) ?? '?'}SOL/$${w.usdc?.toFixed?.(2) ?? '?'}`).join(' '),
+ });
+ }
+
+ return { configured: true, wallets, breaches };
+}
+
/**
* Run the wallet balance monitor. Conforms to the run()-style registry contract.
*
@@ -249,6 +405,17 @@ export async function run(ctx = {}) {
};
await writeRedisState(redis, sample);
+ // ── Ring wallets (payer / treasury / sponsor) — role-floor breach alerts ──
+ // Independent of the seed-wallet reading above: these are the closed-loop
+ // ring's own wallets, watched on-chain against their role floors so the loop
+ // never halts on a drained sponsor or an empty payer float. Never throws.
+ let ring = { configured: false, wallets: [], breaches: [] };
+ try {
+ ring = await checkRingWallets({ redis });
+ } catch (err) {
+ log.warn('ring_balance_check_failed', { message: err?.message });
+ }
+
if (lowBalance) {
log.warn('agent_wallet_low_balance', {
run_id: runId, address, usdc, threshold: ALERT_THRESHOLD_USDC,
@@ -271,8 +438,13 @@ export async function run(ctx = {}) {
threshold_usdc: ALERT_THRESHOLD_USDC,
usdc_delta: usdcDelta,
spend_rate_usdc_hr: spendRateUsdcHr,
+ ring: ring.configured ? { wallets: ring.wallets, breaches: ring.breaches } : null,
};
+ const ringNote = ring.configured
+ ? ` ring:${ring.breaches.length ? `BREACH(${ring.breaches.length})` : 'ok'}`
+ : '';
+
return {
// success = we obtained a live, usable reading from a configured wallet.
// An unconfigured wallet is a real, recorded state (not a crash) but not a
@@ -280,12 +452,12 @@ export async function run(ctx = {}) {
success: configured,
amountAtomic: 0,
txSig: null,
- responseData: { configured, address, usdc, sol },
+ responseData: { configured, address, usdc, sol, ring },
signalData,
errorMsg: configured ? null : (body?.code || 'wallet_unconfigured'),
- note: configured
+ note: (configured
? `usdc=${usdc?.toFixed?.(4) ?? usdc} sol=${sol?.toFixed?.(4) ?? sol}${lowBalance ? ' LOW_BALANCE' : ''}`
- : 'wallet_unconfigured',
+ : 'wallet_unconfigured') + ringNote,
};
}
@@ -294,4 +466,12 @@ export const WALLET_BALANCE = Object.freeze({
alertThresholdUsdc: ALERT_THRESHOLD_USDC,
redisLatestKey: REDIS_LATEST_KEY,
redisAlertKey: REDIS_ALERT_KEY,
+ // Ring-wallet floors (role-appropriate). Treasury is intentionally absent —
+ // it fills from payments and is swept back, so it has no floor.
+ ring: {
+ redisKey: REDIS_RING_KEY,
+ solFloorLamports: RING_SOL_FLOOR_LAMPORTS,
+ payerUsdcFloorAtomic: RING_PAYER_USDC_FLOOR_ATOMIC,
+ sponsorHardFloorLamports: SPONSOR_SOL_FLOOR_LAMPORTS,
+ },
});
diff --git a/api/cron/x402-ring-leak-scan.js b/api/cron/x402-ring-leak-scan.js
new file mode 100644
index 000000000..e0f51806e
--- /dev/null
+++ b/api/cron/x402-ring-leak-scan.js
@@ -0,0 +1,554 @@
+// @ts-check
+// GET /api/cron/x402-ring-leak-scan — the ACTIVE, on-chain half of the
+// leak-proofing invariant: **no SOL or USDC ever leaves the controlled-wallet
+// set.** The runtime assertions (api/_lib/x402/ring-allowlist.js) stop the ring
+// from *initiating* a leaking spend; this scanner watches the chain itself and
+// alarms within minutes if money leaves anyway — a compromised key, a bug, or a
+// path the assertions don't cover.
+//
+// Every 10 min, for each ring wallet:
+// 1. getSignaturesForAddress(limit 100, until=<persisted cursor>) — only
+// signatures newer than the last scan. Cursor persisted per wallet so RPC
+// stays bounded and each tx is classified exactly once.
+// 2. Batched getParsedTransactions over the new signatures.
+// 3. classifyWalletDebits() (pure, exported, unit-tested) labels every debit:
+// • internal — counterparty ∈ ringAllowedAddresses()
+// • network_fee — the tx fee our wallet paid
+// • LEAK — anything else: USDC to an unknown address, ANY
+// non-USDC token out, an unexplained SOL debit, a
+// System transfer to an unknown address
+// • delegation — an SPL Approve on a ring ATA (a leak vector before
+// funds even move) — alerted on sight
+// 4. Any LEAK / delegation → CRITICAL sendOpsAlert (signature, counterparty,
+// amount, rotate-the-key recommendation) + a payment_reconciliation verdict
+// (source 'x402_ring_onchain'), mirroring economy-reconcile.js.
+// 5. Per-day observed network-fee sum is accumulated and cross-checked against
+// task 05's x402_fee_audit rollup — a >20% mismatch WARNs (fees paid
+// outside the ring's accounting).
+//
+// STRICTLY read-only on chain. It never moves funds, never rotates keys. When
+// classification is ambiguous it classifies as LEAK (false-negative is worse
+// than false-positive here).
+
+import { randomUUID } from 'node:crypto';
+
+import { json, wrapCron, method, error } 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 { ringAllowedAddresses, ringRoleWallets } from '../_lib/x402/ring-allowlist.js';
+
+// ── Tuning ────────────────────────────────────────────────────────────────────
+const SIG_SCAN_LIMIT = 100; // hard per-wallet-per-run cap (task constraint)
+const PARSED_BATCH = 50; // getParsedTransactions batch size
+// Residual SOL debit (after fee + accounted outflows) above this is a LEAK. One
+// base-fee unit — small enough to catch a real drain, above lamport rounding.
+const SOL_RESIDUAL_FLOOR_LAMPORTS = 5_000;
+// Fee-book divergence: on-chain observed fees vs task 05's audit rollup.
+const FEE_DIVERGENCE_THRESHOLD = 0.20;
+const CANONICAL_USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+
+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;
+}
+
+// ── Pure classification (exported for tests) ──────────────────────────────────
+
+/**
+ * Normalize a parsed message's accountKeys to an array of pubkey strings.
+ * jsonParsed encodes them as { pubkey, signer, writable }; legacy shapes as raw
+ * strings. Returns [] when unreadable.
+ * @param {any} message
+ * @returns {string[]}
+ */
+export function accountKeyStrings(message) {
+ const keys = message?.accountKeys;
+ if (!Array.isArray(keys)) return [];
+ return keys.map((k) => (typeof k === 'string' ? k : (k?.pubkey || k?.toString?.() || '')));
+}
+
+/** Flatten top-level + inner instructions into one list of parsed instructions. */
+function allInstructions(tx) {
+ const top = tx?.transaction?.message?.instructions || [];
+ const inner = (tx?.meta?.innerInstructions || []).flatMap((g) => g?.instructions || []);
+ return [...top, ...inner];
+}
+
+/** Map accountIndex → { mint, owner, amount(BigInt) } from a token-balance array. */
+function tokenBalanceMap(arr) {
+ const m = new Map();
+ for (const b of arr || []) {
+ if (b?.accountIndex == null) continue;
+ let amount = 0n;
+ try { amount = BigInt(b?.uiTokenAmount?.amount ?? '0'); } catch { amount = 0n; }
+ m.set(b.accountIndex, { mint: b.mint, owner: b.owner, amount });
+ }
+ return m;
+}
+
+/**
+ * Classify every SOL/USDC debit a single parsed transaction makes FROM `wallet`.
+ *
+ * @param {any} tx a jsonParsed transaction (getParsedTransaction[s] shape)
+ * @param {{ wallet: string, allowed: Set<string>, usdcMint: string }} ctx
+ * @returns {{
+ * unreadable: boolean,
+ * signature: string|null,
+ * fee: { lamports: number, ours: boolean },
+ * events: Array<{ type: 'internal'|'leak'|'delegation', asset: string, counterparty: string|null, amountAtomic: number, reason: string }>,
+ * }}
+ */
+export function classifyWalletDebits(tx, { wallet, allowed, usdcMint }) {
+ const usdc = usdcMint || CANONICAL_USDC;
+ const signature = tx?.transaction?.signatures?.[0] || null;
+ const msg = tx?.transaction?.message;
+ const meta = tx?.meta;
+ const events = [];
+
+ if (!msg || !meta) return { unreadable: true, signature, fee: { lamports: 0, ours: false }, events };
+
+ const keys = accountKeyStrings(msg);
+ const walletIdx = keys.indexOf(wallet);
+
+ // Network fee: attributed to the fee payer (account index 0).
+ const feeLamports = Number(meta.fee || 0);
+ const feeOurs = keys[0] === wallet;
+ const fee = { lamports: feeLamports, ours: feeOurs };
+
+ // A failed tx moved no funds (fee still burned, captured above).
+ if (meta.err) return { unreadable: false, signature, fee, events };
+ if (walletIdx < 0) return { unreadable: false, signature, fee, events };
+
+ const isInternal = (addr) => addr != null && allowed.has(addr);
+
+ // ── SOL outflows we can attribute to a counterparty ──────────────────────
+ let accountedSolOut = 0;
+ for (const ix of allInstructions(tx)) {
+ const info = ix?.parsed?.info;
+ const type = ix?.parsed?.type;
+ if (!info || !type) continue;
+
+ if (ix.program === 'system') {
+ // transfer / transferWithSeed: lamports leaving `wallet`.
+ if ((type === 'transfer' || type === 'transferWithSeed') && info.source === wallet) {
+ const lamports = Number(info.lamports || 0);
+ accountedSolOut += lamports;
+ events.push({
+ type: isInternal(info.destination) ? 'internal' : 'leak',
+ asset: 'SOL', counterparty: info.destination ?? null, amountAtomic: lamports,
+ reason: isInternal(info.destination) ? 'system_transfer_internal' : 'system_transfer_to_unknown',
+ });
+ } else if (type === 'createAccount' && info.source === wallet) {
+ const lamports = Number(info.lamports || 0);
+ accountedSolOut += lamports;
+ events.push({
+ type: isInternal(info.newAccount) ? 'internal' : 'leak',
+ asset: 'SOL', counterparty: info.newAccount ?? null, amountAtomic: lamports,
+ reason: isInternal(info.newAccount) ? 'create_account_internal' : 'create_account_unknown_owner',
+ });
+ }
+ } else if (ix.program === 'spl-associated-token-account') {
+ // ATA create: rent leaves the funder for a NEW token account. Internal
+ // only when the account's OWNER (info.wallet) is a controlled address.
+ if ((type === 'create' || type === 'createIdempotent') && info.source === wallet) {
+ const owner = info.wallet ?? null;
+ // rent is not in `info`; it surfaces as residual — do not double-count.
+ events.push({
+ type: isInternal(owner) ? 'internal' : 'leak',
+ asset: 'SOL', counterparty: owner, amountAtomic: 0,
+ reason: isInternal(owner) ? 'ata_create_internal' : 'ata_create_unknown_owner',
+ });
+ }
+ } else if (ix.program === 'spl-token' || ix.program === 'spl-token-2022') {
+ // Delegation risk: an Approve on a ring token account authorizes a
+ // delegate to move funds later — a leak vector before any transfer.
+ if ((type === 'approve' || type === 'approveChecked') && (info.owner === wallet || isInternal(info.source))) {
+ let amount = 0;
+ try { amount = Number(info.amount ?? info.tokenAmount?.amount ?? 0); } catch { amount = 0; }
+ events.push({
+ type: 'delegation', asset: info.mint || 'token', counterparty: info.delegate ?? null,
+ amountAtomic: amount, reason: 'spl_approve_on_ring_ata',
+ });
+ }
+ }
+ }
+
+ // ── Token outflows via balance deltas (mechanism-agnostic) ───────────────
+ const pre = tokenBalanceMap(meta.preTokenBalances);
+ const post = tokenBalanceMap(meta.postTokenBalances);
+ for (const [idx, before] of pre) {
+ if (before.owner !== wallet) continue;
+ const after = post.get(idx);
+ const delta = before.amount - (after?.amount ?? 0n); // >0 ⇒ tokens left the account
+ if (delta <= 0n) continue;
+
+ const nonUsdc = before.mint !== usdc;
+ // Counterparty: the account that GAINED this mint in the same tx.
+ let counterparty = null;
+ for (const [j, a2] of post) {
+ if (j === idx || a2.mint !== before.mint) continue;
+ const gain = a2.amount - (pre.get(j)?.amount ?? 0n);
+ if (gain > 0n) { counterparty = a2.owner || keys[j] || null; break; }
+ }
+
+ // Non-USDC out is ALWAYS a leak (the ring only ever moves USDC). USDC out
+ // is internal only to a controlled counterparty; unknown counterparty →
+ // leak (false-negative averse).
+ const internal = !nonUsdc && (isInternal(counterparty) || isInternal(after?.owner));
+ events.push({
+ type: internal ? 'internal' : 'leak',
+ asset: nonUsdc ? (before.mint || 'token') : 'USDC',
+ counterparty, amountAtomic: Number(delta),
+ reason: nonUsdc ? 'non_usdc_token_out' : (internal ? 'usdc_transfer_internal' : 'usdc_to_unknown'),
+ });
+ }
+
+ // ── Residual SOL: any unexplained lamport debit is a LEAK ────────────────
+ const pre0 = Number(meta.preBalances?.[walletIdx]);
+ const post0 = Number(meta.postBalances?.[walletIdx]);
+ if (Number.isFinite(pre0) && Number.isFinite(post0)) {
+ const solDebit = pre0 - post0;
+ const explained = (feeOurs ? feeLamports : 0) + accountedSolOut;
+ const residual = solDebit - explained;
+ if (residual > SOL_RESIDUAL_FLOOR_LAMPORTS) {
+ events.push({
+ type: 'leak', asset: 'SOL', counterparty: null, amountAtomic: residual,
+ reason: 'unexplained_sol_debit',
+ });
+ }
+ }
+
+ return { unreadable: false, signature, fee, events };
+}
+
+// ── DB helpers ────────────────────────────────────────────────────────────────
+
+async function ensureSchema() {
+ try {
+ await withDbRetry(() => sql`
+ CREATE TABLE IF NOT EXISTS x402_ring_scan_cursor (
+ wallet text PRIMARY KEY,
+ last_signature text,
+ last_slot bigint,
+ scanned_total bigint NOT NULL DEFAULT 0,
+ leaks_total bigint NOT NULL DEFAULT 0,
+ last_run_id uuid,
+ updated_at timestamptz NOT NULL DEFAULT now()
+ )
+ `);
+ } catch { /* migration owns it */ }
+ try {
+ await withDbRetry(() => sql`
+ CREATE TABLE IF NOT EXISTS x402_ring_fee_observed (
+ day date PRIMARY KEY,
+ fee_lamports bigint NOT NULL DEFAULT 0,
+ tx_count bigint NOT NULL DEFAULT 0,
+ updated_at timestamptz NOT NULL DEFAULT now()
+ )
+ `);
+ } catch { /* migration owns it */ }
+}
+
+async function loadCursor(wallet) {
+ try {
+ const [row] = await withDbRetry(() => sql`
+ SELECT last_signature, scanned_total, leaks_total
+ FROM x402_ring_scan_cursor WHERE wallet = ${wallet}
+ `);
+ return row || null;
+ } catch { return null; }
+}
+
+async function saveCursor(wallet, { lastSignature, lastSlot, scannedDelta, leaksDelta, runId }) {
+ try {
+ await withDbRetry(() => sql`
+ INSERT INTO x402_ring_scan_cursor
+ (wallet, last_signature, last_slot, scanned_total, leaks_total, last_run_id, updated_at)
+ VALUES (${wallet}, ${lastSignature}, ${lastSlot}, ${scannedDelta}, ${leaksDelta}, ${runId}, now())
+ ON CONFLICT (wallet) DO UPDATE SET
+ last_signature = COALESCE(EXCLUDED.last_signature, x402_ring_scan_cursor.last_signature),
+ last_slot = COALESCE(EXCLUDED.last_slot, x402_ring_scan_cursor.last_slot),
+ scanned_total = x402_ring_scan_cursor.scanned_total + ${scannedDelta},
+ leaks_total = x402_ring_scan_cursor.leaks_total + ${leaksDelta},
+ last_run_id = EXCLUDED.last_run_id,
+ updated_at = now()
+ `);
+ } catch (err) {
+ console.warn('[ring-leak-scan] cursor upsert failed', { wallet, message: err?.message });
+ }
+}
+
+async function accrueObservedFee(dayToLamports) {
+ for (const [day, { lamports, count }] of dayToLamports) {
+ if (lamports <= 0 && count <= 0) continue;
+ try {
+ await withDbRetry(() => sql`
+ INSERT INTO x402_ring_fee_observed (day, fee_lamports, tx_count, updated_at)
+ VALUES (${day}::date, ${lamports}, ${count}, now())
+ ON CONFLICT (day) DO UPDATE SET
+ fee_lamports = x402_ring_fee_observed.fee_lamports + ${lamports},
+ tx_count = x402_ring_fee_observed.tx_count + ${count},
+ updated_at = now()
+ `);
+ } catch (err) {
+ console.warn('[ring-leak-scan] fee rollup upsert failed', { day, message: err?.message });
+ }
+ }
+}
+
+async function upsertVerdict(v) {
+ 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
+ (${v.source}, ${v.sourceRef}, ${v.txSig}, ${v.network}, ${v.amountAtomic},
+ ${v.dbStatus}, ${v.chainStatus}, ${v.reconciled}, ${v.discrepancy},
+ ${v.detail ? JSON.stringify(v.detail) : null}, ${v.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('[ring-leak-scan] verdict upsert failed', { ref: v.sourceRef, message: err?.message });
+ }
+}
+
+/** UTC day string for a blockTime (unix seconds), or today when absent. */
+function dayOf(blockTime, nowMs) {
+ const ms = blockTime ? blockTime * 1000 : nowMs;
+ return new Date(ms).toISOString().slice(0, 10);
+}
+
+// ── Wallets to scan ───────────────────────────────────────────────────────────
+
+/** The ring wallets that actually hold/move funds: the role wallets + registry. */
+async function ringScanWallets() {
+ const out = new Set();
+ const roles = await ringRoleWallets();
+ for (const pk of Object.values(roles)) if (pk) out.add(pk);
+ try {
+ const rows = await withDbRetry(() => sql`SELECT pubkey FROM x402_ring_wallets WHERE enabled = true`);
+ for (const r of rows) if (r?.pubkey) out.add(r.pubkey);
+ } catch { /* env-derived set stands */ }
+ return [...out];
+}
+
+// ── Per-wallet scan ───────────────────────────────────────────────────────────
+
+async function scanWallet(conn, PublicKey, wallet, { allowed, usdcMint, runId, feeByDay }) {
+ const summary = { wallet, scanned: 0, leaks: 0, delegations: 0, truncated: false };
+ const cursor = await loadCursor(wallet);
+
+ let sigInfos = [];
+ try {
+ const opts = { limit: SIG_SCAN_LIMIT };
+ if (cursor?.last_signature) opts.until = cursor.last_signature;
+ sigInfos = await conn.getSignaturesForAddress(new PublicKey(wallet), opts);
+ } catch (err) {
+ summary.error = err?.message || 'sig_fetch_failed';
+ return summary;
+ }
+ if (sigInfos.length === 0) return summary;
+ summary.truncated = sigInfos.length >= SIG_SCAN_LIMIT && !!cursor?.last_signature;
+
+ // getSignaturesForAddress returns newest→oldest; results[0] is the new cursor.
+ const newestSig = sigInfos[0].signature;
+ const newestSlot = sigInfos[0].slot ?? null;
+ const signatures = sigInfos.map((s) => s.signature);
+ const blockTimeBySig = new Map(sigInfos.map((s) => [s.signature, s.blockTime ?? null]));
+
+ // Batched parsed fetch.
+ const parsed = [];
+ for (let i = 0; i < signatures.length; i += PARSED_BATCH) {
+ const batch = signatures.slice(i, i + PARSED_BATCH);
+ try {
+ const got = await conn.getParsedTransactions(batch, { maxSupportedTransactionVersion: 0, commitment: 'confirmed' });
+ parsed.push(...got);
+ } catch {
+ // Fall back to per-sig on a batch failure so one bad sig can't blind the run.
+ for (const s of batch) {
+ try { parsed.push(await conn.getParsedTransaction(s, { maxSupportedTransactionVersion: 0, commitment: 'confirmed' })); }
+ catch { parsed.push(null); }
+ }
+ }
+ }
+
+ let scannedDelta = 0;
+ let leaksDelta = 0;
+ const nowMs = Date.now();
+
+ for (let i = 0; i < parsed.length; i++) {
+ const tx = parsed[i];
+ const sig = signatures[i];
+ if (!tx) continue; // unreadable — a later run retries (cursor not yet advanced past it only if newest; acceptable)
+ scannedDelta += 1;
+
+ const { unreadable, fee, events } = classifyWalletDebits(tx, { wallet, allowed, usdcMint });
+ if (unreadable) continue;
+
+ // Accrue the network fee our wallet paid, bucketed by UTC day.
+ if (fee.ours && fee.lamports > 0) {
+ const day = dayOf(blockTimeBySig.get(sig), nowMs);
+ const cur = feeByDay.get(day) || { lamports: 0, count: 0 };
+ cur.lamports += fee.lamports; cur.count += 1;
+ feeByDay.set(day, cur);
+ }
+
+ for (const ev of events) {
+ if (ev.type === 'internal') continue;
+
+ summary[ev.type === 'delegation' ? 'delegations' : 'leaks'] += 1;
+ leaksDelta += 1;
+
+ const isDelegation = ev.type === 'delegation';
+ await upsertVerdict({
+ source: 'x402_ring_onchain',
+ sourceRef: `${sig}:${wallet}:${ev.asset}:${ev.reason}`,
+ txSig: sig, network: 'mainnet', amountAtomic: ev.amountAtomic,
+ dbStatus: isDelegation ? 'delegation_risk' : 'onchain_leak',
+ chainStatus: ev.reason, reconciled: false,
+ discrepancy: isDelegation
+ ? `SPL approve on ring ATA of ${wallet} → delegate ${ev.counterparty}`
+ : `${ev.asset} left ${wallet} to ${ev.counterparty ?? 'unknown'} (${ev.reason})`,
+ detail: { wallet, asset: ev.asset, counterparty: ev.counterparty, reason: ev.reason, amountAtomic: ev.amountAtomic },
+ runId,
+ });
+
+ const amtLabel = ev.asset === 'SOL'
+ ? `${(ev.amountAtomic / 1e9).toFixed(6)} SOL`
+ : `${ev.amountAtomic} ${ev.asset} atoms`;
+ await sendOpsAlert(
+ isDelegation ? '🚨 x402 ring delegation risk — SPL Approve on a ring ATA' : '🚨 x402 ring LEAK — funds left the controlled set',
+ isDelegation
+ ? `Ring wallet ${wallet} approved delegate ${ev.counterparty} to move ${amtLabel} in tx ${sig}. A delegate can drain the account later. ROTATE the wallet's secret and revoke the approval now. https://solscan.io/tx/${sig}`
+ : `${amtLabel} left ring wallet ${wallet} to ${ev.counterparty ?? 'an unknown address'} (${ev.reason}) in tx ${sig}. This should be impossible in the closed loop — treat the wallet's key as COMPROMISED: rotate its secret, drain remaining funds to the treasury, and re-verify with scripts/x402-ring-verify.mjs. https://solscan.io/tx/${sig}`,
+ { signature: `ring-leak:${sig}:${wallet}:${ev.reason}` },
+ );
+ }
+ }
+
+ summary.scanned = scannedDelta;
+ summary.leaks_and_delegations = leaksDelta;
+ await saveCursor(wallet, { lastSignature: newestSig, lastSlot: newestSlot, scannedDelta, leaksDelta, runId });
+
+ if (summary.truncated) {
+ console.warn('[ring-leak-scan] sig backlog', { wallet, note: `>=${SIG_SCAN_LIMIT} new sigs in one run` });
+ }
+ return summary;
+}
+
+// ── Fee-book cross-check ──────────────────────────────────────────────────────
+
+/** |observed - audited| / max(...). null when either side is unknown/zero. */
+export function feeDivergence(observed, audited) {
+ const a = Number(observed);
+ const b = Number(audited);
+ if (!Number.isFinite(a) || !Number.isFinite(b)) return null;
+ const denom = Math.max(a, b);
+ if (denom <= 0) return null;
+ return Math.abs(a - b) / denom;
+}
+
+async function crossCheckFees(runId, nowMs) {
+ // Compare the last complete UTC day's observed on-chain fees against task 05's
+ // fee-audit rollup. Divergence ⇒ fees paid outside the ring's accounting.
+ const day = new Date(nowMs - 86_400_000).toISOString().slice(0, 10);
+ let observed = null;
+ let audited = null;
+ try {
+ const [row] = await withDbRetry(() => sql`SELECT fee_lamports FROM x402_ring_fee_observed WHERE day = ${day}::date`);
+ observed = row ? Number(row.fee_lamports) : null;
+ } catch { /* table absent → skip */ }
+ try {
+ const [row] = await withDbRetry(() => sql`SELECT total_fee_lamports FROM x402_fee_audit WHERE day = ${day}::date`);
+ audited = row ? Number(row.total_fee_lamports) : null;
+ } catch { /* task 05 audit not present yet → skip cross-check */ }
+
+ if (observed == null || audited == null) return { day, observed, audited, divergence: null, skipped: true };
+ const divergence = feeDivergence(observed, audited);
+ if (divergence != null && divergence > FEE_DIVERGENCE_THRESHOLD) {
+ await upsertVerdict({
+ source: 'x402_ring_onchain', sourceRef: `fee-coherence:${day}`, txSig: null, network: 'mainnet',
+ amountAtomic: observed, dbStatus: 'fees_observed_onchain', chainStatus: 'fee_divergence', reconciled: false,
+ discrepancy: `on-chain fees diverge ${(divergence * 100).toFixed(1)}% from the fee-audit rollup on ${day}`,
+ detail: { day, observed_lamports: observed, audited_lamports: audited, divergence }, runId,
+ });
+ await sendOpsAlert(
+ '⚠️ x402 ring fee books diverge — fees paid outside the ring accounting',
+ `On ${day} ring wallets burned ${observed} lamports in network fees on-chain, but the fee-audit rollup recorded ${audited}. A >${(FEE_DIVERGENCE_THRESHOLD * 100).toFixed(0)}% gap means something outside the ring's accounting is paying fees from our wallets. Reconcile x402_ring_fee_observed vs x402_fee_audit for ${day}.`,
+ { signature: `ring-fee-divergence:${day}` },
+ );
+ }
+ return { day, observed, audited, divergence };
+}
+
+// ── Handler ───────────────────────────────────────────────────────────────────
+
+export default wrapCron(async (req, res) => {
+ if (!method(req, res, ['GET', 'POST'])) return;
+ if (!requireCron(req, res)) return;
+
+ const runId = randomUUID();
+ const nowMs = Date.now();
+ await ensureSchema();
+
+ const { PublicKey } = await import('@solana/web3.js');
+ const { solanaConnection } = await import('../_lib/solana/connection.js');
+ const conn = solanaConnection({
+ url: process.env.SOLANA_RPC_URL || env.SOLANA_RPC_URL,
+ network: 'mainnet', commitment: 'confirmed',
+ });
+
+ const [allowed, wallets] = await Promise.all([ringAllowedAddresses(), ringScanWallets()]);
+ const usdcMint = env.X402_ASSET_MINT_SOLANA;
+
+ if (wallets.length === 0) {
+ return json(res, 200, { ok: true, run_id: runId, skipped: true, reason: 'no_ring_wallets_configured' });
+ }
+
+ const feeByDay = new Map();
+ const results = [];
+ let leaks = 0;
+ let delegations = 0;
+ for (const wallet of wallets) {
+ try {
+ const s = await scanWallet(conn, PublicKey, wallet, { allowed, usdcMint, runId, feeByDay });
+ results.push(s);
+ leaks += s.leaks || 0;
+ delegations += s.delegations || 0;
+ } catch (err) {
+ results.push({ wallet, error: err?.message || 'scan_failed' });
+ }
+ }
+
+ await accrueObservedFee(feeByDay);
+ const feeCheck = await crossCheckFees(runId, nowMs);
+
+ return json(res, 200, {
+ ok: true,
+ run_id: runId,
+ wallets: wallets.length,
+ allowed_set_size: allowed.size,
+ leaks,
+ delegations,
+ fee_cross_check: feeCheck,
+ results,
+ });
+});
diff --git a/api/x402-ring.js b/api/x402-ring.js
index 5df2fc5e2..003981723 100644
--- a/api/x402-ring.js
+++ b/api/x402-ring.js
@@ -100,7 +100,7 @@ export default wrap(async (req, res) => {
const since = sinceFor(periodKey); // ISO string, or null = lifetime
let settlements = { count: 0, gross_usdc: 0, avg_call_usdc: null };
- let fees = { tx_count: 0, sol_burned_lamports: 0, sol_burned: 0, per_tx_avg_lamports: null };
+ let fees = { tx_count: 0, sol_burned_lamports: 0, sol_burned: 0, per_tx_avg_lamports: null, lamports_per_settlement: null, sol_per_100_usd: null };
let sweeps = { count: 0, swept_usdc: 0 };
let recent = [];
let dbOk = true;
@@ -119,11 +119,19 @@ export default wrap(async (req, res) => {
gross_usdc: usdc(s.gross),
avg_call_usdc: s.n > 0 ? usdc(Number(s.gross) / s.n) : null,
};
+ // The two fee-efficiency numbers the "lowest fees always" rule is measured
+ // on. lamports_per_settlement is the real SOL burned per settled payment
+ // (~5,000 at the 1-signature self-pay floor); sol_per_100_usd normalizes
+ // the burn against gross volume — the headline "cost of moving a dollar".
+ const solBurned = sol(s.fee) || 0;
+ const grossUsd = usdc(s.gross) || 0;
fees = {
tx_count: s.n,
sol_burned_lamports: Number(s.fee),
sol_burned: sol(s.fee),
per_tx_avg_lamports: s.n > 0 ? Math.round(Number(s.fee) / s.n) : null,
+ lamports_per_settlement: s.n > 0 ? Math.round(Number(s.fee) / s.n) : null,
+ sol_per_100_usd: grossUsd > 0 ? Number(((solBurned / grossUsd) * 100).toFixed(9)) : null,
};
const [w] = await sql`
diff --git a/packages/agent-sniper/runbooks/02-platform-native.md b/packages/agent-sniper/runbooks/02-platform-native.md
index 614b4f08c..5ef6eaac6 100644
--- a/packages/agent-sniper/runbooks/02-platform-native.md
+++ b/packages/agent-sniper/runbooks/02-platform-native.md
@@ -22,8 +22,15 @@ as an operator action. Read [00-overview.md](00-overview.md) for shared economic
Otherwise you fund each agent address manually (step 3).
## Important platform constraints (verified)
-- **One agent-identity per user** — `agent_identities` has a unique constraint on
- `user_id`. 33 platform agents therefore need **33 users**. The SQL below creates them.
+- **A user may own many agents.** The old one-agent-per-user unique index
+ (`agent_identities_user_unique`) was **dropped on 2026-05-13**
+ (`api/_lib/migrations/2026-05-13-drop-agent-identities-user-unique.sql`) so the
+ dashboard can create multiple agents per owner. 33 Scouts do **not** require 33
+ users — but the SQL below still creates one user per Scout for a clean 1:1
+ mapping and stable, email-keyed idempotency. Do **not** use
+ `on conflict (user_id)` on `agent_identities`; there is no matching constraint
+ and it errors with `no unique or exclusion constraint matching the ON CONFLICT
+ specification`.
- **Appearing on `/play/arena` requires a `agent_sniper_positions` row**, not just an armed
strategy. Let the live worker open positions, or the arena stays empty for these agents.
- **Appearing on `/theater` requires `is_public = true`** and, for a real 3D body, an
@@ -44,14 +51,21 @@ AVATAR_ID=$(psql "$DATABASE_URL" -tAc "select id from avatars where model_url is
echo "using avatar $AVATAR_ID"
psql "$DATABASE_URL" <<SQL
do \$\$
-declare uid uuid; i int;
+declare uid uuid; nm text; i int;
begin
for i in 1..33 loop
+ nm := 'Scout '||lpad(i::text,2,'0');
+ -- users.email is UNIQUE, so this is the real idempotency key across re-runs
insert into users (email) values ('scout'||lpad(i::text,2,'0')||'@fleet.three.ws')
on conflict (email) do update set email=excluded.email returning id into uid;
+ -- agent_identities.user_id is NOT unique (agent_identities_user_unique was
+ -- dropped 2026-05-13), so guard on (user_id, name) instead of ON CONFLICT.
insert into agent_identities (user_id, name, description, is_public, avatar_id)
- values (uid, 'Scout '||lpad(i::text,2,'0'), 'Throwaway sniper fleet agent', true, '${AVATAR_ID}')
- on conflict (user_id) do update set name=excluded.name, is_public=true, avatar_id=excluded.avatar_id;
+ select uid, nm, 'Throwaway sniper fleet agent', true, '${AVATAR_ID}'
+ where not exists (select 1 from agent_identities where user_id = uid and name = nm);
+ -- re-assert the fields a re-run should refresh (idempotent)
+ update agent_identities set is_public = true, avatar_id = '${AVATAR_ID}'
+ where user_id = uid and name = nm;
end loop;
end \$\$;
SQL
diff --git a/packages/agent-sniper/scripts/reel.js b/packages/agent-sniper/scripts/reel.js
index a417de4b2..19e8b7eb3 100644
--- a/packages/agent-sniper/scripts/reel.js
+++ b/packages/agent-sniper/scripts/reel.js
@@ -148,10 +148,20 @@ async function main() {
await caption(page, scene.caption);
if (scene.act) await scene.act(page).catch((e) => console.log('act:', e.message));
await page.waitForTimeout(scene.dwellMs ?? 5000);
+ // The scene is captured in the video by this point (the dwell already ran).
+ // The per-scene PNG is a bonus still — never let it fail the scene. Live 3D /
+ // feed pages render continuously, so a default screenshot never reaches a
+ // stable frame; freeze animations, hide the caret, and cap the wait.
const shot = path.join(OUT, `${scene.key}.png`);
- await page.screenshot({ path: shot });
- console.log(`ok (${((Date.now?.() ?? 0) - t0) / 1000 | 0}s)`);
- log.push({ key: scene.key, url, ok: true, shot });
+ let shotOk = false;
+ try {
+ await page.screenshot({ path: shot, animations: 'disabled', caret: 'hide', timeout: 15_000 });
+ shotOk = true;
+ } catch (shotErr) {
+ console.log(`\n (still skipped: ${shotErr.message.split('\n')[0].slice(0, 60)})`);
+ }
+ console.log(`ok (${((Date.now?.() ?? 0) - t0) / 1000 | 0}s)${shotOk ? '' : ' — video only'}`);
+ log.push({ key: scene.key, url, ok: true, shot: shotOk ? shot : null });
} catch (e) {
console.log(`FAIL ${e.message.slice(0, 80)}`);
log.push({ key: scene.key, url, ok: false, error: e.message });
diff --git a/pages/admin/ring.html b/pages/admin/ring.html
new file mode 100644
index 000000000..a35643f3e
--- /dev/null
+++ b/pages/admin/ring.html
@@ -0,0 +1,174 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <script>
+ /* three.ws theme boot — no-flash */ (function () {
+ document.documentElement.classList.add('js');
+ try {
+ var m = localStorage.getItem('twx_theme');
+ var l =
+ m === 'auto'
+ ? window.matchMedia &&
+ window.matchMedia('(prefers-color-scheme: light)').matches
+ : m === 'light';
+ document.documentElement.setAttribute('data-theme', l ? 'light' : 'dark');
+ } catch (e) {
+ document.documentElement.setAttribute('data-theme', 'dark');
+ }
+ })();
+ </script>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <meta name="robots" content="noindex, nofollow" />
+ <title>Ring Dashboard · Control · three.ws</title>
+ <meta
+ name="description"
+ content="Operator dashboard for the closed-loop x402 ring economy — live settlement pulse, loop balances, activity feed, fees, integrity, and coverage."
+ />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/src/admin-ring.css" />
+ </head>
+ <body>
+ <header><div id="nav-container"></div></header>
+ <script src="/nav.js"></script>
+
+ <main class="rg-wrap" id="rg-root" aria-busy="true">
+ <!-- Auth gate -->
+ <section class="rg-gate" id="rg-gate" hidden>
+ <div class="rg-gate-mark" aria-hidden="true">◎</div>
+ <h1>Ring Dashboard</h1>
+ <p>Operator control. Enter the secret to watch the economy breathe.</p>
+ <form id="rg-gate-form" autocomplete="off">
+ <input
+ type="password"
+ id="rg-secret"
+ class="rg-input"
+ placeholder="CRON_SECRET"
+ aria-label="Operator secret"
+ autocomplete="current-password"
+ />
+ <button type="submit" class="rg-btn rg-btn-primary">Unlock</button>
+ <p class="rg-gate-err" id="rg-gate-err" role="alert" aria-live="assertive"></p>
+ </form>
+ </section>
+
+ <!-- Dashboard -->
+ <div id="rg-panel" hidden>
+ <!-- Persistent internal-volume label -->
+ <div class="rg-flag" role="note">
+ <span aria-hidden="true">⚠</span>
+ <b>INTERNAL DOGFOODING VOLUME</b>
+ <span
+ >— not organic revenue. Every payment below is platform wallets paying platform
+ endpoints, in a closed loop.</span
+ >
+ </div>
+
+ <!-- Hero -->
+ <header class="rg-hero">
+ <div>
+ <p class="rg-kicker">
+ <span class="rg-pulse-dot" id="rg-hero-dot"></span>
+ <span id="rg-hero-word">Loading</span> · closed-loop x402
+ </p>
+ <h1 class="rg-title">Ring <em>Dashboard</em></h1>
+ <p class="rg-sub">
+ The heartbeat of the self-cycled agent economy — per-minute settlement
+ pulse, who bought what, SOL burned vs budget, wallet floors, and integrity.
+ </p>
+ </div>
+ <div class="rg-hero-r">
+ <div class="rg-periods" id="rg-periods" role="group" aria-label="Report window">
+ <button data-period="24h" class="on">24h</button>
+ <button data-period="7d">7d</button>
+ <button data-period="30d">30d</button>
+ <button data-period="all">All</button>
+ </div>
+ <button class="rg-btn" id="rg-pause" title="Pause polling (p)">⏸ Pause</button>
+ <button class="rg-btn" id="rg-refresh" title="Refresh now (r)">↻ Refresh</button>
+ </div>
+ </header>
+
+ <!-- Error banner (API unreachable) -->
+ <div id="rg-error" hidden></div>
+
+ <div class="rg-grid">
+ <!-- Pulse strip -->
+ <section class="rg-card" aria-labelledby="rg-pulse-h">
+ <div class="rg-card-h">
+ <h2 id="rg-pulse-h">Settlement pulse</h2>
+ <span class="rg-meta" id="rg-pulse-meta">last 60 min</span>
+ </div>
+ <div class="rg-pulse">
+ <div class="rg-pulse-num">
+ <div class="rg-pulse-big" id="rg-pulse-big">—</div>
+ <div class="rg-pulse-lbl" id="rg-pulse-lbl">min since settle</div>
+ </div>
+ <div>
+ <div class="rg-spark" id="rg-spark" aria-hidden="true"></div>
+ <div class="rg-spark-axis">
+ <span>60m ago</span><span id="rg-spark-mid"></span><span>now</span>
+ </div>
+ </div>
+ </div>
+ </section>
+
+ <!-- Loop diagram -->
+ <section class="rg-card" aria-labelledby="rg-loop-h">
+ <div class="rg-card-h">
+ <h2 id="rg-loop-h">The loop</h2>
+ <span class="rg-meta" id="rg-loop-meta"></span>
+ </div>
+ <div class="rg-loop" id="rg-loop"></div>
+ </section>
+
+ <div class="rg-row">
+ <!-- Activity feed -->
+ <section class="rg-card" aria-labelledby="rg-feed-h">
+ <div class="rg-card-h">
+ <h2 id="rg-feed-h">Activity feed</h2>
+ <span class="rg-meta" id="rg-feed-meta"></span>
+ </div>
+ <div class="rg-feed-wrap" id="rg-feed-wrap"></div>
+ </section>
+
+ <div class="rg-grid">
+ <!-- Fees -->
+ <section class="rg-card" aria-labelledby="rg-fees-h">
+ <div class="rg-card-h">
+ <h2 id="rg-fees-h">Fees &amp; burn</h2>
+ <span class="rg-meta" id="rg-fees-meta"></span>
+ </div>
+ <dl class="rg-metrics" id="rg-fees"></dl>
+ </section>
+
+ <!-- Integrity -->
+ <section class="rg-card" aria-labelledby="rg-int-h">
+ <div class="rg-card-h">
+ <h2 id="rg-int-h">Integrity</h2>
+ <span class="rg-meta" id="rg-int-meta"></span>
+ </div>
+ <div id="rg-integrity"></div>
+ </section>
+ </div>
+ </div>
+
+ <!-- Coverage -->
+ <section class="rg-card" aria-labelledby="rg-cov-h">
+ <div class="rg-card-h">
+ <h2 id="rg-cov-h">Endpoint coverage</h2>
+ <span class="rg-meta" id="rg-cov-meta"></span>
+ </div>
+ <div class="rg-cov" id="rg-coverage"></div>
+ </section>
+ </div>
+ </div>
+ </main>
+
+ <div class="rg-hint" id="rg-hint" hidden>
+ <kbd>r</kbd> refresh · <kbd>p</kbd> pause
+ </div>
+
+ <script type="module" src="/src/admin-ring.js"></script>
+ </body>
+</html>
diff --git a/src/admin-ring.css b/src/admin-ring.css
new file mode 100644
index 000000000..c0141ed4d
--- /dev/null
+++ b/src/admin-ring.css
@@ -0,0 +1,846 @@
+/* /admin/ring — x402 ring economy operator dashboard.
+ Dark ops surface tuned to see the economy breathe: a live per-minute pulse
+ strip, a loop diagram with live balances, a streaming activity feed, and
+ fee / integrity / coverage panels. Shares the seeder control room's token
+ language (violet accent, glass cards) so the admin surfaces feel like one
+ product. */
+
+:root {
+ --rg-bg: #07070b;
+ --rg-panel: rgba(255, 255, 255, 0.035);
+ --rg-panel-2: rgba(255, 255, 255, 0.055);
+ --rg-line: rgba(255, 255, 255, 0.08);
+ --rg-line-2: rgba(255, 255, 255, 0.13);
+ --rg-text: #eef0f6;
+ --rg-dim: rgba(238, 240, 246, 0.56);
+ --rg-faint: rgba(238, 240, 246, 0.34);
+ --rg-accent: #7c5cff;
+ --rg-accent-2: #a78bfa;
+ --rg-good: #2fbf71;
+ --rg-warn: #f0a93b;
+ --rg-bad: #f87171;
+ --rg-radius: 16px;
+ --rg-shadow: 0 24px 60px -28px rgba(0, 0, 0, 0.8);
+ --rg-ease: cubic-bezier(0.22, 1, 0.36, 1);
+ --rg-mono: ui-monospace, 'SF Mono', 'JetBrains Mono', 'Roboto Mono', monospace;
+}
+
+:root[data-theme='light'] {
+ --rg-bg: #f6f7fb;
+ --rg-panel: rgba(10, 12, 24, 0.025);
+ --rg-panel-2: rgba(10, 12, 24, 0.045);
+ --rg-line: rgba(10, 12, 24, 0.09);
+ --rg-line-2: rgba(10, 12, 24, 0.15);
+ --rg-text: #14161f;
+ --rg-dim: rgba(20, 22, 31, 0.62);
+ --rg-faint: rgba(20, 22, 31, 0.4);
+ --rg-shadow: 0 20px 50px -30px rgba(20, 22, 40, 0.35);
+}
+
+* {
+ box-sizing: border-box;
+}
+body {
+ margin: 0;
+ background:
+ radial-gradient(1100px 620px at 78% -8%, rgba(124, 92, 255, 0.16), transparent 60%),
+ radial-gradient(900px 520px at 8% 4%, rgba(47, 191, 113, 0.08), transparent 55%),
+ var(--rg-bg);
+ color: var(--rg-text);
+ font:
+ 14px/1.55 -apple-system,
+ system-ui,
+ 'Segoe UI',
+ Inter,
+ sans-serif;
+ min-height: 100vh;
+ -webkit-font-smoothing: antialiased;
+}
+
+.rg-wrap {
+ max-width: 1280px;
+ margin: 0 auto;
+ padding: clamp(1.1rem, 3vw, 2.5rem) 1.15rem 6rem;
+}
+
+/* ── Internal-volume label (persistent) ─────────────────────────────────────── */
+.rg-flag {
+ display: flex;
+ align-items: center;
+ gap: 9px;
+ padding: 9px 14px;
+ margin-bottom: 18px;
+ border-radius: 11px;
+ font-size: 12px;
+ font-weight: 700;
+ letter-spacing: 0.02em;
+ color: #ffd7a1;
+ background: rgba(240, 169, 59, 0.1);
+ border: 1px solid rgba(240, 169, 59, 0.28);
+}
+.rg-flag b {
+ color: var(--rg-warn);
+}
+.rg-flag span {
+ font-weight: 500;
+ color: var(--rg-dim);
+ letter-spacing: 0;
+}
+
+/* ── Auth gate ─────────────────────────────────────────────────────────────── */
+.rg-gate {
+ max-width: 420px;
+ margin: 8vh auto;
+ text-align: center;
+ animation: rg-rise 0.5s var(--rg-ease);
+}
+.rg-gate-mark {
+ width: 64px;
+ height: 64px;
+ margin: 0 auto 20px;
+ border-radius: 20px;
+ display: grid;
+ place-items: center;
+ font-size: 30px;
+ background: linear-gradient(135deg, rgba(124, 92, 255, 0.25), rgba(124, 92, 255, 0.05));
+ border: 1px solid rgba(124, 92, 255, 0.35);
+ box-shadow: 0 0 40px -6px rgba(124, 92, 255, 0.5);
+}
+.rg-gate h1 {
+ font-size: 1.35rem;
+ font-weight: 800;
+ letter-spacing: -0.02em;
+ margin: 0 0 6px;
+}
+.rg-gate p {
+ color: var(--rg-dim);
+ margin: 0 0 22px;
+ font-size: 13.5px;
+}
+.rg-gate form {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+}
+.rg-input {
+ width: 100%;
+ font: inherit;
+ font-size: 14px;
+ padding: 12px 15px;
+ color: var(--rg-text);
+ background: var(--rg-panel);
+ border: 1px solid var(--rg-line-2);
+ border-radius: 12px;
+ outline: none;
+ transition:
+ border-color 0.15s,
+ box-shadow 0.15s;
+}
+.rg-input:focus {
+ border-color: rgba(124, 92, 255, 0.6);
+ box-shadow: 0 0 0 4px rgba(124, 92, 255, 0.14);
+}
+.rg-gate-err {
+ color: var(--rg-bad);
+ font-size: 12.5px;
+ min-height: 16px;
+ margin: 2px 0 0;
+}
+
+/* ── Buttons ───────────────────────────────────────────────────────────────── */
+.rg-btn {
+ font: inherit;
+ font-size: 13px;
+ font-weight: 600;
+ padding: 9px 15px;
+ border-radius: 11px;
+ border: 1px solid var(--rg-line-2);
+ background: var(--rg-panel);
+ color: var(--rg-text);
+ cursor: pointer;
+ transition:
+ background 0.15s,
+ border-color 0.15s,
+ transform 0.1s,
+ box-shadow 0.15s;
+}
+.rg-btn:hover {
+ background: var(--rg-panel-2);
+ border-color: var(--rg-accent);
+}
+.rg-btn:focus-visible {
+ outline: none;
+ box-shadow: 0 0 0 3px rgba(124, 92, 255, 0.35);
+}
+.rg-btn:active {
+ transform: translateY(1px);
+}
+.rg-btn-primary {
+ background: linear-gradient(135deg, var(--rg-accent), #6a49ff);
+ border-color: transparent;
+ color: #fff;
+}
+.rg-btn.on {
+ border-color: var(--rg-accent);
+ color: var(--rg-accent-2);
+}
+
+/* ── Hero ──────────────────────────────────────────────────────────────────── */
+.rg-hero {
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ gap: 20px;
+ flex-wrap: wrap;
+ margin-bottom: 22px;
+}
+.rg-kicker {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ font-size: 12px;
+ font-weight: 600;
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+ color: var(--rg-dim);
+ margin: 0 0 8px;
+}
+.rg-title {
+ font-size: clamp(1.5rem, 3vw, 2rem);
+ font-weight: 800;
+ letter-spacing: -0.025em;
+ margin: 0;
+}
+.rg-title em {
+ font-style: normal;
+ color: var(--rg-accent-2);
+}
+.rg-sub {
+ color: var(--rg-dim);
+ margin: 6px 0 0;
+ max-width: 60ch;
+}
+.rg-hero-r {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ flex-wrap: wrap;
+}
+.rg-periods {
+ display: inline-flex;
+ border: 1px solid var(--rg-line-2);
+ border-radius: 11px;
+ overflow: hidden;
+}
+.rg-periods button {
+ font: inherit;
+ font-size: 12.5px;
+ font-weight: 600;
+ padding: 8px 12px;
+ border: none;
+ background: transparent;
+ color: var(--rg-dim);
+ cursor: pointer;
+ transition:
+ background 0.15s,
+ color 0.15s;
+}
+.rg-periods button:hover {
+ color: var(--rg-text);
+ background: var(--rg-panel);
+}
+.rg-periods button.on {
+ background: var(--rg-accent);
+ color: #fff;
+}
+.rg-periods button:focus-visible {
+ outline: none;
+ box-shadow: inset 0 0 0 2px rgba(255, 255, 255, 0.5);
+}
+
+/* ── Cards / sections ──────────────────────────────────────────────────────── */
+.rg-grid {
+ display: grid;
+ gap: 16px;
+}
+.rg-row {
+ display: grid;
+ gap: 16px;
+ grid-template-columns: 1.35fr 1fr;
+}
+@media (max-width: 900px) {
+ .rg-row {
+ grid-template-columns: 1fr;
+ }
+}
+.rg-card {
+ background: var(--rg-panel);
+ border: 1px solid var(--rg-line);
+ border-radius: var(--rg-radius);
+ padding: 18px;
+ box-shadow: var(--rg-shadow);
+}
+.rg-card-h {
+ display: flex;
+ align-items: baseline;
+ justify-content: space-between;
+ gap: 12px;
+ margin: 0 0 14px;
+}
+.rg-card-h h2 {
+ font-size: 0.95rem;
+ font-weight: 700;
+ letter-spacing: -0.01em;
+ margin: 0;
+}
+.rg-card-h .rg-meta {
+ font-size: 12px;
+ color: var(--rg-faint);
+ font-variant-numeric: tabular-nums;
+}
+
+/* ── Pulse strip ───────────────────────────────────────────────────────────── */
+.rg-pulse {
+ display: grid;
+ grid-template-columns: auto 1fr;
+ gap: 20px;
+ align-items: center;
+}
+@media (max-width: 640px) {
+ .rg-pulse {
+ grid-template-columns: 1fr;
+ }
+}
+.rg-pulse-num {
+ text-align: center;
+ min-width: 132px;
+}
+.rg-pulse-big {
+ font-size: 3rem;
+ font-weight: 800;
+ line-height: 1;
+ letter-spacing: -0.03em;
+ font-variant-numeric: tabular-nums;
+}
+.rg-pulse-big.green {
+ color: var(--rg-good);
+}
+.rg-pulse-big.amber {
+ color: var(--rg-warn);
+}
+.rg-pulse-big.red {
+ color: var(--rg-bad);
+}
+.rg-pulse-lbl {
+ font-size: 11.5px;
+ color: var(--rg-dim);
+ margin-top: 6px;
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+}
+.rg-pulse-dot {
+ display: inline-block;
+ width: 9px;
+ height: 9px;
+ border-radius: 50%;
+ margin-right: 6px;
+ vertical-align: middle;
+}
+.rg-pulse-dot.green {
+ background: var(--rg-good);
+ box-shadow: 0 0 0 0 rgba(47, 191, 113, 0.6);
+ animation: rg-beat 1.6s infinite;
+}
+.rg-pulse-dot.amber {
+ background: var(--rg-warn);
+}
+.rg-pulse-dot.red {
+ background: var(--rg-bad);
+}
+.rg-spark {
+ display: flex;
+ align-items: flex-end;
+ gap: 2px;
+ height: 84px;
+ padding-top: 6px;
+}
+.rg-spark-bar {
+ flex: 1;
+ min-width: 0;
+ min-height: 3px;
+ border-radius: 2px 2px 0 0;
+ background: linear-gradient(180deg, var(--rg-accent-2), var(--rg-accent));
+ opacity: 0.9;
+ transition:
+ height 0.3s var(--rg-ease),
+ opacity 0.15s;
+ position: relative;
+}
+.rg-spark-bar:hover {
+ opacity: 1;
+}
+.rg-spark-bar.empty {
+ background: var(--rg-line-2);
+ min-height: 2px;
+ opacity: 0.5;
+}
+.rg-spark-axis {
+ display: flex;
+ justify-content: space-between;
+ font-size: 10.5px;
+ color: var(--rg-faint);
+ padding-top: 6px;
+}
+
+/* ── Loop diagram ──────────────────────────────────────────────────────────── */
+.rg-loop {
+ display: flex;
+ align-items: stretch;
+ gap: 8px;
+ flex-wrap: wrap;
+}
+.rg-node {
+ flex: 1;
+ min-width: 120px;
+ background: var(--rg-panel-2);
+ border: 1px solid var(--rg-line-2);
+ border-radius: 13px;
+ padding: 13px;
+ text-align: center;
+ position: relative;
+}
+.rg-node.below {
+ border-color: rgba(248, 113, 113, 0.5);
+ box-shadow: 0 0 0 3px rgba(248, 113, 113, 0.1);
+}
+.rg-node-role {
+ font-size: 11px;
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ color: var(--rg-dim);
+ margin-bottom: 6px;
+}
+.rg-node-bal {
+ font-size: 1.15rem;
+ font-weight: 800;
+ font-variant-numeric: tabular-nums;
+ letter-spacing: -0.01em;
+}
+.rg-node-addr {
+ font-family: var(--rg-mono);
+ font-size: 10.5px;
+ color: var(--rg-faint);
+ margin-top: 4px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+.rg-node-floor {
+ font-size: 10.5px;
+ margin-top: 4px;
+ color: var(--rg-dim);
+}
+.rg-node-floor.below {
+ color: var(--rg-bad);
+ font-weight: 700;
+}
+.rg-arrow {
+ display: grid;
+ place-items: center;
+ color: var(--rg-accent-2);
+ font-size: 18px;
+ min-width: 22px;
+}
+@media (max-width: 700px) {
+ .rg-arrow {
+ transform: rotate(90deg);
+ min-height: 20px;
+ }
+}
+
+/* ── Fees panel ────────────────────────────────────────────────────────────── */
+.rg-metrics {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
+ gap: 12px;
+}
+.rg-metric {
+ background: var(--rg-panel-2);
+ border: 1px solid var(--rg-line);
+ border-radius: 12px;
+ padding: 12px 13px;
+}
+.rg-metric dt {
+ font-size: 11px;
+ color: var(--rg-dim);
+ text-transform: uppercase;
+ letter-spacing: 0.04em;
+}
+.rg-metric dd {
+ margin: 6px 0 0;
+ font-size: 1.35rem;
+ font-weight: 800;
+ font-variant-numeric: tabular-nums;
+ letter-spacing: -0.02em;
+}
+.rg-metric small {
+ color: var(--rg-faint);
+ font-size: 11px;
+}
+.rg-metric dd.good {
+ color: var(--rg-good);
+}
+.rg-metric dd.warn {
+ color: var(--rg-warn);
+}
+.rg-metric dd.bad {
+ color: var(--rg-bad);
+}
+.rg-budget-bar {
+ grid-column: 1 / -1;
+ margin-top: 4px;
+}
+.rg-budget-track {
+ height: 8px;
+ border-radius: 6px;
+ background: var(--rg-line-2);
+ overflow: hidden;
+ margin-top: 6px;
+}
+.rg-budget-fill {
+ height: 100%;
+ border-radius: 6px;
+ background: linear-gradient(90deg, var(--rg-good), var(--rg-accent));
+ transition: width 0.4s var(--rg-ease);
+}
+.rg-budget-fill.warn {
+ background: linear-gradient(90deg, var(--rg-warn), #e0862a);
+}
+.rg-budget-fill.bad {
+ background: linear-gradient(90deg, var(--rg-bad), #d64545);
+}
+
+/* ── Activity feed ─────────────────────────────────────────────────────────── */
+.rg-feed-wrap {
+ overflow-x: auto;
+}
+.rg-feed {
+ width: 100%;
+ border-collapse: collapse;
+ font-size: 12.5px;
+ min-width: 620px;
+}
+.rg-feed th {
+ text-align: left;
+ font-weight: 600;
+ color: var(--rg-faint);
+ font-size: 11px;
+ text-transform: uppercase;
+ letter-spacing: 0.04em;
+ padding: 6px 10px;
+ border-bottom: 1px solid var(--rg-line);
+ position: sticky;
+ top: 0;
+ background: var(--rg-bg);
+}
+.rg-feed td {
+ padding: 8px 10px;
+ border-bottom: 1px solid var(--rg-line);
+ vertical-align: middle;
+}
+.rg-feed tbody tr {
+ transition: background 0.12s;
+}
+.rg-feed tbody tr:hover {
+ background: var(--rg-panel);
+}
+.rg-feed tr.new {
+ animation: rg-flash 1.2s var(--rg-ease);
+}
+.rg-feed td.num {
+ font-variant-numeric: tabular-nums;
+ text-align: right;
+}
+.rg-agent {
+ font-weight: 600;
+}
+.rg-slug {
+ font-family: var(--rg-mono);
+ font-size: 11.5px;
+ color: var(--rg-dim);
+}
+.rg-kind {
+ display: inline-block;
+ font-size: 10.5px;
+ font-weight: 700;
+ padding: 2px 7px;
+ border-radius: 6px;
+ text-transform: uppercase;
+ letter-spacing: 0.03em;
+ border: 1px solid var(--rg-line-2);
+ color: var(--rg-dim);
+}
+.rg-kind.settle {
+ color: var(--rg-accent-2);
+ border-color: rgba(167, 139, 250, 0.4);
+}
+.rg-kind.tip {
+ color: #6fd3a3;
+ border-color: rgba(47, 191, 113, 0.35);
+}
+.rg-kind.intel {
+ color: #7fb4ff;
+ border-color: rgba(127, 180, 255, 0.35);
+}
+.rg-kind.commerce {
+ color: #f2c66d;
+ border-color: rgba(240, 169, 59, 0.35);
+}
+.rg-status {
+ font-weight: 700;
+ font-size: 11px;
+}
+.rg-status.paid,
+.rg-status.ok {
+ color: var(--rg-good);
+}
+.rg-status.skipped {
+ color: var(--rg-warn);
+}
+.rg-status.failed {
+ color: var(--rg-bad);
+}
+.rg-reason {
+ font-family: var(--rg-mono);
+ font-size: 10.5px;
+ color: var(--rg-warn);
+}
+.rg-status.failed + .rg-reason,
+tr .rg-reason.failed {
+ color: var(--rg-bad);
+}
+.rg-sig {
+ font-family: var(--rg-mono);
+ font-size: 11px;
+ color: var(--rg-accent-2);
+ text-decoration: none;
+}
+.rg-sig:hover {
+ text-decoration: underline;
+}
+
+/* ── Integrity + coverage ──────────────────────────────────────────────────── */
+.rg-calm {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 12px 14px;
+ border-radius: 11px;
+ background: rgba(47, 191, 113, 0.08);
+ border: 1px solid rgba(47, 191, 113, 0.25);
+ color: var(--rg-good);
+ font-weight: 600;
+ font-size: 13px;
+}
+.rg-alert {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+}
+.rg-alert-row {
+ display: flex;
+ align-items: flex-start;
+ gap: 10px;
+ padding: 10px 13px;
+ border-radius: 10px;
+ background: rgba(248, 113, 113, 0.08);
+ border: 1px solid rgba(248, 113, 113, 0.28);
+ font-size: 12.5px;
+}
+.rg-alert-row.warn {
+ background: rgba(240, 169, 59, 0.08);
+ border-color: rgba(240, 169, 59, 0.28);
+}
+.rg-alert-row.info {
+ background: var(--rg-panel-2);
+ border-color: var(--rg-line-2);
+}
+.rg-alert-row code {
+ font-family: var(--rg-mono);
+ font-size: 11px;
+ color: var(--rg-faint);
+}
+.rg-chips {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 7px;
+ margin-top: 10px;
+}
+.rg-chip {
+ font-size: 11px;
+ padding: 3px 9px;
+ border-radius: 7px;
+ background: var(--rg-panel-2);
+ border: 1px solid var(--rg-line-2);
+ color: var(--rg-dim);
+ font-variant-numeric: tabular-nums;
+}
+
+.rg-cov {
+ display: grid;
+ gap: 8px;
+}
+.rg-cov-row {
+ display: grid;
+ grid-template-columns: 1fr auto auto;
+ gap: 12px;
+ align-items: center;
+ padding: 9px 12px;
+ border-radius: 10px;
+ background: var(--rg-panel-2);
+ border: 1px solid var(--rg-line);
+}
+.rg-cov-row.stale {
+ border-color: rgba(240, 169, 59, 0.4);
+}
+.rg-cov-name {
+ font-weight: 600;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.rg-cov-name small {
+ display: block;
+ font-family: var(--rg-mono);
+ font-size: 10.5px;
+ color: var(--rg-faint);
+ font-weight: 400;
+}
+.rg-cov-age {
+ font-size: 12px;
+ font-variant-numeric: tabular-nums;
+ color: var(--rg-dim);
+}
+.rg-cov-age.stale {
+ color: var(--rg-warn);
+ font-weight: 700;
+}
+.rg-cov-vol {
+ font-size: 12px;
+ font-variant-numeric: tabular-nums;
+ color: var(--rg-faint);
+}
+
+/* ── States (skeleton, empty, error) ──────────────────────────────────────── */
+.rg-skel {
+ background: linear-gradient(
+ 100deg,
+ var(--rg-panel) 30%,
+ var(--rg-panel-2) 50%,
+ var(--rg-panel) 70%
+ );
+ background-size: 200% 100%;
+ animation: rg-shimmer 1.3s infinite;
+ border-radius: 8px;
+}
+.rg-empty,
+.rg-errbox {
+ text-align: center;
+ padding: 30px 20px;
+ color: var(--rg-dim);
+}
+.rg-empty-mark {
+ font-size: 28px;
+ margin-bottom: 10px;
+ opacity: 0.7;
+}
+.rg-empty strong,
+.rg-errbox strong {
+ display: block;
+ color: var(--rg-text);
+ font-size: 15px;
+ margin-bottom: 6px;
+}
+.rg-errbox {
+ background: rgba(248, 113, 113, 0.06);
+ border: 1px solid rgba(248, 113, 113, 0.25);
+ border-radius: var(--rg-radius);
+}
+.rg-errbox code {
+ display: block;
+ margin-top: 12px;
+ padding: 10px 12px;
+ border-radius: 9px;
+ background: rgba(0, 0, 0, 0.3);
+ font-family: var(--rg-mono);
+ font-size: 11.5px;
+ color: var(--rg-accent-2);
+ text-align: left;
+ overflow-x: auto;
+ white-space: pre;
+}
+
+/* ── Toast / keyboard hint ─────────────────────────────────────────────────── */
+.rg-hint {
+ position: fixed;
+ bottom: 14px;
+ right: 16px;
+ font-size: 11.5px;
+ color: var(--rg-faint);
+ background: var(--rg-panel-2);
+ border: 1px solid var(--rg-line);
+ border-radius: 9px;
+ padding: 6px 11px;
+ backdrop-filter: blur(8px);
+}
+.rg-hint kbd {
+ font-family: var(--rg-mono);
+ font-size: 10.5px;
+ padding: 1px 5px;
+ border-radius: 5px;
+ border: 1px solid var(--rg-line-2);
+ background: var(--rg-panel);
+ color: var(--rg-dim);
+}
+.rg-paused-badge {
+ color: var(--rg-warn);
+ font-weight: 700;
+}
+
+/* ── Animations ────────────────────────────────────────────────────────────── */
+@keyframes rg-rise {
+ from {
+ opacity: 0;
+ transform: translateY(8px);
+ }
+}
+@keyframes rg-shimmer {
+ to {
+ background-position: -200% 0;
+ }
+}
+@keyframes rg-flash {
+ from {
+ background: rgba(124, 92, 255, 0.18);
+ }
+}
+@keyframes rg-beat {
+ 0% {
+ box-shadow: 0 0 0 0 rgba(47, 191, 113, 0.5);
+ }
+ 70% {
+ box-shadow: 0 0 0 7px rgba(47, 191, 113, 0);
+ }
+ 100% {
+ box-shadow: 0 0 0 0 rgba(47, 191, 113, 0);
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .rg-skel,
+ .rg-pulse-dot,
+ .rg-feed tr.new,
+ .rg-spark-bar {
+ animation: none !important;
+ transition: none !important;
+ }
+}
diff --git a/tasks/x402-ring/STATUS.md b/tasks/x402-ring/STATUS.md
new file mode 100644
index 000000000..e12dd1711
--- /dev/null
+++ b/tasks/x402-ring/STATUS.md
@@ -0,0 +1,341 @@
+# Task 01 — Live-State Audit of the x402 Ring Economy
+
+**Date:** 2026-07-03 (~04:40 UTC)
+**Mode:** READ-ONLY. No env writes, no code changes, no funds moved, no DB writes.
+**Auditor environment access:** codespace shell only. **No `vercel` CLI**, **no
+`DATABASE_URL`**, **no `psql`/`pg`**, **no Helius/RPC key**, no `.env` (only
+`.env.example`). Evidence therefore comes from: (a) **live HTTP probes** against
+`https://three.ws`, and (b) **public Solana mainnet RPC**
+(`https://api.mainnet-beta.solana.com`, no key needed). The env truth table below
+is **inferred** from those two sources — it is not a `vercel env ls` dump, and
+each row states the evidence and confidence. This limitation is called out
+wherever it changes a verdict.
+
+---
+
+## ⚠️ Headline finding — the premise is inverted
+
+**The ring is NOT producing zero volume. It is settling real USDC on-chain right
+now — roughly one settlement per minute — and has been continuously since
+2026-07-02.** The "zero" exists only inside the `/api/x402-ring` report, which
+reads a table (`x402_self_facilitator_log`) that is empty because the self-hosted
+facilitator is disabled. The actual settlements route through the sponsor-co-signed
+path and never write that table, so **the scoreboard is blind to the volume the
+chain proves is flowing.**
+
+The most recent on-chain settlement observed during this audit was
+**2026-07-03T04:38:25Z** — a $0.001 USDC transfer from the ring payer to the ring
+treasury, co-signed by the sponsor (fee payer), landing while this report was
+being written.
+
+So the real problem is two-fold, and neither part is "the loop is dead":
+1. **Accounting blind spot** — `/api/x402-ring` reports 0 settlements / $0 gross
+ while ~1,500 real settlements have landed since 2026-07-02.
+2. **Fee-inefficient mode** — the volume that *is* flowing is thousands of tiny
+ $0.001 two-signature payments (10,001 lamports each), i.e. the exact
+ fee-maximising mode `docs/x402-ring-economy.md` warns against. The fee-optimal
+ `ring-settle` ($1.00, fewer/larger) path, the self-hosted facilitator, and the
+ rebalancer are all disabled.
+
+---
+
+## Section 1 — Env truth table (inferred; no `vercel env ls` access)
+
+`vercel` CLI is not installed and no token is present, so this table is
+**reconstructed from live probes + chain**, not read from Vercel. Confidence and
+evidence per row. "Present value" shows non-secret public values only; secrets are
+recorded as presence, never printed.
+
+| Var | Verdict | Evidence | Conf. |
+|---|---|---|---|
+| `X402_SELF_FACILITATOR_ENABLED` | **NOT `true` (disabled)** | `/api/x402-ring` → `self_hosted_facilitator:false`; `/api/x402-facilitator/*` unreachable (404 SPA). | High |
+| `X402_FACILITATOR_URL_SOLANA` | **default (PayAI)** | `/api/x402-status` lists solana facilitator `https://facilitator.payai.network` `ok:true`. No override visible. | High |
+| `X402_PAY_TO_SOLANA` | **SET** = `wwwwwDxFWRn7grgr3Esrsg5C6NvDoDHSA4gaCffccrU` | `/api/x402-status` `env` block + every 402 challenge `payTo`. | High |
+| `X402_TREASURY_SECRET_BASE58` | **NOT SET** | `/api/x402-ring` `sweeps.count:0`; rebalancer no-ops without it (`ring-rebalance.js:71-72`); treasury is filling (7.7 USDC) and never swept. | High |
+| `X402_FEE_PAYER_SOLANA` | **SET** = `2wKupLR9q6wXYppw8Gr2NvWxKBUqm4PPJKkQfoxHDBg4` | `/api/x402-status` `env.X402_FEE_PAYER_SOLANA`; advertised as `extra.feePayer` in every challenge. | High |
+| `X402_FEE_PAYER_SECRET_BASE58` | **SET** | Sponsor `2wKup…` is a **co-signer on every settlement tx on chain** — the key is loaded somewhere and signing. | High |
+| `X402_SEED_SOLANA_SECRET_BASE58` | **SET** | `x402-seed-cron` is actively producing settlements; payer `X4o2…` signs each. | High |
+| `X402_AGENT_SOLANA_SECRET_BASE58` | undeterminable | Only a fallback for the seed key; seed key is set, so this is untested. | — |
+| `X402_RING_SELF_PAY` | **NOT `true`** | Settlements are **2-signature, fee = 10,001 lamports** (buyer + sponsor). Self-pay would be 1 sig / ~5,000 lamports (`docs` Lever 2). | High |
+| `X402_PRICE_RING_SETTLE` | **NOT SET (default $1.00)** | POST `/api/x402/ring-settle` 402 challenge advertises `amount:"1000000"` = default `1_000_000`. | High |
+| `X402_VOLUME_PER_RUN_CAP_ATOMIC` | **NOT SET (default $0.05)** | Cannot read directly; `volume-bootstrap-loop.js:59-62` default `50_000`. Consistent with ring-settle being skipped. | Med |
+| `X402_AUTONOMOUS_DAILY_CAP_ATOMIC` | undeterminable | No unauthenticated surface exposes it. | — |
+| `X402_AUTONOMOUS_ENABLED` | undeterminable | Cron is `Bearer CRON_SECRET`-gated; cannot invoke. (Note: volume is driven by `x402-seed-cron`, a *separate* per-minute driver, which is clearly live.) | — |
+| `X402_EXTERNAL_ENABLED` | undeterminable | No unauthenticated surface. | — |
+| `X402_CHARITY_AUDIT_BPS` | undeterminable | No unauthenticated surface. | — |
+| `X402_SPONSOR_SOL_FLOOR_LAMPORTS` | **NOT SET (default 0.02 SOL)** | `/api/x402-ring` → `sponsor.floor_sol:0.02` = default `20_000_000`. | High |
+| `X402_SELF_FACILITATOR_PAYTO_ALLOWLIST` | undeterminable | Facilitator route is 404; cannot probe allowlist. | — |
+| `SOLANA_RPC_URL` / `HELIUS_API_KEY` | **SET (working)** | `/api/x402-ring` returns live on-chain balances → server-side RPC is configured and healthy. | High |
+| `DATABASE_URL` | **SET (working)** | `/api/x402-ring` → `db_available:true` and DB queries return rows (counts). | High |
+
+---
+
+## Section 2 — Live HTTP probes (real output)
+
+### 2a. `GET /api/x402-facilitator/supported` — expected 503-if-off; **actually 404**
+```
+HTTP 404 (returns the SPA 404 HTML, not JSON)
+```
+Also tried `POST /api/x402-facilitator/verify` → **404 SPA**, and
+`GET /api/x402-facilitator?action=supported` → **404 SPA**. The entire
+`/api/x402-facilitator/*` route resolves to the site's 404 page — the function is
+**not routed/reachable in production at all** (worse than the hypothesised 503).
+The code path that *would* return 503 (`[action].js:89-96`) is never reached
+because the request never lands on the function. Net effect is the same:
+self-hosted facilitator does not settle anything.
+
+### 2b. `GET /api/x402-ring?period=7d` — the report says zero
+```json
+{"ok":true,"self_hosted_facilitator":false,"internal":true,
+ "period":"7d","db_available":true,
+ "settlements":{"count":0,"gross_usdc":0,"avg_call_usdc":null},
+ "fees":{"tx_count":0,"sol_burned_lamports":0,"sol_burned":0,...},
+ "sweeps":{"count":0,"swept_usdc":0},
+ "wallets":{
+ "treasury":{"address":"wwwwwDxFWRn7grgr3Esrsg5C6NvDoDHSA4gaCffccrU","usdc":7.698},
+ "payer":{"address":"X4o2UuVNMxnrgkzVy97kPF5gmS6CLRCVJGB48VastML","usdc":82.26289},
+ "sponsor":{"address":"2wKupLR9q6wXYppw8Gr2NvWxKBUqm4PPJKkQfoxHDBg4","sol":0.247539808,"floor_sol":0.02,"below_floor":false}},
+ "net":{"ring_float_usdc":89.96089,"gross_volume_usdc":0,"real_cost_usdc":0},
+ "recent":[]}
+```
+`period=30d` returns the same `count:0`. **Root cause of the "0":** the report
+queries `x402_self_facilitator_log WHERE action='settle' AND ok=true`
+(`api/x402-ring.js:108-115`) and `x402_ring_ledger WHERE kind='sweep'`
+(`:128-133`). The self-facilitator is disabled → the first table is empty; the
+rebalancer is disabled → the second is empty. **The report has no visibility into
+settlements that route through the sponsor-co-signed / PayAI path** (Section 4
+proves those are happening). `db_available:true` and the queries returning `0`
+(not erroring) confirm both tables **exist** — the migration was applied; they are
+simply empty.
+
+### 2c. `POST /api/x402/ring-settle` — 402 challenge, price = $1.00
+```json
+{"accepts":[
+ {"scheme":"exact","amount":"1000000","network":"solana:5eykt4Us…",
+ "payTo":"wwwwwDxFWRn7grgr3Esrsg5C6NvDoDHSA4gaCffccrU",
+ "asset":"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
+ "extra":{"name":"USDC","decimals":6,"feePayer":"2wKupLR9q6wXYppw8Gr2NvWxKBUqm4PPJKkQfoxHDBg4"}},
+ {"scheme":"exact","amount":"10000000","asset":"FeMbDoX7…pump","extra":{"name":"THREE",…}}]}
+```
+`amount:"1000000"` = **$1.00** (default `X402_PRICE_RING_SETTLE`). A Solana USDC
+accept **is present**, `payTo`=treasury, `feePayer`=sponsor. `discoverable:false`
+(correct — internal). (`GET` returns `405 use POST`, as designed.)
+
+### 2d. `GET /api/x402-status` — facilitator health
+```json
+HTTP 503 {"ok":false,"x402Version":2,
+ "facilitators":[
+ {"network":"eip155:8453","url":"https://x402.sperax.io","ok":false,"reason":"/supported probe failed: status 404"},
+ {"network":"solana:5eykt4Us…","url":"https://facilitator.payai.network","ok":true,
+ "reason":"facilitator advertises exact/solana…"}],
+ "env":{"X402_PAY_TO_SOLANA":"wwwwwDxFWRn7grgr3Esrsg5C6NvDoDHSA4gaCffccrU",
+ "X402_FEE_PAYER_SOLANA":"2wKupLR9q6wXYppw8Gr2NvWxKBUqm4PPJKkQfoxHDBg4",
+ "X402_ASSET_MINT_SOLANA":"EPjFWdd5…","X402_MAX_AMOUNT_REQUIRED":"1000"},
+ "siwx":{"configured":true,"paymentsRowCount":22,"noncesRowCount":0}}
+```
+The `503`/`ok:false` is driven by the **Base** facilitator (`x402.sperax.io`)
+failing its `/supported` probe (404). The **Solana** facilitator (PayAI) is
+`ok:true`. Solana settlement rail is healthy; the status endpoint reports overall
+`ok:false` because one configured facilitator (Base) is down. The advertised
+Solana `feePayer` is our sponsor — **so `X402_FEE_PAYER_SOLANA` is set and the
+Solana accept is live.**
+
+### 2e. `GET /api/x402/dance-tip` — cheap catalog endpoint, 402 challenge
+```json
+HTTP 402 {"accepts":[
+ {"scheme":"exact","amount":"1000","network":"solana:5eykt4Us…",
+ "payTo":"wwwwwDxFWRn7grgr3Esrsg5C6NvDoDHSA4gaCffccrU",
+ "asset":"EPjFWdd5…","extra":{"feePayer":"2wKupLR9q6wXYppw8Gr2NvWxKBUqm4PPJKkQfoxHDBg4"}},
+ {"scheme":"exact","amount":"10000000","asset":"FeMbDoX7…pump","extra":{"name":"THREE"}}]}
+```
+`amount:"1000"` = **$0.001**. This is the endpoint the per-minute driver actually
+pays (Section 4). Solana accept present, feePayer set.
+
+---
+
+## Section 3 — Database evidence (derived; no direct DB access)
+
+No `DATABASE_URL`/`psql` locally, so table state is derived from the deployed
+report's query behaviour plus on-chain ground truth:
+
+- **`x402_self_facilitator_log` — EXISTS, effectively 0 settle rows.**
+ `/api/x402-ring` queries it (`api/x402-ring.js:108-115`) and returns
+ `settlements.count:0` with `db_available:true` and no error → the table exists
+ (query planned/ran) but has **no `action='settle', ok=true` rows** in 7d or 30d.
+ Expected: the self-facilitator is the only writer of this table
+ (`x402-facilitator/[action].js:44-55 logOp`), and it is disabled.
+- **`x402_ring_ledger` — EXISTS, 0 sweep rows.** Queried at
+ `api/x402-ring.js:128-133`; `sweeps.count:0`. The only writer is the rebalancer
+ (`ring-rebalance.js:170-174`), which no-ops without `X402_TREASURY_SECRET_BASE58`.
+- **`x402_wallets` / `x402_ring_wallets`** — no unauthenticated surface exposes
+ row counts; **undeterminable** from here. Evidence missing: DB read access.
+- **`x402_autonomous_log`** (last-50 / group-by-status) and **`x402_volume_metrics`**
+ (per-endpoint last-paid) — the task asks for these to date the stop/start of the
+ loop. **No unauthenticated API surfaces them** (grep of `api/*.js` found no
+ public reader of either table), and I have no DB access. **Undeterminable via
+ the tools available.** *Evidence missing: `DATABASE_URL`.* This gap is fully
+ compensated by Section 4 — the chain is the authoritative settlement ledger and
+ gives an exact, second-resolution timeline that does not depend on any app table.
+
+**Migration status:** `2026-07-01-x402-ring-economy.sql` was **applied** — both
+ring tables answer queries without a "relation does not exist" error.
+
+---
+
+## Section 4 — On-chain wallet & settlement state (public RPC — ground truth)
+
+Public mainnet RPC, no key. All three role wallets and the two USDC ATAs involved
+in settlement:
+
+| Role | Owner pubkey | SOL | USDC | USDC ATA |
+|---|---|---|---|---|
+| treasury | `wwwwwDxFWRn7grgr3Esrsg5C6NvDoDHSA4gaCffccrU` | 0.1022 | 7.70 | `HgwbNyweQUiV5diWJ1a7ocxgzf3AYSLhTpphEYRLujtN` |
+| payer | `X4o2UuVNMxnrgkzVy97kPF5gmS6CLRCVJGB48VastML` | 0.3372 | 82.26 | `4eE8iCmTAdMpwLaqKvn2wj2g5v2TV31fRVoWbwyxrgFh` |
+| sponsor | `2wKupLR9q6wXYppw8Gr2NvWxKBUqm4PPJKkQfoxHDBg4` | 0.2472 | — | (fee payer only) |
+
+**Ring float = 89.96 USDC** (payer 82.26 + treasury 7.70), intact — **not
+drained.** Sponsor 0.247 SOL, above the 0.02 floor.
+
+### The settlements are real and continuous
+Decoded newest payer settlement (`getTransaction`, jsonParsed):
+```
+tx JX4QAHT16Ljph… blockTime 2026-07-03T04:33:25Z fee 10001 lamports
+signers: 2wKup… (sponsor / feePayer) , X4o2… (payer / authority)
+ix[2] spl-token transferChecked authority=X4o2… mint=EPjFWdd5…(USDC)
+ source=4eE8…(payer ATA) destination=HgwbNy…(treasury ATA) amount=1000 ($0.001)
+preTokenBalances: payer 82.26089 , treasury 7.700
+postTokenBalances: payer 82.25989 , treasury 7.701 ← payer −0.001, treasury +0.001
+```
+Newest treasury settlement fee/signers (`2Q4bjj…`, 04:38:25Z):
+`fee: 10001 lamports | signers: 2 | 2wKup…, X4o2…`.
+
+### Cadence — one settlement per minute
+Newest 15 treasury-ATA inbound settlements, all `ok`, spacing in seconds:
+```
+04:38:25, 04:37:25, 04:36:29, 04:35:25, 04:35:10, 04:34:25, 04:33:25,
+04:32:25, 04:31:25, 04:30:25, 04:30:13, 04:30:10, 04:29:26, 04:28:25, 04:27:25
+gaps(s): 60,56,64,15,45,60,60,60,60,12,3,44,61,60 → ~1 per minute
+```
+This matches the `x402-seed-cron` schedule `* * * * *` in `vercel.json:4869-4870`.
+**Note (efficiency defect):** `x402-seed-cron.js` builds `X402_SEED_BATCH_SIZE`
+(default **60**) transactions per tick, but `buildPaymentTx` (`:130-166`) produces
+**byte-identical** txs (same amount, source, dest, single blockhash, single
+signer) → identical signatures → **only one unique settlement lands per tick**;
+the other 59 are duplicate-signature no-ops. So the effective rate is ~1/min, not
+60/min — the intended "60 real micropayments per tick" is not being achieved on
+chain.
+
+### Last-signature timeline per ATA (paged, up to 6k sigs)
+```
+treasury USDC ATA (HgwbNy…): 1523 sigs, 0 errored
+ 2026-06-21: 32 2026-06-22: 10 2026-06-23: 4
+ << largest gap ~8.5 days (12,291 min), ending ~2026-06-23T19:06Z >>
+ 2026-07-02: 1124 2026-07-03: 353 (newest 04:38:25Z, ongoing)
+payer USDC ATA (4eE8…): 1471 sigs, 0 errored
+ 2026-06-27: 1 2026-07-02: 1117 2026-07-03: 353 (newest 04:38:25Z)
+```
+No errored settlement signatures on either ATA — every landed settlement succeeded.
+
+---
+
+## Section 5 — Chronology (stop/start date + mechanism)
+
+The chain gives an unambiguous timeline (this supersedes the missing
+`x402_autonomous_log` DB evidence):
+
+- **2026-06-21 → 06-23:** sporadic settlements to treasury (32 / 10 / 4 per day) —
+ early manual/low-rate activity.
+- **2026-06-23T19:06Z → 2026-07-02:** an **~8.5-day dead gap**, zero settlements.
+ This aligns with the known **June 2026 Vercel cron outage** (an account block
+ killed all `vercel.json` crons; see `memory/economy-cron-outage-2026-06.md` and
+ commit `b15f97b0c` "external cron failover heartbeat driving all vercel.json
+ crons from GitHub Actions"). With no cron firing, `x402-seed-cron` did not run →
+ no settlements.
+- **2026-07-02:** settlements **resume hard — 1124 in the day** — coincident with
+ the GitHub-Actions heartbeat failover restoring cron execution. This is the
+ "restart," not a stop.
+- **2026-07-03 (today):** **353 settlements so far and counting**, ~1/min, newest
+ 04:38:25Z during this audit.
+
+**Mechanism of the reported "zero":** never a chain stoppage. The
+`/api/x402-ring` report has *always* shown zero for this run because it reads
+`x402_self_facilitator_log`, which the disabled self-hosted facilitator never
+writes. The settlements route through the sponsor-co-signed path (advertised
+feePayer = our sponsor; facilitator default = PayAI) and land on chain without
+touching that table. **The loop's real stop was the 8.5-day cron outage
+(2026-06-23 → 07-02); it restarted 2026-07-02 and is live now.** What is genuinely
+"off" (and always was) is the *designed* fee-optimal closed loop: self-hosted
+facilitator, `ring-settle` large payments, and the rebalancer.
+
+---
+
+## Section 6 — Hypothesis verdicts + task mapping
+
+| # | Static hypothesis | Verdict | Evidence |
+|---|---|---|---|
+| 1 | `X402_FACILITATOR_URL_SOLANA` defaults to PayAI; settlement never reaches self-facilitator | **CONFIRMED** (but not fatal) | `/api/x402-status` solana facilitator = `facilitator.payai.network`, `ok:true`. Settlement *does* succeed on chain via the sponsor-co-signed path — routing default is true, but it is **not** what stops volume. |
+| 2 | `X402_SELF_FACILITATOR_ENABLED` false → facilitator 503 | **CONFIRMED (disabled); PARTIAL on "503"** | Self-facilitator is off (`self_hosted_facilitator:false`). The route returns **404 (unrouted), not 503** — the function is unreachable in prod, so the 503 branch is never even hit. Consequence (empty `x402_self_facilitator_log`, blind report) confirmed. |
+| 3 | `ring-settle` $1.00 > per-run cap $0.05 → `cap_would_exceed` every cycle | **CONFIRMED (for ring-settle only)** | Live 402: ring-settle `amount:1000000` ($1.00); `VOLUME_PER_RUN_CAP_ATOMIC` default `50000` ($0.05). ring-settle is skipped by the volume loop — but the cheap $0.001 endpoints settle fine, so this causes **fee-inefficiency**, not zero volume. |
+| 4 | Rebalancer no-ops without `X402_TREASURY_SECRET_BASE58` | **CONFIRMED** | `sweeps.count:0`; `x402_ring_ledger` empty; treasury filling (7.70 USDC) with no sweep-back. Not yet fatal only because payments are $0.001. |
+| 5 | Solana accept dropped when `X402_FEE_PAYER_SOLANA` unset | **REFUTED** | Fee payer **is set** (`2wKup…`); Solana accept present in every 402 challenge; sponsor co-signs on chain. |
+| 6 | Only driver is `/api/cron/x402-autonomous-loop` @ `*/5`; `X402_AUTONOMOUS_ENABLED=false` kills it | **REFUTED** | There is a **second, separate driver** — `x402-seed-cron` @ `* * * * *` (`vercel.json:4869-4870`) — and it is the one producing the live per-minute volume. Whether the `*/5` autonomous loop is enabled is undeterminable from here, but it is not "the only driver." |
+
+### Which downstream task each finding maps to
+- **Blind report / `x402_self_facilitator_log` unwritten (Headline, §2b, §5)** →
+ **07 (reconciliation)** + **10 (dashboard)**: the report must count real
+ on-chain settlements (or the sponsor-co-signed path must log to the ledger), not
+ only self-facilitator rows.
+- **Facilitator route 404 + self-facilitator disabled (§2a, H2)** →
+ **02 (facilitator-routing)**: deploy/route `/api/x402-facilitator`, enable it,
+ and point `X402_FACILITATOR_URL_SOLANA` at it so settlement is in-house and
+ logged.
+- **PayAI still the active Solana facilitator (§2d, H1)** → **02**.
+- **ring-settle $1 skipped by $0.05 cap; fee-inefficient $0.001 spam (H3, §4)** →
+ **04 (per-minute cadence, cap-coherent)** + **05 (fee minimization)**: raise
+ `X402_PRICE_RING_SETTLE` + caps together, enable self-pay (1-sig) — currently
+ 2-sig at 10,001 lamports.
+- **60 identical txs/tick collapse to 1 settlement (§4)** → **04** + **08
+ (endpoint coverage)**: `x402-seed-cron.buildPaymentTx` needs a per-tx
+ differentiator (memo/nonce) or the batch is wasted.
+- **Rebalancer disabled, treasury not swept (H4)** → **03 (wallets/provisioning:
+ register `X402_TREASURY_SECRET_BASE58`)**.
+- **2-sig sponsor mode, not self-pay (§4, env `X402_RING_SELF_PAY` not true)** →
+ **05 (fee minimization)**.
+- **8.5-day cron outage / GH-Actions failover dependency (§5)** → **04** +
+ **11 (activation & acceptance: prove cron reliability under the failover)**.
+- **`x402_autonomous_log` / `x402_volume_metrics` have no read surface (§3)** →
+ **07** + **10**: expose them so the stop/start is observable without chain
+ spelunking.
+
+---
+
+## Acceptance criteria
+
+- [x] `STATUS.md` exists with all six sections and real command output.
+- [x] Every hypothesis marked CONFIRMED / REFUTED / PARTIAL with evidence.
+- [x] Stop/start date + mechanism identified: **stopped 2026-06-23T19:06Z (8.5-day
+ Vercel cron outage), restarted 2026-07-02, live at ~1 settlement/min now.**
+ The `/api/x402-ring` "zero" is an accounting artifact (empty
+ `x402_self_facilitator_log`), not a settlement stoppage.
+- [x] **Zero mutations performed.** No env writes, no code edits, no funds moved,
+ no DB writes. Only read-only HTTP GET/POST-challenge probes and read-only
+ Solana RPC queries were issued.
+
+### Proof of no mutation (working tree)
+**The only file this audit created is `tasks/x402-ring/STATUS.md`.** This worktree
+is **shared with concurrent agents** running the downstream code tasks (02–11)
+per `README.md`, so `git status` also shows *their* in-flight edits — none of
+which this read-only audit touched. `git status --short` at completion:
+```
+ M api/_lib/x402/wallet-balance-monitor.js (another agent — task 03/10)
+ M tests/api/x402-spec.test.js (another agent)
+ M tests/x402-ring-reconciliation.test.js (another agent — task 07)
+?? api/_lib/x402/pipelines/fee-audit.js (another agent — task 05)
+?? tasks/x402-ring/STATUS.md ← THIS report (my only write)
+```
+I issued only read-only HTTP GET/POST-challenge probes and read-only Solana RPC
+queries, and wrote one file (this report) plus temp scripts in the session
+scratchpad (outside the repo). No env writes, no funds moved, no DB writes, and no
+edit to any `api/`, `src/`, `tests/`, or config file. The changes shown above
+belong to the parallel task agents and were present-and-growing independently of
+this audit.
diff --git a/tests/api/x402-ring-config.test.js b/tests/api/x402-ring-config.test.js
new file mode 100644
index 000000000..fca712916
--- /dev/null
+++ b/tests/api/x402-ring-config.test.js
@@ -0,0 +1,244 @@
+// Unit tests for the ring routing + config-truth helpers in
+// api/_lib/x402/ring-config.js (task 02). Pure logic — no network, no DB, no
+// @solana/web3.js. Covers:
+//
+// - resolveSolanaFacilitator: explicit-URL-wins > flag-on-self > external default.
+// - validateRingConfig: the six-finding matrix (facilitator off, URL external,
+// missing treasury secret, missing fee-payer pubkey, price>cap, self-pay off).
+// - warnIfRingRoutesExternal: one warning per boot; null when routing is self.
+//
+// ring-config.js imports only env.js + x402-prices.js, both of which read
+// process.env through getters, so env mutations here take effect immediately
+// without a module reset.
+
+import { afterEach, beforeEach, describe, it, expect, vi } from 'vitest';
+
+import {
+ resolveSolanaFacilitator,
+ validateRingConfig,
+ warnIfRingRoutesExternal,
+ isSelfFacilitatorUrl,
+ selfFacilitatorUrl,
+ _resetRingConfigWarningsForTest,
+} from '../../api/_lib/x402/ring-config.js';
+
+const SELF_URL = 'https://three.ws/api/x402-facilitator';
+const PAYAI = 'https://facilitator.payai.network';
+
+// The full env envelope of a correctly-configured ring — start from this and
+// remove/override a single var per test to isolate each finding.
+function healthyRingEnv() {
+ process.env.X402_SELF_FACILITATOR_ENABLED = 'true';
+ delete process.env.X402_FACILITATOR_URL_SOLANA;
+ delete process.env.X402_FACILITATOR_URL;
+ process.env.X402_FEE_PAYER_SOLANA = '2wKupLR9q6wXYppw8Gr2NvWxKBUqm4PPJKkQfoxHDBg4';
+ process.env.X402_TREASURY_SECRET_BASE58 = 'z'.repeat(64);
+ process.env.X402_RING_SELF_PAY = 'true';
+ process.env.X402_PRICE_RING_SETTLE = '1000000';
+ process.env.X402_VOLUME_PER_RUN_CAP_ATOMIC = '2000000';
+ delete process.env.PUBLIC_APP_ORIGIN;
+}
+
+const RING_VARS = [
+ 'X402_SELF_FACILITATOR_ENABLED',
+ 'X402_FACILITATOR_URL_SOLANA',
+ 'X402_FACILITATOR_URL',
+ 'X402_FEE_PAYER_SOLANA',
+ 'X402_TREASURY_SECRET_BASE58',
+ 'X402_RING_SELF_PAY',
+ 'X402_PRICE_RING_SETTLE',
+ 'X402_VOLUME_PER_RUN_CAP_ATOMIC',
+ 'PUBLIC_APP_ORIGIN',
+];
+
+const ORIG = {};
+
+beforeEach(() => {
+ for (const k of RING_VARS) ORIG[k] = process.env[k];
+ _resetRingConfigWarningsForTest();
+});
+
+afterEach(() => {
+ for (const k of RING_VARS) {
+ if (ORIG[k] === undefined) delete process.env[k];
+ else process.env[k] = ORIG[k];
+ }
+ vi.restoreAllMocks();
+});
+
+const codes = (findings) => findings.map((f) => f.code);
+
+describe('resolveSolanaFacilitator', () => {
+ it('flag off, no URL → external default, self:false', () => {
+ delete process.env.X402_SELF_FACILITATOR_ENABLED;
+ delete process.env.X402_FACILITATOR_URL_SOLANA;
+ delete process.env.X402_FACILITATOR_URL;
+ const r = resolveSolanaFacilitator();
+ expect(r).toEqual({ url: PAYAI, self: false });
+ });
+
+ it('flag on, no URL → self facilitator, self:true', () => {
+ process.env.X402_SELF_FACILITATOR_ENABLED = 'true';
+ delete process.env.X402_FACILITATOR_URL_SOLANA;
+ delete process.env.X402_FACILITATOR_URL;
+ const r = resolveSolanaFacilitator();
+ expect(r).toEqual({ url: SELF_URL, self: true });
+ });
+
+ it('explicit external URL always wins over the flag', () => {
+ process.env.X402_SELF_FACILITATOR_ENABLED = 'true';
+ process.env.X402_FACILITATOR_URL_SOLANA = 'https://ext.example.test';
+ const r = resolveSolanaFacilitator();
+ expect(r).toEqual({ url: 'https://ext.example.test', self: false });
+ });
+
+ it('a blank explicit URL is treated as unset', () => {
+ process.env.X402_SELF_FACILITATOR_ENABLED = 'true';
+ process.env.X402_FACILITATOR_URL_SOLANA = ' ';
+ const r = resolveSolanaFacilitator();
+ expect(r).toEqual({ url: SELF_URL, self: true });
+ });
+
+ it('a trailing slash is trimmed', () => {
+ process.env.X402_FACILITATOR_URL_SOLANA = 'https://ext.example.test/';
+ expect(resolveSolanaFacilitator().url).toBe('https://ext.example.test');
+ });
+});
+
+describe('isSelfFacilitatorUrl', () => {
+ it('matches the facilitator route on any host', () => {
+ expect(isSelfFacilitatorUrl(SELF_URL)).toBe(true);
+ expect(isSelfFacilitatorUrl('https://preview.three.ws/api/x402-facilitator/')).toBe(true);
+ });
+ it('rejects external and malformed URLs', () => {
+ expect(isSelfFacilitatorUrl(PAYAI)).toBe(false);
+ expect(isSelfFacilitatorUrl('not a url')).toBe(false);
+ expect(isSelfFacilitatorUrl('')).toBe(false);
+ });
+});
+
+describe('validateRingConfig finding matrix', () => {
+ it('a fully-healthy ring produces no findings', () => {
+ healthyRingEnv();
+ expect(validateRingConfig()).toEqual([]);
+ });
+
+ it('flags self_facilitator_disabled AND facilitator_url_external when the flag is off', () => {
+ healthyRingEnv();
+ delete process.env.X402_SELF_FACILITATOR_ENABLED;
+ const c = codes(validateRingConfig());
+ expect(c).toContain('self_facilitator_disabled');
+ expect(c).toContain('facilitator_url_external');
+ });
+
+ it('flags facilitator_url_external when the flag is on but an external URL wins', () => {
+ healthyRingEnv();
+ process.env.X402_FACILITATOR_URL_SOLANA = 'https://ext.example.test';
+ const c = codes(validateRingConfig());
+ expect(c).toContain('facilitator_url_external');
+ expect(c).not.toContain('self_facilitator_disabled');
+ });
+
+ it('flags treasury_secret_missing (warn severity)', () => {
+ healthyRingEnv();
+ delete process.env.X402_TREASURY_SECRET_BASE58;
+ const f = validateRingConfig().find((x) => x.code === 'treasury_secret_missing');
+ expect(f).toBeTruthy();
+ expect(f.severity).toBe('warn');
+ });
+
+ it('flags fee_payer_pubkey_missing (error severity)', () => {
+ healthyRingEnv();
+ delete process.env.X402_FEE_PAYER_SOLANA;
+ const f = validateRingConfig().find((x) => x.code === 'fee_payer_pubkey_missing');
+ expect(f).toBeTruthy();
+ expect(f.severity).toBe('error');
+ });
+
+ it('flags ring_price_exceeds_run_cap when the per-call price exceeds the per-run cap', () => {
+ healthyRingEnv();
+ process.env.X402_PRICE_RING_SETTLE = '5000000'; // $5.00
+ process.env.X402_VOLUME_PER_RUN_CAP_ATOMIC = '1000000'; // $1.00 cap
+ expect(codes(validateRingConfig())).toContain('ring_price_exceeds_run_cap');
+ });
+
+ it('does NOT flag price>cap when the cap is 0 (uncapped)', () => {
+ healthyRingEnv();
+ process.env.X402_PRICE_RING_SETTLE = '5000000';
+ process.env.X402_VOLUME_PER_RUN_CAP_ATOMIC = '0';
+ expect(codes(validateRingConfig())).not.toContain('ring_price_exceeds_run_cap');
+ });
+
+ it('flags ring_self_pay_off (warn) when self-pay is not enabled', () => {
+ healthyRingEnv();
+ delete process.env.X402_RING_SELF_PAY;
+ const f = validateRingConfig().find((x) => x.code === 'ring_self_pay_off');
+ expect(f).toBeTruthy();
+ expect(f.severity).toBe('warn');
+ });
+
+ it('catches all six misconfigurations at once', () => {
+ // Bare env: flag off, no URL (external), no treasury secret, no fee payer,
+ // price above cap, self-pay off.
+ delete process.env.X402_SELF_FACILITATOR_ENABLED;
+ delete process.env.X402_FACILITATOR_URL_SOLANA;
+ delete process.env.X402_FACILITATOR_URL;
+ delete process.env.X402_FEE_PAYER_SOLANA;
+ delete process.env.X402_TREASURY_SECRET_BASE58;
+ delete process.env.X402_RING_SELF_PAY;
+ process.env.X402_PRICE_RING_SETTLE = '5000000';
+ process.env.X402_VOLUME_PER_RUN_CAP_ATOMIC = '1000000';
+ const c = codes(validateRingConfig());
+ expect(c).toEqual(
+ expect.arrayContaining([
+ 'self_facilitator_disabled',
+ 'facilitator_url_external',
+ 'treasury_secret_missing',
+ 'fee_payer_pubkey_missing',
+ 'ring_price_exceeds_run_cap',
+ 'ring_self_pay_off',
+ ]),
+ );
+ });
+
+ it('every finding carries code, severity, message, and fix', () => {
+ delete process.env.X402_SELF_FACILITATOR_ENABLED;
+ for (const f of validateRingConfig()) {
+ expect(typeof f.code).toBe('string');
+ expect(['error', 'warn']).toContain(f.severity);
+ expect(f.message.length).toBeGreaterThan(0);
+ expect(f.fix.length).toBeGreaterThan(0);
+ }
+ });
+});
+
+describe('warnIfRingRoutesExternal', () => {
+ it('returns a structured warning and logs once when routing is external', () => {
+ delete process.env.X402_SELF_FACILITATOR_ENABLED;
+ delete process.env.X402_FACILITATOR_URL_SOLANA;
+ const spy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const w1 = warnIfRingRoutesExternal('test');
+ const w2 = warnIfRingRoutesExternal('test');
+ expect(w1).toBeTruthy();
+ expect(w1.code).toBe('ring_external_facilitator');
+ expect(w1.facilitator_url).toBe(PAYAI);
+ // Both calls return the warning, but it is logged only once per boot.
+ expect(w2).toBeTruthy();
+ expect(spy).toHaveBeenCalledTimes(1);
+ });
+
+ it('returns null (no warning) when routing is self-hosted', () => {
+ process.env.X402_SELF_FACILITATOR_ENABLED = 'true';
+ delete process.env.X402_FACILITATOR_URL_SOLANA;
+ const spy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ expect(warnIfRingRoutesExternal('test')).toBeNull();
+ expect(spy).not.toHaveBeenCalled();
+ });
+});
+
+describe('selfFacilitatorUrl', () => {
+ it('anchors on APP_ORIGIN', () => {
+ process.env.PUBLIC_APP_ORIGIN = 'https://preview.three.ws';
+ expect(selfFacilitatorUrl()).toBe('https://preview.three.ws/api/x402-facilitator');
+ });
+});
diff --git a/tests/api/x402-spec.test.js b/tests/api/x402-spec.test.js
index a87104d2d..f7aaeb94d 100644
--- a/tests/api/x402-spec.test.js
+++ b/tests/api/x402-spec.test.js
@@ -608,3 +608,81 @@ describe('buildExactRequirements', () => {
expect(reqs.every((r) => r.amount === '250000')).toBe(true);
});
});
+
+describe('facilitatorFor Solana resolution matrix', () => {
+ // The single seam every settle path routes through (task 02). Solana routing:
+ // 1. an explicit X402_FACILITATOR_URL_SOLANA (or legacy X402_FACILITATOR_URL)
+ // ALWAYS wins — existing non-ring deploys never silently re-route;
+ // 2. else X402_SELF_FACILITATOR_ENABLED=true defaults to this deploy's own
+ // /api/x402-facilitator;
+ // 3. else the external PayAI default.
+ const SOLANA = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';
+ const SELF_URL = 'https://three.ws/api/x402-facilitator';
+ const PAYAI = 'https://facilitator.payai.network';
+
+ beforeEach(() => {
+ delete process.env.X402_SELF_FACILITATOR_ENABLED;
+ delete process.env.X402_FACILITATOR_URL_SOLANA;
+ delete process.env.X402_FACILITATOR_URL;
+ // APP_ORIGIN default is https://three.ws, so the self URL resolves there.
+ delete process.env.PUBLIC_APP_ORIGIN;
+ });
+
+ it('flag OFF, no URL → external PayAI default (byte-identical to today)', async () => {
+ const { facilitatorFor } = await loadSpec();
+ const cfg = facilitatorFor(SOLANA);
+ expect(cfg.url).toBe(PAYAI);
+ expect(cfg.self).toBe(false);
+ });
+
+ it('flag ON, no URL → routes to our own /api/x402-facilitator', async () => {
+ process.env.X402_SELF_FACILITATOR_ENABLED = 'true';
+ const { facilitatorFor } = await loadSpec();
+ const cfg = facilitatorFor(SOLANA);
+ expect(cfg.url).toBe(SELF_URL);
+ expect(cfg.self).toBe(true);
+ });
+
+ it('explicit external URL wins even when the flag is ON (no surprise re-route)', async () => {
+ process.env.X402_SELF_FACILITATOR_ENABLED = 'true';
+ process.env.X402_FACILITATOR_URL_SOLANA = 'https://facilitator.example.test';
+ const { facilitatorFor } = await loadSpec();
+ const cfg = facilitatorFor(SOLANA);
+ expect(cfg.url).toBe('https://facilitator.example.test');
+ expect(cfg.self).toBe(false);
+ });
+
+ it('explicit self URL is recognized as self when the flag is ON', async () => {
+ process.env.X402_SELF_FACILITATOR_ENABLED = 'true';
+ process.env.X402_FACILITATOR_URL_SOLANA = 'https://preview.three.ws/api/x402-facilitator';
+ const { facilitatorFor } = await loadSpec();
+ const cfg = facilitatorFor(SOLANA);
+ expect(cfg.url).toBe('https://preview.three.ws/api/x402-facilitator');
+ expect(cfg.self).toBe(true);
+ });
+
+ it('explicit URL wins with the flag OFF too', async () => {
+ process.env.X402_FACILITATOR_URL_SOLANA = 'https://facilitator.example.test';
+ const { facilitatorFor } = await loadSpec();
+ const cfg = facilitatorFor(SOLANA);
+ expect(cfg.url).toBe('https://facilitator.example.test');
+ expect(cfg.self).toBe(false);
+ });
+
+ it('legacy X402_FACILITATOR_URL is honored as an explicit URL', async () => {
+ process.env.X402_SELF_FACILITATOR_ENABLED = 'true';
+ process.env.X402_FACILITATOR_URL = 'https://legacy.example.test';
+ const { facilitatorFor } = await loadSpec();
+ const cfg = facilitatorFor(SOLANA);
+ expect(cfg.url).toBe('https://legacy.example.test');
+ expect(cfg.self).toBe(false);
+ });
+
+ it('a non-"true" flag value does not route to self', async () => {
+ process.env.X402_SELF_FACILITATOR_ENABLED = '1';
+ const { facilitatorFor } = await loadSpec();
+ const cfg = facilitatorFor(SOLANA);
+ expect(cfg.url).toBe(PAYAI);
+ expect(cfg.self).toBe(false);
+ });
+});
diff --git a/tests/x402-ring-reconciliation.test.js b/tests/x402-ring-reconciliation.test.js
index ca68fea95..3cd64fb6b 100644
--- a/tests/x402-ring-reconciliation.test.js
+++ b/tests/x402-ring-reconciliation.test.js
@@ -182,34 +182,34 @@ describe('ring-reconciliation run() — settle integrity (check 1)', () => {
expect(v.values).toContain('ring_facilitator_settle');
});
- it('settle missing on-chain → CRITICAL x402_ring_settle_missing', async () => {
+ it('settle whose tx is absent on-chain (null status) → CRITICAL x402_ring_settle_missing', async () => {
const settle = [{ id: 2, ts: iso(60_000), payer: PAYER, pay_to: TREASURY, mint: MINT, amount_atomic: 1_000_000, tx_sig: 'sigGONE' }];
const sql = mockSql({ settle });
- const conn = mockConn({ statuses: { sigGONE: null } }); // present in map but null value → not found
- // force "found:false" by returning null status. mockConn maps absent to null too;
- // use explicit not-found:
+ // A null value from getSignatureStatuses = the RPC searched and did NOT find
+ // the signature → found:false → missing_onchain discrepancy.
+ const conn = mockConn();
conn.getSignatureStatuses = async (sigs) => ({ value: sigs.map(() => null) });
const ctx = baseCtx({ sql, conn });
const out = await run(ctx);
- // A null status = RPC could not resolve → unknown, NOT a discrepancy.
- expect(out.responseData.settles_unknown).toBe(1);
- expect(out.responseData.settles_missing).toBe(0);
+ expect(out.responseData.settles_missing).toBe(1);
+ expect(out.responseData.discrepancies).toBe(1);
+ const v = sql.calls.find((c) => /INSERT INTO payment_reconciliation/i.test(c.text) && c.values.includes('x402_ring_settle_missing'));
+ expect(v).toBeTruthy();
});
- it('settle with a definitively-absent tx → missing_onchain CRITICAL', async () => {
- const settle = [{ id: 3, ts: iso(60_000), payer: PAYER, pay_to: TREASURY, mint: MINT, amount_atomic: 1_000_000, tx_sig: 'sigABSENT' }];
+ it('RPC batch failure → unknown, NOT a discrepancy (self-heals next run)', async () => {
+ const settle = [{ id: 3, ts: iso(60_000), payer: PAYER, pay_to: TREASURY, mint: MINT, amount_atomic: 1_000_000, tx_sig: 'sigRPCDOWN' }];
const sql = mockSql({ settle });
- const conn = mockConn({ statuses: { sigABSENT: { found: false, err: null } } });
- // mockConn only emits found via presence; craft explicit found:false:
- conn.getSignatureStatuses = async () => ({ value: [null] }); // null → unknown
- // Instead drive the classifier through the module's own found:false path:
- conn.getSignatureStatuses = async () => ({ value: [{ /* present but empty */ }] });
- // A present-but-no-err status object means found:true, err:null → confirmed.
+ const conn = mockConn();
+ conn.getSignatureStatuses = async () => { throw new Error('rpc_unreachable'); };
const ctx = baseCtx({ sql, conn });
- await run(ctx);
- // This case is covered more precisely by the failed-onchain test below; keep as smoke.
- expect(true).toBe(true);
+ const out = await run(ctx);
+
+ expect(out.responseData.settles_unknown).toBe(1);
+ expect(out.responseData.settles_missing).toBe(0);
+ expect(out.responseData.discrepancies).toBe(0);
+ expect(ctx.alerts.length).toBe(0);
});
it('settle reverted on-chain → CRITICAL x402_ring_settle_failed + page', async () => {