Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
Add comprehensive tests for x402 ring functionality
nrpob658e0bcac70
diff --git a/.env.example b/.env.exampleindex b4d3f6abf..95dfe7070 100644--- a/.env.example+++ b/.env.example@@ -405,6 +405,9 @@ X402_FEE_PAYER_SECRET_BASE58=# Sponsor SOL floor (lamports). Below this the facilitator refuses to settle,# pausing the loop before it can drain your SOL. Default 0.02 SOL.X402_SPONSOR_SOL_FLOOR_LAMPORTS=20000000+# Ring payer USDC float floor (atomic, 6dp). Below this the wallet-balance monitor+# raises an ops alert to top up the payer's recirculating USDC. Default $5.+X402_RING_PAYER_USDC_FLOOR_ATOMIC=5000000# Self-pay mode (RECOMMENDED, lowest fee): the payer pays its own 1-signature fee# (5000 lamports) and no sponsor key is needed. Off = sponsor mode (2 signatures,# ~2× the base fee). When off, /api/x402-ring flags ring_self_pay_off.@@ -417,16 +420,44 @@ X402_SEED_SOLANA_SECRET_BASE58=X402_TREASURY_SECRET_BASE58=# Per-call ring settlement size (USDC atomics, 6dp). Bigger = fewer txs = less# SOL burned for the same gross volume. $1.00 default; raise to $10–$100 for-# near-zero SOL. MUST be ≤ X402_VOLUME_PER_RUN_CAP_ATOMIC or the volume loop-# skips ring-settle every tick (flagged ring_price_exceeds_run_cap).+# near-zero SOL. MUST be ≤ X402_VOLUME_PER_RUN_CAP_ATOMIC (5-min volume loop) AND+# ≤ X402_RING_TICK_CAP_ATOMIC (per-minute ring tick) or ring-settle is skipped+# every tick (flagged ring_price_exceeds_run_cap; payX402 also logs it loudly).+# The two cap defaults below are set to fit this price out of the box.X402_PRICE_RING_SETTLE=1000000-# Per-tick spend ceiling for the volume loop (USDC atomics). One tick can't-# exceed this on top of the daily cap. Raise it above X402_PRICE_RING_SETTLE to-# let ring-settle run. Default $0.05.-X402_VOLUME_PER_RUN_CAP_ATOMIC=50000+# Per-tick spend ceiling for the 5-min VOLUME LOOP (USDC atomics). One tick can't+# exceed this on top of the daily cap. Default $1.10 — RAISED from the old $0.05+# so it accommodates the $1.00 ring-settle it rotates (at $0.05 ring-settle was+# silently skipped every cycle). Keep it ≥ X402_PRICE_RING_SETTLE.+X402_VOLUME_PER_RUN_CAP_ATOMIC=1100000# Daily spend cap for the autonomous loop (USDC atomics) — your daily volume-# target. Leave unset for the loop's built-in default.+# target. Leave unset for the loop's built-in default. SEPARATE from the ring+# tick's own daily cap (X402_RING_DAILY_CAP_ATOMIC below) — the two never mix.X402_AUTONOMOUS_DAILY_CAP_ATOMIC=++# ── Per-minute ring tick (api/cron/x402-ring-tick.js) ──────────────────────────+# A dedicated * * * * * cron that produces steady, capped, fee-minimal paid+# traffic: cheap tips/services every minute plus a periodic ring-settle carrier.+# ON by default once the ring envelope above is valid (validateRingConfig clean);+# X402_RING_TICK_ENABLED=false or the global X402_AUTONOMOUS_ENABLED=false pause it.+X402_RING_TICK_ENABLED=true+# Paid calls attempted per minute (cheap tips dominate the count). Default 3.+X402_RING_TICK_CALLS=3+# Fire one ring-settle every Nth tick (the fee-optimal large-volume carrier;+# 0 disables it). Default 5 → a settle roughly every 5 minutes.+X402_RING_SETTLE_EVERY_N_TICKS=5+# Per-tick spend ceiling (USDC atomics). MUST fit a settle tick: ring-settle+# price + the cheap co-riders. Default $1.10 (fits $1.00 ring-settle + 2 tips).+X402_RING_TICK_CAP_ATOMIC=1100000+# Ring tick's OWN daily ceiling (USDC atomics), summed from x402_autonomous_log+# rows tagged pipeline='ring-tick'. Does NOT consume the autonomous loop's cap.+# Default $50. At 3 calls/min the tick reaches this bound mid-day then no-ops+# cleanly until UTC midnight — raise it for full-day coverage.+X402_RING_DAILY_CAP_ATOMIC=50000000+# Minimum treasury→payer sweep the rebalancer bothers with (USDC atomics).+# Default $0.10. Lower it so the (120s) rebalancer tops the payer up sooner as+# the per-minute tick cycles the float in small increments.+X402_RING_MIN_SWEEP_ATOMIC=100000# Only OUR endpoints get paid — disables the external x402 section of the loop.X402_EXTERNAL_ENABLED=false# No charity split leaves the ring (basis points; 0 = nothing leaves).diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ca59c74d5..b26a9845d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,7 +6,9 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr## 2026-07-03+- **Every ring settlement is now proven on-chain — reconciliation blind spot closed** — The closed-loop agent economy settles real USDC through the platform's own facilitator, and until now those settlements were trusted but never verified against the blockchain. A new reconciler runs every 30 minutes and holds the ring to the same standard the funding wallet already meets: every recorded settlement and every treasury→payer sweep from the last 72 hours is checked to exist and succeed on-chain, a sample of each is parsed to prove the exact dollar amount and recipient match the books, and the two internal ledgers are cross-checked so a settlement with no matching spend record — the tell-tale sign of value leaking through our own facilitator — is caught. It also runs a silence alarm: if the ring is switched on but goes quiet for 30 minutes, operators are paged, closing the gap where 'it was working, then it wasn't' used to pass unnoticed. Any missing, failed, or mismatched settlement raises an immediate alert; every finding lands on the finance-integrity board, tagged so ring issues stand apart from the rest. `[security, infra]`- **Full audit trail + breach monitoring on the economy's funding wallet** — The master wallet that fuels the platform's autonomous economy now keeps a tamper-evident accounting book of every move it makes. Each SOL transfer is recorded with the engine it funded, the amount, the on-chain signature, the running balance, and the US-dollar value at the moment of the transfer — cryptographically hash-chained so no past entry can be altered or deleted without detection. A monitor runs every 30 minutes and checks three things: that the book hasn't been tampered with, that every transfer we recorded really happened on-chain, and — most importantly — that no SOL ever left the wallet without a matching record, which is the tell-tale sign of a stolen key. Anything off raises an immediate operator alert and lands on the finance-integrity board. There's also a one-command accounting export (CSV or JSON, with running balance and dollar totals) for bookkeeping and review. `[security, infra, docs]`+- **Ring settlements stay in-house — routing made truthful, mis-config now caught** — The closed-loop agent economy is built so no third party ever touches a ring settlement — but the configuration used to say one thing while the code did another: the setup guide claimed the platform's own facilitator was 'always-on' while Solana payments still defaulted to an outside settlement service. That contradiction is gone. When the self-hosted facilitator is switched on, ring payments now settle through it by default, and an explicitly-set external facilitator is the only thing that overrides that — no other coin or user rail is affected. Just as important, a mis-configured deploy now says so loudly instead of silently sending volume elsewhere: the status and ring reports list every problem — facilitator disabled, settlement pointing at an outside service, a missing treasury or fee-payer key, a per-call price set above the per-run cap — so operators can confirm the whole envelope is correct before funding anything. A clean deploy shows an empty warnings list. `[fix, infra]`## 2026-07-02diff --git a/api/_lib/economy-sweepback.js b/api/_lib/economy-sweepback.jsnew file mode 100644index 000000000..820f5c927--- /dev/null+++ b/api/_lib/economy-sweepback.js@@ -0,0 +1,259 @@+// @ts-check+// api/_lib/economy-sweepback.js+//+// The reverse of economy-master.js. Where the master tops engines UP, sweepback+// brings balances BACK: it walks every configured engine signer in the+// SOLANA_SIGNERS registry and returns SOL — and, where safe, SPL token+// balances — to the ONE economy master wallet. Together the two close the loop:+// master funds engines → engines do the work → surplus consolidates to master.+//+// Destination-locked by construction: the only recipient this module can pay is+// ECONOMY_MASTER_ADDRESS (a module constant, never a parameter). A caller —+// buggy, compromised, or confused — cannot point a sweep anywhere else, so+// consolidation can never become a leak.+//+// Two modes:+// • 'excess' (default, safe to schedule) — skim only SOL above each signer's+// operating float (the same refillTo the treasury-topup cron refills to, so+// the two never oscillate: topup lifts a signer TO its float, sweepback only+// takes what is ABOVE it). Token balances are swept only from signers that+// do not operationally hold tokens (`holdsTokens` in the registry protects+// e.g. the buyback wallet's USDC revenue).+// • 'drain' (explicit, on-demand) — full consolidation: every token balance+// transferred, every emptied token account closed (rent refunds straight to+// the master), then all SOL minus a small fee headroom. Leaves the engines+// unfunded until the next treasury-topup, so it is for decommission or+// emergency recovery, never a schedule.++import { SOLANA_SIGNERS, loadSignerKeypair } from './solana-signers.js';+import { ECONOMY_MASTER_ADDRESS } from './economy-master.js';+import { sendSol, LAMPORTS_PER_SOL } from './avatar-wallet.js';+import { submitProtected } from './execution-engine.js';++// Same float the treasury-topup cron refills to — sweep only above it.+const DEFAULT_REFILL_MULTIPLE = 3;++function num(envName, dflt) {+ const v = Number(process.env[envName]);+ return Number.isFinite(v) && v >= 0 ? v : dflt;+}++/** Skip a SOL sweep smaller than this — moving dust costs more than it returns. */+export const MIN_SWEEP_SOL = num('ECONOMY_SWEEPBACK_MIN_SOL', 0.01);+/** Lamports a drained signer keeps to cover its own sweep transaction fees. */+export const DRAIN_HEADROOM_LAMPORTS = 20_000;+/** Most token accounts settled in one transaction (size + CU bound). */+const TOKEN_ACCOUNTS_PER_TX = 6;++/**+ * Compute the guarded per-signer SOL sweep amounts. Pure — no RPC — so the plan+ * is unit-testable and the cron can log it before touching a key.+ *+ * @param {Array<{name:string,pubkey:string,currentSol:number,floorSol:number}>} targets+ * @param {{mode?:'excess'|'drain', minSweepSol?:number}} [opts]+ * @returns {{ plan: Array<{name:string,pubkey:string,sol:number}>, skipped: Array<{name:string,reason:string}>, totalSol: number }}+ */+export function planSweepback(targets, opts = {}) {+ const mode = opts.mode === 'drain' ? 'drain' : 'excess';+ const minSweep = Number.isFinite(opts.minSweepSol) ? opts.minSweepSol : MIN_SWEEP_SOL;+ const plan = [];+ const skipped = [];+ let total = 0;+ for (const t of targets) {+ const available =+ mode === 'drain'+ ? round(t.currentSol - DRAIN_HEADROOM_LAMPORTS / LAMPORTS_PER_SOL)+ : round(t.currentSol - t.floorSol);+ if (available < minSweep) {+ skipped.push({ name: t.name, reason: mode === 'drain' ? 'below_dust_threshold' : 'at_or_below_float' });+ continue;+ }+ plan.push({ name: t.name, pubkey: t.pubkey, sol: available });+ total = round(total + available);+ }+ return { plan, skipped, totalSol: total };+}++/**+ * Sweep every non-zero SPL token balance a signer owns to the master's ATA,+ * closing each emptied source account so its rent refund lands on the master+ * too. Covers both the classic token program and Token-2022. Transactions are+ * chunked and submitted through the fee-optimized engine (no Jito tip).+ *+ * @param {object} args+ * @param {import('@solana/web3.js').Connection} args.connection+ * @param {import('@solana/web3.js').Keypair} args.owner+ * @param {'mainnet'|'devnet'} args.network+ * @returns {Promise<{ swept: Array<{mint:string,amount:string,decimals:number,signature:string}>, failed: Array<{mint:string,reason:string}> }>}+ */+async function sweepTokenBalances({ connection, owner, network }) {+ const { PublicKey } = await import('@solana/web3.js');+ const {+ TOKEN_PROGRAM_ID,+ TOKEN_2022_PROGRAM_ID,+ getAssociatedTokenAddressSync,+ createAssociatedTokenAccountIdempotentInstruction,+ createTransferCheckedInstruction,+ createCloseAccountInstruction,+ } = await import('@solana/spl-token');++ const master = new PublicKey(ECONOMY_MASTER_ADDRESS);+ const swept = [];+ const failed = [];++ for (const programId of [TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID]) {+ let accounts;+ try {+ ({ value: accounts } = await connection.getParsedTokenAccountsByOwner(owner.publicKey, { programId }));+ } catch (e) {+ failed.push({ mint: `program:${programId.toBase58()}`, reason: `rpc_error: ${e?.message}` });+ continue;+ }+ const holdings = accounts+ .map((a) => ({+ address: a.pubkey,+ mint: a.account.data.parsed?.info?.mint,+ amount: BigInt(a.account.data.parsed?.info?.tokenAmount?.amount || '0'),+ decimals: Number(a.account.data.parsed?.info?.tokenAmount?.decimals || 0),+ }))+ .filter((h) => h.mint && h.amount > 0n);++ for (let i = 0; i < holdings.length; i += TOKEN_ACCOUNTS_PER_TX) {+ const chunk = holdings.slice(i, i + TOKEN_ACCOUNTS_PER_TX);+ const instructions = [];+ for (const h of chunk) {+ const mint = new PublicKey(h.mint);+ const masterAta = getAssociatedTokenAddressSync(mint, master, false, programId);+ instructions.push(+ createAssociatedTokenAccountIdempotentInstruction(owner.publicKey, masterAta, master, mint, programId),+ createTransferCheckedInstruction(h.address, mint, masterAta, owner.publicKey, h.amount, h.decimals, [], programId),+ // Rent refund straight to the master — the destination lock applies+ // to every lamport this module moves, including reclaimed rent.+ createCloseAccountInstruction(h.address, master, owner.publicKey, [], programId),+ );+ }+ try {+ const { signature } = await submitProtected({ network, connection, payer: owner, instructions });+ for (const h of chunk) {+ swept.push({ mint: h.mint, amount: h.amount.toString(), decimals: h.decimals, signature });+ }+ } catch (e) {+ for (const h of chunk) failed.push({ mint: h.mint, reason: e?.message || 'send_failed' });+ }+ }+ }+ return { swept, failed };+}++/**+ * Execute the consolidation sweep across every configured registry signer.+ * Tokens first (their fees and rent refunds settle before the SOL read), then+ * SOL per the mode's plan. Duplicate pubkeys (fallback env vars resolving to+ * the same wallet) are swept once. Never throws for a business-rule stop.+ *+ * @param {object} args+ * @param {import('@solana/web3.js').Connection} args.connection+ * @param {'excess'|'drain'} [args.mode]+ * @param {boolean} [args.includeTokens]+ * @param {'mainnet'|'devnet'} [args.network]+ * @returns {Promise<object>}+ */+export async function sweepBack({ connection, mode = 'excess', includeTokens = true, network = 'mainnet' }) {+ const { PublicKey } = await import('@solana/web3.js');+ const master = ECONOMY_MASTER_ADDRESS;++ let masterSolBefore = null;+ try {+ masterSolBefore = round((await connection.getBalance(new PublicKey(master), 'confirmed')) / LAMPORTS_PER_SOL);+ } catch {+ /* balance context is best-effort; the sweep itself does not need it */+ }++ const seen = new Set();+ const sweptSol = [];+ const sweptTokens = [];+ const failed = [];+ const skipped = [];+ const readErrors = [];++ for (const spec of SOLANA_SIGNERS) {+ if (spec.isMaster || spec.network === 'devnet') continue;+ const { keypair, configured, decodeError } = await loadSignerKeypair(spec);+ if (!configured) continue;+ if (decodeError || !keypair) {+ readErrors.push({ name: spec.name, reason: 'secret_decode_failed' });+ continue;+ }+ const pubkey = keypair.publicKey.toBase58();+ if (pubkey === master) {+ skipped.push({ name: spec.name, reason: 'is_master' });+ continue;+ }+ if (seen.has(pubkey)) {+ skipped.push({ name: spec.name, reason: 'duplicate_pubkey' });+ continue;+ }+ seen.add(pubkey);++ // Tokens first. In excess mode a signer that operationally holds tokens+ // (buyback USDC, withdrawal SPL float, …) keeps them; a drain takes all.+ if (includeTokens && (mode === 'drain' || !spec.holdsTokens)) {+ const tokens = await sweepTokenBalances({ connection, owner: keypair, network });+ for (const t of tokens.swept) sweptTokens.push({ name: spec.name, pubkey, ...t });+ for (const f of tokens.failed) failed.push({ name: spec.name, pubkey, sol: null, reason: `token ${f.mint}: ${f.reason}` });+ }++ let currentSol;+ try {+ currentSol = round((await connection.getBalance(keypair.publicKey, 'confirmed')) / LAMPORTS_PER_SOL);+ } catch (e) {+ readErrors.push({ name: spec.name, pubkey, reason: `rpc_error: ${e?.message}` });+ continue;+ }+ const floorSol = spec.refillTo ?? spec.minSol * DEFAULT_REFILL_MULTIPLE;+ const { plan, skipped: planSkipped } = planSweepback(+ [{ name: spec.name, pubkey, currentSol, floorSol }],+ { mode },+ );+ skipped.push(...planSkipped);+ for (const step of plan) {+ try {+ const signature = await sendSol({+ connection,+ fromKeypair: keypair,+ to: master,+ lamports: Math.round(step.sol * LAMPORTS_PER_SOL),+ memo: `three.ws sweepback ${spec.name} → economy-master`,+ network,+ });+ sweptSol.push({ name: step.name, pubkey: step.pubkey, sol: step.sol, signature });+ } catch (e) {+ failed.push({ name: step.name, pubkey: step.pubkey, sol: step.sol, reason: e?.message || 'send_failed' });+ }+ }+ }++ let masterSolAfter = null;+ try {+ masterSolAfter = round((await connection.getBalance(new PublicKey(master), 'confirmed')) / LAMPORTS_PER_SOL);+ } catch {+ /* best-effort */+ }++ return {+ mode,+ master,+ masterSolBefore,+ masterSolAfter,+ sweptSol,+ sweptTokens,+ failed,+ skipped,+ readErrors,+ receivedSol: round(sweptSol.reduce((s, f) => s + f.sol, 0)),+ };+}++function round(n) {+ return Math.round(n * 1e9) / 1e9;+}diff --git a/api/_lib/solana-signers.js b/api/_lib/solana-signers.jsindex 36c5ca0ef..f31c82c8b 100644--- a/api/_lib/solana-signers.js+++ b/api/_lib/solana-signers.js@@ -118,6 +118,30 @@ export const SOLANA_SIGNERS = [purpose: 'co-signs SPL TransferChecked for agent-to-agent mandate settlements',network: 'mainnet',},+ {+ name: 'x402-ring-sponsor',+ env: 'X402_FEE_PAYER_SECRET_BASE58',+ // The self-hosted facilitator's fee payer: co-signs + burns SOL on every+ // ring settle. If it drops below X402_SPONSOR_SOL_FLOOR_LAMPORTS (0.02 SOL)+ // the facilitator refuses to settle and the ring silently halts — so keep+ // the topup floor a hair above that hard floor and let the economy master's+ // treasury-topup cron refill it before the loop stops.+ minSol: 0.03,+ purpose: 'x402 ring sponsor (fee payer): co-signs + pays SOL on every self-hosted-facilitator settle; below-floor pauses the whole ring',+ network: 'mainnet',+ },+ {+ name: 'x402-ring-payer',+ env: 'X402_SEED_SOLANA_SECRET_BASE58',+ fallbackEnv: 'X402_AGENT_SOLANA_SECRET_BASE58',+ // In self-pay mode (X402_RING_SELF_PAY) the payer signs and pays its own+ // 1-signature fee, so it needs its own SOL headroom just like the sponsor.+ // Its USDC float is watched separately by the wallet-balance monitor; the+ // economy master only ever tops up SOL, never USDC.+ minSol: 0.03,+ purpose: 'x402 ring payer (self-pay mode): signs + pays its own 1-sig fee on each ring settle; USDC float watched by the balance monitor',+ network: 'mainnet',+ },{name: 'collection-authority',env: 'SOLANA_AGENT_COLLECTION_AUTHORITY_KEY',diff --git a/api/_lib/x402/agents/agora-citizen.js b/api/_lib/x402/agents/agora-citizen.jsnew file mode 100644index 000000000..b682602e2--- /dev/null+++ b/api/_lib/x402/agents/agora-citizen.js@@ -0,0 +1,74 @@+// @ts-check+// api/_lib/x402/agents/agora-citizen.js+//+// Persona: the Agora Citizen — a working agent who spends its earnings socially.+//+// The agora citizens (workers/agora-citizens/) are real on-chain AgenC agents that+// post, claim, work, and earn. In character, once a citizen finishes a job it+// unwinds at the club: it pays the door cover and tips a dancer. That is its ring-+// buyer behaviour here — a deterministic rotation over the social/tip tier+// (club-cover + dance-tip). It's the "an agora citizen tips dancers and pays club+// cover after completing work" behaviour from the Task 09 brief.+//+// Revenue path (loop closure): both the cover charge and the tip pay the ring+// treasury (X402_PAY_TO_SOLANA) — the club's takings are platform-controlled. The+// dancer is a stage slot on the 3D club stage, not a separate external wallet, so+// the tip never leaves the controlled set: it settles to the treasury, is recorded+// in club_tips (business layer) + x402_ring_ledger (settlement layer), and recycles+// back to this citizen's float via ring-rebalance's float-top-up step.+//+// All USDC. Personas are labeled internal — never presented as organic club-goers.++import { priceFor } from '../../x402-prices.js';+import { buildUrl, pickDeterministic, mulberry32 } from './persona-kit.js';++// Free-floor dance styles the club stage supports (from api/x402/dance-tip.js STYLES).+const DANCE_STYLES = ['rumba', 'silly', 'thriller', 'capoeira', 'hiphop', 'spin', 'climb', 'combo'];++export const persona = {+ id: 'agora-citizen',+ label: 'Agora Citizen',+ kind: 'tip',+ agentName: 'Ring Agora Citizen',+ describe: 'A working AgenC citizen who pays club cover and tips dancers after completing a job.',+ // A citizen tips small and often. Daily ceiling bounds the loop; per-tx covers+ // the $0.01 cover charge with headroom over the $0.001 tips.+ spendLimits: { daily_usd: 3, per_tx_usd: 0.1 },++ /**+ * Deterministic purchase plan for one tick: pay the door, tip a dancer. The+ * dancer slot (1-4) and style are chosen deterministically from the seed so the+ * plan is reproducible.+ * @param {{ origin: string, seed: number, maxBuys?: number }} ctx+ */+ plan({ origin, seed, maxBuys = 1 }) {+ const rng = mulberry32(seed ^ 0x9e3779b9);+ const dancer = String(1 + Math.floor(rng() * 4));+ const style = DANCE_STYLES[Math.floor(rng() * DANCE_STYLES.length)];++ const actions = [+ {+ slug: 'club-cover', kind: 'commerce', path: '/api/x402/club-cover', method: 'GET',+ priceAtomic: Number(priceFor('club-cover', '10000')), memo: 'agora-citizen:door',+ },+ {+ slug: 'dance-tip', kind: 'tip', path: '/api/x402/dance-tip', method: 'GET',+ query: { dancer, dance: style },+ priceAtomic: Number(priceFor('dance-tip', '1000')), memo: `agora-citizen:tip:${style}`,+ },+ ];++ // A citizen entering the club pays cover first, then tips — deterministic+ // order. When maxBuys clamps to 1, pick one so a single-buy tick still varies.+ const chosen = maxBuys >= actions.length ? actions : pickDeterministic(actions, seed, maxBuys);+ return chosen.map((a) => ({+ slug: a.slug,+ url: buildUrl(origin, a.path, a.query),+ method: a.method,+ body: null,+ priceAtomic: a.priceAtomic,+ kind: a.kind,+ memo: a.memo,+ }));+ },+};diff --git a/api/_lib/x402/agents/curator.js b/api/_lib/x402/agents/curator.jsnew file mode 100644index 000000000..add26d7f2--- /dev/null+++ b/api/_lib/x402/agents/curator.js@@ -0,0 +1,74 @@+// @ts-check+// api/_lib/x402/agents/curator.js+//+// Persona: the Curator — a marketplace/promotion agent.+//+// In character, the Curator keeps the marketplace healthy: it shops skill listings+// (to know what's for sale and at what price) and buys billboard slots to promote+// the platform coin. That is its ring-buyer behaviour — a deterministic rotation+// over the commerce tier (skill-marketplace + billboard). It's the "a curator agent+// buys skill-marketplace listings + billboards" behaviour from the Task 09 brief.+//+// Revenue path (loop closure): both purchases pay the ring treasury+// (X402_PAY_TO_SOLANA). The skill-marketplace call buys the pricing index (a+// platform-owned read); the billboard slot promotes $THREE (the platform's own+// coin — the ONLY coin this platform promotes, per CLAUDE.md). Proceeds land in the+// treasury, show in x402_ring_ledger, and recycle back to the Curator's float via+// ring-rebalance's float-top-up step. Nothing leaves the controlled-wallet set.+//+// The billboard's `coin` is the $THREE mint — the promoted coin — never a+// third-party project. All payment in USDC.++import { priceFor } from '../../x402-prices.js';+import { buildUrl, pickDeterministic } from './persona-kit.js';++// $THREE — the only coin this platform promotes (CLAUDE.md). The Curator's+// billboard advertises it; no other mint is ever hardcoded here.+const THREE_CA = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';++const CAPTIONS = [+ 'gm from the ring',+ 'the agent economy runs on $THREE',+ 'built on three.ws',+ 'live agent-to-agent settlement',+];++export const persona = {+ id: 'curator',+ label: 'Marketplace Curator',+ kind: 'commerce',+ agentName: 'Ring Marketplace Curator',+ describe: 'Shops skill-marketplace listings and buys billboard slots promoting $THREE.',+ // The billboard tier ($0.05) is the priciest routine purchase in the roster, so+ // the per-tx ceiling is set to clear it; the daily ceiling bounds the loop.+ spendLimits: { daily_usd: 8, per_tx_usd: 0.5 },++ /**+ * Deterministic purchase plan for one tick.+ * @param {{ origin: string, seed: number, maxBuys?: number }} ctx+ */+ plan({ origin, seed, maxBuys = 1 }) {+ const caption = CAPTIONS[seed % CAPTIONS.length];+ const actions = [+ {+ slug: 'skill-marketplace', kind: 'commerce', path: '/api/x402/skill-marketplace', method: 'GET',+ priceAtomic: Number(priceFor('skill-marketplace', '1000')), memo: 'curator:shop-listings',+ },+ {+ slug: 'billboard', kind: 'commerce', path: '/api/x402/billboard', method: 'GET',+ query: { coin: THREE_CA, image: 'https://three.ws/og-image.png', caption },+ priceAtomic: Number(priceFor('billboard', '50000')), memo: 'curator:promote-three',+ },+ ];+ const chosen = maxBuys >= actions.length ? actions : pickDeterministic(actions, seed, maxBuys);+ return chosen.map((a) => ({+ slug: a.slug,+ url: buildUrl(origin, a.path, a.query),+ method: a.method,+ body: null,+ priceAtomic: a.priceAtomic,+ kind: a.kind,+ memo: a.memo,+ }));+ },+};diff --git a/api/_lib/x402/agents/endpoint-shopper.js b/api/_lib/x402/agents/endpoint-shopper.jsnew file mode 100644index 000000000..061e1fb6a--- /dev/null+++ b/api/_lib/x402/agents/endpoint-shopper.js@@ -0,0 +1,69 @@+// @ts-check+// api/_lib/x402/agents/endpoint-shopper.js+//+// Persona: the Endpoint Shopper — a market-intelligence agent.+//+// In character, this agent's whole job is to shop the ring for signal: it buys+// paid intel endpoints (token/market/$THREE feeds) and continuously health-probes+// the paid surface it depends on. So its ring-buyer behaviour is exactly that —+// a deterministic rotation over the intel + health tier of the catalog. It mirrors+// the real /api/agents/endpoint-shopper-run agent (itself a paid endpoint that+// shops endpoints); here it is enlisted as a genuine x402 BUYER inside the ring.+//+// Revenue path (loop closure): every purchase pays the ring treasury+// (X402_PAY_TO_SOLANA) — the seller side is the platform itself. The USDC lands in+// the treasury, is visible in x402_ring_ledger via the settlement, and is+// recycled back to this agent's float by ring-rebalance's float-top-up step. The+// business layer (intel/health responses) is consumed for real; no money leaves+// the controlled-wallet set.+//+// All USDC. Never $THREE or any third-party coin as the payment asset. Labeled+// internal in every log row.++import { priceFor } from '../../x402-prices.js';+import { buildUrl } from './persona-kit.js';+import { pickDeterministic } from './persona-kit.js';++const THREE_CA = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';++// The intel + health endpoints this persona shops. Method/body/query match each+// handler's real contract (verified against the route files). priceSlug feeds+// priceFor() so the spend-limit pre-check uses the deployed price.+const SHOP = [+ { slug: 'three-intel', priceSlug: 'three-intel', priceDefault: '10000', kind: 'intel', path: '/api/x402/three-intel', method: 'GET' },+ { slug: 'crypto-intel', priceSlug: 'crypto-intel', priceDefault: '10000', kind: 'intel', path: '/api/x402/crypto-intel', method: 'POST', body: { topic: 'solana' } },+ { slug: 'token-intel', priceSlug: 'token-intel', priceDefault: '10000', kind: 'intel', path: '/api/x402/token-intel', method: 'GET', query: { mint: THREE_CA, network: 'mainnet' } },+ { slug: 'feed-health', priceSlug: 'feed-health', priceDefault: '1000', kind: 'health', path: '/api/x402/feed-health', method: 'POST', body: {} },+ { slug: 'api-key-health', priceSlug: 'api-key-health', priceDefault: '1000', kind: 'health', path: '/api/x402/api-key-health', method: 'POST', body: {} },+ { slug: 'solana-register-health', priceSlug: 'solana-register-health', priceDefault: '1000', kind: 'health', path: '/api/x402/solana-register-health', method: 'GET' },+ { slug: 'auth-health', priceSlug: 'auth-health', priceDefault: '1000', kind: 'health', path: '/api/x402/auth-health', method: 'POST', body: {} },+];++export const persona = {+ id: 'endpoint-shopper',+ label: 'Endpoint Shopper',+ kind: 'intel',+ agentName: 'Ring Endpoint Shopper',+ describe: 'Shops the ring for market/$THREE intel and health-probes the paid surface it relies on.',+ // Conservative caps — an intel shopper makes many tiny buys; the daily ceiling+ // bounds a runaway loop, the per-tx ceiling covers the $0.01 intel tier with headroom.+ spendLimits: { daily_usd: 5, per_tx_usd: 0.25 },++ /**+ * Deterministic purchase plan for one tick.+ * @param {{ origin: string, seed: number, maxBuys?: number }} ctx+ * @returns {Array<{ slug, url, method, body, priceAtomic, kind, memo }>}+ */+ plan({ origin, seed, maxBuys = 1 }) {+ const picks = pickDeterministic(SHOP, seed, maxBuys);+ return picks.map((p) => ({+ slug: p.slug,+ url: buildUrl(origin, p.path, p.query),+ method: p.method,+ body: p.body ?? null,+ priceAtomic: Number(priceFor(p.priceSlug, p.priceDefault)),+ kind: p.kind,+ memo: `endpoint-shopper:${p.kind}`,+ }));+ },+};diff --git a/api/_lib/x402/agents/index.js b/api/_lib/x402/agents/index.jsnew file mode 100644index 000000000..d7fadb1a9--- /dev/null+++ b/api/_lib/x402/agents/index.js@@ -0,0 +1,387 @@+// @ts-check+// api/_lib/x402/agents/index.js+//+// The agent-buyer roster + the ring-tick driver (Task 09).+//+// This is what turns the closed-loop ring from "a cron paying itself" into an+// agent-to-agent economy: a handful of REAL platform agents (agent_identities rows+// with custodial Solana wallets) each shop the ring every tick, in character, with+// their spend limits enforced and every purchase attributed to them.+//+// Pieces:+// • PERSONAS — the persona modules (endpoint-shopper, agora-citizen,+// curator), each a description of what one agent buys.+// • ensureRosterAgents() — idempotently resolve/create the backing agent+// identities, provision their custodial wallets+// (ensureAgentWallet), stamp their spend limits, and+// register them in x402_ring_wallets(role='agent') so+// they land inside ringAllowedAddresses() (Task 06) and+// the ring verify script (Task 03) automatically.+// • selectPersonasForTick()— deterministic persona selection from a tick seed.+// • run(ctx) — the driver the autonomous loop invokes as an+// alternative buyer set: resolve roster → plan →+// guarded settle (persona-kit.executePurchase) → record+// each purchase to x402_autonomous_log WITH agent_id →+// at low cadence, land one real on-chain program call.+//+// Wiring: registered in autonomous-registry.js as the `agent-buyers` run()-entry;+// the per-tick loop hands it { origin, buyer, conn, blockhash, mintInfo, redis,+// sql, runId, remainingCap }. Standalone callers (scripts/x402-ring-agents-run.mjs)+// pass the same shape.+//+// Money invariant: buyers are platform-controlled custodial wallets; every payTo is+// the ring treasury; the on-chain fee payer is a roster (ring) wallet. USDC only.+// Personas are labeled internal in every log row — never organic users.++import { randomUUID } from 'node:crypto';++import { sql as defaultSql } from '../../db.js';+import { env } from '../../env.js';+import { logger } from '../../usage.js';+import { ensureAgentWallet } from '../../agent-wallet.js';+import { ringAllowedAddresses } from '../ring-allowlist.js';+import { bootstrapSolanaContext, USDC_MINT } from '../pay.js';+import {+ executePurchase,+ recoverAgentBuyer,+ seedFromString,+ usdcConfigured,+ treasuryPubkey,+} from './persona-kit.js';+import { maybeRecordOnchainReceipt } from './onchain.js';++import { persona as endpointShopper } from './endpoint-shopper.js';+import { persona as agoraCitizen } from './agora-citizen.js';+import { persona as curator } from './curator.js';++const log = logger('x402-ring-agents');++/** The roster's personas, in stable order. Add a persona module + one import here. */+export const PERSONAS = [endpointShopper, agoraCitizen, curator];++// How many purchases each active persona makes per tick (bounds per-tick spend on+// top of the loop's caps). Default 1 — one buy per agent per minute.+const MAX_BUYS_PER_PERSONA = Math.max(1, Number(process.env.X402_RING_AGENT_MAX_BUYS_PER_TICK || 1));++// How many personas act per tick. Default = all of them (so every roster agent+// buys each minute → ≥3 distinct agent_ids per tick). Set < PERSONAS.length to+// rotate a deterministic window instead.+function personasPerTick() {+ const n = Number(process.env.X402_RING_AGENT_PERSONAS_PER_TICK || PERSONAS.length);+ return Math.max(1, Math.min(PERSONAS.length, n));+}++/**+ * Deterministically select which personas act on a given tick. When the window+ * equals the roster size (default) all personas act, in order. Otherwise it+ * rotates a contiguous window by seed so every persona gets equal airtime.+ * Pure — no I/O — so selection is reproducible and unit-testable.+ * @param {number} seed+ * @param {{ personas?: Array, window?: number }} [opts]+ * @returns {Array}+ */+export function selectPersonasForTick(seed, { personas = PERSONAS, window = personasPerTick() } = {}) {+ const w = Math.max(1, Math.min(personas.length, window));+ if (w >= personas.length) return personas.slice();+ const start = (seed >>> 0) % personas.length;+ const out = [];+ for (let i = 0; i < w; i++) out.push(personas[(start + i) % personas.length]);+ return out;+}++// ── Roster provisioning ────────────────────────────────────────────────────────++/** Resolve the owner user_id for roster agents: env override, else reuse an+ * existing agent's owner (roster agents are platform-operated circulation agents,+ * not a specific human's). Returns null when neither is available. */+async function resolveOwnerUserId(sql) {+ const envId = process.env.X402_RING_AGENT_OWNER_USER_ID;+ if (envId) return envId;+ try {+ const [row] = await sql`+ SELECT user_id FROM agent_identities+ WHERE user_id IS NOT NULL AND deleted_at IS NULL+ ORDER BY created_at ASC LIMIT 1+ `;+ return row?.user_id || null;+ } catch {+ return null;+ }+}++/** Merge the persona's spend limits into an agent meta blob (idempotent). */+function withPersonaMeta(meta, persona) {+ const next = { ...(meta || {}) };+ next.ring_persona = persona.id;+ next.circulation = 'true'; // platform-operated, not a human's agent+ next.spend_limits = { ...(next.spend_limits || {}), ...persona.spendLimits };+ return next;+}++/**+ * Idempotently resolve (and, when possible, create) the backing agent identity for+ * one persona: find by meta.ring_persona, else create; provision the custodial+ * Solana wallet; stamp spend limits + persona meta; register in x402_ring_wallets.+ * Returns the resolved roster member, or null when it can't be provisioned in this+ * environment (no DB, no owner to create under) — the driver simply skips it.+ *+ * @returns {Promise<{ persona: object, id: string, name: string, address: string,+ * user_id: string|null, meta: object }|null>}+ */+export async function ensureRosterAgent(sql, persona) {+ // 1 — find an existing agent tagged with this persona.+ let row;+ try {+ [row] = await sql`+ SELECT id, user_id, name, meta FROM agent_identities+ WHERE meta->>'ring_persona' = ${persona.id} AND deleted_at IS NULL+ ORDER BY created_at ASC LIMIT 1+ `;+ } catch (err) {+ log.warn('roster_lookup_failed', { persona: persona.id, message: err?.message });+ return null;+ }++ // 2 — create it if absent (needs an owner to attach to).+ if (!row) {+ const ownerId = await resolveOwnerUserId(sql);+ if (!ownerId) {+ log.info('roster_no_owner', { persona: persona.id, note: 'set X402_RING_AGENT_OWNER_USER_ID to provision' });+ return null;+ }+ const meta = withPersonaMeta({ internal: true }, persona);+ try {+ [row] = await sql`+ INSERT INTO agent_identities (user_id, name, description, skills, meta)+ VALUES (${ownerId}, ${persona.agentName}, ${persona.describe},+ ${['x402-buy', 'ring-participant']}, ${JSON.stringify(meta)}::jsonb)+ RETURNING id, user_id, name, meta+ `;+ log.info('roster_agent_created', { persona: persona.id, agent_id: row.id });+ } catch (err) {+ log.warn('roster_create_failed', { persona: persona.id, message: err?.message });+ return null;+ }+ }++ // 3 — provision the custodial Solana wallet (idempotent) + reload meta.+ let address = row.meta?.solana_address || null;+ try {+ const w = await ensureAgentWallet(row.id, row.user_id ?? null, { reason: 'ring_roster_provision' });+ address = w.address;+ } catch (err) {+ log.warn('roster_wallet_failed', { persona: persona.id, message: err?.message });+ }++ // 4 — ensure spend limits + persona meta are stamped (idempotent update). Reload+ // the row so meta carries the freshly-provisioned encrypted_solana_secret.+ let meta = row.meta || {};+ try {+ const [fresh] = await sql`SELECT meta FROM agent_identities WHERE id = ${row.id} LIMIT 1`;+ meta = withPersonaMeta(fresh?.meta || meta, persona);+ await sql`UPDATE agent_identities SET meta = ${JSON.stringify(meta)}::jsonb WHERE id = ${row.id}`;+ } catch (err) {+ log.warn('roster_meta_update_failed', { persona: persona.id, message: err?.message });+ }++ // 5 — register in x402_ring_wallets(role='agent') so the wallet is inside+ // ringAllowedAddresses() and the ring verify script. Best-effort.+ if (address) {+ try {+ await sql`+ INSERT INTO x402_ring_wallets (pubkey, label, role, enabled, note)+ VALUES (${address}, ${`agent:${persona.id}`}, 'agent', true, ${`roster persona ${persona.id} (agent ${row.id})`})+ ON CONFLICT (pubkey) DO UPDATE SET label = EXCLUDED.label, role = 'agent', enabled = true, note = EXCLUDED.note+ `;+ } catch (err) {+ log.warn('roster_registry_upsert_failed', { persona: persona.id, message: err?.message });+ }+ }++ if (!address) return null;+ return { persona, id: row.id, name: row.name, address, user_id: row.user_id ?? null, meta };+}++/** Resolve the whole roster (idempotent). Members that can't be provisioned in+ * this environment are dropped, never faked. */+export async function ensureRosterAgents(sql = defaultSql) {+ const out = [];+ for (const persona of PERSONAS) {+ const member = await ensureRosterAgent(sql, persona);+ if (member) out.push(member);+ }+ return out;+}++// ── Per-call attribution log ───────────────────────────────────────────────────++let _schemaReady = false;+async function ensureSchema(sql) {+ if (_schemaReady) return;+ // agent_id attribution column (mirrors the migration; idempotent so a warm+ // instance is safe before the migration file is applied).+ await sql`ALTER TABLE x402_autonomous_log ADD COLUMN IF NOT EXISTS agent_id uuid`;+ await sql`CREATE INDEX IF NOT EXISTS x402_autonomous_log_agent_ts ON x402_autonomous_log (agent_id, ts DESC)`;+ _schemaReady = true;+}++/** One attributed row per persona purchase. agent_id is what makes the ring feed+ * read as an agent economy, not a cron. */+async function recordAgentPurchase(sql, runId, outcome, { endpointUrl }) {+ try {+ await sql`+ INSERT INTO x402_autonomous_log+ (run_id, agent_id, endpoint_type, service_name, endpoint_url,+ network, amount_atomic, asset, tx_signature,+ signal_data, value_extracted, duration_ms, success, error_msg, pipeline)+ VALUES+ (${runId}, ${outcome.agentId}, 'self',+ ${`ring-agent:${outcome.persona}:${outcome.slug}`}, ${endpointUrl},+ 'solana:mainnet', ${outcome.amountAtomic || 0},+ ${USDC_MINT || 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'},+ ${outcome.txSig || null},+ ${JSON.stringify({ persona: outcome.persona, kind: outcome.kind, internal: true, status: outcome.status })},+ ${JSON.stringify({ payTo: outcome.payTo, liveness: outcome.responseLiveness, reason: outcome.reason })},+ ${outcome.durationMs || 0}, ${outcome.status === 'paid' || outcome.status === 'free'},+ ${outcome.reason || null}, 'ring-agents')+ `;+ } catch (err) {+ log.warn('agent_purchase_log_failed', { persona: outcome.persona, slug: outcome.slug, message: err?.message });+ }+}++// ── Driver ─────────────────────────────────────────────────────────────────────++/** Read + advance the monotonic tick counter (Redis), or derive a stable seed from+ * the runId when Redis is absent. Seed drives deterministic persona/endpoint choice. */+async function nextTickSeed(redis, runId) {+ if (redis) {+ try {+ const n = Number(await redis.incr('x402:ring:agent:tick'));+ if (Number.isFinite(n)) return n >>> 0;+ } catch { /* fall through to runId-derived seed */ }+ }+ return seedFromString(runId || randomUUID());+}++/**+ * Ring agent-buyer tick. Conforms to the run()-style registry contract.+ * Returns the aggregate outcome the loop records as ONE summary row; the granular+ * per-purchase rows (with agent_id) are self-recorded here, so `recorded:true`.+ *+ * @param {object} ctx { origin, buyer, conn, blockhash, mintInfo, redis, sql, runId, remainingCap }+ */+export async function run(ctx = {}) {+ const sql = ctx.sql || defaultSql;+ const runId = ctx.runId || randomUUID();+ const origin = ctx.origin || env.APP_ORIGIN || 'https://three.ws';+ const redis = ctx.redis || null;++ if (!usdcConfigured()) {+ return { success: true, skipped: true, recorded: true, amountAtomic: 0, note: 'usdc_mint_unset' };+ }+ const treasury = treasuryPubkey();+ if (!treasury) {+ return { success: true, skipped: true, recorded: true, amountAtomic: 0, note: 'treasury_unset' };+ }++ try {+ await ensureSchema(sql);+ } catch (err) {+ return { success: false, skipped: true, recorded: true, amountAtomic: 0, errorMsg: `schema_failed:${err?.message}` };+ }++ // Resolve the roster (idempotent provision). Empty → nothing to drive.+ const roster = await ensureRosterAgents(sql);+ if (roster.length === 0) {+ return { success: true, skipped: true, recorded: true, amountAtomic: 0, note: 'no_roster_agents' };+ }++ // Shared Solana context: reuse the loop's, else bootstrap standalone.+ let { conn, blockhash, mintInfo } = ctx;+ if (!conn || !blockhash || !mintInfo) {+ try {+ ({ conn, blockhash, mintInfo } = await bootstrapSolanaContext({ buyer: ctx.buyer }));+ } catch (err) {+ return { success: false, skipped: true, recorded: true, amountAtomic: 0, errorMsg: `solana_ctx_failed:${err?.message}`, note: 'wallet_or_rpc_unconfigured' };+ }+ }++ // The controlled-wallet set — resolved once per tick and shared across every+ // purchase's payTo check. Roster wallets are already in it (registered above).+ const allowed = await ringAllowedAddresses({ sql });++ const seed = await nextTickSeed(redis, runId);+ const active = selectPersonasForTick(seed);++ let remaining = ctx.remainingCap ?? Number.POSITIVE_INFINITY;+ let spentAtomic = 0;+ let paid = 0;+ let refused = 0;+ let errors = 0;+ let lastTxSig = null;+ const purchases = [];++ for (const persona of active) {+ const member = roster.find((m) => m.persona.id === persona.id);+ if (!member) continue;++ const keypair = await recoverAgentBuyer(member);+ if (!keypair) {+ log.info('roster_key_unavailable', { persona: persona.id });+ continue;+ }+ const agent = { id: member.id, name: member.name, address: member.address, keypair, meta: member.meta };++ // Persona-specific, seed-deterministic plan for this tick.+ const plan = persona.plan({ origin, seed, maxBuys: MAX_BUYS_PER_PERSONA });+ for (const purchase of plan) {+ if (remaining <= 0) break;+ const outcome = await executePurchase({+ agent, purchase, persona: persona.id, allowed,+ solana: { conn, blockhash, mintInfo },+ remainingCap: remaining,+ });+ await recordAgentPurchase(sql, runId, outcome, { endpointUrl: purchase.url });++ if (outcome.status === 'paid') {+ paid += 1;+ spentAtomic += outcome.amountAtomic;+ remaining -= outcome.amountAtomic;+ if (outcome.txSig) lastTxSig = outcome.txSig;+ } else if (outcome.status === 'refused') {+ refused += 1;+ } else if (outcome.status === 'error') {+ errors += 1;+ }+ purchases.push({ persona: persona.id, slug: purchase.slug, status: outcome.status, agent_id: agent.id, tx: outcome.txSig });+ }+ }++ // Low-cadence on-chain program call (agent-invocation receipt). Bounded by+ // X402_RING_ONCHAIN_EVERY_N_TICKS; fee payer is a roster (ring) wallet; skips+ // cleanly when the program/env is absent or unfunded.+ let onchain = null;+ try {+ onchain = await maybeRecordOnchainReceipt({ sql, roster, seed, runId, recoverAgentBuyer });+ } catch (err) {+ onchain = { attempted: true, landed: false, reason: `onchain_error:${String(err?.message || err).slice(0, 120)}` };+ }++ log.info('ring_agents_tick_complete', {+ run_id: runId, seed, active: active.length, roster: roster.length,+ paid, refused, errors, spent_usdc: (spentAtomic / 1e6).toFixed(4),+ onchain: onchain?.landed ? onchain.signature : (onchain?.reason || 'skipped'),+ });++ return {+ success: paid > 0 || purchases.length > 0,+ amountAtomic: spentAtomic,+ txSig: lastTxSig,+ recorded: true, // granular per-purchase rows already written (with agent_id)+ skipped: purchases.length === 0,+ signalData: { seed, active: active.map((p) => p.id), paid, refused, errors, onchain },+ responseData: { purchases, onchain },+ note: `ring_agents paid=${paid} refused=${refused} errors=${errors}` + (onchain?.landed ? ` onchain=${onchain.signature}` : ''),+ };+}diff --git a/api/_lib/x402/agents/onchain.js b/api/_lib/x402/agents/onchain.jsnew file mode 100644index 000000000..32964b63a--- /dev/null+++ b/api/_lib/x402/agents/onchain.js@@ -0,0 +1,186 @@+// @ts-check+// api/_lib/x402/agents/onchain.js+//+// One real on-chain program interaction, in the ring rotation, at low cadence+// (Task 09 step 4 — "on-chain deployments being utilized").+//+// What it does: at most once every X402_RING_ONCHAIN_EVERY_N_TICKS ticks (default+// 60 ≈ hourly at a 1/min cadence), one roster agent records a genuine agent-to-+// agent invocation receipt on the `agent_invocation` Anchor program+// (api/_lib/agent-invocation-onchain.js → recordInvocationReceipt). The invoking+// agent's own custodial keypair signs and pays the (tiny) network fee — so the+// FEE PAYER IS A RING WALLET, exactly as the brief requires. The program moves no+// funds and grants no capability; it emits a SkillInvoked event, giving the ring a+// permanent, explorer-linkable proof that two platform agents transacted.+//+// Why this program (not the skill-license mint): invoke_skill's accounts are+// UncheckedAccount PDAs constrained only by seeds — no prior registration, no rent-+// bearing init, and the single required signer is the fee payer. That lets a roster+// wallet BE the fee payer with one signature; the license mint is minter-signed and+// rent-bearing, which would put the fee on the minter, not a ring wallet.+//+// Safety rails (all fail-CLOSED / skip-clean, never throw into the tick):+// • cadence gate — only fires on the Nth tick.+// • env gate — needs AGENT_INVOCATION_PROGRAM_ID; runs on AGENT_INVOCATION_NETWORK+// (default 'devnet' here — no new mainnet program calls, per the constraints).+// • deploy gate — verifies the program is executable on that cluster first; if+// not deployed, records a clean skip.+// • rent bound — invoke_skill allocates no account, so there is no rent to bound+// beyond the base fee (~5000 lamports), which the roster wallet pays.+//+// Every attempt (landed or skipped) is logged to x402_autonomous_log (pipeline+// 'ring-onchain', agent_id = invoker) and, on success, a custody event — so the+// on-chain activity is visibly attributed just like the USDC purchases.++import { PublicKey } from '@solana/web3.js';++import { env } from '../../env.js';+import { logger } from '../../usage.js';+import { solanaConnection } from '../../solana/connection.js';+import { recordCustodyEvent } from '../../agent-trade-guards.js';+import {+ recordInvocationReceipt,+ AGENT_INVOCATION_PROGRAM_ID,+} from '../../agent-invocation-onchain.js';++const log = logger('x402-ring-onchain');++/** Ticks between on-chain interactions. Default 60. Set 0 to disable entirely. */+export function onchainEveryNTicks() {+ const n = Number(process.env.X402_RING_ONCHAIN_EVERY_N_TICKS ?? 60);+ return Number.isFinite(n) && n >= 0 ? Math.floor(n) : 60;+}++/** The cluster the on-chain receipt lands on. Devnet by default — the constraints+ * forbid new mainnet program calls in this task. */+export function onchainNetwork() {+ return process.env.AGENT_INVOCATION_NETWORK === 'mainnet' ? 'mainnet' : 'devnet';+}++/** True on ticks where the on-chain step should fire. Pure — unit-testable. */+export function isOnchainTick(seed, everyN = onchainEveryNTicks()) {+ if (!everyN || everyN <= 0) return false;+ return (seed >>> 0) % everyN === 0;+}++/**+ * Maybe land one on-chain agent-invocation receipt this tick.+ *+ * @param {object} p+ * @param {Function} p.sql+ * @param {Array<{ persona: object, id: string, name: string, address: string, user_id: string|null, meta: object }>} p.roster+ * @param {number} p.seed+ * @param {string} p.runId+ * @param {(row: object) => Promise<import('@solana/web3.js').Keypair|null>} p.recoverAgentBuyer+ * @returns {Promise<{ attempted: boolean, landed: boolean, signature?: string, explorer?: string,+ * invoker?: string, target?: string, network?: string, reason?: string }>}+ */+export async function maybeRecordOnchainReceipt({ sql, roster, seed, runId, recoverAgentBuyer }) {+ const everyN = onchainEveryNTicks();+ if (!isOnchainTick(seed, everyN)) {+ return { attempted: false, landed: false, reason: `not_onchain_tick(every_${everyN})` };+ }+ if (!AGENT_INVOCATION_PROGRAM_ID) {+ return { attempted: false, landed: false, reason: 'program_id_unset' };+ }+ if (!Array.isArray(roster) || roster.length < 2) {+ // Need a distinct invoker + target to record an agent-to-agent receipt.+ return { attempted: false, landed: false, reason: 'need_two_roster_agents' };+ }++ const network = onchainNetwork();++ // Deterministically pick invoker + a distinct target from the roster.+ const invokerMember = roster[(seed >>> 0) % roster.length];+ const targetMember = roster[((seed >>> 0) + 1) % roster.length];++ const conn = solanaConnection({ network, commitment: 'confirmed' });++ // Deploy gate — only attempt if the program is actually executable on this+ // cluster. Absent/unfunded env is a clean skip, not a failure.+ try {+ const info = await conn.getAccountInfo(new PublicKey(AGENT_INVOCATION_PROGRAM_ID));+ if (!info || !info.executable) {+ await recordOnchainAttempt(sql, runId, invokerMember, { landed: false, network, reason: 'program_not_deployed' });+ return { attempted: true, landed: false, network, reason: 'program_not_deployed' };+ }+ } catch (err) {+ return { attempted: true, landed: false, network, reason: `rpc_probe_failed:${String(err?.message || err).slice(0, 80)}` };+ }++ const invokerKeypair = await recoverAgentBuyer(invokerMember);+ if (!invokerKeypair) {+ return { attempted: true, landed: false, network, reason: 'invoker_key_unavailable' };+ }++ let receipt;+ try {+ receipt = await recordInvocationReceipt({+ invokerKeypair,+ targetAuthority: targetMember.address,+ skillName: `ring:${invokerMember.persona.id}->${targetMember.persona.id}`.slice(0, 64),+ parameters: JSON.stringify({ ring: true, tick_seed: seed, run_id: runId }).slice(0, 512),+ network,+ connection: conn,+ });+ } catch (err) {+ // Unfunded invoker on devnet, RPC hiccup, program mismatch — clean skip.+ const reason = String(err?.message || err).slice(0, 140);+ await recordOnchainAttempt(sql, runId, invokerMember, { landed: false, network, reason });+ return { attempted: true, landed: false, network, reason };+ }++ // Landed. Attribute it: log row + custody event on the invoker.+ await recordOnchainAttempt(sql, runId, invokerMember, {+ landed: true, network,+ signature: receipt.signature, explorer: receipt.explorer,+ target: targetMember.address,+ });+ await recordCustodyEvent({+ agentId: invokerMember.id,+ userId: invokerMember.user_id ?? null,+ eventType: 'onchain_event',+ network,+ signature: receipt.signature,+ reason: 'ring_invocation_receipt',+ status: 'confirmed',+ meta: {+ internal: true, program: receipt.programId,+ target_agent: targetMember.id, target_persona: targetMember.persona.id,+ explorer: receipt.explorer,+ },+ }).catch(() => {});++ log.info('ring_onchain_receipt_landed', {+ signature: receipt.signature, network,+ invoker: invokerMember.persona.id, target: targetMember.persona.id,+ });++ return {+ attempted: true, landed: true, network,+ signature: receipt.signature, explorer: receipt.explorer,+ invoker: invokerMember.address, target: targetMember.address,+ };+}++/** Log an on-chain attempt (landed or skipped) to x402_autonomous_log for the feed. */+async function recordOnchainAttempt(sql, runId, invokerMember, { landed, network, signature = null, explorer = null, target = null, reason = null }) {+ try {+ await sql`+ INSERT INTO x402_autonomous_log+ (run_id, agent_id, endpoint_type, service_name, endpoint_url,+ network, amount_atomic, asset, tx_signature,+ signal_data, value_extracted, duration_ms, success, error_msg, pipeline)+ VALUES+ (${runId}, ${invokerMember.id}, 'self',+ ${`ring-onchain:${invokerMember.persona.id}`},+ ${`agent_invocation:${AGENT_INVOCATION_PROGRAM_ID}`},+ ${`solana:${network}`}, 0, ${'SOL'}, ${signature},+ ${JSON.stringify({ persona: invokerMember.persona.id, internal: true, onchain: true, network })},+ ${JSON.stringify({ landed, explorer, target, program: AGENT_INVOCATION_PROGRAM_ID })},+ 0, ${landed}, ${reason}, 'ring-onchain')+ `;+ } catch (err) {+ log.warn('onchain_log_failed', { message: err?.message });+ }+}diff --git a/api/_lib/x402/agents/persona-kit.js b/api/_lib/x402/agents/persona-kit.jsnew file mode 100644index 000000000..b6af24987--- /dev/null+++ b/api/_lib/x402/agents/persona-kit.js@@ -0,0 +1,345 @@+// @ts-check+// api/_lib/x402/agents/persona-kit.js+//+// Shared machinery for the ring's agent-buyer personas (Task 09). Every persona+// module (endpoint-shopper.js, agora-citizen.js, curator.js) is a thin,+// pure-ish description of WHAT an agent buys; this kit is the HOW that all of+// them share:+//+// • deterministic selection — mulberry32(seed) + helpers so "which persona+// acts this tick" and "which endpoint it buys" are a pure function of a tick+// seed. Same seed ⇒ same plan, every time (the property Task 09 tests assert+// and the dashboard relies on for reproducibility).+// • float math — planFloatMove(): pure floor/target/ceiling arithmetic the+// rebalancer's float-top-up step (ring-rebalance.js) and its tests share.+// • executePurchase() — the ONE guarded settle path every persona routes+// through: spend-limit-check (enforceSpendLimit) → ring-allowlist the+// counterparty → pay via payX402 with the AGENT's keypair → custody-log the+// spend → return a structured record the driver writes to x402_autonomous_log+// with agent_id attribution. No persona is allowed to move money any other+// way — that is what keeps every agent purchase spend-limited, allowlisted,+// and attributable.+//+// Money invariant: the buyer is a platform-controlled custodial agent wallet and+// the payTo is the ring treasury (X402_PAY_TO_SOLANA) — both inside+// ringAllowedAddresses(). USDC only; never $THREE or any third-party coin (the+// commit gate in CLAUDE.md applies). Personas are labeled internal in every log+// row (`persona` + `internal:true`), never presented as organic users.++import { PublicKey } from '@solana/web3.js';++import { payX402, USDC_MINT } from '../pay.js';+import { ringAllowedAddresses } from '../ring-allowlist.js';+import {+ enforceSpendLimit,+ recordSpend,+ SpendLimitError,+ getSpendLimits,+} from '../../agent-trade-guards.js';+import { recoverSolanaAgentKeypair } from '../../agent-wallet.js';+import { env } from '../../env.js';++// ── Deterministic RNG ─────────────────────────────────────────────────────────++/**+ * mulberry32 — a tiny, fast, well-distributed 32-bit PRNG. Seeded, deterministic,+ * dependency-free. Used so persona selection and per-tick endpoint choice are a+ * pure function of the tick seed (reproducible across processes and tests).+ * @param {number} seed+ * @returns {() => number} next float in [0,1)+ */+export function mulberry32(seed) {+ let a = seed >>> 0;+ return function next() {+ a |= 0;+ a = (a + 0x6d2b79f5) | 0;+ let t = Math.imul(a ^ (a >>> 15), 1 | a);+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}++/**+ * Fold an arbitrary string (e.g. a runId) into a 32-bit seed. Lets the driver+ * derive a stable seed when no monotonic tick counter is available.+ * @param {string} str+ * @returns {number}+ */+export function seedFromString(str) {+ let h = 2166136261 >>> 0;+ const s = String(str || '');+ for (let i = 0; i < s.length; i++) {+ h ^= s.charCodeAt(i);+ h = Math.imul(h, 16777619);+ }+ return h >>> 0;+}++/**+ * Deterministically pick `n` distinct items from `items` given a seed. Stable:+ * same (items, seed, n) ⇒ same picks in the same order. Used by personas to+ * choose which endpoint(s) to buy this tick.+ * @template T+ * @param {T[]} items+ * @param {number} seed+ * @param {number} [n=1]+ * @returns {T[]}+ */+export function pickDeterministic(items, seed, n = 1) {+ const pool = items.slice();+ const rng = mulberry32(seed);+ const out = [];+ const take = Math.min(n, pool.length);+ for (let i = 0; i < take; i++) {+ const idx = Math.floor(rng() * pool.length);+ out.push(pool.splice(idx, 1)[0]);+ }+ return out;+}++// ── Float math (shared with ring-rebalance float-top-up) ───────────────────────++/**+ * Pure float-band arithmetic. Given an agent's current USDC balance and the+ * band, decide the single next move that returns it toward target:+ * balance < floor → 'top_up' by (target − balance) (treasury → agent)+ * balance > ceiling → 'sweep' by (balance − target) (agent → treasury)+ * otherwise → 'none'+ * All amounts are atomic USDC (6dp). Never returns a negative amount.+ *+ * @param {{ balanceAtomic: number|bigint, floorAtomic: number, targetAtomic: number, ceilingAtomic: number }} p+ * @returns {{ action: 'top_up'|'sweep'|'none', amountAtomic: number }}+ */+export function planFloatMove({ balanceAtomic, floorAtomic, targetAtomic, ceilingAtomic }) {+ const bal = Number(balanceAtomic);+ if (bal < floorAtomic) {+ return { action: 'top_up', amountAtomic: Math.max(0, targetAtomic - bal) };+ }+ if (bal > ceilingAtomic) {+ return { action: 'sweep', amountAtomic: Math.max(0, bal - targetAtomic) };+ }+ return { action: 'none', amountAtomic: 0 };+}++/**+ * Resolve the float band from env, once per call. FLOAT is the target; floor is+ * half of it, ceiling is double — a symmetric band that keeps a small working+ * balance without letting winnings accumulate off-ledger.+ * @returns {{ floorAtomic: number, targetAtomic: number, ceilingAtomic: number }}+ */+export function floatBand() {+ const target = Math.max(0, Number(process.env.X402_RING_AGENT_FLOAT_ATOMIC || 2_000_000));+ const floor = Math.max(0, Number(process.env.X402_RING_AGENT_FLOAT_FLOOR_ATOMIC || Math.floor(target / 2)));+ const ceiling = Math.max(target, Number(process.env.X402_RING_AGENT_FLOAT_CEIL_ATOMIC || target * 2));+ return { floorAtomic: floor, targetAtomic: target, ceilingAtomic: ceiling };+}++// ── Guarded purchase path ──────────────────────────────────────────────────────++/**+ * Is `address` inside the platform-controlled ring set? Accepts a pre-resolved+ * allowlist Set to avoid re-querying per purchase within a tick.+ * @param {string} address+ * @param {Set<string>} allowed+ * @returns {boolean}+ */+export function isRingAddress(address, allowed) {+ return typeof address === 'string' && allowed.has(address);+}++const ATOMIC_PER_USD = 1_000_000;++/**+ * Execute ONE persona purchase through the full guard chain. Never throws — every+ * failure (spend-limit refusal, allowlist miss, protocol/network fault) is+ * returned as a structured, recordable outcome so a single bad purchase can never+ * crash the ring tick.+ *+ * Flow:+ * 1. enforceSpendLimit({ category:'x402', usdValue }) — the agent's own caps.+ * A SpendLimitError is caught and surfaced as { status:'refused' }, NOT+ * rethrown (the tick continues; the refusal is logged + custody-recorded).+ * 2. Probe the endpoint's 402 challenge via payX402 to learn payTo, then assert+ * payTo ∈ ringAllowedAddresses(). A non-ring recipient is refused BEFORE any+ * payment (defence in depth over the facilitator's own payTo allowlist).+ * 3. Pay via payX402 with the AGENT's recovered keypair as buyer.+ * 4. Record a custody 'spend' event (durable, owner-viewable) with the settle+ * signature so the loop stays closed through the business layer.+ *+ * @param {object} p+ * @param {{ id:string, name?:string, address:string, keypair:import('@solana/web3.js').Keypair, meta?:object }} p.agent+ * @param {{ slug:string, url:string, method:string, body:any, priceAtomic:number, kind:string, memo?:string }} p.purchase+ * @param {{ conn:any, blockhash:string, mintInfo:any }} p.solana+ * @param {Set<string>} p.allowed pre-resolved ringAllowedAddresses()+ * @param {string} p.persona persona id (attribution / logs)+ * @param {number} [p.remainingCap] atomic cap remaining this tick+ * @returns {Promise<{ status:'paid'|'free'|'refused'|'error'|'skipped', persona:string, agentId:string,+ * slug:string, kind:string, amountAtomic:number, txSig:string|null, payTo:string|null,+ * reason:string|null, durationMs:number, responseLiveness:object }>}+ */+export async function executePurchase({ agent, purchase, solana, allowed, persona, remainingCap = Infinity }) {+ const t0 = Date.now();+ const base = {+ persona,+ agentId: agent.id,+ slug: purchase.slug,+ kind: purchase.kind,+ amountAtomic: 0,+ txSig: null,+ payTo: null,+ reason: null,+ };+ const done = (extra) => ({ ...base, ...extra, durationMs: Date.now() - t0, responseLiveness: extra.responseLiveness || {} });++ const usdValue = (purchase.priceAtomic || 0) / ATOMIC_PER_USD;++ // 1 — the agent's own spend policy. A breach is a REFUSAL, not a crash.+ try {+ await enforceSpendLimit({+ agentId: agent.id,+ meta: agent.meta || {},+ category: 'x402',+ usdValue,+ asset: USDC_MINT,+ network: 'mainnet',+ });+ } catch (err) {+ if (err instanceof SpendLimitError) {+ await recordSpend({+ agentId: agent.id,+ category: 'x402',+ network: 'mainnet',+ asset: USDC_MINT,+ usd: usdValue,+ status: 'failed',+ reason: `spend_limit:${err.code}`,+ meta: { persona, slug: purchase.slug, internal: true, refused: true },+ }).catch(() => {});+ return done({ status: 'refused', reason: `spend_limit:${err.code}` });+ }+ return done({ status: 'error', reason: `enforce_error:${String(err?.message || err).slice(0, 120)}` });+ }++ // 2 — probe first so we can allowlist the recipient BEFORE paying. payX402+ // returns a structured outcome; a thrown fault is caught below.+ let result;+ try {+ result = await payX402({+ url: purchase.url,+ method: purchase.method || 'GET',+ body: purchase.body ?? null,+ buyer: agent.keypair,+ conn: solana.conn,+ blockhash: solana.blockhash,+ mintInfo: solana.mintInfo,+ remainingCap,+ userAgent: `threews-ring-agent/${persona}`,+ // A distinct nonce per (agent, slug, tick) keeps byte-identical+ // same-price transfers from colliding on one shared blockhash.+ nonce: seedFromString(`${agent.id}:${purchase.slug}:${solana.blockhash}`) % 997,+ // The purchase-recipient allowlist is enforced here, pre-broadcast, via+ // the onAccept hook: payX402 hands us the resolved accept so we can+ // refuse a non-ring payTo before signing.+ onAccept: (accept) => {+ const payTo = accept?.payTo || null;+ base.payTo = payTo;+ if (!isRingAddress(payTo, allowed)) {+ return { abort: true, reason: `payto_not_ring:${payTo}` };+ }+ return null;+ },+ });+ } catch (err) {+ return done({ status: 'error', reason: `pay_error:${String(err?.message || err).slice(0, 120)}` });+ }++ if (result.refusedByHook) {+ return done({ status: 'refused', reason: result.errorMsg || 'payto_not_ring' });+ }+ if (result.free) {+ return done({ status: 'free', responseLiveness: summarizeLiveness(result.responseBody) });+ }+ if (!result.paid) {+ return done({ status: result.skipped ? 'skipped' : 'error', reason: result.errorMsg, responseLiveness: summarizeLiveness(result.responseBody) });+ }++ // 4 — durable custody record of the settled spend (owner-viewable trail).+ await recordSpend({+ agentId: agent.id,+ category: 'x402',+ network: 'mainnet',+ asset: USDC_MINT,+ amountRaw: result.amountAtomic,+ usd: result.amountAtomic / ATOMIC_PER_USD,+ destination: base.payTo,+ signature: result.txSig,+ status: 'confirmed',+ reason: `ring:${persona}:${purchase.slug}`,+ meta: { persona, slug: purchase.slug, kind: purchase.kind, internal: true, memo: purchase.memo || null },+ }).catch(() => {});++ return done({+ status: 'paid',+ amountAtomic: result.amountAtomic,+ txSig: result.txSig,+ responseLiveness: summarizeLiveness(result.responseBody),+ });+}++/** Compact liveness summary — keeps the log row small while proving a real reply. */+export function summarizeLiveness(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, 10) };+ }+ return { ok: true, shape: typeof body };+}++/**+ * Recover an agent's custodial Solana keypair for signing, auditing the decrypt.+ * Returns null (never throws) when the agent has no usable secret — the driver+ * skips that agent for the tick.+ * @param {{ id:string, user_id?:string, meta?:object }} row+ * @returns {Promise<import('@solana/web3.js').Keypair|null>}+ */+export async function recoverAgentBuyer(row) {+ const enc = row?.meta?.encrypted_solana_secret;+ if (!enc) return null;+ try {+ return await recoverSolanaAgentKeypair(enc, {+ agentId: row.id,+ userId: row.user_id ?? null,+ reason: 'x402_ring_buy',+ meta: { context: 'ring-agent-buyer' },+ });+ } catch {+ return null;+ }+}++/** Build a GET URL with query params, or return the path unchanged for POST. */+export function buildUrl(origin, path, query) {+ if (!query || Object.keys(query).length === 0) return `${origin}${path}`;+ const qs = new URLSearchParams(query).toString();+ const sep = path.includes('?') ? '&' : '?';+ return `${origin}${path}${sep}${qs}`;+}++/** Assert USDC is configured; personas call this before planning real spends. */+export function usdcConfigured() {+ return Boolean(USDC_MINT);+}++/** The ring treasury pubkey, or null. Personas verify it parses as a real key. */+export function treasuryPubkey() {+ const addr = env.X402_PAY_TO_SOLANA;+ if (!addr) return null;+ try {+ return new PublicKey(addr).toBase58();+ } catch {+ return null;+ }+}diff --git a/api/_lib/x402/autonomous-registry.js b/api/_lib/x402/autonomous-registry.jsindex 821591a31..86cc47950 100644--- a/api/_lib/x402/autonomous-registry.js+++ b/api/_lib/x402/autonomous-registry.js@@ -44,7 +44,8 @@ import { run as reputationRefresh } from './pipelines/reputation-refresh.js';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 ringRebalance, floatTopUp as ringFloatTopUp } from './pipelines/ring-rebalance.js';+import { run as ringAgentBuyers } from './agents/index.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';@@ -2669,19 +2670,74 @@ const SELF_ENDPOINTS = [// it never consumes the daily spend cap. No-op until X402_TREASURY_SECRET_BASE58// is set. Value sink: x402_ring_ledger (kind='sweep'). See// pipelines/ring-rebalance.js.+ //+ // Cooldown 120s (was 300s): the per-minute ring tick cycles the payer float+ // far faster than the old 5-min volume-only cadence, so the rebalancer must+ // keep up or the payer drains between sweeps. Sweep threshold is env-tunable+ // via X402_RING_MIN_SWEEP_ATOMIC.{id: 'ring-rebalance',name: 'Ring Rebalancer',path: '/api/x402/ring-settle',method: 'POST',body: null,- cooldown_s: 300,+ cooldown_s: 120,priority: 20,pipeline: 'volume',enabled: true,run: (ctx) => ringRebalance(ctx),},+ // ── Ring Agent Buyers (Task 09) ──────────────────────────────────────────────+ // The roster of platform agents that make the ring an agent-to-agent economy+ // rather than a cron paying itself. Each tick, the provisioned personas+ // (endpoint-shopper, agora-citizen, curator — api/_lib/x402/agents/) shop the+ // ring in character: intel + health, club cover + dance tips, marketplace ++ // billboards. Every purchase pays with the AGENT's custodial keypair, is+ // spend-limit-checked via enforceSpendLimit, custody-logged, and recorded to+ // x402_autonomous_log WITH agent_id for attribution. Recirculation stays closed:+ // the treasury is the seller and float-top-up recycles proceeds back to the+ // agents. At low cadence (X402_RING_ONCHAIN_EVERY_N_TICKS) one roster agent also+ // lands a real on-chain agent-invocation receipt (devnet), fee-paid by its own+ // ring wallet. run() self-records granular per-purchase rows, so the loop adds no+ // duplicate summary. No-op until a roster can be provisioned. Value sink:+ // x402_autonomous_log (pipeline='ring-agents'/'ring-onchain') + agent_custody_events.+ {+ id: 'agent-buyers',+ name: 'Ring Agent Buyers',+ // path is informational — run() drives the persona roster across the catalog.+ path: '/api/x402/*',+ method: 'POST',+ body: null,+ cooldown_s: 60,+ priority: 40,+ pipeline: 'agents',+ enabled: true,+ run: (ctx) => ringAgentBuyers(ctx),+ },++ // ── Ring Agent Float Top-Up (Task 09) ────────────────────────────────────────+ // Keeps each roster agent's USDC float inside a floor/target/ceiling band+ // (X402_RING_AGENT_FLOAT_ATOMIC, default $2): tops up a hungry agent from the+ // treasury, sweeps an overfull one back. Same closed loop as the payer+ // rebalancer, applied to the agent wallets. Every counterparty is asserted+ // against ringAllowedAddresses() before any move (fail-closed). Recorded to+ // x402_ring_ledger (kind='fund'). Recirculation, not spend — returns+ // amountAtomic:0. No-op until X402_TREASURY_SECRET_BASE58 is set. See+ // pipelines/ring-rebalance.js floatTopUp().+ {+ id: 'ring-float-topup',+ name: 'Ring Agent Float Top-Up',+ path: '/api/x402/ring-settle',+ method: 'POST',+ body: null,+ cooldown_s: 120,+ priority: 22,+ pipeline: 'agents',+ enabled: true,+ run: (ctx) => ringFloatTopUp(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 +diff --git a/api/_lib/x402/pay.js b/api/_lib/x402/pay.jsindex e38be04c1..3306041aa 100644--- a/api/_lib/x402/pay.js+++ b/api/_lib/x402/pay.js@@ -28,6 +28,33 @@ export const USDC_MINT = env.X402_ASSET_MINT_SOLANA;export const SOLANA_RPC = env.SOLANA_RPC_URL;export const FETCH_TIMEOUT_MS = 20_000;+// ── Loud price-vs-cap skip ──────────────────────────────────────────────────────+// A silent skip when an endpoint's advertised price exceeds the caller's remaining+// per-run cap is exactly the bug the ring economy was built to kill: the flagship+// ring-settle ($1.00) was dropped every cycle because the volume loop's per-run+// cap ($0.05) was below it, and nobody saw it. Now the skip is LOUD — it names the+// endpoint, the price, the cap, and the envs to raise — throttled to once per hour+// per (url,cap) signature so a per-minute driver can't flood the logs.+const _capWarnAt = new Map();+const CAP_WARN_TTL_MS = 60 * 60 * 1000;+export function warnCapExceeded(url, priceAtomic, capAtomic) {+ const now = Date.now();+ const sig = `${url}|${capAtomic}`;+ const last = _capWarnAt.get(sig) || 0;+ if (now - last < CAP_WARN_TTL_MS) return;+ _capWarnAt.set(sig, now);+ if (_capWarnAt.size > 512) {+ for (const [k, t] of _capWarnAt) if (now - t >= CAP_WARN_TTL_MS) _capWarnAt.delete(k);+ }+ console.warn(+ `[x402-pay] price_exceeds_cap — ${url} advertises ${(priceAtomic / 1e6).toFixed(6)} USDC ` ++ `but the remaining per-run cap is ${(capAtomic / 1e6).toFixed(6)} USDC, so the call was SKIPPED ` ++ `(never settled). Raise the applicable cap to fit: X402_RING_TICK_CAP_ATOMIC (per-minute ring tick), ` ++ `X402_VOLUME_PER_RUN_CAP_ATOMIC (5-min volume loop), X402_RING_DAILY_CAP_ATOMIC / ` ++ `X402_AUTONOMOUS_DAILY_CAP_ATOMIC (daily), or lower X402_PRICE_RING_SETTLE.`,+ );+}+// ── Fee floor ─────────────────────────────────────────────────────────────────// The ring's operating rule is "lowest fees always": 1-signature self-pay// settlement (5,000 lamports base) with the priority fee pinned at the floor.@@ -196,6 +223,14 @@ export async function payX402({// only an explicit X402_RING_SELF_PAY=false selects sponsor mode. See// ringSelfPayDefault() and buildPaymentTx.selfPay = ringSelfPayDefault(),+ // Optional pre-broadcast recipient gate. Called with the resolved Solana+ // `accept` (payTo, asset, amount, …) AFTER the 402 challenge is parsed and+ // BEFORE the payment tx is built/signed. Return `{ abort: true, reason }` to+ // refuse the payment without moving money — the ring agent buyers use this to+ // enforce that every counterparty is inside ringAllowedAddresses(). Returning+ // null/undefined continues the normal flow. Sync or async; a thrown hook is+ // treated as an abort (fail-closed), never a crash.+ onAccept = null,}) {const reqInit = {method,@@ -226,8 +261,27 @@ export async function payX402({return { success: false, paid: false, free: false, skipped: true, amountAtomic: 0, txSig: null, status: 402, responseBody: probe.body, errorMsg: 'missing_fee_payer' };}+ // Pre-broadcast recipient gate. A thrown hook is a fail-closed refusal, never+ // a crash — the whole point is to stop money moving to an unexpected payTo.+ if (typeof onAccept === 'function') {+ let hook;+ try {+ hook = await onAccept(accept);+ } catch (err) {+ hook = { abort: true, reason: `onaccept_error:${String(err?.message || err).slice(0, 80)}` };+ }+ if (hook?.abort) {+ return {+ success: false, paid: false, free: false, skipped: true, refusedByHook: true,+ amountAtomic: Number(accept.amount || 0), txSig: null, status: 402,+ responseBody: probe.body, errorMsg: hook.reason || 'onaccept_abort',+ };+ }+ }+const amountAtomic = Number(accept.amount || 0);if (amountAtomic > remainingCap) {+ warnCapExceeded(url, amountAtomic, Number.isFinite(remainingCap) ? remainingCap : 0);return { success: false, paid: false, free: false, skipped: true, amountAtomic, txSig: null, status: 402, responseBody: probe.body, errorMsg: 'cap_would_exceed' };}diff --git a/api/_lib/x402/pipelines/ring-rebalance.js b/api/_lib/x402/pipelines/ring-rebalance.jsindex 6c38aa703..4d2c387d1 100644--- a/api/_lib/x402/pipelines/ring-rebalance.js+++ b/api/_lib/x402/pipelines/ring-rebalance.js@@ -45,7 +45,10 @@ function loadKp(b58) {// Keep this much USDC in the treasury after a sweep (default 0 — sweep all).const TREASURY_BUFFER_ATOMIC = BigInt(process.env.X402_RING_TREASURY_BUFFER_ATOMIC || 0);-// Don't bother sweeping dust — default $0.10 minimum.+// Don't bother sweeping dust — default $0.10 minimum. Env-tunable via+// X402_RING_MIN_SWEEP_ATOMIC: lower it when the per-minute ring tick cycles the+// float in small increments so the rebalancer sweeps sooner and the payer never+// starves between the (now 120s) rebalance ticks.const MIN_SWEEP_ATOMIC = BigInt(process.env.X402_RING_MIN_SWEEP_ATOMIC || 100_000);async function confirmSignature(conn, signature, timeoutMs = 30_000) {@@ -189,3 +192,196 @@ export async function run(ctx = {}) {note: `swept ${Number(sweep) / 1e6} USDC treasury→payer`,};}++// ── Agent float top-up / sweep (Task 09) ───────────────────────────────────────+//+// The treasury→payer sweep above keeps the seed PAYER funded. This step does the+// same for the ROSTER AGENTS (api/_lib/x402/agents/): it keeps each agent's USDC+// balance inside a floor/target/ceiling band by moving float between the treasury+// and the agent — top up a hungry agent, sweep an overfull one back. Same closed+// loop, same platform-controlled wallets, recorded to x402_ring_ledger as+// kind='fund'. It deliberately does NOT touch the treasury→payer core above.+//+// Every counterparty is asserted against ringAllowedAddresses() before any move —+// a wallet outside the controlled set is skipped (fail-closed), never funded.+// Recirculation, not spend: returns amountAtomic:0 so it never consumes the daily+// spend cap. No-op until the treasury secret is set (same gate as run()).++/**+ * Build, sign, broadcast and confirm ONE USDC transfer between two ring wallets.+ * `from` is the token-transfer authority (must sign); `feePayer` pays the SOL fee+ * (may be the same as `from`). Returns { ok, signature } | { ok:false, err }.+ */+async function transferUsdcBetween({ conn, mint, mintInfo, fromKp, toPub, amountAtomic, feePayerKp }) {+ const fromAta = getAssociatedTokenAddressSync(mint, fromKp.publicKey, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID);+ const toAta = getAssociatedTokenAddressSync(mint, toPub, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID);+ const toAtaInfo = await conn.getAccountInfo(toAta).catch(() => null);+ const { blockhash } = await conn.getLatestBlockhash('confirmed');++ const ixs = [+ ComputeBudgetProgram.setComputeUnitLimit({ units: 60_000 }),+ ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 5 }),+ ];+ if (!toAtaInfo) {+ ixs.push(createAssociatedTokenAccountIdempotentInstruction(+ feePayerKp.publicKey, toAta, toPub, mint, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,+ ));+ }+ ixs.push(createTransferCheckedInstruction(+ fromAta, mint, toAta, fromKp.publicKey, BigInt(amountAtomic), mintInfo.decimals, [], TOKEN_PROGRAM_ID,+ ));++ const msg = new TransactionMessage({+ payerKey: feePayerKp.publicKey,+ recentBlockhash: blockhash,+ instructions: ixs,+ }).compileToV0Message();+ const vtx = new VersionedTransaction(msg);+ const signers = feePayerKp.publicKey.equals(fromKp.publicKey) ? [fromKp] : [feePayerKp, fromKp];+ vtx.sign(signers);++ let signature;+ try {+ signature = await conn.sendRawTransaction(vtx.serialize(), { skipPreflight: false, maxRetries: 5 });+ } catch (err) {+ return { ok: false, err: `broadcast_failed:${String(err?.message || err).slice(0, 160)}` };+ }+ const conf = await confirmSignature(conn, signature);+ if (!conf.confirmed) return { ok: false, err: `not_confirmed:${conf.err}`, signature };+ return { ok: true, signature };+}++/**+ * Keep every roster agent's USDC float inside its band. Conforms to the run()-style+ * registry contract (cap-neutral recirculation). Standalone-safe.+ *+ * @param {object} ctx { sql?, conn?, runId? }+ * @returns {Promise<{ success:boolean, amountAtomic:0, skipped?:boolean, note?:string, moves?:Array }>}+ */+export async function floatTopUp(ctx = {}) {+ const sql = ctx.sql || defaultSql;+ const runId = ctx.runId || null;++ const treasurySecret = process.env.X402_TREASURY_SECRET_BASE58;+ if (!treasurySecret) return { success: true, skipped: true, amountAtomic: 0, note: 'treasury_secret_unset' };+ if (!USDC_MINT) return { success: true, skipped: true, amountAtomic: 0, note: 'usdc_mint_unset' };++ let treasury;+ try {+ treasury = loadKp(treasurySecret);+ } catch (err) {+ return { success: false, amountAtomic: 0, errorMsg: `bad_treasury_key:${err.message}` };+ }+ if (env.X402_PAY_TO_SOLANA && treasury.publicKey.toBase58() !== env.X402_PAY_TO_SOLANA) {+ return { success: false, amountAtomic: 0, errorMsg: 'treasury_pubkey_mismatch' };+ }++ // Lazy imports: keep the rebalancer's core dependency graph small, and avoid a+ // module-load cycle with the agents driver (which imports pay.js).+ const [{ ensureRosterAgents }, { planFloatMove, floatBand, recoverAgentBuyer }, { ringAllowedAddresses }] = await Promise.all([+ import('../agents/index.js'),+ import('../agents/persona-kit.js'),+ import('../ring-allowlist.js'),+ ]);++ const roster = await ensureRosterAgents(sql);+ if (roster.length === 0) return { success: true, skipped: true, amountAtomic: 0, note: 'no_roster_agents' };++ const allowed = await ringAllowedAddresses({ sql });+ if (!allowed.has(treasury.publicKey.toBase58())) {+ return { success: false, amountAtomic: 0, errorMsg: 'treasury_not_allowlisted' };+ }++ const conn = ctx.conn || solanaConnection({ url: env.SOLANA_RPC_URL, commitment: 'confirmed' });+ const mint = new PublicKey(USDC_MINT);+ const mintInfo = await getMint(conn, mint);+ const band = floatBand();++ // Sponsor pays fees when configured so SOL burn stays on one wallet.+ let sponsorKp = null;+ if (process.env.X402_FEE_PAYER_SECRET_BASE58) {+ try { sponsorKp = loadKp(process.env.X402_FEE_PAYER_SECRET_BASE58); } catch { sponsorKp = null; }+ }++ const moves = [];+ const minMove = Math.max(0, Number(process.env.X402_RING_AGENT_MIN_FLOAT_MOVE_ATOMIC || 100_000)); // $0.10++ for (const member of roster) {+ // Both counterparties must be inside the controlled set — fail-closed.+ if (!allowed.has(member.address)) {+ moves.push({ agent: member.id, action: 'skip', reason: 'agent_not_allowlisted' });+ continue;+ }+ const agentPub = new PublicKey(member.address);+ const agentAta = getAssociatedTokenAddressSync(mint, agentPub, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID);+ let balance = 0n;+ try {+ const acc = await getAccount(conn, agentAta);+ balance = acc.amount;+ } catch {+ balance = 0n; // no ATA yet → treated as empty; a top-up creates it+ }++ const plan = planFloatMove({+ balanceAtomic: balance, floorAtomic: band.floorAtomic,+ targetAtomic: band.targetAtomic, ceilingAtomic: band.ceilingAtomic,+ });+ if (plan.action === 'none' || plan.amountAtomic < minMove) {+ moves.push({ agent: member.id, action: 'none', balance_atomic: Number(balance) });+ continue;+ }++ let res;+ let fromWallet;+ let toWallet;+ if (plan.action === 'top_up') {+ // treasury → agent, sponsor (or treasury) pays the fee.+ fromWallet = treasury.publicKey.toBase58();+ toWallet = member.address;+ res = await transferUsdcBetween({+ conn, mint, mintInfo, fromKp: treasury, toPub: agentPub,+ amountAtomic: plan.amountAtomic, feePayerKp: sponsorKp || treasury,+ });+ } else {+ // agent → treasury (sweep overflow). The agent signs; sponsor (or the+ // agent) pays the fee. Needs the agent's custodial key.+ const agentKp = await recoverAgentBuyer(member);+ if (!agentKp) {+ moves.push({ agent: member.id, action: 'sweep', reason: 'agent_key_unavailable' });+ continue;+ }+ fromWallet = member.address;+ toWallet = treasury.publicKey.toBase58();+ res = await transferUsdcBetween({+ conn, mint, mintInfo, fromKp: agentKp, toPub: treasury.publicKey,+ amountAtomic: plan.amountAtomic, feePayerKp: sponsorKp || agentKp,+ });+ }++ if (!res.ok) {+ moves.push({ agent: member.id, action: plan.action, reason: res.err });+ continue;+ }++ try {+ await sql`+ INSERT INTO x402_ring_ledger (kind, from_wallet, to_wallet, mint, amount_atomic, tx_sig, run_id)+ VALUES ('fund', ${fromWallet}, ${toWallet}, ${USDC_MINT}, ${plan.amountAtomic}, ${res.signature}, ${runId})+ `;+ } catch (err) {+ log.warn('float_fund_ledger_write_failed', { agent: member.id, message: err?.message });+ }+ moves.push({ agent: member.id, persona: member.persona.id, action: plan.action, amount_atomic: plan.amountAtomic, tx: res.signature });+ log.info('ring_float_move', { agent: member.id, action: plan.action, amount_atomic: plan.amountAtomic, tx: res.signature });+ }++ const funded = moves.filter((m) => m.tx).length;+ return {+ success: true,+ amountAtomic: 0, // recirculation, not spend — cap-neutral+ recorded: false,+ skipped: funded === 0,+ note: `float_top_up moves=${funded}/${roster.length}`,+ moves,+ };+}diff --git a/api/_lib/x402/pipelines/volume-bootstrap-loop.js b/api/_lib/x402/pipelines/volume-bootstrap-loop.jsindex ad1344644..effdd3753 100644--- a/api/_lib/x402/pipelines/volume-bootstrap-loop.js+++ b/api/_lib/x402/pipelines/volume-bootstrap-loop.js@@ -9,6 +9,11 @@// payments across all of them so the platform accrues genuine agent-to-agent// transaction volume (the metric agentic.market ranks facilitators on).//+// Fires every 5 minutes from the autonomous loop. The per-minute cadence for+// steady, capped ring traffic lives in api/cron/x402-ring-tick.js — both drivers+// share one payment + recording path (pipelines/volume-shared.js), so there is+// exactly one settlement code path, not two that drift.+//// On each run it:// 1. Advances a Redis-backed round-robin cursor and reserves the next window of// VOLUME_BATCH_PER_RUN endpoints from VOLUME_ENDPOINTS (stable across warm@@ -41,176 +46,25 @@ import { randomUUID } from 'node:crypto';import { sql as defaultSql } from '../../db.js';import { env } from '../../env.js';import { logger } from '../../usage.js';-import { payX402, bootstrapSolanaContext, USDC_MINT } from '../pay.js';+import { payX402, bootstrapSolanaContext } from '../pay.js';+import {+ ASSET,+ VOLUME_ENDPOINTS,+ VOLUME_BATCH_PER_RUN,+ VOLUME_PER_RUN_CAP_ATOMIC,+ reserveWindow,+ ensureVolumeSchema,+ settleAndRecord,+} from './volume-shared.js';const log = logger('x402-volume-bootstrap');-const ASSET = USDC_MINT || 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';--// How many endpoints to sweep per run (cursor advances by this each tick). With-// the catalog below (~11 endpoints) 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),-);--// Self-imposed per-run USDC budget (atomics, 6dp). Bounds a single tick on top of-// the loop's daily cap so one run can't drain the day. Default $0.05 = 50_000.-export const VOLUME_PER_RUN_CAP_ATOMIC = Math.max(- 0,- Number(process.env.X402_VOLUME_PER_RUN_CAP_ATOMIC || 50_000),-);--// The canonical catalog of paid self x402 endpoints the loop round-robins. 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.-// To add an endpoint to the bootstrap volume, add it here — the cursor and the-// metrics ledger pick it up automatically. The volume loop itself is never listed-// (it is not an HTTP endpoint; no self-recursion).-export const VOLUME_ENDPOINTS = [- // Ring-settle is the price-configurable, INTERNAL settlement primitive — the- // fee-optimal way to move real volume (fewer, larger payments). By default- // ($0.10) it is skipped when the per-run cap is the stock $0.05; raise- // X402_PRICE_RING_SETTLE + the caps to make it the volume engine. 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 } },-];+// Re-exported for the registry, the ring tick, and existing tests that read the+// catalog and caps from this module. The canonical definitions live in+// volume-shared.js so both drivers agree.+export { ASSET, VOLUME_ENDPOINTS, VOLUME_BATCH_PER_RUN, VOLUME_PER_RUN_CAP_ATOMIC };const CURSOR_KEY = 'x402:auto:volume:cursor';-let _memCursor = 0;--// Reserve the next window of `batch` endpoint indices, advancing the cursor-// atomically. Redis INCRBY gives a stable rotation across warm instances; the-// in-memory counter is the single-process fallback.-async function reserveWindow(redis, batch, len) {- let end;- if (redis) {- try {- end = Number(await redis.incrby(CURSOR_KEY, batch));- } catch {- end = (_memCursor += batch);- }- } else {- end = (_memCursor += batch);- }- 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 (mirrors the loop's ensureSchema idiom).-let _schemaReady = false;-async function ensureSchema(sql) {- if (_schemaReady) return;- // Per-endpoint cumulative volume ledger. PRIMARY KEY endpoint_key → one row- // per paid endpoint, accumulated across every sweep.- 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.-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.-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. The loop records one aggregate summary-// row for the run() entry; these are the granular per-endpoint sweep rows.-async function recordCall(sql, runId, ep, { endpointUrl, amountAtomic, txSig, responseData, durationMs, success, errorMsg, valueExtracted }) {- 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'}, ${`Volume: ${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}, ${'volume'})- `;- } catch (err) {- log.warn('volume_bootstrap_log_insert_failed', { endpoint: ep.key, message: err?.message });- }-}/*** Run the volume bootstrap sweep. Conforms to the run()-style registry contract:@@ -229,7 +83,7 @@ export async function run(ctx = {}) {// ── Schema first: without the sink there is nothing to extract value into, so// don't pay. A schema failure is a graceful skip (no spend).try {- await ensureSchema(sql);+ await ensureVolumeSchema(sql);} catch (err) {log.warn('volume_bootstrap_schema_failed', { message: err?.message });return { success: false, skipped: true, amountAtomic: 0, errorMsg: `schema_failed: ${err?.message}` };@@ -254,7 +108,7 @@ export async function run(ctx = {}) {: loopCap;// ── Select this run's window of endpoints (round-robin).- const indices = await reserveWindow(redis, VOLUME_BATCH_PER_RUN, VOLUME_ENDPOINTS.length);+ const indices = await reserveWindow(redis, VOLUME_BATCH_PER_RUN, VOLUME_ENDPOINTS.length, CURSOR_KEY);let spentAtomic = 0;let paid = 0;@@ -270,74 +124,21 @@ export async function run(ctx = {}) {break;}- const endpointUrl = `${origin}${ep.path}`;- const t0 = Date.now();-- // Pay (or detect free / skip). payX402 never throws for protocol/network- // faults — it returns a structured outcome; a thrown error (rare) is still- // caught so the sweep continues and the failure is recorded.- let result;- try {- result = await payX402({- url: endpointUrl,- method: ep.method || 'POST',- body: ep.body,- buyer, conn, blockhash, mintInfo,- remainingCap: remaining,- });- } catch (err) {- result = { success: false, paid: false, amountAtomic: 0, txSig: null, status: 0, responseBody: null, errorMsg: err?.message || 'fetch_failed' };- }+ const { result, paidAmount } = await settleAndRecord({+ sql, runId, ep, origin, remaining,+ ctx: { buyer, conn, blockhash, mintInfo },+ pipeline: 'volume', namePrefix: 'Volume', payFn: payX402, log,+ });calls += 1;if (!result.success) errors += 1;if (result.paid) {- spentAtomic += result.amountAtomic;- remaining -= result.amountAtomic;+ spentAtomic += paidAmount;+ remaining -= paidAmount;paid += 1;if (result.txSig) lastTxSig = result.txSig;}- // Upsert the per-endpoint volume ledger; DB faults are logged, never fatal.- let metric = null;- try {- metric = await upsertVolumeMetric(sql, ep, {- amountAtomic: result.amountAtomic,- 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: result.amountAtomic || 0,- 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 recordCall(sql, runId, ep, {- endpointUrl,- amountAtomic: result.amountAtomic,- txSig: result.txSig,- // Trim the (possibly bulky) endpoint payload — the ledger holds the- // useful aggregate; keep just the call status + liveness here.- responseData: { status: result.status, liveness: valueExtracted.liveness },- durationMs: Date.now() - t0,- success: result.success,- errorMsg: result.errorMsg,- valueExtracted,- });-swept.push({ key: ep.key, paid: result.paid === true, success: result.success, status: result.status });}diff --git a/api/_lib/x402/pipelines/volume-shared.js b/api/_lib/x402/pipelines/volume-shared.jsindex 015829ce9..5fced9f5d 100644--- a/api/_lib/x402/pipelines/volume-shared.js+++ b/api/_lib/x402/pipelines/volume-shared.js@@ -12,6 +12,7 @@// The payment itself is always payX402 (../pay.js); callers own budget/cadence.import { USDC_MINT } from '../pay.js';+import { rotationPlan } from '../ring-catalog.js';export const ASSET = USDC_MINT || 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';@@ -37,34 +38,40 @@ export const VOLUME_BATCH_PER_RUN = Math.max(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 catalog of paid self x402 endpoints the ring drivers round-robin is now the+// single source of truth in ../ring-catalog.js — every paid endpoint on the+// platform, each with a body()/query proven against the handler it points at.+// This module maps the catalog's autobuy, weighted rotation into the flat+// { key, name, path, method, body } shape both drivers already consume. INTERNAL+// paths only — the ring never pays anything outside three.ws; X402_EXTERNAL_ENABLED+// has no effect on it. To add an endpoint to ring volume, add it to ring-catalog.js+// with autobuy:true — the cursor, the metrics ledger, and the per-minute tick pick+// it up automatically (and tests/x402-ring-catalog.test.js fails until it is+// cataloged). The drivers themselves are never listed (no self-recursion).+//+// Turn a display name from a slug: 'club-cover-snapshot' → 'Club Cover Snapshot'.+function displayName(slug) {+ return slug.replace(/-/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase());+}++// Fold a catalog entry into the driver's flat endpoint shape. GET query params+// are baked into the path (the settle path already appends nothing else), so the+// shared settleAndRecord needs no change; POST bodies are resolved once from+// body() (the payloads are static canaries).+function toVolumeEndpoint(e) {+ const qs = e.query ? `?${new URLSearchParams(e.query).toString()}` : '';+ return {+ key: e.slug,+ name: displayName(e.slug),+ path: `${e.path}${qs}`,+ method: e.method,+ body: e.method === 'POST' ? e.body() : null,+ };+}++// The weighted, interleaved autobuy rotation — a full pass touches every autobuy+// slug at least once (weight-N entries appear N times so they are hit more often).+export const VOLUME_ENDPOINTS = rotationPlan().map(toVolumeEndpoint);// The ring-settle catalog entry (the periodic large volume carrier).export const RING_SETTLE_ENDPOINT = VOLUME_ENDPOINTS.find((e) => e.key === 'ring-settle');diff --git a/api/_lib/x402/ring-catalog.js b/api/_lib/x402/ring-catalog.jsnew file mode 100644index 000000000..ac4847963--- /dev/null+++ b/api/_lib/x402/ring-catalog.js@@ -0,0 +1,854 @@+// api/_lib/x402/ring-catalog.js+//+// The canonical catalog of EVERY paid x402 endpoint on three.ws — the single+// source of truth the ring economy pays against. It replaces the hand-maintained+// `VOLUME_ENDPOINTS` list that had drifted out of sync with the handlers (stale+// methods, wrong bodies, endpoints missing entirely) and silently 405'd or 400'd+// paid requests.+//+// Every entry is derived from reading the handler it points at — the `method`,+// the `query`/`body()` request contract, and the default price all match what+// `api/<path>.js` actually validates, so a rotation call never spends money on a+// request the endpoint would reject. When a new paid endpoint lands, it must be+// added here or tests/x402-ring-catalog.test.js fails (the count-parity guard+// greps every `paidEndpoint(` construction site and asserts each is cataloged).+//+// Consumers:+// • api/_lib/x402/pipelines/volume-bootstrap-loop.js round-robins rotationPlan()+// • tasks/x402-ring/COVERAGE.md documents the one-time settle proof per entry+// • the ring tick (task 04) drives the same plan at its own cadence+//+// Field contract (see CatalogEntry typedef below):+// slug — stable catalog id (usually the pricing slug; a `-…`+// suffix disambiguates a second priced surface on one file)+// sourceFile — repo-relative handler file (parity + stale-path key)+// path — clean route; `api${path}.js` resolves to the handler+// method — GET | POST, matching the handler's dispatch+// query — GET query params (object) or undefined+// body() — POST JSON body (function → object) or () => null+// priceAtomicDefault — default price in USDC atomics (6dp), pre env-override+// priceSlug — the slug passed to priceFor() (env override key source)+// tier — coarse price bucket for rotation filtering+// kind — tip | service | intel | health | commerce | settle+// network — 'solana' when the handler is Solana-only, else null+// autobuy — safe for the ring payer to purchase on a loop?+// weight — relative rotation frequency (autobuy entries only)+// businessEffect — one line: what a settled call actually does+// note — required justification when autobuy === false++// Synthetic, clearly-non-production identifiers used by canary purchases so a+// looped buy never clobbers a real user's record. RING_CANARY_MINT is a valid+// base58 pump-style mint (32–44 chars, no 0/O/I/l) that maps to no real+// coin-world, so the billboard placement it writes is inert. RING_CANARY_UUID is+// a well-formed v4 UUID that resolves to no registered agent (endpoints return a+// truthful "newcomer / not verified" verdict rather than 404).+export const RING_CANARY_MINT = 'Bi11boardRingCanaryMint22222222222222222222';+export const RING_CANARY_UUID = '00000000-0000-4000-8000-000000000001';+// Solana mainnet CAIP-2 chain id (genesis hash), for onchain-identity-verify.+const SOLANA_CAIP2 = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';+// $THREE — the platform coin, guaranteed to resolve on the market data feed.+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+// Wrapped SOL — a real, always-resolvable SPL mint for the mesh minter.+const WSOL_MINT = 'So11111111111111111111111111111111111111112';++/**+ * @typedef {Object} CatalogEntry+ * @property {string} slug+ * @property {string} sourceFile+ * @property {string} path+ * @property {'GET'|'POST'} method+ * @property {Object} [query]+ * @property {() => (Object|null)} body+ * @property {number} priceAtomicDefault+ * @property {string} priceSlug+ * @property {'settle'|'commerce'|'intel'|'service'|'health'} tier+ * @property {'tip'|'service'|'intel'|'health'|'commerce'|'settle'} kind+ * @property {string|null} network+ * @property {boolean} autobuy+ * @property {number} weight+ * @property {string} businessEffect+ * @property {string} [note]+ */++const NO_BODY = () => null;++/** @type {CatalogEntry[]} */+export const RING_CATALOG = [+ // ── settle ────────────────────────────────────────────────────────────────+ {+ slug: 'ring-settle',+ sourceFile: 'api/x402/ring-settle.js',+ path: '/api/x402/ring-settle',+ method: 'POST',+ body: () => ({ note: 'ring-cycle', seq: 1 }),+ priceAtomicDefault: 1_000_000,+ priceSlug: 'ring-settle',+ tier: 'settle',+ kind: 'settle',+ network: 'solana',+ autobuy: true,+ weight: 1,+ businessEffect: 'Real USDC settlement payer→treasury; returns a signed ring-tick receipt. The ring volume primitive (discoverable:false).',+ },++ // ── commerce (tips & goods bought/sold) ─────────────────────────────────────+ {+ slug: 'dance-tip',+ sourceFile: 'api/x402/dance-tip.js',+ path: '/api/x402/dance-tip',+ method: 'GET',+ query: { dancer: '1', dance: 'rumba' },+ body: NO_BODY,+ priceAtomicDefault: 1_000,+ priceSlug: 'dance-tip',+ tier: 'commerce',+ kind: 'tip',+ network: 'solana',+ autobuy: true,+ weight: 2,+ businessEffect: 'Inserts a row into club_tips (the tip ledger feeding visit tiers + club revenue).',+ },+ {+ slug: 'club-cover',+ sourceFile: 'api/x402/club-cover.js',+ path: '/api/x402/club-cover',+ method: 'GET',+ body: NO_BODY,+ priceAtomicDefault: 10_000,+ priceSlug: 'club-cover',+ tier: 'intel',+ kind: 'commerce',+ network: 'solana',+ autobuy: true,+ weight: 2,+ businessEffect: 'Charges the door cover (settled USDC → x402_audit_log cover record) and mints an admission pass after a ban/visit check.',+ },+ {+ slug: 'club-cover-snapshot',+ sourceFile: 'api/x402/club-cover.js',+ path: '/api/x402/club-cover',+ method: 'POST',+ body: () => ({ mode: 'snapshot', club: 'three_holders' }),+ priceAtomicDefault: 10_000,+ priceSlug: 'club-cover',+ tier: 'intel',+ kind: 'intel',+ network: 'solana',+ autobuy: true,+ weight: 1,+ businessEffect: 'Reads club_tips into a membership snapshot (revenue/analytics surface).',+ },+ {+ slug: 'billboard',+ sourceFile: 'api/x402/billboard.js',+ path: '/api/x402/billboard',+ method: 'GET',+ query: { coin: RING_CANARY_MINT, caption: 'ring canary placement' },+ body: NO_BODY,+ priceAtomicDefault: 50_000,+ priceSlug: 'billboard',+ tier: 'commerce',+ kind: 'commerce',+ network: null,+ autobuy: true,+ weight: 1,+ businessEffect: 'Writes a billboard placement (Redis billboard:<coin>, 6h TTL). Canary targets a synthetic mint so no real coin-world board is overwritten.',+ },+ {+ slug: 'mint-to-mesh-batch',+ sourceFile: 'api/x402/mint-to-mesh-batch.js',+ path: '/api/x402/mint-to-mesh-batch',+ method: 'POST',+ body: () => ({ mints: [WSOL_MINT] }),+ priceAtomicDefault: 50_000,+ priceSlug: 'mint-to-mesh-batch',+ tier: 'commerce',+ kind: 'service',+ network: null,+ autobuy: true,+ weight: 1,+ businessEffect: 'Fetches token metadata via Solana RPC and returns synthesized GLB bytes (read-only, no state written).',+ },++ // ── intel ───────────────────────────────────────────────────────────────────+ {+ slug: 'pump-agent-audit',+ sourceFile: 'api/x402/pump-agent-audit.js',+ path: '/api/x402/pump-agent-audit',+ method: 'GET',+ query: { limit: '10', sort: 'newest' },+ body: NO_BODY,+ priceAtomicDefault: 20_000,+ priceSlug: 'pump-agent-audit',+ tier: 'intel',+ kind: 'intel',+ network: null,+ autobuy: true,+ weight: 1,+ businessEffect: 'Lists recent pump.fun launches cross-referenced against pump_agent_mints (read-only).',+ },+ {+ slug: 'pump-agent-audit-whale',+ sourceFile: 'api/x402/pump-agent-audit.js',+ path: '/api/x402/pump-agent-audit',+ method: 'POST',+ body: () => ({ mode: 'whale_activity', limit: 5 }),+ priceAtomicDefault: 20_000,+ priceSlug: 'pump-agent-audit',+ tier: 'intel',+ kind: 'intel',+ network: null,+ autobuy: true,+ weight: 1,+ businessEffect: 'Scans live pump.fun feeds for whale buys and returns an aggregated signal (read-only).',+ },+ {+ slug: 'three-intel',+ sourceFile: 'api/x402/three-intel.js',+ path: '/api/x402/three-intel',+ method: 'GET',+ body: NO_BODY,+ priceAtomicDefault: 10_000,+ priceSlug: 'three-intel',+ tier: 'intel',+ kind: 'intel',+ network: null,+ autobuy: true,+ weight: 2,+ businessEffect: 'Returns a live $THREE market signal from DexScreener (read-only).',+ },+ {+ slug: 'crypto-intel',+ sourceFile: 'api/x402/crypto-intel.js',+ path: '/api/x402/crypto-intel',+ method: 'POST',+ body: () => ({ topic: 'btc' }),+ priceAtomicDefault: 10_000,+ priceSlug: 'crypto_intel',+ tier: 'intel',+ kind: 'intel',+ network: null,+ autobuy: true,+ weight: 1,+ businessEffect: 'Returns live market intel for the topic (CoinGecko→Coinbase, read-only).',+ },+ {+ slug: 'token-intel',+ sourceFile: 'api/x402/token-intel.js',+ path: '/api/x402/token-intel',+ method: 'GET',+ query: { mint: THREE_MINT },+ body: NO_BODY,+ priceAtomicDefault: 10_000,+ priceSlug: 'token-intel',+ tier: 'intel',+ kind: 'intel',+ network: null,+ autobuy: true,+ weight: 1,+ businessEffect: 'Returns a token market + risk signal for the mint (DexScreener, read-only).',+ },+ {+ slug: 'agent-reputation',+ sourceFile: 'api/x402/agent-reputation.js',+ path: '/api/x402/agent-reputation',+ method: 'POST',+ body: () => ({ mode: 'sweep', limit: 10 }),+ priceAtomicDefault: 10_000,+ priceSlug: 'agent-reputation',+ tier: 'intel',+ kind: 'intel',+ network: null,+ autobuy: true,+ weight: 1,+ // The GET single-agent surface throws on an unknown agent_id; the POST+ // sweep has no record dependency, so the loop uses it.+ businessEffect: 'Sweeps recent agents into a reputation aggregate (read-only).',+ },+ {+ slug: 'agent-bouncer',+ sourceFile: 'api/x402/agent-bouncer.js',+ path: '/api/x402/agent-bouncer',+ method: 'GET',+ query: { agent_id: RING_CANARY_UUID },+ body: NO_BODY,+ priceAtomicDefault: 10_000,+ priceSlug: 'agent-bouncer',+ tier: 'intel',+ kind: 'intel',+ network: null,+ autobuy: true,+ weight: 1,+ businessEffect: 'Vets an agent id against the trust ledger; a canary id returns a newcomer verdict (read-only).',+ },+ {+ slug: 'cross-chain',+ sourceFile: 'api/x402/cross-chain.js',+ path: '/api/x402/cross-chain',+ method: 'POST',+ body: () => ({ mode: 'bridge_status' }),+ priceAtomicDefault: 5_000,+ priceSlug: 'cross_chain_bridge_status',+ tier: 'service',+ kind: 'intel',+ network: null,+ autobuy: true,+ weight: 1,+ businessEffect: 'Probes external bridge status APIs and returns a health signal (read-only).',+ },+ {+ slug: 'analytics',+ sourceFile: 'api/x402/analytics.js',+ path: '/api/x402/analytics',+ method: 'POST',+ body: () => ({ report: 'clubs', period: '24h' }),+ priceAtomicDefault: 5_000,+ priceSlug: 'analytics',+ tier: 'service',+ kind: 'intel',+ network: null,+ autobuy: true,+ weight: 1,+ businessEffect: 'Runs a live analytics report (club/marketplace/revenue aggregates, read-only).',+ },+ {+ slug: 'onchain-identity-verify',+ sourceFile: 'api/x402/onchain-identity-verify.js',+ path: '/api/x402/onchain-identity-verify',+ method: 'GET',+ query: { agent_id: RING_CANARY_UUID, chain: SOLANA_CAIP2, contract_or_mint: THREE_MINT },+ body: NO_BODY,+ priceAtomicDefault: 5_000,+ priceSlug: 'onchain-identity-verify',+ tier: 'service',+ kind: 'intel',+ network: null,+ autobuy: true,+ weight: 1,+ businessEffect: 'Checks the agent→onchain ownership index; a canary id returns verified:false (read-only).',+ },+ {+ slug: 'bazaar-feed',+ sourceFile: 'api/x402/bazaar-feed.js',+ path: '/api/x402/bazaar-feed',+ method: 'POST',+ body: () => ({ filter: 'new', limit: 5 }),+ priceAtomicDefault: 1_000,+ priceSlug: 'bazaar-feed',+ tier: 'health',+ kind: 'intel',+ network: null,+ autobuy: true,+ weight: 1,+ businessEffect: 'Returns the bazaar service discovery feed (read-only).',+ },++ // ── service ─────────────────────────────────────────────────────────────────+ {+ slug: 'unstoppable-status',+ sourceFile: 'api/agents/unstoppable-status.js',+ path: '/api/agents/unstoppable-status',+ method: 'GET',+ body: NO_BODY,+ priceAtomicDefault: 10_000,+ priceSlug: 'unstoppable-status',+ tier: 'intel',+ kind: 'service',+ network: null,+ autobuy: true,+ weight: 1,+ businessEffect: 'Reads and records the agent treasury status (writes its own revenue ledger only).',+ },+ {+ slug: 'symbol-availability-batch',+ sourceFile: 'api/x402/symbol-availability.js',+ path: '/api/x402/symbol-availability',+ method: 'POST',+ body: () => ({ symbols: ['MOON'], network: 'mainnet' }),+ priceAtomicDefault: 5_000,+ priceSlug: 'symbol-availability-batch',+ tier: 'service',+ kind: 'service',+ network: null,+ autobuy: true,+ weight: 1,+ businessEffect: 'Checks symbol collisions against pump_agent_mints for a batch (read-only).',+ },+ {+ slug: 'symbol-availability',+ sourceFile: 'api/x402/symbol-availability.js',+ path: '/api/x402/symbol-availability',+ method: 'GET',+ query: { ticker: 'HELIO', network: 'mainnet' },+ body: NO_BODY,+ priceAtomicDefault: 1_000,+ priceSlug: 'symbol-availability',+ tier: 'health',+ kind: 'service',+ network: null,+ autobuy: true,+ weight: 1,+ businessEffect: 'Checks a single symbol for collision/similarity against pump_agent_mints (read-only).',+ },+ {+ slug: 'skill-marketplace',+ sourceFile: 'api/x402/skill-marketplace.js',+ path: '/api/x402/skill-marketplace',+ method: 'GET',+ body: NO_BODY,+ priceAtomicDefault: 1_000,+ priceSlug: 'skill-marketplace',+ tier: 'health',+ kind: 'service',+ network: null,+ autobuy: true,+ weight: 1,+ // Discovery/analytics surface. The actual per-listing purchase + author+ // royalty is skill-call (dynamic, autobuy:false) below.+ businessEffect: 'Returns the skill marketplace catalog (read-only discovery).',+ },+ {+ slug: 'mcp-tool-catalog',+ sourceFile: 'api/x402/mcp-tool-catalog.js',+ path: '/api/x402/mcp-tool-catalog',+ method: 'POST',+ body: () => ({ mode: 'list' }),+ priceAtomicDefault: 1_000,+ priceSlug: 'mcp-tool-catalog',+ tier: 'health',+ kind: 'service',+ network: null,+ autobuy: true,+ weight: 1,+ businessEffect: 'Returns the MCP tool catalog snapshot in list mode (read-only; discover-mode writes are avoided).',+ },+ {+ slug: 'avatar-optimize-batch',+ sourceFile: 'api/x402/avatar-optimize-batch.js',+ path: '/api/x402/avatar-optimize-batch',+ method: 'POST',+ body: () => ({ limit: 1 }),+ priceAtomicDefault: 1_000,+ priceSlug: 'avatar-optimize-batch',+ tier: 'health',+ kind: 'service',+ network: null,+ autobuy: true,+ weight: 1,+ businessEffect: 'Analyzes one public avatar GLB and upserts avatar_optimization_results (our own table).',+ },++ // ── health (canary/liveness paid endpoints) ─────────────────────────────────+ {+ slug: 'spend-session',+ sourceFile: 'api/x402/spend-session.js',+ path: '/api/x402/spend-session',+ method: 'POST',+ body: () => ({ mode: 'canary', budget: 0.01 }),+ priceAtomicDefault: 10_000,+ priceSlug: 'spend-session',+ tier: 'intel',+ kind: 'health',+ network: 'solana',+ autobuy: true,+ weight: 1,+ businessEffect: 'Exercises the spend-session create/consume cycle and logs to spend_session_health_log.',+ },+ {+ slug: 'telegram-health',+ sourceFile: 'api/x402/telegram-health.js',+ path: '/api/x402/telegram-health',+ method: 'POST',+ body: () => ({ bot: 'changelog' }),+ priceAtomicDefault: 1_000,+ priceSlug: 'telegram-health',+ tier: 'health',+ kind: 'health',+ network: null,+ autobuy: true,+ weight: 1,+ businessEffect: 'Probes the Telegram bot getMe endpoint and returns reachability (read-only + self-expiring alert key).',+ },+ {+ slug: 'api-key-health',+ sourceFile: 'api/x402/api-key-health.js',+ path: '/api/x402/api-key-health',+ method: 'POST',+ body: () => ({ scope: 'autonomous_loop' }),+ priceAtomicDefault: 1_000,+ priceSlug: 'api-key-health',+ tier: 'health',+ kind: 'health',+ network: null,+ autobuy: true,+ weight: 1,+ businessEffect: 'Validates the subscription/internal API key for a scope (read-only).',+ },+ {+ slug: 'did-verify',+ sourceFile: 'api/x402/did.js',+ path: '/api/x402/did',+ method: 'POST',+ body: () => ({ mode: 'verify' }),+ priceAtomicDefault: 1_000,+ priceSlug: 'did_verify',+ tier: 'health',+ kind: 'health',+ network: null,+ autobuy: true,+ weight: 1,+ businessEffect: 'Resolves and verifies the platform DID document (read-only).',+ },+ {+ slug: 'notify',+ sourceFile: 'api/x402/notify.js',+ path: '/api/x402/notify',+ method: 'POST',+ body: () => ({ channel: 'canary', message: 'ring heartbeat', priority: 'low' }),+ priceAtomicDefault: 1_000,+ priceSlug: 'notify',+ tier: 'health',+ kind: 'health',+ network: null,+ autobuy: true,+ weight: 1,+ businessEffect: 'Records a notification into canary_notification_log (no external send).',+ },+ {+ slug: 'auth-health',+ sourceFile: 'api/x402/auth-health.js',+ path: '/api/x402/auth-health',+ method: 'POST',+ body: () => ({ mode: 'session_lifecycle' }),+ priceAtomicDefault: 1_000,+ priceSlug: 'auth_health',+ tier: 'health',+ kind: 'health',+ network: null,+ autobuy: true,+ weight: 1,+ businessEffect: 'Runs the JWT mint/verify/refresh/expire self-test on a synthetic identity (in-process crypto).',+ },+ {+ slug: 'model-validation-sweep',+ sourceFile: 'api/x402/model-validation-sweep.js',+ path: '/api/x402/model-validation-sweep',+ method: 'POST',+ body: () => ({}),+ priceAtomicDefault: 1_000,+ priceSlug: 'model-validation-sweep',+ tier: 'health',+ kind: 'health',+ network: null,+ autobuy: true,+ weight: 1,+ businessEffect: 'Scores the stalest public avatar and upserts model_quality_scores (our own table).',+ },+ {+ slug: 'rate-limit-probe',+ sourceFile: 'api/x402/rate-limit-probe.js',+ path: '/api/x402/rate-limit-probe',+ method: 'POST',+ body: () => ({ endpoint: '/api/x402/crypto-intel' }),+ priceAtomicDefault: 1_000,+ priceSlug: 'rate-limit-probe',+ tier: 'health',+ kind: 'health',+ network: null,+ autobuy: true,+ weight: 1,+ businessEffect: 'Probes a target endpoint 402 price + reads the daily spend budget (read-only).',+ },+ {+ slug: 'wallet-connect-health',+ sourceFile: 'api/x402/wallet-connect.js',+ path: '/api/x402/wallet-connect',+ method: 'POST',+ body: () => ({ mode: 'health' }),+ priceAtomicDefault: 1_000,+ priceSlug: 'wallet-connect-health',+ tier: 'health',+ kind: 'health',+ network: null,+ autobuy: true,+ weight: 1,+ businessEffect: 'Probes the SIWS nonce endpoint and measures latency (read-only).',+ },+ {+ slug: 'solana-register-health',+ sourceFile: 'api/x402/solana-register-health.js',+ path: '/api/x402/solana-register-health',+ method: 'GET',+ body: NO_BODY,+ priceAtomicDefault: 1_000,+ priceSlug: 'solana-register-health',+ tier: 'health',+ kind: 'health',+ network: null,+ autobuy: true,+ weight: 1,+ businessEffect: 'Checks the canary agent registration via Solana RPC and upserts mcp_health_canary (one row).',+ },+ {+ slug: 'feed-health',+ sourceFile: 'api/x402/feed-health.js',+ path: '/api/x402/feed-health',+ method: 'POST',+ body: () => ({ feed: 'changelog_rss' }),+ priceAtomicDefault: 1_000,+ priceSlug: 'feed-health',+ tier: 'health',+ kind: 'health',+ network: 'solana',+ autobuy: true,+ weight: 1,+ businessEffect: 'Fetches and validates the changelog RSS feed against the bundled changelog (read-only).',+ },+ {+ slug: 'schema-check',+ sourceFile: 'api/x402/schema-check.js',+ path: '/api/x402/schema-check',+ method: 'POST',+ body: () => ({ api: 'changelog_json' }),+ priceAtomicDefault: 1_000,+ priceSlug: 'schema-check',+ tier: 'health',+ kind: 'health',+ network: null,+ autobuy: true,+ weight: 1,+ businessEffect: 'Fetches changelog.json and validates it against the published schema (read-only).',+ },++ // ── autobuy:false — covered by one-time verification, not the loop ──────────+ {+ slug: 'pump-launch',+ sourceFile: 'api/x402/pump-launch.js',+ path: '/api/x402/pump-launch',+ method: 'POST',+ body: () => ({ name: 'Helios', symbol: 'HELIO', metadataUri: 'https://ipfs.io/ipfs/QmRingCanaryMetadataPlaceholder' }),+ priceAtomicDefault: 5_000_000,+ priceSlug: 'pump-launch',+ tier: 'commerce',+ kind: 'commerce',+ network: null,+ autobuy: false,+ weight: 0,+ businessEffect: 'Mints a real pump.fun coin on Solana mainnet (~0.022 SOL + a live on-chain token).',+ note: 'autobuy:false — every call deploys a real coin and spends launcher SOL. Verify on devnet or with explicit owner sign-off only.',+ },+ {+ slug: 'endpoint-shopper-run',+ sourceFile: 'api/agents/endpoint-shopper-run.js',+ path: '/api/agents/endpoint-shopper-run',+ method: 'POST',+ body: () => ({ task: 'What is the current price of Ethereum?' }),+ priceAtomicDefault: 10_000,+ priceSlug: 'endpoint-shopper-run',+ tier: 'intel',+ kind: 'service',+ network: null,+ autobuy: false,+ weight: 0,+ businessEffect: 'Orchestrates downstream paid x402 calls (up to $2) plus an LLM plan/synthesis step.',+ note: 'autobuy:false — spends up to maxCostUsd of additional USDC downstream + real LLM tokens per call.',+ },+ {+ slug: 'fact-check',+ sourceFile: 'api/x402/fact-check.js',+ path: '/api/x402/fact-check',+ method: 'POST',+ body: () => ({ claim: 'The Eiffel Tower is 330 meters tall.', strictness: 'low' }),+ priceAtomicDefault: 100_000,+ priceSlug: 'fact-check',+ tier: 'commerce',+ kind: 'intel',+ network: null,+ autobuy: false,+ weight: 0,+ businessEffect: 'Runs a live LLM + web-search + authority-scoring verdict pipeline ($0.10).',+ note: 'autobuy:false — each uncached call burns real LLM tokens + external search quota; priciest catalog intel endpoint.',+ },+ {+ slug: 'llm-proxy',+ sourceFile: 'api/x402/llm-proxy.js',+ path: '/api/x402/llm-proxy',+ method: 'POST',+ body: () => ({ model: 'fast', prompt: 'Count to 3.', max_tokens: 10 }),+ priceAtomicDefault: 5_000,+ priceSlug: 'llm-proxy',+ tier: 'service',+ kind: 'service',+ network: null,+ autobuy: false,+ weight: 0,+ businessEffect: 'Runs a real LLM completion through the provider chain (Groq→OpenRouter→NVIDIA→Anthropic).',+ note: 'autobuy:false — every call burns real LLM provider tokens.',+ },+ {+ slug: 'tutor',+ sourceFile: 'api/x402/tutor.js',+ path: '/api/x402/tutor',+ method: 'POST',+ body: () => ({ question: 'Why does recursion overflow the stack?' }),+ priceAtomicDefault: 10_000,+ priceSlug: 'tutor',+ tier: 'intel',+ kind: 'service',+ network: null,+ autobuy: false,+ weight: 0,+ businessEffect: 'Runs an LLM tutoring answer and appends to the session tab.',+ note: 'autobuy:false — consumes real LLM tokens and writes a session row per call.',+ },+ {+ slug: 'cosmetic-purchase',+ sourceFile: 'api/x402/cosmetic-purchase.js',+ path: '/api/x402/cosmetic-purchase',+ method: 'GET',+ query: { id: 'legendary_crown', account: 'g_ringcanary' },+ body: NO_BODY,+ priceAtomicDefault: 0,+ priceSlug: 'cosmetic-purchase',+ tier: 'commerce',+ kind: 'commerce',+ network: null,+ autobuy: false,+ weight: 0,+ // Price is per-item from api/_lib/cosmetics.js (priceUsdcAtomicsOf), not a+ // priceFor() default — priceAtomicDefault:0 marks "dynamic, see handler".+ businessEffect: 'Grants durable cosmetic ownership, inserts cosmetic_sales, and may send a real on-chain USDC creator payout.',+ note: 'autobuy:false — writes durable ownership, records a sale, and can trigger a real on-chain USDC payout to a third-party creator wallet; price up to several dollars. Verify once with a known premium item id.',+ },+ {+ slug: 'skill-call',+ sourceFile: 'api/x402/skill-call.js',+ path: '/api/x402/skill-call',+ method: 'GET',+ query: { skill: 'wallet-balance' },+ body: NO_BODY,+ priceAtomicDefault: 0,+ priceSlug: 'skill-call',+ tier: 'service',+ kind: 'service',+ network: null,+ autobuy: false,+ weight: 0,+ // Price = the listing's price_per_call_usd → atomics; payee = the skill+ // author's wallet. Depends on a live public, priced marketplace_skills row.+ businessEffect: 'Buys one skill call; settles USDC to the skill author and returns the skill payload.',+ note: 'autobuy:false — pays an author-set price to a third-party author wallet and depends on a live listing slug. Verify once against a known public priced skill.',+ },+ {+ slug: 'service',+ sourceFile: 'api/x402/service.js',+ path: '/api/x402/service',+ method: 'GET',+ body: NO_BODY,+ priceAtomicDefault: 0,+ priceSlug: 'service',+ tier: 'service',+ kind: 'service',+ network: null,+ autobuy: false,+ weight: 0,+ // Per-agent-service dispatcher: /api/x402/service/<slug>. Price, payee and+ // upstream are all row-controlled (agent_paid_services), so it can't be+ // swept generically. Path is the base; the real route carries a slug.+ businessEffect: 'Proxies a paid agent service; settles USDC to the agent wallet and returns the upstream result.',+ note: 'autobuy:false — price/payee/upstream are agent-controlled per agent_paid_services row; not a fixed known endpoint.',+ },+ {+ slug: 'animation-download',+ sourceFile: 'api/x402/animation-download.js',+ path: '/api/x402/animation-download',+ method: 'GET',+ body: NO_BODY,+ priceAtomicDefault: 0,+ priceSlug: 'animation-download',+ tier: 'commerce',+ kind: 'commerce',+ network: null,+ autobuy: false,+ weight: 0,+ businessEffect: 'Returns a presigned download URL for a paid animation clip and bumps its purchase_count.',+ note: 'autobuy:false — price is per animation_clips row and requires a real listed clip id; verify once against a known priced clip.',+ },+ {+ slug: 'asset-download',+ sourceFile: 'api/x402/asset-download.js',+ path: '/api/x402/asset-download',+ method: 'GET',+ body: NO_BODY,+ priceAtomicDefault: 0,+ priceSlug: 'asset-download',+ tier: 'commerce',+ kind: 'commerce',+ network: null,+ autobuy: false,+ weight: 0,+ businessEffect: 'Returns a presigned download URL for a paid asset.',+ note: 'autobuy:false — price is per paid_assets row and requires a real asset slug; verify once against a known asset.',+ },+ {+ slug: 'permit2-paid-demo',+ sourceFile: 'api/x402/permit2-paid-demo.js',+ path: '/api/x402/permit2-paid-demo',+ method: 'GET',+ body: NO_BODY,+ priceAtomicDefault: 1_000,+ priceSlug: 'permit2-paid-demo',+ tier: 'health',+ kind: 'commerce',+ network: null,+ autobuy: false,+ weight: 0,+ businessEffect: 'Settles a Base-mainnet Permit2/EIP-2612 USDC payment and returns the tx hash.',+ note: 'autobuy:false — Base-only, Permit2/EIP-2612-only (no Solana accept). The Solana ring payer structurally cannot pay it; verify with an @x402/evm wallet.',+ },+];++// ── selectors ─────────────────────────────────────────────────────────────────++/** All entries the ring payer may purchase on a loop. */+export function autobuyEntries() {+ return RING_CATALOG.filter((e) => e.autobuy);+}++/** Look up a catalog entry by slug. */+export function bySlug(slug) {+ return RING_CATALOG.find((e) => e.slug === slug) || null;+}++/**+ * Build the round-robin rotation the volume loop / ring tick walks. Each autobuy+ * entry is expanded `weight` times and the copies are INTERLEAVED (round-robin+ * fill) rather than block-repeated, so a batch of N consecutive picks spreads+ * across distinct endpoints instead of clustering weighted duplicates together.+ *+ * A full pass over the returned array touches every autobuy slug at least once;+ * the cursor in the loop advances by its batch size each tick, so coverage is+ * guaranteed within ceil(rotation.length / batch) ticks. See+ * AUTONOMOUS_TICKS_PER_HOUR for the default-cadence math.+ *+ * @returns {CatalogEntry[]}+ */+export function rotationPlan() {+ const entries = autobuyEntries();+ const maxWeight = entries.reduce((m, e) => Math.max(m, e.weight || 1), 1);+ const plan = [];+ for (let pass = 0; pass < maxWeight; pass++) {+ for (const e of entries) {+ if ((e.weight || 1) > pass) plan.push(e);+ }+ }+ return plan;+}++// The x402 autonomous loop cron runs every 5 minutes (vercel.json:+// `/api/cron/x402-autonomous-loop` → `*/5 * * * *`) → 12 ticks/hour. The volume+// loop reserves VOLUME_BATCH_PER_RUN endpoints per tick, so default-cadence+// coverage = 12 * batch selections/hour. With batch 4 that is 48 selections/hour,+// comfortably above the rotation length, so every autobuy endpoint is selected+// at least once per hour. tests/x402-ring-catalog.test.js asserts this holds.+export const AUTONOMOUS_TICKS_PER_HOUR = 12;diff --git a/api/_lib/x402/ring-config.js b/api/_lib/x402/ring-config.jsindex c6f1e9a05..f5d394bac 100644--- a/api/_lib/x402/ring-config.js+++ b/api/_lib/x402/ring-config.js@@ -38,11 +38,14 @@ export const EXTERNAL_FACILITATOR_URL_DEFAULT = 'https://facilitator.payai.netwo// paid-endpoint wiring into this pure config module.const RING_SETTLE_DEFAULT_PRICE_ATOMICS = '1000000';-// Mirrors VOLUME_PER_RUN_CAP_ATOMIC in x402/pipelines/volume-bootstrap-loop.js-// ($0.05 default) — same env var, same default, read here without importing the-// pipeline (task 04 owns it, and it pulls db/pay/web3 at module load).+// Mirrors VOLUME_PER_RUN_CAP_ATOMIC in x402/pipelines/volume-shared.js+// ($1.10 default) — same env var, same default, read here without importing the+// pipeline (it pulls db/pay/web3 at module load). The default was raised from+// $0.05 to $1.10 (task 04) precisely so it accommodates the ring-settle price it+// rotates ($1.00); keep this mirror in lockstep or the price>cap finding below+// false-positives on stock config.function volumePerRunCapAtomic() {- return Math.max(0, Number(process.env.X402_VOLUME_PER_RUN_CAP_ATOMIC || 50_000));+ return Math.max(0, Number(process.env.X402_VOLUME_PER_RUN_CAP_ATOMIC || 1_100_000));}export function selfFacilitatorEnabled() {diff --git a/api/_lib/x402/ring-floors.js b/api/_lib/x402/ring-floors.jsnew file mode 100644index 000000000..0190e2c8a--- /dev/null+++ b/api/_lib/x402/ring-floors.js@@ -0,0 +1,62 @@+// api/_lib/x402/ring-floors.js+//+// Pure floor-evaluation for the three closed-loop ring wallets (payer,+// treasury, sponsor). No network, no @solana imports — balances are passed in,+// verdicts come out. Kept dependency-free on purpose: the balance monitor reads+// the chain and hands the numbers here, and this stays cheap to unit-test and+// impossible to break with an RPC hiccup.+//+// Floors are role-appropriate:+// • sponsor SOL — the fee wallet. Below the facilitator's hard floor+// settlement is refused and the ring halts; we watch a little above it.+// • payer SOL — only in self-pay mode, where the payer signs (and pays) its+// own 1-signature fee, so it needs the same SOL headroom as the sponsor.+// • payer USDC — the recirculating float; below it the daily cap can't fund.+// • treasury — NO floor. It only receives payments and is swept back to the+// payer, so a low balance is its healthy resting state, not an alert.++export const LAMPORTS_PER_SOL = 1_000_000_000;++/**+ * Build the per-role floor spec.+ * @param {object} cfg+ * @param {number} cfg.solFloorLamports SOL floor for sponsor (and payer in self-pay)+ * @param {number} cfg.payerUsdcFloorAtomic USDC float floor for the payer (atomic, 6dp)+ * @param {boolean} cfg.selfPay X402_RING_SELF_PAY — payer pays its own fee+ * @returns {{ role: string, solFloor: number|null, usdcFloor: number|null, watchUsdc: boolean }[]}+ */+export function ringFloorSpecs({ solFloorLamports, payerUsdcFloorAtomic, selfPay }) {+ return [+ { role: 'sponsor', solFloor: solFloorLamports, usdcFloor: null, watchUsdc: false },+ { role: 'payer', solFloor: selfPay ? solFloorLamports : null, usdcFloor: payerUsdcFloorAtomic, watchUsdc: true },+ // Treasury USDC is read for the dashboard but has no floor — informational.+ { role: 'treasury', solFloor: null, usdcFloor: null, watchUsdc: true },+ ];+}++/**+ * Evaluate one wallet's live balances against its floor spec.+ * A null balance (RPC failure) never counts as a breach — we don't fabricate an+ * alert from a missing reading.+ *+ * @param {{ role: string, solFloor: number|null, usdcFloor: number|null }} spec+ * @param {string|null} address+ * @param {number|null} lamports live SOL balance in lamports (null = unknown)+ * @param {number|null} usdcAtomic live USDC balance atomic (null = unknown)+ */+export function evaluateRingWallet(spec, address, lamports, usdcAtomic) {+ if (!address) return { role: spec.role, address: null, configured: false };+ const solLow = spec.solFloor != null && lamports != null && lamports < spec.solFloor;+ const usdcLow = spec.usdcFloor != null && usdcAtomic != null && usdcAtomic < spec.usdcFloor;+ return {+ role: spec.role,+ 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,+ };+}diff --git a/api/_lib/x402/ring-tick-plan.js b/api/_lib/x402/ring-tick-plan.jsnew file mode 100644index 000000000..827179d8f--- /dev/null+++ b/api/_lib/x402/ring-tick-plan.js@@ -0,0 +1,110 @@+// api/_lib/x402/ring-tick-plan.js+//+// Pure planning + guard logic for the per-minute ring tick+// (api/cron/x402-ring-tick.js). No network, no DB, no @solana/web3.js — every+// function here is deterministic given its inputs, so the ring tick's cadence,+// cap arithmetic, back-pressure decisions, and config gating are all unit-tested+// (tests/x402-ring-tick.test.js) without touching the chain.+//+// The cron does the I/O (probe, sign, settle, log); this module decides WHAT to+// do each minute and WHETHER it is safe to do it.++// ── Config knobs ────────────────────────────────────────────────────────────────+// Read once per tick. Defaults are chosen to cohere with the stock ring-settle+// price ($1.00): the per-tick cap fits one ring-settle plus the cheap calls that+// ride alongside it, and the daily cap bounds gross throughput. See+// docs/x402-ring-economy.md "Cadence".+export function ringTickConfig(e = process.env) {+ const num = (v, d) => {+ const n = Number(v);+ return Number.isFinite(n) && n >= 0 ? n : d;+ };+ return {+ // Kill switch: default ON. Only an explicit "false" disables it (subject to+ // validateRingConfig() being clean — the cron enforces that separately).+ enabled: String(e.X402_RING_TICK_ENABLED ?? '').trim().toLowerCase() !== 'false',+ // Paid calls to attempt per minute.+ calls: Math.max(1, Math.floor(num(e.X402_RING_TICK_CALLS, 3))),+ // Fire one ring-settle every Nth tick (0 disables the settle carrier).+ settleEveryN: Math.max(0, Math.floor(num(e.X402_RING_SETTLE_EVERY_N_TICKS, 5))),+ // Spend ceiling for a single tick (atomics). Must fit a ring-settle tick:+ // ring-settle price + (calls-1) cheap calls. Default $1.10.+ tickCapAtomic: num(e.X402_RING_TICK_CAP_ATOMIC, 1_100_000),+ // Ring tick's OWN daily ceiling (atomics), summed from x402_autonomous_log+ // rows tagged pipeline='ring-tick'. Separate from the autonomous loop's+ // X402_AUTONOMOUS_DAILY_CAP_ATOMIC — the two budgets never touch. Default $50.+ dailyCapAtomic: num(e.X402_RING_DAILY_CAP_ATOMIC, 50_000_000),+ // Sponsor/payer SOL floor (lamports). Mirrors self-facilitator's+ // SPONSOR_SOL_FLOOR_LAMPORTS default (0.02 SOL) — below it, settlement is+ // paused, so we skip the tick rather than fire calls that will 502.+ solFloorLamports: num(e.X402_SPONSOR_SOL_FLOOR_LAMPORTS, 20_000_000),+ };+}++// ── Cadence: which endpoints does this tick pay? ────────────────────────────────+// Weighted rotation: cheap tips/services dominate the count; every Nth tick one of+// the slots is the ring-settle carrier. `tickSeq` is a monotonic per-minute+// counter (Redis-backed in the cron, in-memory fallback), `cheapStart` is the+// reserved cheap-rotation cursor. Pure: same inputs → same plan.+//+// Returns { isSettleTick, cheapNeeded, cheapIndices } where cheapIndices index+// into the CHEAP_ENDPOINTS catalog (ring-settle excluded).+export function planTick({ tickSeq, calls, settleEveryN, cheapCount, cheapStart = 0 }) {+ const isSettleTick = settleEveryN > 0 && cheapCount >= 0+ && Number.isFinite(tickSeq) && (tickSeq % settleEveryN === 0);+ const settleCalls = isSettleTick ? 1 : 0;+ const cheapNeeded = Math.max(0, calls - settleCalls);+ const cheapIndices = [];+ for (let i = 0; i < cheapNeeded && cheapCount > 0; i++) {+ cheapIndices.push(((cheapStart + i) % cheapCount + cheapCount) % cheapCount);+ }+ return { isSettleTick, cheapNeeded, cheapIndices };+}++// The largest single payment this tick could attempt — used to size the minimum+// payer USDC balance we require before firing (so we never start a tick we can't+// afford and trigger a settle failure). On a settle tick that is the ring-settle+// price; otherwise a small tip headroom.+export function minUsdcForTick({ isSettleTick, ringSettlePriceAtomic, tipHeadroomAtomic = 20_000 }) {+ return isSettleTick ? Math.max(ringSettlePriceAtomic, tipHeadroomAtomic) : tipHeadroomAtomic;+}++// ── Budget arithmetic ───────────────────────────────────────────────────────────+// Remaining ring-tick daily budget, and the effective cap for THIS tick (the+// smaller of the per-tick cap and what's left in the day). Never negative.+export function dailyRemaining(dailySpentAtomic, dailyCapAtomic) {+ return Math.max(0, dailyCapAtomic - dailySpentAtomic);+}+export function tickBudget(dailySpentAtomic, dailyCapAtomic, tickCapAtomic) {+ return Math.max(0, Math.min(tickCapAtomic, dailyRemaining(dailySpentAtomic, dailyCapAtomic)));+}++// ── Back-pressure ───────────────────────────────────────────────────────────────+// Decide, BEFORE paying, whether the tick is safe to run. Returns+// { ok, reason }. A false-with-reason is a clean no-op (logged + one throttled+// alert), never a retry-storm of failing settles. Order matters: RPC/context+// failure first, then SOL floor (settlement paused), then payer USDC.+export function assessBackpressure({ solLamports, usdcAtomic, floorLamports, minUsdcAtomic }) {+ if (!Number.isFinite(solLamports)) return { ok: false, reason: 'rpc_balance_unavailable' };+ if (solLamports < floorLamports) {+ return { ok: false, reason: 'sponsor_sol_floor', detail: `${solLamports}<${floorLamports}` };+ }+ if (!Number.isFinite(usdcAtomic)) return { ok: false, reason: 'rpc_balance_unavailable' };+ if (usdcAtomic < minUsdcAtomic) {+ return { ok: false, reason: 'insufficient_payer_usdc', detail: `${usdcAtomic}<${minUsdcAtomic}` };+ }+ return { ok: true, reason: null };+}++// ── Config gate ─────────────────────────────────────────────────────────────────+// validateRingConfig() returns findings [{ code, severity, message, fix }].+// The tick runs only when there are no ERROR-severity findings — those mean+// settlement would route to a third party or can't be built at all, which is the+// one thing the ring must never do. WARN findings (sponsor mode, missing+// rebalancer) degrade economics but still settle in-house, so they are logged,+// not blocking. Returns { blocked, errors, warnings }.+export function gateOnRingConfig(findings = []) {+ const errors = findings.filter((f) => f?.severity === 'error');+ const warnings = findings.filter((f) => f?.severity !== 'error');+ return { blocked: errors.length > 0, errors, warnings };+}diff --git a/api/_lib/x402/wallet-balance-monitor.js b/api/_lib/x402/wallet-balance-monitor.jsindex 1596ce1ad..89e224839 100644--- a/api/_lib/x402/wallet-balance-monitor.js+++ b/api/_lib/x402/wallet-balance-monitor.js@@ -43,6 +43,7 @@ import { randomUUID } from 'node:crypto';import { fetchWithTimeout, loadSeedKeypair, USDC_MINT } from './pay.js';import { SPONSOR_SOL_FLOOR_LAMPORTS } from './self-facilitator.js';+import { ringFloorSpecs, evaluateRingWallet, LAMPORTS_PER_SOL } from './ring-floors.js';import { sql as defaultSql } from '../db.js';import { env } from '../env.js';import { sendOpsAlert } from '../alerts.js';@@ -51,8 +52,6 @@ import { logger } from '../usage.js';const log = logger('x402-wallet-balance-monitor');-const LAMPORTS_PER_SOL = 1_000_000_000;-// ── Ring-wallet floors ──────────────────────────────────────────────────────// The closed-loop ring has three platform-controlled wallets (payer, treasury,// sponsor). Each has a role-appropriate floor the monitor watches so the loop@@ -210,78 +209,80 @@ function resolveRingAddresses() {* 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.+ * The floor math lives in ring-floors.js (pure, dependency-free) so it can be+ * unit-tested without a chain. Here we resolve addresses, read balances, hand+ * them to the evaluator, and fire alerts on breach.+ *+ * @param {object} ctx — all optional:+ * { redis } cheap-read snapshot sink+ * { readBalance } async (address) => { lamports, usdcAtomic } — override the+ * on-chain reader (used by tests to avoid RPC + spl-token)+ * { sendAlert } override sendOpsAlert (tests assert on it)* @returns {Promise<{ configured: boolean, wallets: object[], breaches: string[] }>}*/export async function checkRingWallets(ctx = {}) {const redis = ctx.redis || null;+ const sendAlert = ctx.sendAlert || sendOpsAlert;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' };- }+ // On-chain balance reader — injectable for tests. Reads SOL always and USDC+ // only for the roles that watch it (payer float, treasury for the dashboard).+ let conn = null;+ const readBalance = ctx.readBalance || (async (address, watchUsdc) => {+ if (!conn) conn = solanaConnection({ url: env.SOLANA_RPC_URL, commitment: 'confirmed' });+ return {+ lamports: await readSol(conn, address),+ usdcAtomic: watchUsdc ? await readUsdc(conn, address) : null,+ };+ });- // 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 specs = ringFloorSpecs({+ solFloorLamports: RING_SOL_FLOOR_LAMPORTS,+ payerUsdcFloorAtomic: RING_PAYER_USDC_FLOOR_ATOMIC,+ selfPay,+ });+ const addrFor = { sponsor: addrs.sponsor, payer: addrs.payer, treasury: addrs.treasury };const wallets = [];const breaches = [];for (const spec of specs) {- if (!spec.address) {+ const address = addrFor[spec.role] || null;+ if (!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,- };+ let lamports = null;+ let usdcAtomic = null;+ try {+ ({ lamports, usdcAtomic } = await readBalance(address, spec.watchUsdc));+ } catch (err) {+ log.warn('ring_balance_read_failed', { role: spec.role, message: err?.message });+ }+ const entry = evaluateRingWallet(spec, address, lamports, usdcAtomic);wallets.push(entry);- if (solLow) {+ if (entry.sol_low) {breaches.push(`${spec.role} SOL ${entry.sol.toFixed(4)} < floor ${entry.sol_floor.toFixed(4)}`);- await sendOpsAlert(+ await sendAlert(`⛽ 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. ` ++ `${spec.role} ${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}` },+ { signature: `x402-ring-sol-low:${address}` },);}- if (usdcLow) {+ if (entry.usdc_low) {breaches.push(`${spec.role} USDC ${entry.usdc.toFixed(2)} < floor ${entry.usdc_floor.toFixed(2)}`);- await sendOpsAlert(+ await sendAlert(`💵 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. ` ++ `${spec.role} ${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}` },+ { signature: `x402-ring-usdc-low:${address}` },);}}diff --git a/api/cron/x402-ring-leak-scan.js b/api/cron/x402-ring-leak-scan.jsindex e0f51806e..29d4b539a 100644--- a/api/cron/x402-ring-leak-scan.js+++ b/api/cron/x402-ring-leak-scan.js@@ -352,7 +352,7 @@ async function ringScanWallets() {// ── Per-wallet scan ───────────────────────────────────────────────────────────-async function scanWallet(conn, PublicKey, wallet, { allowed, usdcMint, runId, feeByDay }) {+export 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);diff --git a/api/cron/x402-ring-tick.js b/api/cron/x402-ring-tick.jsnew file mode 100644index 000000000..ca5d95989--- /dev/null+++ b/api/cron/x402-ring-tick.js@@ -0,0 +1,345 @@+// GET /api/cron/x402-ring-tick+//+// Per-minute ring tick — the driver that makes three.ws's x402 endpoints get hit+// every minute, many times: tips, services, and settlements bought and sold on a+// continuous cadence, all inside hard caps and settled by the self-hosted+// facilitator so no third party ever touches ring money.+//+// The 5-minute autonomous loop (x402-autonomous-loop.js) already sweeps the+// catalog, but at 300s cooldowns and a $0.05 per-run cap the flagship ring-settle+// ($1.00) was skipped every cycle. This cron runs EVERY MINUTE with its own,+// separate budget and a weighted rotation:+//+// • X402_RING_TICK_CALLS paid calls per minute (default 3), cheap tips/services+// ($0.001–$0.01) dominating the count so the platform shows constant activity.+// • one ring-settle at X402_PRICE_RING_SETTLE every X402_RING_SETTLE_EVERY_N_TICKS+// ticks (default 5) to carry real volume cheaply (fewer, larger payments —+// the fee-optimal lever; see docs/x402-ring-economy.md "Cadence").+//+// Budgets (both enforced, both SEPARATE from the autonomous loop's daily cap):+// • X402_RING_TICK_CAP_ATOMIC per-tick spend ceiling (default $1.10 — fits one+// ring-settle plus its cheap co-riders).+// • X402_RING_DAILY_CAP_ATOMIC ring-tick daily ceiling (default $50), summed+// from x402_autonomous_log rows tagged pipeline='ring-tick'. The autonomous+// loop's Redis spend accumulator is never touched.+//+// Safety:+// • Kill switches: X402_AUTONOMOUS_ENABLED=false (global) OR+// X402_RING_TICK_ENABLED=false (this driver) → clean skip.+// • Config gate: runs only when validateRingConfig() reports no ERROR findings+// (settlement routes in-house and is buildable); WARN findings are logged.+// • Back-pressure: below the SOL floor, insufficient payer USDC, or an RPC+// fault → skip the whole tick with a structured log row and ONE throttled+// ops alert (max 1/hour per reason). Never a retry-storm of failing settles.+//+// Real on-chain payments only — no mocks. Shares the ONE payment + recording path+// (pipelines/volume-shared.js) with the volume loop.++import { randomUUID } from 'node:crypto';+import { PublicKey } from '@solana/web3.js';+import {+ getAssociatedTokenAddressSync, getAccount, getMint,+ TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,+} from '@solana/spl-token';++import { json, wrapCron } from '../_lib/http.js';+import { env } from '../_lib/env.js';+import { constantTimeEquals } from '../_lib/crypto.js';+import { getRedis } from '../_lib/redis.js';+import { sql } from '../_lib/db.js';+import { solanaConnection } from '../_lib/solana/connection.js';+import { logger } from '../_lib/usage.js';+import { sendOpsAlert } from '../_lib/alerts.js';+import { priceFor } from '../_lib/x402-prices.js';+import { loadSeedKeypair, payX402, USDC_MINT, SOLANA_RPC } from '../_lib/x402/pay.js';+import { validateRingConfig } from '../_lib/x402/ring-config.js';+import {+ ASSET,+ RING_SETTLE_ENDPOINT,+ CHEAP_ENDPOINTS,+ ensureVolumeSchema,+ settleAndRecord,+} from '../_lib/x402/pipelines/volume-shared.js';+import {+ ringTickConfig,+ planTick,+ minUsdcForTick,+ tickBudget,+ assessBackpressure,+ gateOnRingConfig,+} from '../_lib/x402/ring-tick-plan.js';++const log = logger('x402-ring-tick');++const ORIGIN = () => env.APP_ORIGIN || 'https://three.ws';+const RING_SETTLE_DEFAULT_PRICE = '1000000'; // $1.00 — mirrors ring-settle.js++// Redis keys: a monotonic per-minute tick counter and the cheap-rotation cursor.+// Independent of the volume loop's cursor so the two drivers rotate separately.+const TICK_SEQ_KEY = 'x402:ring:tick:seq';+const CHEAP_CURSOR_KEY = 'x402:ring:tick:cheap';+let _memTickSeq = 0;+let _memCheapCursor = 0;++function requireCron(req, res) {+ const secret = process.env.CRON_SECRET || env.CRON_SECRET;+ if (!secret) { json(res, 503, { error: 'CRON_SECRET unset' }); return false; }+ const auth = req.headers['authorization'] || '';+ const token = auth.startsWith('Bearer ') ? auth.slice(7) : '';+ if (!constantTimeEquals(token, secret)) { json(res, 401, { error: 'unauthorized' }); return false; }+ return true;+}++// Advance the durable per-minute counter (Redis INCR, in-memory fallback).+async function nextTickSeq(redis) {+ if (redis) {+ try { return Number(await redis.incr(TICK_SEQ_KEY)); } catch { /* fall through */ }+ }+ return (_memTickSeq += 1);+}++// Reserve the next `count` cheap-rotation indices, returning the start cursor.+async function reserveCheapCursor(redis, count) {+ if (count <= 0) return 0;+ if (redis) {+ try {+ const end = Number(await redis.incrby(CHEAP_CURSOR_KEY, count));+ return end - count;+ } catch { /* fall through */ }+ }+ const start = _memCheapCursor;+ _memCheapCursor += count;+ return start;+}++// Sum of ring-tick spend so far this UTC day (paid amounts only — settleAndRecord+// records 0 for non-paid calls). Separate from the autonomous loop's budget by+// construction: it filters on pipeline='ring-tick'.+async function ringDailySpent() {+ const since = new Date(new Date().toISOString().slice(0, 10) + 'T00:00:00.000Z');+ const rows = await sql`+ SELECT COALESCE(SUM(amount_atomic), 0)::bigint AS spent+ FROM x402_autonomous_log+ WHERE pipeline = 'ring-tick' AND ts >= ${since}+ `;+ return Number(rows[0]?.spent || 0);+}++// One structured, queryable row for a skipped/failed tick. Every non-paying tick+// outcome leaves a trail (task 04 constraint). Wrapped — a DB fault never crashes+// the cron.+async function recordSkip(runId, origin, reason, extra = {}) {+ try {+ await sql`+ INSERT INTO x402_autonomous_log+ (run_id, endpoint_type, service_name, endpoint_url,+ network, amount_atomic, asset, success, error_msg, pipeline, value_extracted)+ VALUES+ (${runId}, ${'self'}, ${'Ring Tick'}, ${`${origin}/api/cron/x402-ring-tick`},+ ${'solana:mainnet'}, ${0}, ${ASSET}, ${false}, ${reason}, ${'ring-tick'},+ ${JSON.stringify({ skipped: true, reason, ...extra })})+ `;+ } catch (err) {+ log.warn('ring_tick_skip_log_failed', { reason, message: err?.message });+ }+}++// Does a paid result carry a facilitator SOL-floor signal? (Back-pressure that+// appeared mid-tick — the pre-flight check passed but the floor was crossed.)+function isFloorSignal(result) {+ const hay = `${result?.errorMsg || ''} ${JSON.stringify(result?.responseBody || '')}`;+ return /below_floor|sol_floor|fee_wallet_below/i.test(hay);+}++export default wrapCron(async (req, res) => {+ if (req.method !== 'GET') return json(res, 405, { error: 'method_not_allowed' });+ if (!requireCron(req, res)) return;++ const origin = ORIGIN();++ // ── Kill switches ─────────────────────────────────────────────────────────+ if (process.env.X402_AUTONOMOUS_ENABLED === 'false') {+ return json(res, 200, { ok: true, skipped: true, reason: 'X402_AUTONOMOUS_ENABLED=false' });+ }+ const cfg = ringTickConfig();+ if (!cfg.enabled) {+ return json(res, 200, { ok: true, skipped: true, reason: 'X402_RING_TICK_ENABLED=false' });+ }++ // ── Config gate: only run with a clean (no-error) ring envelope ────────────+ const findings = validateRingConfig();+ const gate = gateOnRingConfig(findings);+ if (gate.warnings.length) {+ log.warn('ring_tick_config_warnings', { warnings: gate.warnings.map((w) => w.code) });+ }+ if (gate.blocked) {+ log.warn('ring_tick_config_blocked', { errors: gate.errors.map((e) => e.code) });+ return json(res, 200, {+ ok: true,+ skipped: true,+ reason: 'ring_config_invalid',+ findings: gate.errors,+ });+ }++ const runId = randomUUID();+ const redis = getRedis();++ // ── Payer keypair ─────────────────────────────────────────────────────────+ let payer;+ try { payer = loadSeedKeypair(); } catch (err) {+ return json(res, 200, { ok: false, skipped: true, reason: err.message });+ }++ if (redis) {+ try { await redis.ping(); } catch (err) {+ return json(res, 200, { ok: false, skipped: true, reason: `redis_unavailable: ${err?.message}` });+ }+ }++ // ── Schema (shared ledger + log column) ────────────────────────────────────+ try {+ await ensureVolumeSchema(sql);+ } catch (err) {+ return json(res, 200, { ok: false, skipped: true, reason: `schema_failed: ${err?.message}` });+ }++ // ── Shared Solana state (one blockhash per tick) ──────────────────────────+ const conn = solanaConnection({ url: SOLANA_RPC, commitment: 'confirmed' });+ let blockhash, mintInfo;+ try {+ [{ blockhash }, mintInfo] = await Promise.all([+ conn.getLatestBlockhash('confirmed'),+ getMint(conn, new PublicKey(USDC_MINT)),+ ]);+ } catch (err) {+ await recordSkip(runId, origin, 'rpc_preflight_failed', { message: err?.message });+ await sendOpsAlert('x402 ring tick paused: RPC preflight failed', String(err?.message || err), { signature: 'ring-tick:rpc' });+ return json(res, 200, { ok: false, skipped: true, reason: `rpc_preflight_failed: ${err?.message}`, run_id: runId });+ }++ // ── Plan this tick (durable cadence counters) ──────────────────────────────+ const tickSeq = await nextTickSeq(redis);+ const isSettleTick = cfg.settleEveryN > 0 && (tickSeq % cfg.settleEveryN === 0) && !!RING_SETTLE_ENDPOINT;+ const cheapNeeded = Math.max(0, cfg.calls - (isSettleTick ? 1 : 0));+ const cheapStart = await reserveCheapCursor(redis, cheapNeeded);+ const plan = planTick({+ tickSeq,+ calls: cfg.calls,+ settleEveryN: RING_SETTLE_ENDPOINT ? cfg.settleEveryN : 0,+ cheapCount: CHEAP_ENDPOINTS.length,+ cheapStart,+ });++ // ── Back-pressure pre-flight (never fire calls that will 502) ──────────────+ const ringSettlePriceAtomic = Number(priceFor('ring-settle', RING_SETTLE_DEFAULT_PRICE));+ let solLamports = Number.NaN;+ try { solLamports = await conn.getBalance(payer.publicKey); } catch { solLamports = Number.NaN; }+ // If SOL read succeeded the RPC is up, so a missing ATA means 0 USDC (not a+ // fault); only a genuine read failure leaves it NaN → rpc_balance_unavailable.+ let usdcAtomic = 0;+ try {+ const payerAta = getAssociatedTokenAddressSync(+ new PublicKey(USDC_MINT), payer.publicKey, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,+ );+ usdcAtomic = Number((await getAccount(conn, payerAta)).amount);+ } catch { usdcAtomic = Number.isFinite(solLamports) ? 0 : Number.NaN; }++ const minUsdc = minUsdcForTick({ isSettleTick: plan.isSettleTick, ringSettlePriceAtomic });+ const bp = assessBackpressure({+ solLamports, usdcAtomic, floorLamports: cfg.solFloorLamports, minUsdcAtomic: minUsdc,+ });+ if (!bp.ok) {+ await recordSkip(runId, origin, bp.reason, {+ detail: bp.detail, sol_lamports: Number.isFinite(solLamports) ? solLamports : null,+ usdc_atomic: Number.isFinite(usdcAtomic) ? usdcAtomic : null, min_usdc_atomic: minUsdc,+ });+ await sendOpsAlert(+ `x402 ring tick paused: ${bp.reason}`,+ `sol=${solLamports} usdc=${usdcAtomic} floor=${cfg.solFloorLamports} min_usdc=${minUsdc}`,+ { signature: `ring-tick:${bp.reason}` },+ );+ log.warn('ring_tick_backpressure', { reason: bp.reason, detail: bp.detail });+ return json(res, 200, { ok: true, skipped: true, reason: bp.reason, run_id: runId });+ }++ // ── Daily cap ──────────────────────────────────────────────────────────────+ let dailySpent = 0;+ try { dailySpent = await ringDailySpent(); } catch (err) {+ log.warn('ring_tick_daily_query_failed', { message: err?.message });+ }+ let remaining = tickBudget(dailySpent, cfg.dailyCapAtomic, cfg.tickCapAtomic);+ if (remaining <= 0) {+ await recordSkip(runId, origin, 'ring_daily_cap_reached', {+ daily_spent_atomic: dailySpent, daily_cap_atomic: cfg.dailyCapAtomic,+ });+ log.info('ring_tick_daily_cap_reached', { spent: dailySpent, cap: cfg.dailyCapAtomic });+ return json(res, 200, {+ ok: true, skipped: true, reason: 'ring_daily_cap_reached',+ daily_spent_usdc: (dailySpent / 1e6).toFixed(4), run_id: runId,+ });+ }++ // ── Build the ordered pick list for this tick ─────────────────────────────+ const picks = [];+ if (plan.isSettleTick) picks.push(RING_SETTLE_ENDPOINT);+ for (const idx of plan.cheapIndices) picks.push(CHEAP_ENDPOINTS[idx]);++ // ── Pay each pick through the shared path ─────────────────────────────────+ const payCtx = { buyer: payer, conn, blockhash, mintInfo };+ const results = [];+ let paid = 0, calls = 0, errors = 0, spent = 0, lastTxSig = null;+ let floorHit = false;++ for (const ep of picks) {+ if (remaining <= 0) {+ log.info('ring_tick_cap_reached', { endpoint: ep.key, spent_atomic: spent });+ break;+ }+ const { result, paidAmount } = await settleAndRecord({+ sql, runId, ep, origin, remaining, ctx: payCtx,+ pipeline: 'ring-tick', namePrefix: 'Ring', payFn: payX402, log,+ });+ calls += 1;+ if (!result.success) errors += 1;+ if (result.paid) {+ paid += 1; spent += paidAmount; remaining -= paidAmount;+ if (result.txSig) lastTxSig = result.txSig;+ }+ results.push({ key: ep.key, paid: result.paid === true, success: result.success, status: result.status, amount_usdc: paidAmount / 1e6 });++ // Mid-tick back-pressure: the floor was crossed after pre-flight. Stop the+ // tick (don't keep firing settles that will fail) and alert once.+ if (!result.success && isFloorSignal(result)) { floorHit = true; break; }+ }++ if (floorHit) {+ await sendOpsAlert(+ 'x402 ring tick paused: sponsor_sol_floor (mid-tick)',+ `fee wallet crossed the SOL floor mid-tick; stopped after ${calls} calls`,+ { signature: 'ring-tick:sponsor_sol_floor' },+ );+ log.warn('ring_tick_floor_midtick', { run_id: runId, calls });+ }++ log.info('ring_tick_complete', {+ run_id: runId, tick_seq: tickSeq, settle_tick: plan.isSettleTick,+ calls, paid, errors, spent_usdc: (spent / 1e6).toFixed(4),+ payer: payer.publicKey.toBase58(),+ });++ return json(res, 200, {+ ok: true,+ run_id: runId,+ tick_seq: tickSeq,+ settle_tick: plan.isSettleTick,+ calls,+ paid,+ errors,+ spent_usdc: (spent / 1e6).toFixed(4),+ daily_spent_usdc: ((dailySpent + spent) / 1e6).toFixed(4),+ daily_cap_usdc: (cfg.dailyCapAtomic / 1e6).toFixed(2),+ tick_cap_usdc: (cfg.tickCapAtomic / 1e6).toFixed(2),+ results,+ });+});diff --git a/api/x402/api-key-health.js b/api/x402/api-key-health.jsindex 7bc5bd273..38c9ada70 100644--- a/api/x402/api-key-health.js+++ b/api/x402/api-key-health.js@@ -141,10 +141,24 @@ export default paidEndpoint({serviceName: 'three.ws API Key Health Check',tags: ['health', 'api-key', 'autonomous', 'access-control'],}),- async handler(req) {+ async handler({ req }) {const checkedAt = new Date().toISOString();+ // paidEndpoint invokes handler({ req, res, ... }); read the client body off+ // the real request. Vercel does not reliably pre-parse it for these POST+ // routes, so drain the stream (falling back to a pre-parsed req.body when+ // present) rather than trusting req.body — which was always undefined here+ // and silently pinned scope to the default.let body = {};- try { body = typeof req.body === 'object' ? req.body : JSON.parse(req.body || '{}'); } catch { /* use empty */ }+ if (req.body && typeof req.body === 'object') {+ body = req.body;+ } else {+ try {+ const chunks = [];+ for await (const c of req) chunks.push(c);+ const raw = Buffer.concat(chunks).toString('utf8');+ if (raw) body = JSON.parse(raw);+ } catch { /* tolerate an empty/unparseable body → default scope */ }+ }const scope = (typeof body?.scope === 'string' && body.scope.trim()) || 'autonomous_loop';// 1. Check for a dedicated subscription key covering this scope.diff --git a/api/x402/feed-health.js b/api/x402/feed-health.jsindex 1b887b2e1..94549db76 100644--- a/api/x402/feed-health.js+++ b/api/x402/feed-health.js@@ -216,7 +216,20 @@ export default paidEndpoint({requiredScope: 'x402:bypass',accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),async handler({ req }) {- const body = req.body || {};+ // Drain the stream — Vercel does not reliably pre-parse req.body for this+ // POST route, and `feed` is required, so trusting req.body would 400 every+ // paid call. Fall back to a pre-parsed body when the runtime supplies one.+ let body = {};+ if (req.body && typeof req.body === 'object') {+ body = req.body;+ } else {+ try {+ const chunks = [];+ for await (const c of req) chunks.push(c);+ const raw = Buffer.concat(chunks).toString('utf8');+ if (raw) body = JSON.parse(raw);+ } catch { /* tolerate an empty/unparseable body → unsupported_feed below */ }+ }const feed = String(body.feed || '').trim();if (!SUPPORTED_FEEDS.includes(feed)) {diff --git a/api/x402/rate-limit-probe.js b/api/x402/rate-limit-probe.jsindex 644de652b..6d03ed534 100644--- a/api/x402/rate-limit-probe.js+++ b/api/x402/rate-limit-probe.js@@ -194,7 +194,21 @@ export default paidEndpoint({accessControl: installAccessControl({ requiredScope: 'x402:bypass' }),async handler({ req }) {- const body = req.body || {};+ // Drain the stream — Vercel does not reliably pre-parse req.body for this+ // POST route, and `endpoint` is required, so trusting req.body would 400+ // every paid call. Fall back to a pre-parsed body when the runtime supplies+ // one.+ let body = {};+ if (req.body && typeof req.body === 'object') {+ body = req.body;+ } else {+ try {+ const chunks = [];+ for await (const c of req) chunks.push(c);+ const raw = Buffer.concat(chunks).toString('utf8');+ if (raw) body = JSON.parse(raw);+ } catch { /* tolerate an empty/unparseable body → missing_endpoint below */ }+ }const endpoint = typeof body.endpoint === 'string' ? body.endpoint.trim() : '';if (!endpoint) {diff --git a/api/x402/wallet-connect.js b/api/x402/wallet-connect.jsindex 8d7698a81..ae4d80334 100644--- a/api/x402/wallet-connect.js+++ b/api/x402/wallet-connect.js@@ -15,9 +15,9 @@// a malformed challenge, or timed out (> 3s). Wallet connect is degraded.//// The autonomous loop pays this probe every 5 min and records the verdict to-// x402_autonomous_log (signal_data: { session_created, latency_ms }). A Redis-// alert key (x402:wallet-connect:alert) is set on degradation and cleared on-// recovery — same convention as the forge-health and DID-sweep alerts.+// x402_autonomous_log (signal_data: { session_created, latency_ms }); alerting+// on a degraded verdict is handled by the loop's downstream monitors, not by+// this handler.//// Pay-per-call: $0.001 USDC on Solana or Base mainnet.diff --git a/data/changelog.json b/data/changelog.jsonindex fa47dd1e8..c815ed878 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,41 @@{"$comment": "Curated changelog entries for three.ws \u2014 the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-07-03",+ "title": "Leak-proofing the closed-loop economy: fail-closed spend guards + an on-chain leak scanner",+ "summary": "The rule behind the closed-loop agent economy is simple: no dollar and no SOL ever leaves the wallets the platform controls. Until now the safeguards that enforced it were passive — a couple of configuration switches that, if flipped or forgotten, could quietly re-open spending to the outside world, and nothing actually watched the blockchain to confirm money wasn't leaving. Both gaps are now closed. Before the economy spends anything, it re-checks the three switches that keep the loop sealed — external spending off, no charity split, settlements routed only through the platform's own settlement service — and if any of them is wrong it stops spending entirely and pages operators, naming the switch that changed. Separately, a new monitor reads the chain itself every ten minutes: for each ring wallet it inspects every recent transaction and flags anything that moved value to an address the platform doesn't control — a stablecoin payment to a stranger, any non-stablecoin token leaving, an unexplained SOL debit, or a permission grant that would let someone else move funds later. Any such finding pages operators within minutes with the transaction, the counterparty, the amount, and the exact recovery steps, and is filed on the same financial-integrity board as the rest of the platform's money checks. It also tallies the network fees the wallets actually paid and cross-checks them against the books, so fees paid outside the accounting get caught too. The monitor only ever reads the chain — it never moves funds or touches keys.",+ "tags": [+ "security"+ ]+ },+ {+ "date": "2026-07-03",+ "title": "Ring wallets: watched for drain, auto-refilled, and verifiable in one command",+ "summary": "The three platform wallets that power the closed-loop agent economy — the one that pays, the one that receives, and the one that covers network fees — are now monitored and self-healing so the loop can run unattended without silently stalling or draining. A balance monitor checks all three on-chain every ten minutes and pages operators before trouble: the fee and paying wallets alert when their SOL dips near the level where settlements would be refused, and the paying wallet alerts when its USDC float runs low. The receiving wallet is intentionally left unbounded — it fills up and gets swept back automatically, so a low balance there is healthy, not a problem. The fee and paying wallets are also registered with the platform's funding root, which now tops up their fee SOL automatically when they fall below floor — closing the failure where the fee wallet ran dry and the whole ring quietly halted. A new one-command check confirms every wallet is correctly configured, registered, and reachable, prints their live balances, and refuses to pass on any mismatch, without ever exposing a secret. A funding runbook documents exactly how much to send and how to confirm it landed.",+ "tags": [+ "infra",+ "security"+ ]+ },+ {+ "date": "2026-07-03",+ "title": "Ring settlements stay in-house — routing made truthful, mis-config now caught",+ "summary": "The closed-loop agent economy is built so no third party ever touches a ring settlement — but the configuration used to say one thing while the code did another: the setup guide claimed the platform's own facilitator was 'always-on' while Solana payments still defaulted to an outside settlement service. That contradiction is gone. When the self-hosted facilitator is switched on, ring payments now settle through it by default, and an explicitly-set external facilitator is the only thing that overrides that — no other coin or user rail is affected. Just as important, a mis-configured deploy now says so loudly instead of silently sending volume elsewhere: the status and ring reports list every problem — facilitator disabled, settlement pointing at an outside service, a missing treasury or fee-payer key, a per-call price set above the per-run cap — so operators can confirm the whole envelope is correct before funding anything. A clean deploy shows an empty warnings list.",+ "tags": [+ "fix",+ "infra"+ ]+ },+ {+ "date": "2026-07-03",+ "title": "Every ring settlement is now proven on-chain — reconciliation blind spot closed",+ "summary": "The closed-loop agent economy settles real USDC through the platform's own facilitator, and until now those settlements were trusted but never verified against the blockchain. A new reconciler runs every 30 minutes and holds the ring to the same standard the funding wallet already meets: every recorded settlement and every treasury→payer sweep from the last 72 hours is checked to exist and succeed on-chain, a sample of each is parsed to prove the exact dollar amount and recipient match the books, and the two internal ledgers are cross-checked so a settlement with no matching spend record — the tell-tale sign of value leaking through our own facilitator — is caught. It also runs a silence alarm: if the ring is switched on but goes quiet for 30 minutes, operators are paged, closing the gap where 'it was working, then it wasn't' used to pass unnoticed. Any missing, failed, or mismatched settlement raises an immediate alert; every finding lands on the finance-integrity board, tagged so ring issues stand apart from the rest.",+ "tags": [+ "security",+ "infra"+ ]+ },{"date": "2026-07-03","title": "Full audit trail + breach monitoring on the economy's funding wallet",diff --git a/data/pages.json b/data/pages.jsonindex dbaab5725..146fae783 100644--- a/data/pages.json+++ b/data/pages.json@@ -817,6 +817,13 @@"changefreq": "always","added": "2026-06-30"},+ {+ "path": "/admin/ring",+ "title": "Ring Dashboard (admin)",+ "description": "Operator dashboard for the closed-loop x402 ring economy — live per-minute settlement pulse, loop diagram with wallet balances and floors, streaming activity feed with agent attribution and Solscan links, fee/burn efficiency vs the daily budget, integrity (leak scan + reconciliation), and per-endpoint coverage. Admin-authed, noindex. Labels all ring volume as internal dogfooding, not organic revenue.",+ "auth": "admin",+ "indexable": false+ },{"path": "/deployments","title": "On-chain Deployments",diff --git a/docs/x402-ring-economy.md b/docs/x402-ring-economy.mdindex 4ee603441..d43619486 100644--- a/docs/x402-ring-economy.md+++ b/docs/x402-ring-economy.md@@ -76,6 +76,45 @@ The three roles are all platform-controlled:> **sponsor** role becomes optional. Sponsor mode exists for buyers that hold no> SOL and want gas sponsored (2 signatures, ~2× the base fee).+### Provisioning, verification & monitoring++Every ring wallet is provisioned once, registered in `x402_ring_wallets`, and+then kept in a verified, watched, auto-fundable state:++- **Verify** — [scripts/x402-ring-verify.mjs](../scripts/x402-ring-verify.mjs)+ resolves each role from env, checks the secret decodes to its declared pubkey+ (treasury secret ↔ `X402_PAY_TO_SOLANA`, sponsor secret ↔+ `X402_FEE_PAYER_SOLANA`), confirms `x402_ring_wallets` holds exactly one enabled+ row per role, checks the treasury is inside the facilitator's `payToAllowlist()`,+ prints a 3-row table with live SOL/USDC, and exits non-zero on any mismatch. It+ never prints a secret. `--fix` reconciles the DB registry to env (upsert the env+ pubkey, disable stray rows); `--json` emits machine-readable output.+- **Balance monitor** — [api/_lib/x402/wallet-balance-monitor.js](../api/_lib/x402/wallet-balance-monitor.js)+ (`checkRingWallets`, run every 10 min by the autonomous loop) reads all three+ wallets on-chain and alerts via `sendOpsAlert` on a role-floor breach:++ | Role | SOL floor | USDC floor |+ |---|---|---|+ | **sponsor** | 0.03 SOL (1.5× the 0.02 hard floor) | — |+ | **payer** | 0.03 SOL *(self-pay mode only)* | `X402_RING_PAYER_USDC_FLOOR_ATOMIC`, default **$5** |+ | **treasury** | — (unbounded: fills + gets swept) | — |++ The 0.03 SOL floor sits a hair above the facilitator's `X402_SPONSOR_SOL_FLOOR_LAMPORTS`+ (0.02 SOL) hard stop, so operators are warned *before* settlement is refused.+ A breach snapshot is published to Redis `x402:ring-wallets:latest` for cheap+ dashboard reads. The pure floor math is in+ [ring-floors.js](../api/_lib/x402/ring-floors.js).+- **Auto-topup** — the sponsor (`x402-ring-sponsor`) and payer (`x402-ring-payer`)+ are entries in [api/_lib/solana-signers.js](../api/_lib/solana-signers.js) with+ `minSol: 0.03`, so the economy master's+ [treasury-topup](../api/cron/treasury-topup.js) cron refills their fee **SOL**+ automatically when they fall below floor — closing the "sponsor runs dry and the+ ring silently halts" failure. The **treasury is deliberately not a signer** (the+ master must never top up a wallet that only receives and gets swept), and the+ master only ever moves SOL, so the payer's **USDC** float is a manual top-up when+ the monitor alerts. Funding amounts and verification commands live in+ [tasks/x402-ring/FUNDING.md](../tasks/x402-ring/FUNDING.md).+## Components- **Self-hosted facilitator** — [api/x402-facilitator/[action].js](../api/x402-facilitator/[action].js),@@ -121,11 +160,12 @@ node scripts/x402-ring-setup.mjspsql "$DATABASE_URL" -f api/_lib/migrations/2026-07-01-x402-ring-economy.sql# 3. Set env (Vercel), from the printed block:-# X402_SELF_FACILITATOR_ENABLED=true-# X402_FACILITATOR_URL_SOLANA=https://three.ws/api/x402-facilitator+# X402_SELF_FACILITATOR_ENABLED=true # else /api/x402-facilitator → 503# X402_EXTERNAL_ENABLED=false # only OUR endpoints get paid# X402_CHARITY_AUDIT_BPS=0 # no charity split leaves the ring+# X402_RING_SELF_PAY=true # 1-signature settles, lowest SOL# X402_PRICE_RING_SETTLE=1000000 # $1.00/call+# X402_VOLUME_PER_RUN_CAP_ATOMIC=… # must be ≥ X402_PRICE_RING_SETTLE# X402_AUTONOMOUS_DAILY_CAP_ATOMIC=… # your daily volume target# X402_SPONSOR_SOL_FLOOR_LAMPORTS=20000000# + the payer / treasury / sponsor pub+secret pairs@@ -135,10 +175,49 @@ psql "$DATABASE_URL" -f api/_lib/migrations/2026-07-01-x402-ring-economy.sql# sponsor → SOL for fees, e.g. 0.1 SOL (≈ thousands of settlements)# treasury→ nothing; it fills and gets swept back-# 5. Watch it.-curl https://three.ws/api/x402-ring?period=24h+# 5. Confirm the envelope is correct BEFORE funding — config_warnings must be [].+curl https://three.ws/api/x402-status | jq '.ring'+curl https://three.ws/api/x402-ring | jq '.config_warnings'```+### How Solana settlement routes++Turning on `X402_SELF_FACILITATOR_ENABLED=true` is what makes the self-hosted+facilitator the *default* Solana settle path — it is **not** always-on. The+resolver ([api/_lib/x402/ring-config.js](../api/_lib/x402/ring-config.js), used+by `facilitatorFor()`) decides in this order:++1. **An explicit `X402_FACILITATOR_URL_SOLANA` always wins.** Existing non-ring+ deploys never silently re-route. Point it at+ `https://three.ws/api/x402-facilitator` to force in-house settlement+ regardless of the flag, or at an external facilitator to opt out.+2. **Else, with `X402_SELF_FACILITATOR_ENABLED=true`,** Solana settlement+ defaults to this deploy's own `$APP_ORIGIN/api/x402-facilitator` — no URL+ needed.+3. **Else** it falls back to the external PayAI facilitator.++So the correctly-enveloped ring deploy sets the flag and **leaves+`X402_FACILITATOR_URL_SOLANA` unset** (or points it at the self URL). Setting the+flag while an external URL still wins is the mis-envelope the surfaces below flag.++### Fail loud, not silent++A mis-enveloped deploy — flag on but settlement still routing externally, or a+missing secret, or `X402_PRICE_RING_SETTLE` above the per-run cap — never routes+volume elsewhere quietly:++- **`/api/x402-status`** returns a `ring` block: `self_facilitator_enabled`, the+ resolved `self_facilitator_url`, and `config_warnings[]`. The self-hosted+ facilitator's `/supported` is probed as a distinct `self: true` entry whenever+ the flag is on, even if an external URL wins routing.+- **`/api/x402-ring`** returns the same `config_warnings[]` alongside the+ net-position report, and logs one structured warning per boot when settlement+ would route to an external facilitator.++`validateRingConfig()` reports six findings — facilitator disabled, URL external,+missing treasury secret, missing fee-payer pubkey, price-above-cap, and self-pay+off. A green ring is `config_warnings: []`.+Everything is **off by default**: without `X402_SELF_FACILITATOR_ENABLED=true` andthe sponsor secret, the facilitator returns `503` and nothing settles.@@ -156,9 +235,98 @@ For a monthly gross target `V` at per-call size `p`:Example: $10k/mo at $1/call ≈ 10k txs ≈ 0.05 SOL ≈ ~$10 real cost. At $100/call itis ~$0.10.+## Leak-proofing — the invariant, made active++**The invariant:** no SOL or USDC ever leaves the set of wallets three.ws+controls — not to another user, not to a charity, not to an external facilitator,+not as a fee beyond the network's own. The anti-drain gate above already refuses+to *settle* a leaking transaction; leak-proofing closes the remaining gap — a+flipped guard env, a compromised key, or any path that moves money without going+through the facilitator — by asserting the invariant at runtime **and** watching+the chain for money actually leaving.++### The controlled-wallet set++[api/_lib/x402/ring-allowlist.js](../api/_lib/x402/ring-allowlist.js) resolves+`ringAllowedAddresses()` — every address the platform controls:++- the three ring role wallets (payer, treasury, sponsor — env + derived),+- the `x402_ring_wallets` registry,+- every platform signer in [api/_lib/solana-signers.js](../api/_lib/solana-signers.js),+- explicit extras from `X402_SELF_FACILITATOR_PAYTO_ALLOWLIST`,+- and the USDC ATAs of all of the above (SPL credits land on the token account).++> This is the **membership** set (is a counterparty ours?), and it is deliberately+> broader than the facilitator's `payToAllowlist()` **receiving** set (may we+> settle *to* this address?). Receiving is stricter than membership — a wallet can+> be controlled without being a valid settlement recipient.++### Assertion points — the ring fails CLOSED++Before any spend, the spend entry points call `assertRingSpendInvariants()`,+which checks three guards:++1. `X402_EXTERNAL_ENABLED === 'false'` — external spending disabled (unset = violation),+2. `X402_CHARITY_AUDIT_BPS` parses to exactly `0` — no split leaves the ring,+3. facilitator resolves to **self** — `X402_SELF_FACILITATOR_ENABLED=true` and+ settlement routes to our own `/api/x402-facilitator` (via `resolveSolanaFacilitator()`).++Any violation **no-ops the entire spend path** and fires one throttled CRITICAL+ops alert naming the flipped flag. A forgotten or tampered flag can no longer+silently re-open external spending — the loop stops spending instead.+Wired into [api/cron/x402-autonomous-loop.js](../api/cron/x402-autonomous-loop.js)+(the loop that runs ring settlement) and the ring tick.++### On-chain leak scanner++[api/cron/x402-ring-leak-scan.js](../api/cron/x402-ring-leak-scan.js) runs every+10 min (`CRON_SECRET`-authed, **strictly read-only** on chain). For each ring+wallet it pulls the new signatures since a persisted per-wallet cursor+(`x402_ring_scan_cursor`, ≤100/run), batches `getParsedTransactions`, and+classifies every debit:++| class | meaning |+|---|---|+| `internal` | counterparty ∈ `ringAllowedAddresses()` — money stayed in the set |+| `network_fee` | the Solana fee our wallet paid (the only permitted outflow) |+| **`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 move |++Every `LEAK`/`delegation` fires a CRITICAL `sendOpsAlert` (signature,+counterparty, amount, rotate-the-key recommendation) and upserts a verdict into+`payment_reconciliation` with source `x402_ring_onchain`, alongside the economy+master's breach verdicts on the same ops financial-integrity board. When+classification is ambiguous it errs to `LEAK` — a false positive is cheaper than+a missed drain.++**Fee-leak line item.** The scanner accumulates the per-day network fees ring+wallets actually paid on chain (`x402_ring_fee_observed`) and cross-checks the+last complete UTC day against task 05's `x402_fee_audit` rollup. A >20% mismatch+means something is paying fees from our wallets outside the ring's accounting →+WARN.++### Response runbook — a leak alert fired++1. **Confirm** — open the `solscan.io/tx/<sig>` link in the alert; read the+ counterparty and amount. Cross-check the verdict:+ `SELECT * FROM payment_reconciliation WHERE source = 'x402_ring_onchain' AND reconciled = false`.+2. **Rotate** — treat the affected wallet's key as compromised. Generate a new+ secret (`node scripts/x402-ring-setup.mjs` for a ring role; the signer's own+ runbook otherwise) and replace it in Vercel env.+3. **Drain** — move remaining funds from the old wallet to the treasury+ (`X402_PAY_TO_SOLANA`) before the old key can move more.+4. **Revoke** (delegation alerts) — send an SPL `Revoke` on the approved ATA to+ kill the delegate's authority.+5. **Re-verify** — run `node scripts/x402-ring-verify.mjs` to confirm the wallet+ set is clean, then mark the verdict reconciled.+## Related- [STRUCTURE.md](../STRUCTURE.md) — surface map- [/api/x402-revenue](../api/x402-revenue.js) — the **public** organic-revenuefeed (self-cycled ring volume is excluded from the "organic" framing here)- [docs/x402-revenue.md](./x402-revenue.md) — revenue surface docs+- [api/_lib/x402/ring-allowlist.js](../api/_lib/x402/ring-allowlist.js) — the+ controlled-wallet set + spend invariants+- [api/cron/x402-ring-leak-scan.js](../api/cron/x402-ring-leak-scan.js) — the+ on-chain leak scannerdiff --git a/fees-github-account-before-fix.png b/fees-github-account-before-fix.pngdeleted file mode 100644index 22f656d96..000000000Binary files a/fees-github-account-before-fix.png and /dev/null differdiff --git a/fees-github-account.png b/fees-github-account.pngdeleted file mode 100644index d7b7e7ba4..000000000Binary files a/fees-github-account.png and /dev/null differdiff --git a/fees-github-owner-only.png b/fees-github-owner-only.pngdeleted file mode 100644index a53be8c87..000000000Binary files a/fees-github-owner-only.png and /dev/null differdiff --git a/fees-reward-anyone.png b/fees-reward-anyone.pngdeleted file mode 100644index b72102505..000000000Binary files a/fees-reward-anyone.png and /dev/null differdiff --git a/packages/agent-sniper/.npmrc b/packages/agent-sniper/.npmrcnew file mode 100644index 000000000..217a69495--- /dev/null+++ b/packages/agent-sniper/.npmrc@@ -0,0 +1 @@+install-strategy=nesteddiff --git a/public/admin/index.html b/public/admin/index.htmlindex 64a963435..f32c91bb9 100644--- a/public/admin/index.html+++ b/public/admin/index.html@@ -120,6 +120,7 @@<a class="nav-item" href="/admin/news">News</a><a class="nav-item" href="/admin/sdp">Solana Platform</a><a class="nav-item" href="/admin/seeder">Avatar Seeder</a>+ <a class="nav-item" href="/admin/ring">Ring Economy</a><a class="nav-item" href="/admin/ops">Ops Health</a><a class="nav-item" href="/admin/launcher">Launcher</a><a class="nav-item" href="/dashboard/">Dashboard</a>diff --git a/public/changelog.json b/public/changelog.jsonindex 5757818d1..62021a5d7 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,11 +1,22 @@{- "generated_at": "2026-07-03T00:09:38.457Z",+ "generated_at": "2026-07-03T04:51:42.848Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws","url": "https://three.ws"},"entries": [+ {+ "date": "2026-07-03",+ "type": "update",+ "title": "Every ring settlement is now proven on-chain — reconciliation blind spot closed",+ "summary": "The closed-loop agent economy settles real USDC through the platform's own facilitator, and until now those settlements were trusted but never verified against the blockchain. A new reconciler runs every 30 minutes and holds the ring to the same standard the funding wallet already meets: every recorded settlement and every treasury→payer sweep from the last 72 hours is checked to exist and succeed on-chain, a sample of each is parsed to prove the exact dollar amount and recipient match the books, and the two internal ledgers are cross-checked so a settlement with no matching spend record — the tell-tale sign of value leaking through our own facilitator — is caught. It also runs a silence alarm: if the ring is switched on but goes quiet for 30 minutes, operators are paged, closing the gap where 'it was working, then it wasn't' used to pass unnoticed. Any missing, failed, or mismatched settlement raises an immediate alert; every finding lands on the finance-integrity board, tagged so ring issues stand apart from the rest.",+ "link": null,+ "tags": [+ "security",+ "infra"+ ]+ },{"date": "2026-07-03","type": "update",@@ -18,6 +29,17 @@"docs"]},+ {+ "date": "2026-07-03",+ "type": "update",+ "title": "Ring settlements stay in-house — routing made truthful, mis-config now caught",+ "summary": "The closed-loop agent economy is built so no third party ever touches a ring settlement — but the configuration used to say one thing while the code did another: the setup guide claimed the platform's own facilitator was 'always-on' while Solana payments still defaulted to an outside settlement service. That contradiction is gone. When the self-hosted facilitator is switched on, ring payments now settle through it by default, and an explicitly-set external facilitator is the only thing that overrides that — no other coin or user rail is affected. Just as important, a mis-configured deploy now says so loudly instead of silently sending volume elsewhere: the status and ring reports list every problem — facilitator disabled, settlement pointing at an outside service, a missing treasury or fee-payer key, a per-call price set above the per-run cap — so operators can confirm the whole envelope is correct before funding anything. A clean deploy shows an empty warnings list.",+ "link": null,+ "tags": [+ "fix",+ "infra"+ ]+ },{"date": "2026-07-02","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex d220f6f0f..156d8b894 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -6,6 +6,14 @@<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/><description>What's new on three.ws — features, improvements, and releases, newest first.</description><language>en</language>+ <item>+ <title>Every ring settlement is now proven on-chain — reconciliation blind spot closed</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-07-03:Every ring settlement is now proven on-chain — reconciliation blind spot closed</guid>+ <pubDate>Fri, 03 Jul 2026 12:00:00 GMT</pubDate>+ <category>security</category>+ <description>The closed-loop agent economy settles real USDC through the platform's own facilitator, and until now those settlements were trusted but never verified against the blockchain. A new reconciler runs every 30 minutes and holds the ring to the same standard the funding wallet already meets: every recorded settlement and every treasury→payer sweep from the last 72 hours is checked to exist and succeed on-chain, a sample of each is parsed to prove the exact dollar amount and recipient match the books, and the two internal ledgers are cross-checked so a settlement with no matching spend record — the tell-tale sign of value leaking through our own facilitator — is caught. It also runs a silence alarm: if the ring is switched on but goes quiet for 30 minutes, operators are paged, closing the gap where 'it was working, then it wasn't' used to pass unnoticed. Any missing, failed, or mismatched settlement raises an immediate alert; every finding lands on the finance-integrity board, tagged so ring issues stand apart from the rest.</description>+ </item><item><title>Full audit trail + breach monitoring on the economy's funding wallet</title><link>https://three.ws/changelog</link>@@ -14,6 +22,14 @@<category>security</category><description>The master wallet that fuels the platform's autonomous economy now keeps a tamper-evident accounting book of every move it makes. Each SOL transfer is recorded with the engine it funded, the amount, the on-chain signature, the running balance, and the US-dollar value at the moment of the transfer — cryptographically hash-chained so no past entry can be altered or deleted without detection. A monitor runs every 30 minutes and checks three things: that the book hasn't been tampered with, that every transfer we recorded really happened on-chain, and — most importantly — that no SOL ever left the wallet without a matching record, which is the tell-tale sign of a stolen key. Anything off raises an immediate operator alert and lands on the finance-integrity board. There's also a one-command accounting export (CSV or JSON, with running balance and dollar totals) for bookkeeping and review.</description></item>+ <item>+ <title>Ring settlements stay in-house — routing made truthful, mis-config now caught</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-07-03:Ring settlements stay in-house — routing made truthful, mis-config now caught</guid>+ <pubDate>Fri, 03 Jul 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>The closed-loop agent economy is built so no third party ever touches a ring settlement — but the configuration used to say one thing while the code did another: the setup guide claimed the platform's own facilitator was 'always-on' while Solana payments still defaulted to an outside settlement service. That contradiction is gone. When the self-hosted facilitator is switched on, ring payments now settle through it by default, and an explicitly-set external facilitator is the only thing that overrides that — no other coin or user rail is affected. Just as important, a mis-configured deploy now says so loudly instead of silently sending volume elsewhere: the status and ring reports list every problem — facilitator disabled, settlement pointing at an outside service, a missing treasury or fee-payer key, a per-call price set above the per-run cap — so operators can confirm the whole envelope is correct before funding anything. A clean deploy shows an empty warnings list.</description>+ </item><item><title>Agent wallet creation and vanity addresses restored</title><link>https://three.ws/vanity-wallet</link>diff --git a/public/features.json b/public/features.jsonindex 8c3547326..81fbfe64a 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-03T00:09:38.424Z",+ "generated_at": "2026-07-03T04:51:42.708Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",@@ -996,6 +996,16 @@"tags": [],"showcase": false},+ {+ "path": "/admin/ring",+ "title": "Ring Dashboard (admin)",+ "description": "Operator dashboard for the closed-loop x402 ring economy — live per-minute settlement pulse, loop diagram with wallet balances and floors, streaming activity feed with agent attribution and Solscan links, fee/burn efficiency vs the daily budget, integrity (leak scan + reconciliation), and per-endpoint coverage. Admin-authed, noindex. Labels all ring volume as internal dogfooding, not organic revenue.",+ "added": null,+ "auth": "admin",+ "indexable": false,+ "tags": [],+ "showcase": false+ },{"path": "/deployments","title": "On-chain Deployments",diff --git a/public/llms-full.txt b/public/llms-full.txtindex c0c0445fa..a61e5c924 100644--- a/public/llms-full.txt+++ b/public/llms-full.txt@@ -606,6 +606,13 @@ URL: https://three.ws/viabilityThe honest signal behind three.ws — real marketplace and trading viability. Live $THREE skill GMV, take-rate, repeat buyers and trading pairs, plus real guarded coin-trade flow, cost and realized P&L on closed positions. Real on-chain data only.+### Ring Dashboard (admin)++URL: https://three.ws/admin/ring+Indexable: no (excluded from sitemap)++Operator dashboard for the closed-loop x402 ring economy — live per-minute settlement pulse, loop diagram with wallet balances and floors, streaming activity feed with agent attribution and Solscan links, fee/burn efficiency vs the daily budget, integrity (leak scan + reconciliation), and per-endpoint coverage. Admin-authed, noindex. Labels all ring volume as internal dogfooding, not organic revenue.+### On-chain DeploymentsURL: https://three.ws/deploymentsdiff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex ffe4d939c..6a7c69ff5 100644--- a/public/sitemap/index.html+++ b/public/sitemap/index.html@@ -65,7 +65,7 @@<main class="sm-wrap"><div class="sm-hero"><h1>Sitemap</h1>- <p>All 369 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>+ <p>All 370 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p><div class="sm-formats"><a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a><a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>@@ -77,7 +77,7 @@</div><div class="sm-filter"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>- <input id="sm-filter-input" type="search" placeholder="Filter 369 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />+ <input id="sm-filter-input" type="search" placeholder="Filter 370 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" /><kbd aria-hidden="true">/</kbd></div><p class="sm-filter-count" id="sm-filter-count" role="status" aria-live="polite"></p>@@ -697,7 +697,7 @@<section class="sm-section" id="crypto"><header>- <h2>Crypto<span class="sm-count" data-count>78</span></h2>+ <h2>Crypto<span class="sm-count" data-count>79</span></h2><p class="sm-section-desc">On-chain features: pay-per-call, token launches, vanity wallets.</p></header><ul class="sm-list">@@ -799,6 +799,13 @@<span class="sm-desc">The honest signal behind three.ws — real marketplace and trading viability. Live $THREE skill GMV, take-rate, repeat buyers and trading pairs, plus real guarded coin-trade flow, cost and realized P&L on closed positions. Real on-chain data only.</span></a></li>+ <li>+ <a href="/admin/ring">+ <span class="sm-title">Ring Dashboard (admin)<span class="sm-badge sm-badge-internal">internal</span></span>+ <span class="sm-path">/admin/ring</span>+ <span class="sm-desc">Operator dashboard for the closed-loop x402 ring economy — live per-minute settlement pulse, loop diagram with wallet balances and floors, streaming activity feed with agent attribution and Solscan links, fee/burn efficiency vs the daily budget, integrity (leak scan + reconciliation), and per-endpoint coverage. Admin-authed, noindex. Labels all ring volume as internal dogfooding, not organic revenue.</span>+ </a>+ </li><li><a href="/deployments"><span class="sm-title">On-chain Deployments</span>diff --git a/src/admin-ring.js b/src/admin-ring.jsnew file mode 100644index 000000000..db1834597--- /dev/null+++ b/src/admin-ring.js@@ -0,0 +1,499 @@+// /admin/ring — x402 ring economy operator dashboard controller.+//+// Polls one aggregate endpoint (/api/admin/ring-dashboard) every 15s and paints+// six panels: settlement pulse, loop diagram, activity feed, fees, integrity,+// and endpoint coverage. Admin session OR Bearer secret — the secret lives in+// sessionStorage + memory, sent as Authorization: Bearer, never in a URL,+// cleared on any 401. Every API-sourced string is escaped before it hits the+// DOM. Polling aborts on a hidden tab and can be paused with `p`; `r` refreshes.++const API = '/api/admin/ring-dashboard';+const SECRET_KEY = 'admin_secret';+const POLL_MS = 15_000;++let secret = sessionStorage.getItem(SECRET_KEY) || '';+let period = '24h';+let pollTimer = null;+let clockTimer = null;+let paused = false;+let inFlight = null; // AbortController for the current fetch+let lastData = null;+let seenActivityIds = new Set();++const $ = (id) => document.getElementById(id);+const esc = (s) =>+ String(s == null ? '' : s).replace(+ /[&<>"']/g,+ (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],+ );++// ── Formatting ───────────────────────────────────────────────────────────────+function fmtAgo(iso) {+ if (!iso) return '—';+ const s = Math.floor((Date.now() - new Date(iso).getTime()) / 1000);+ if (s < 5) return 'just now';+ if (s < 60) return `${s}s ago`;+ if (s < 3600) return `${Math.floor(s / 60)}m ago`;+ if (s < 86400) return `${Math.floor(s / 3600)}h ago`;+ return `${Math.floor(s / 86400)}d ago`;+}+function fmtUsd(n, dp = 2) {+ if (n == null) return '—';+ return `$${Number(n).toLocaleString(undefined, { minimumFractionDigits: dp, maximumFractionDigits: dp })}`;+}+function fmtSol(n) {+ if (n == null) return '—';+ const v = Number(n);+ return `${v.toLocaleString(undefined, { maximumFractionDigits: v < 1 ? 5 : 3 })} SOL`;+}+function shortAddr(a) {+ if (!a) return '—';+ return a.length > 12 ? `${a.slice(0, 4)}…${a.slice(-4)}` : a;+}+function solscanTx(sig) {+ return `https://solscan.io/tx/${encodeURIComponent(sig)}`;+}++// ── API ──────────────────────────────────────────────────────────────────────+async function api(url, signal) {+ const r = await fetch(url, {+ headers: { accept: 'application/json', authorization: `Bearer ${secret}` },+ credentials: 'same-origin',+ signal,+ });+ if (r.status === 401 || r.status === 403) {+ secret = '';+ sessionStorage.removeItem(SECRET_KEY);+ stopPolling();+ showGate('Secret rejected. Try again.');+ throw new Error('unauthorized');+ }+ const j = await r.json().catch(() => null);+ if (!r.ok) throw new Error(j?.error_description || j?.error || `HTTP ${r.status}`);+ return j;+}++// ── Gate ─────────────────────────────────────────────────────────────────────+function showGate(err = '') {+ $('rg-root').setAttribute('aria-busy', 'false');+ $('rg-panel').hidden = true;+ $('rg-hint').hidden = true;+ $('rg-gate').hidden = false;+ $('rg-gate-err').textContent = err;+ setTimeout(() => $('rg-secret').focus(), 40);+}+function showPanel() {+ $('rg-gate').hidden = true;+ $('rg-panel').hidden = false;+ $('rg-hint').hidden = false;+ $('rg-root').setAttribute('aria-busy', 'false');+}++$('rg-gate-form').addEventListener('submit', async (e) => {+ e.preventDefault();+ const val = $('rg-secret').value.trim();+ if (!val) return;+ secret = val;+ try {+ await refresh();+ sessionStorage.setItem(SECRET_KEY, secret);+ $('rg-secret').value = '';+ showPanel();+ startPolling();+ } catch {+ /* api() already surfaced the gate error */+ }+});++// ── Fetch + orchestrate ──────────────────────────────────────────────────────+async function refresh() {+ if (inFlight) inFlight.abort();+ inFlight = new AbortController();+ try {+ const d = await api(`${API}?period=${encodeURIComponent(period)}`, inFlight.signal);+ lastData = d;+ clearError();+ render(d);+ } catch (err) {+ if (err?.name === 'AbortError') return;+ if (err?.message === 'unauthorized') return;+ showError(err?.message || 'unreachable');+ throw err;+ } finally {+ inFlight = null;+ }+}++// ── Error banner (API unreachable) ───────────────────────────────────────────+function showError(msg) {+ const box = $('rg-error');+ box.hidden = false;+ box.innerHTML = `<div class="rg-errbox" role="alert">+ <strong>Dashboard API unreachable</strong>+ ${esc(msg)} — the ring may still be settling; this is the read model, not the loop.+ <code>curl -s -H "Authorization: Bearer $CRON_SECRET" \\+ "$APP_ORIGIN/api/admin/ring-dashboard?period=${esc(period)}" | jq .pulse</code>+ </div>`;+}+function clearError() {+ $('rg-error').hidden = true;+ $('rg-error').innerHTML = '';+}++// ── Render ───────────────────────────────────────────────────────────────────+function render(d) {+ renderPulse(d.pulse);+ renderLoop(d.report);+ renderActivity(d.activity || []);+ renderFees(d.fees, d.report);+ renderIntegrity(d.reconciliation, d.config);+ renderCoverage(d.endpoints || []);+}++function renderPulse(pulse) {+ if (!pulse) return;+ const status = pulse.status || 'red';+ const big = $('rg-pulse-big');+ const mins = pulse.minutes_since_last_settle;+ big.textContent = mins == null ? '∞' : mins;+ big.className = `rg-pulse-big ${status}`;+ $('rg-pulse-lbl').textContent =+ mins == null ? 'no settle on record' : mins === 1 ? 'min since settle' : 'min since settle';++ const dot = $('rg-hero-dot');+ dot.className = `rg-pulse-dot ${status}`;+ $('rg-hero-word').textContent =+ status === 'green' ? 'Live' : status === 'amber' ? 'Slowing' : 'Stalled';+ $('rg-pulse-meta').textContent = `${pulse.settles_last_60m || 0} settled · last 60 min`;++ const strip = pulse.minutes || [];+ const max = Math.max(1, ...strip.map((m) => m.count));+ $('rg-spark').innerHTML = strip+ .map((m) => {+ const h = m.count ? Math.max(6, Math.round((m.count / max) * 100)) : 0;+ const cls = m.count ? 'rg-spark-bar' : 'rg-spark-bar empty';+ const t = new Date(m.ts).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });+ return `<div class="${cls}" style="height:${h}%" title="${esc(t)}: ${m.count} settle${m.count === 1 ? '' : 's'}"></div>`;+ })+ .join('');+ if (strip.length) {+ const midIdx = Math.floor(strip.length / 2);+ $('rg-spark-mid').textContent = new Date(strip[midIdx].ts).toLocaleTimeString([], {+ hour: '2-digit',+ minute: '2-digit',+ });+ }+}++function renderLoop(report) {+ const wrap = $('rg-loop');+ if (!report?.wallets) {+ wrap.innerHTML = emptyBlock('◎', 'Loop wallets unavailable', 'Balances load from live RPC.');+ return;+ }+ const w = report.wallets;+ const node = (role, balHtml, addr, floorHtml = '', below = false) =>+ `<div class="rg-node${below ? ' below' : ''}">+ <div class="rg-node-role">${esc(role)}</div>+ <div class="rg-node-bal">${balHtml}</div>+ <div class="rg-node-addr" title="${esc(addr || '')}">${esc(shortAddr(addr))}</div>+ ${floorHtml}+ </div>`;+ const arrow = (label) => `<div class="rg-arrow" title="${esc(label)}" aria-label="${esc(label)}">→</div>`;++ const below = w.sponsor?.below_floor === true;+ const floorHtml = w.sponsor?.floor_sol != null+ ? `<div class="rg-node-floor${below ? ' below' : ''}">floor ${fmtSol(w.sponsor.floor_sol)}${below ? ' · BELOW' : ''}</div>`+ : '';++ const parts = [+ node('Payer', fmtUsd(w.payer?.usdc), w.payer?.address, '<div class="rg-node-floor">pays the ring</div>'),+ arrow('pays USDC'),+ node('Endpoint', '◎', null, '<div class="rg-node-floor">x402 settle</div>'),+ arrow('→ treasury'),+ node('Treasury', fmtUsd(w.treasury?.usdc), w.treasury?.address, '<div class="rg-node-floor">receives</div>'),+ arrow('sweep back'),+ ];+ // Sponsor is optional in self-pay; only show as a node if it has a balance/floor.+ if (w.sponsor?.address) {+ parts.push(+ node('Sponsor (SOL)', fmtSol(w.sponsor?.sol), w.sponsor?.address, floorHtml, below),+ );+ }+ wrap.innerHTML = parts.join('');+ $('rg-loop-meta').textContent = `float ${fmtUsd(report.net?.ring_float_usdc)}`;+}++function renderActivity(rows) {+ const wrap = $('rg-feed-wrap');+ $('rg-feed-meta').textContent = rows.length ? `${rows.length} recent calls` : '';+ if (!rows.length) {+ wrap.innerHTML = emptyBlock(+ '◎',+ 'Ring idle — no paid calls yet',+ 'Run the activation runbook to start the per-minute tick.',+ );+ return;+ }+ const rowsHtml = rows+ .map((r) => {+ const isNew = !seenActivityIds.has(r.id);+ const price = r.usdc != null ? fmtUsd(r.usdc, r.usdc < 0.01 ? 4 : 2) : '—';+ const sig = r.tx_sig+ ? `<a class="rg-sig" href="${esc(solscanTx(r.tx_sig))}" target="_blank" rel="noopener" title="View on Solscan">${esc(r.tx_sig.slice(0, 8))}↗</a>`+ : '—';+ const agent = r.agent ? esc(r.agent) : esc(r.service || '—');+ const statusCell =+ r.status === 'skipped' || r.status === 'failed'+ ? `<span class="rg-status ${r.status}">${r.status}</span>${r.error ? ` <span class="rg-reason ${r.status}">${esc(r.error)}</span>` : ''}`+ : `<span class="rg-status ${r.status}">${r.status}</span>`;+ return `<tr class="${isNew ? 'new' : ''}">+ <td>${fmtAgo(r.ts)}</td>+ <td class="rg-agent">${agent}</td>+ <td><span class="rg-slug">${esc(r.slug)}</span></td>+ <td><span class="rg-kind ${esc(r.kind)}">${esc(r.kind)}</span></td>+ <td class="num">${price}</td>+ <td>${statusCell}</td>+ <td>${sig}</td>+ </tr>`;+ })+ .join('');+ wrap.innerHTML = `<table class="rg-feed">+ <thead><tr>+ <th>Time</th><th>Agent</th><th>Endpoint</th><th>Kind</th>+ <th style="text-align:right">Price</th><th>Status</th><th>Tx</th>+ </tr></thead>+ <tbody>${rowsHtml}</tbody>+ </table>`;+ seenActivityIds = new Set(rows.map((r) => r.id));+}++function renderFees(fees, report) {+ if (!fees) return;+ const el = $('rg-fees');+ const ratio = fees.floor_ratio;+ const ratioCls = ratio == null ? '' : ratio <= 1.05 ? 'good' : ratio <= 1.5 ? 'warn' : 'bad';+ const cards = [+ {+ dt: 'Per settle',+ dd: fees.avg_lamports_per_settle != null ? `${fees.avg_lamports_per_settle.toLocaleString()}` : '—',+ small: `lamports · floor ${fees.floor_lamports.toLocaleString()}`,+ cls: ratioCls,+ },+ {+ dt: 'Floor ratio',+ dd: ratio != null ? `${ratio}×` : '—',+ small: '1.0× = 1-sig minimum',+ cls: ratioCls,+ },+ {+ dt: 'SOL / $100',+ dd: fees.sol_per_100_usd != null ? fees.sol_per_100_usd.toFixed(5) : '—',+ small: 'burn per $100 volume',+ },+ {+ dt: 'Burned today',+ dd: fmtSol((fees.burned_today_lamports || 0) / 1e9),+ small:+ report?.fees?.burned_usd != null ? `≈ ${fmtUsd(report.fees.burned_usd, 4)}` : 'since 00:00 UTC',+ },+ ];+ let html = cards+ .map(+ (c) => `<div class="rg-metric">+ <dt>${esc(c.dt)}</dt>+ <dd class="${c.cls || ''}">${c.dd}</dd>+ <small>${esc(c.small)}</small>+ </div>`,+ )+ .join('');+ if (fees.daily_budget_lamports) {+ const pct = Math.min(100, fees.budget_used_pct || 0);+ const barCls = fees.over_budget ? 'bad' : pct >= 80 ? 'warn' : '';+ html += `<div class="rg-budget-bar">+ <small style="color:var(--rg-dim)">Daily fee budget — ${fees.budget_used_pct ?? 0}% used+ (${((fees.burned_today_lamports || 0) / 1e9).toFixed(5)} / ${(fees.daily_budget_lamports / 1e9).toFixed(5)} SOL)</small>+ <div class="rg-budget-track"><div class="rg-budget-fill ${barCls}" style="width:${pct}%"></div></div>+ </div>`;+ }+ el.innerHTML = html;+ $('rg-fees-meta').textContent = fees.sol_usd != null ? `SOL ${fmtUsd(fees.sol_usd)}` : '';+}++function renderIntegrity(recon, config) {+ const el = $('rg-integrity');+ const warnings = (config?.warnings || []).filter(Boolean);+ const leak = recon?.leak_scan || { open: 0, total: 0, last_checked_at: null };+ const rec = recon?.reconcile || { open: 0, total: 0, last_checked_at: null };+ const openTotal = (leak.open || 0) + (rec.open || 0);+ const errWarnings = warnings.filter((w) => w.level === 'error');+ const allClear = openTotal === 0 && errWarnings.length === 0;++ $('rg-int-meta').textContent = config?.validator ? esc(config.validator) : '';++ if (!recon?.available && !warnings.length) {+ el.innerHTML = emptyBlock('✓', 'No integrity data yet', 'Reconciliation runs on its own cadence.');+ return;+ }++ if (allClear) {+ el.innerHTML = `<div class="rg-calm"><span aria-hidden="true">✓</span>+ All clear — leak scan ${leak.last_checked_at ? fmtAgo(leak.last_checked_at) : 'pending'},+ reconcile ${rec.last_checked_at ? fmtAgo(rec.last_checked_at) : 'pending'}, config valid.</div>`;+ return;+ }++ const alerts = [];+ if (leak.open > 0)+ alerts.push({+ level: 'error',+ code: 'leak_scan',+ msg: `${leak.open} open leak-scan finding${leak.open === 1 ? '' : 's'} — a settlement the chain does not corroborate. Last run ${fmtAgo(leak.last_checked_at)}.`,+ });+ if (rec.open > 0)+ alerts.push({+ level: 'error',+ code: 'reconcile',+ msg: `${rec.open} open reconciliation verdict${rec.open === 1 ? '' : 's'} unresolved. Last run ${fmtAgo(rec.last_checked_at)}.`,+ });+ for (const w of warnings) alerts.push({ level: w.level || 'warn', code: w.code, msg: w.message });++ const byStatus = recon?.open_by_status || {};+ const chips = Object.entries(byStatus)+ .map(([k, v]) => `<span class="rg-chip">${esc(k)}: ${v}</span>`)+ .join('');++ el.innerHTML = `<div class="rg-alert">${alerts+ .map(+ (a) => `<div class="rg-alert-row ${a.level === 'error' ? '' : a.level}">+ <span aria-hidden="true">${a.level === 'error' ? '⚠' : a.level === 'info' ? 'ℹ' : '△'}</span>+ <div>${esc(a.msg)}${a.code ? ` <code>${esc(a.code)}</code>` : ''}</div>+ </div>`,+ )+ .join('')}</div>${chips ? `<div class="rg-chips">${chips}</div>` : ''}`;+}++function renderCoverage(endpoints) {+ const el = $('rg-coverage');+ $('rg-cov-meta').textContent = endpoints.length ? `${endpoints.length} endpoints` : '';+ if (!endpoints.length) {+ el.innerHTML = emptyBlock(+ '◎',+ 'No endpoint metrics yet',+ 'The volume loop records per-endpoint coverage as it pays each one.',+ );+ return;+ }+ el.innerHTML = endpoints+ .map((e) => {+ const stale = e.stale;+ const age = e.age_minutes == null ? 'never' : fmtAgo(e.last_called_at);+ return `<div class="rg-cov-row${stale ? ' stale' : ''}">+ <div class="rg-cov-name">${esc(e.name || e.key)}<small>${esc(e.path || e.key)}</small></div>+ <div class="rg-cov-age${stale ? ' stale' : ''}" title="${e.calls} calls · ${e.success_pct ?? 0}% ok">${esc(age)}</div>+ <div class="rg-cov-vol">${fmtUsd(e.total_usdc, e.total_usdc < 1 ? 4 : 2)}</div>+ </div>`;+ })+ .join('');+}++function emptyBlock(mark, title, sub) {+ return `<div class="rg-empty"><div class="rg-empty-mark" aria-hidden="true">${mark}</div>+ <strong>${esc(title)}</strong>${esc(sub)}</div>`;+}++// ── Skeleton (first paint) ───────────────────────────────────────────────────+function paintSkeleton() {+ $('rg-spark').innerHTML = Array.from({ length: 60 })+ .map(() => '<div class="rg-spark-bar empty" style="height:20%"></div>')+ .join('');+ $('rg-loop').innerHTML = '<div class="rg-skel" style="height:88px;flex:1"></div>';+ $('rg-feed-wrap').innerHTML = '<div class="rg-skel" style="height:180px"></div>';+ $('rg-fees').innerHTML = Array.from({ length: 4 })+ .map(() => '<div class="rg-skel" style="height:66px"></div>')+ .join('');+ $('rg-integrity').innerHTML = '<div class="rg-skel" style="height:46px"></div>';+ $('rg-coverage').innerHTML = '<div class="rg-skel" style="height:120px"></div>';+}++// ── Period switch ────────────────────────────────────────────────────────────+$('rg-periods').addEventListener('click', (e) => {+ const btn = e.target.closest('button[data-period]');+ if (!btn || btn.dataset.period === period) return;+ period = btn.dataset.period;+ $('rg-periods')+ .querySelectorAll('button')+ .forEach((b) => b.classList.toggle('on', b === btn));+ refresh().catch(() => {});+});++// ── Controls ─────────────────────────────────────────────────────────────────+$('rg-refresh').addEventListener('click', () => refresh().catch(() => {}));+$('rg-pause').addEventListener('click', togglePause);++function togglePause() {+ paused = !paused;+ const btn = $('rg-pause');+ btn.classList.toggle('on', paused);+ btn.innerHTML = paused ? '▶ Resume' : '⏸ Pause';+ if (paused) stopPolling(true);+ else if (secret && !$('rg-panel').hidden) {+ refresh().catch(() => {});+ startPolling();+ }+}++document.addEventListener('keydown', (e) => {+ if (e.target.tagName === 'INPUT' || $('rg-panel').hidden) return;+ if (e.key === 'r') {+ e.preventDefault();+ refresh().catch(() => {});+ } else if (e.key === 'p') {+ e.preventDefault();+ togglePause();+ }+});++// ── Poll loop ────────────────────────────────────────────────────────────────+function startPolling() {+ stopPolling(true);+ if (paused) return;+ pollTimer = setInterval(() => refresh().catch(() => {}), POLL_MS);+ // Keep relative timestamps fresh without a network round-trip.+ clockTimer = setInterval(() => {+ if (lastData) {+ renderPulse(lastData.pulse);+ renderActivity(lastData.activity || []);+ }+ }, 1000);+}+function stopPolling(keepPausedFlag = false) {+ clearInterval(pollTimer);+ clearInterval(clockTimer);+ pollTimer = clockTimer = null;+ if (!keepPausedFlag) paused = false;+}+document.addEventListener('visibilitychange', () => {+ if (document.hidden) {+ clearInterval(pollTimer);+ clearInterval(clockTimer);+ pollTimer = clockTimer = null;+ } else if (secret && !$('rg-panel').hidden && !paused) {+ refresh().catch(() => {});+ startPolling();+ }+});++// ── Boot ─────────────────────────────────────────────────────────────────────+(async function boot() {+ paintSkeleton();+ if (!secret) return showGate();+ try {+ await refresh();+ showPanel();+ startPolling();+ } catch {+ /* 401 → gate already shown; other errors → error banner is visible */+ if (secret) showPanel();+ }+})();diff --git a/tasks/onchain-deployment/SOLANA-SIGNERS.md b/tasks/onchain-deployment/SOLANA-SIGNERS.mdindex 011bb9a40..210621b73 100644--- a/tasks/onchain-deployment/SOLANA-SIGNERS.md+++ b/tasks/onchain-deployment/SOLANA-SIGNERS.md@@ -27,9 +27,13 @@ Encodings: `base64` = base64 of the 64 raw secret-key bytes (`…_B64` vars); `b| `VANITY_BOUNTY_PAYOUT_KEY` | Vanity grind-bounty payouts + refunds (strict base58) | base58 | — | mainnet || `CIRCULATION_TREASURY_SECRET` | Circulation engine treasury (agent↔agent tips/pays/trades) | base58 | — | mainnet || `A2A_PAYER_SOLANA_SECRET` (→ `A2A_PAYER_SOLANA_PRIVATE_KEY`) | Co-signs SPL TransferChecked for a2a mandate settlements | base58 | 0.02 | mainnet |+| `X402_FEE_PAYER_SECRET_BASE58` | x402 ring **sponsor**: co-signs + pays SOL on every self-hosted-facilitator settle; below floor the ring halts | base58 | 0.03 | mainnet |+| `X402_SEED_SOLANA_SECRET_BASE58` (→ `X402_AGENT_SOLANA_SECRET_BASE58`) | x402 ring **payer** (self-pay mode): pays its own 1-sig fee per settle; USDC float watched separately | base58 | 0.03 | mainnet || `REWARDS_DISTRIBUTOR_SECRET` | $THREE holder rewards/reflections distributor | base58 | — | mainnet || `SOLANA_AGENT_COLLECTION_AUTHORITY_KEY` | Creates/manages the three.ws agent NFT collection | base64 | 0.02 | both |+> The x402 ring **treasury** (`X402_PAY_TO_SOLANA` / `X402_TREASURY_SECRET_BASE58`) is deliberately **not** a signer here. It only receives ring payments and gets swept back to the payer by the rebalancer, so a low balance is its healthy resting state — the economy master must never top it up. Only the sponsor (and the payer, which pays its own fee in self-pay mode) hold fee SOL, so only they get auto-topped-up. The payer's USDC float is watched by [`api/_lib/x402/wallet-balance-monitor.js`](../../api/_lib/x402/wallet-balance-monitor.js), not this registry (the master only ever moves SOL).+**Do not** overwrite `SOLANA_AGENT_COLLECTION_AUTHORITY_KEY` with a different wallet — it is the on-chain update authority for the NFT collection; changing it breaks NFT management. It is excluded from master-wallet consolidation by default.## Two funding modelsdiff --git a/tasks/x402-ring/FUNDING.md b/tasks/x402-ring/FUNDING.mdnew file mode 100644index 000000000..79f481aab--- /dev/null+++ b/tasks/x402-ring/FUNDING.md@@ -0,0 +1,127 @@+# x402 Ring — Funding Runbook++**Who runs this:** the platform owner, once, at activation (task 11). Nothing in+this repo moves funds. This document tells you exactly how much real USDC/SOL to+send, which address each goes to, and how to confirm it landed.++> **Read the addresses from env, never from this file.** The wallet addresses are+> resolved from Vercel env at runtime and printed by the verify script. Do not+> paste addresses here — a stale address sends real money to the wrong wallet.++---++## 0. Print the live addresses + current balances++```bash+node scripts/x402-ring-verify.mjs+```++This prints a 3-row table (payer / treasury / sponsor) with each wallet's live+pubkey, registry-match, secret-decode, and current SOL/USDC. **Send funds only to+the pubkeys this command prints.** It never prints a secret. It exits non-zero if+any role is misconfigured — fix that before funding.++For a machine-readable copy: `node scripts/x402-ring-verify.mjs --json`.++---++## 1. What each wallet needs++| Role | Fund with | Amount | Why this size |+|---|---|---|---|+| **payer** | USDC | **$50** (float) | The recirculating principal. Sized to comfortably cover `X402_AUTONOMOUS_DAILY_CAP_ATOMIC` (default $5/day) with headroom; the treasury→payer rebalancer keeps it topped as it cycles. Principal is not spent — it moves payer→treasury→payer. |+| **payer** *(self-pay mode)* | SOL | **0.1 SOL** | In `X402_RING_SELF_PAY=true` mode the payer signs and pays its own 1-signature fee (~5,000 lamports). 0.1 SOL ≈ **~20,000 settlements** before it needs a refill. |+| **sponsor** *(sponsor mode only)* | SOL | **0.1 SOL** | Only if you turn **off** self-pay (unset `X402_RING_SELF_PAY`). Then the sponsor co-signs and pays a 2-signature fee (~10,000 lamports) instead. 0.1 SOL ≈ ~10,000 settlements. |+| **treasury** | nothing | **$0** | It fills from ring payments and gets swept back to the payer. Funding it does nothing useful. |++**Pick one fee model, not both:**++- **Self-pay (recommended, lowest fee):** `X402_RING_SELF_PAY=true`. Fund the+ **payer** with the 0.1 SOL. The sponsor still needs a valid key (it is the+ advertised fee payer in the 402 challenge) but burns no SOL, so it can hold a+ minimal balance.+- **Sponsor:** unset `X402_RING_SELF_PAY`. Fund the **sponsor** with the 0.1 SOL+ instead; the payer needs only its USDC float.++Either way, once funded the **economy master** (`ECONOMY_MASTER_SECRET_BASE58`,+wallet `WwwuGbq…T3WwW`) keeps the sponsor and payer **SOL** topped up+automatically via the guarded [`treasury-topup`](../../api/cron/treasury-topup.js)+cron — both are now registry signers (`x402-ring-sponsor`, `x402-ring-payer`,+floor 0.03 SOL). The master **never** moves USDC and **never** tops up the+treasury, so the payer's **USDC** float is a manual top-up when the balance+monitor alerts.++---++## 2. Send the funds++Use any wallet/exchange you control. Send to the **exact pubkeys printed in+step 0**:++- **USDC** → the **payer** pubkey. Send SPL USDC+ (`EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`) on Solana mainnet. The payer's+ USDC ATA is created on first receipt.+- **SOL** → the **payer** (self-pay) or **sponsor** (sponsor mode) pubkey.++Do not send to the treasury.++---++## 3. Confirm arrival++Re-run the verify script — the balances column reflects the new funds within a+slot or two:++```bash+node scripts/x402-ring-verify.mjs+```++Cross-check the live economy view (reads the same wallets on-chain):++```bash+curl -s https://three.ws/api/x402-ring | jq '.wallets'+```++Expected after funding (self-pay mode):++```json+{+ "treasury": { "address": "…", "usdc": 0 },+ "payer": { "address": "…", "usdc": 50 },+ "sponsor": { "address": "…", "sol": 0.1, "floor_sol": 0.02, "below_floor": false }+}+```++Direct on-chain spot checks (optional):++```bash+# SOL balance of a pubkey+curl -s https://api.mainnet-beta.solana.com -X POST -H 'content-type: application/json' \+ -d '{"jsonrpc":"2.0","id":1,"method":"getBalance","params":["<PAYER_OR_SPONSOR_PUBKEY>"]}' | jq '.result.value'++# USDC balance of the payer+curl -s https://api.mainnet-beta.solana.com -X POST -H 'content-type: application/json' \+ -d '{"jsonrpc":"2.0","id":1,"method":"getTokenAccountsByOwner","params":["<PAYER_PUBKEY>",{"mint":"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"},{"encoding":"jsonParsed"}]}' \+ | jq '.result.value[0].account.data.parsed.info.tokenAmount.uiAmount'+```++---++## 4. Monitoring after funding++Once funded and running, the ring wallets are watched automatically:++- **Balance monitor** ([`wallet-balance-monitor.js`](../../api/_lib/x402/wallet-balance-monitor.js))+ runs every 10 min. It reads all three wallets on-chain and raises an ops alert+ when the sponsor or payer SOL drops below **0.03 SOL** (1.5× the facilitator's+ 0.02 SOL hard floor) or the payer USDC float drops below+ `X402_RING_PAYER_USDC_FLOOR_ATOMIC` (default **$5**). The treasury is unbounded+ (it fills and gets swept), so it never alerts on a low balance.+- **Auto-topup** — the economy master refills sponsor/payer **SOL** to ~0.09 SOL+ when they fall under 0.03 SOL, so the ring never halts on fee SOL. USDC is+ manual.++If you see a `💵 x402 ring payer low on USDC float` alert, send more USDC to the+payer per step 2. If you see `⛽ x402 ring … low on SOL` and the master is funded,+the topup cron handles it; if the master itself is empty you'll get a separate+`⛽ Economy master could not refill` alert — fund `WwwuGbq…T3WwW`.diff --git a/tests/x402-ring-dashboard.test.js b/tests/x402-ring-dashboard.test.jsnew file mode 100644index 000000000..d0fc1eae3--- /dev/null+++ b/tests/x402-ring-dashboard.test.js@@ -0,0 +1,227 @@+// Unit tests for the /admin/ring read model — api/admin/ring-dashboard.js.+//+// The aggregation + threshold helpers are pure (fixture rows → shaped payload,+// no I/O), so these tests pin the pulse status colors, the zero-filled pulse+// strip, activity classification/status, fee efficiency math, endpoint staleness,+// and the integrity source split. A second block asserts the page is wired into+// the router (vercel.json rewrite, vite build input + dev alias) and that the+// admin surface links to it — the acceptance criteria for "findable".++import { describe, it, expect } from 'vitest';+import { readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { dirname, resolve } from 'node:path';++import {+ pulseStatus,+ buildPulseStrip,+ classifyKind,+ activityStatus,+ slugFromUrl,+ endpointAge,+ buildFeesPanel,+ splitIntegrity,+ FEE_FLOOR_LAMPORTS,+ ENDPOINT_STALE_MINUTES,+} from '../api/admin/ring-dashboard.js';++const __dirname = dirname(fileURLToPath(import.meta.url));+const p = (...parts) => resolve(__dirname, '..', ...parts);++describe('ring dashboard — pulse status thresholds', () => {+ it('≤1 min is green (per-minute tick alive)', () => {+ expect(pulseStatus(0)).toBe('green');+ expect(pulseStatus(1)).toBe('green');+ expect(pulseStatus(0.5)).toBe('green');+ });+ it('>1 and ≤5 min is amber (tick degraded)', () => {+ expect(pulseStatus(2)).toBe('amber');+ expect(pulseStatus(5)).toBe('amber');+ });+ it('>5 min is red (ring stalled)', () => {+ expect(pulseStatus(6)).toBe('red');+ expect(pulseStatus(120)).toBe('red');+ });+ it('null (no settle on record) is red', () => {+ expect(pulseStatus(null)).toBe('red');+ expect(pulseStatus(undefined)).toBe('red');+ });+});++describe('ring dashboard — pulse strip zero-fill', () => {+ const now = new Date('2026-07-03T12:00:30Z');++ it('always returns a full 60-minute window, oldest → newest', () => {+ const strip = buildPulseStrip([], now);+ expect(strip).toHaveLength(60);+ expect(new Date(strip[0].ts).getTime()).toBeLessThan(new Date(strip[59].ts).getTime());+ expect(strip.every((m) => m.count === 0)).toBe(true);+ });++ it('places settlement counts in the correct minute bucket and zero-fills gaps', () => {+ const rows = [+ { minute: '2026-07-03T12:00:00Z', n: 3, fee: 15000 },+ { minute: '2026-07-03T11:58:00Z', n: 1, fee: 5000 },+ ];+ const strip = buildPulseStrip(rows, now);+ const last = strip[strip.length - 1]; // current minute (12:00)+ expect(last.count).toBe(3);+ expect(last.fee_lamports).toBe(15000);+ // 11:59 has no row → visible gap+ expect(strip[strip.length - 2].count).toBe(0);+ // 11:58 → 1 settle+ expect(strip[strip.length - 3].count).toBe(1);+ });+});++describe('ring dashboard — activity classification', () => {+ it('classifies kind off the endpoint path', () => {+ expect(classifyKind('/api/x402/ring-settle')).toBe('settle');+ expect(classifyKind('/api/x402/dance-tip')).toBe('tip');+ expect(classifyKind('/api/x402/crypto-intel')).toBe('intel');+ expect(classifyKind('/api/x402/agent-reputation')).toBe('intel');+ expect(classifyKind('/api/x402/skill-checkout')).toBe('commerce');+ expect(classifyKind('/api/x402/did')).toBe('service');+ expect(classifyKind('')).toBe('service');+ });++ it('marks paid vs ok vs skipped vs failed', () => {+ expect(activityStatus({ success: true, amount_atomic: 1000 })).toBe('paid');+ expect(activityStatus({ success: true, amount_atomic: 0 })).toBe('ok');+ expect(activityStatus({ success: false, error_msg: 'cap_would_exceed' })).toBe('skipped');+ expect(activityStatus({ success: false, error_msg: 'fee_wallet_below_floor:1<2' })).toBe(+ 'skipped',+ );+ expect(activityStatus({ success: false, error_msg: 'RPC timeout' })).toBe('failed');+ });++ it('derives a short slug from a full URL or a path', () => {+ expect(slugFromUrl('https://three.ws/api/x402/crypto-intel?x=1')).toBe('crypto-intel');+ expect(slugFromUrl('/api/x402/dance-tip')).toBe('dance-tip');+ expect(slugFromUrl('')).toBe('—');+ });+});++describe('ring dashboard — endpoint staleness', () => {+ const now = new Date('2026-07-03T12:00:00Z');+ it('flags stale past the 2h hourly-coverage guarantee', () => {+ const fresh = endpointAge(new Date('2026-07-03T11:30:00Z'), now);+ expect(fresh.stale).toBe(false);+ expect(fresh.age_minutes).toBe(30);++ const stale = endpointAge(new Date('2026-07-03T09:00:00Z'), now);+ expect(stale.stale).toBe(true);+ expect(stale.age_minutes).toBe(180);+ });+ it('never-called endpoints are stale with null age', () => {+ expect(endpointAge(null, now)).toEqual({ age_minutes: null, stale: true });+ });+ it('exposes the 120-minute threshold constant', () => {+ expect(ENDPOINT_STALE_MINUTES).toBe(120);+ });+});++describe('ring dashboard — fee efficiency', () => {+ it('computes avg fee, floor ratio, SOL/$100, and budget usage', () => {+ const fees = buildFeesPanel({+ feeLamports24h: 50_000, // 10 settles @ 5000+ settles24h: 10,+ grossUsdc24h: 1000, // $1000 gross+ burnedTodayLamports: 30_000,+ budgetLamports: 100_000,+ solUsd: 150,+ });+ expect(fees.floor_lamports).toBe(FEE_FLOOR_LAMPORTS);+ expect(fees.avg_lamports_per_settle).toBe(5000);+ expect(fees.floor_ratio).toBe(1); // exactly at the 1-sig floor+ // 50000 lamports = 0.00005 SOL over $1000 → per $100 = 0.000005+ expect(fees.sol_per_100_usd).toBeCloseTo(0.000005, 9);+ expect(fees.budget_used_pct).toBe(30);+ expect(fees.over_budget).toBe(false);+ });++ it('flags over-budget burn', () => {+ const fees = buildFeesPanel({+ feeLamports24h: 0,+ settles24h: 0,+ grossUsdc24h: 0,+ burnedTodayLamports: 120_000,+ budgetLamports: 100_000,+ });+ expect(fees.over_budget).toBe(true);+ expect(fees.budget_used_pct).toBe(120);+ expect(fees.avg_lamports_per_settle).toBeNull();+ expect(fees.sol_per_100_usd).toBeNull();+ });++ it('handles an unset daily budget without dividing by zero', () => {+ const fees = buildFeesPanel({ budgetLamports: null });+ expect(fees.budget_used_pct).toBeNull();+ expect(fees.over_budget).toBe(false);+ });+});++describe('ring dashboard — integrity source split', () => {+ it('separates ring leak-scan sources from revenue reconciliation', () => {+ const split = splitIntegrity([+ { source: 'x402_ring_settle', total: 40, open: 2, last_checked: '2026-07-03T11:00:00Z' },+ { source: 'x402_ring_sweep', total: 10, open: 0, last_checked: '2026-07-03T11:30:00Z' },+ { source: 'autonomous_log', total: 100, open: 1, last_checked: '2026-07-03T10:00:00Z' },+ { source: 'payment_intent', total: 5, open: 0, last_checked: '2026-07-03T09:00:00Z' },+ ]);+ expect(split.leak_scan.sources).toBe(2);+ expect(split.leak_scan.total).toBe(50);+ expect(split.leak_scan.open).toBe(2);+ expect(split.leak_scan.last_checked_at).toBe('2026-07-03T11:30:00.000Z');+ expect(split.reconcile.sources).toBe(2);+ expect(split.reconcile.open).toBe(1);+ });+ it('is all-zero for an empty verdict set', () => {+ const split = splitIntegrity([]);+ expect(split.leak_scan.open).toBe(0);+ expect(split.reconcile.open).toBe(0);+ expect(split.leak_scan.last_checked_at).toBeNull();+ });+});++describe('ring dashboard — routing + navigation wiring', () => {+ const vercel = JSON.parse(readFileSync(p('vercel.json'), 'utf8'));+ const viteConfig = readFileSync(p('vite.config.js'), 'utf8');+ const adminIndex = readFileSync(p('public/admin/index.html'), 'utf8');+ const pages = JSON.parse(readFileSync(p('data/pages.json'), 'utf8'));++ it('has vercel rewrites for /admin/ring (with and without trailing slash)', () => {+ const routes = vercel.routes || vercel.rewrites || [];+ const dests = routes.filter((r) => r.src === '/admin/ring' || r.src === '/admin/ring/');+ expect(dests).toHaveLength(2);+ expect(dests.every((r) => r.dest === '/admin/ring.html')).toBe(true);+ });++ it('registers the page as a vite build input and dev alias', () => {+ expect(viteConfig).toContain("'admin-ring': resolve(__dirname, 'pages/admin/ring.html')");+ expect(viteConfig).toContain("'/admin/ring': resolve(root, 'pages/admin/ring.html')");+ });++ it('is linked from the admin surface so it is findable', () => {+ expect(adminIndex).toContain('href="/admin/ring"');+ });++ it('is registered in pages.json as an admin, noindex surface', () => {+ const all = pages.sections.flatMap((s) => s.pages);+ const entry = all.find((p2) => p2.path === '/admin/ring');+ expect(entry).toBeTruthy();+ expect(entry.indexable).toBe(false);+ expect(entry.auth).toBe('admin');+ });++ it('ships the page, controller, and endpoint files', () => {+ for (const f of [+ 'pages/admin/ring.html',+ 'src/admin-ring.js',+ 'src/admin-ring.css',+ 'api/admin/ring-dashboard.js',+ ]) {+ expect(() => readFileSync(p(f), 'utf8')).not.toThrow();+ }+ });+});diff --git a/tests/x402-ring-fee-floor.test.js b/tests/x402-ring-fee-floor.test.jsnew file mode 100644index 000000000..b62257b92--- /dev/null+++ b/tests/x402-ring-fee-floor.test.js@@ -0,0 +1,233 @@+import { describe, it, expect, beforeAll } from 'vitest';+import { Keypair, PublicKey } from '@solana/web3.js';+import { getAssociatedTokenAddressSync, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID } from '@solana/spl-token';++// Fee-floor regression + self-pay + ATA-reclaim safety for the closed x402 ring.+// The rule under test is "the lowest fees ALWAYS": 1-signature self-pay+// settlement pinned at the floor, a hard per-tx fee ceiling the builders can+// never cross, and a rent reclaim that can NEVER close a funded or active ATA.+// Pure logic — no DB, no chain.+const USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';+process.env.X402_ASSET_MINT_SOLANA = USDC;++const pay = await import('../api/_lib/x402/pay.js');+const {+ expectedFeeLamports, ringPriorityMicrolamports, ringSelfPayDefault,+ ringMaxFeePerTxLamports, buildPaymentTx, SIGNATURE_FEE_LAMPORTS, RING_CU_LIMIT,+} = pay;+const { validateRingTransaction } = await import('../api/_lib/x402/self-facilitator.js');+const {+ computeFeeEfficiency, selectClosableAtas, activeRoleAtas, FEE_AUDIT,+} = await import('../api/_lib/x402/pipelines/fee-audit.js');++const solAddr = () => Keypair.generate().publicKey.toBase58();+const ataFor = (mint, owner) => getAssociatedTokenAddressSync(+ new PublicKey(mint), new PublicKey(owner), false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,+).toBase58();++describe('expectedFeeLamports — the fee-floor math', () => {+ it('self-pay is 1 signature = 5,000 lamports + priority', () => {+ expect(expectedFeeLamports({ selfPay: true, priorityMicrolamports: 0, cuLimit: RING_CU_LIMIT })).toBe(5000);+ // Baseline priority (5 µlamports × 60k CU = 0.3 lamports → floors to 0).+ expect(expectedFeeLamports({ selfPay: true, priorityMicrolamports: 5, cuLimit: RING_CU_LIMIT })).toBe(5000);+ });+ it('sponsor mode is 2 signatures = 10,000 lamports + priority', () => {+ expect(expectedFeeLamports({ selfPay: false, priorityMicrolamports: 0, cuLimit: RING_CU_LIMIT })).toBe(10000);+ });+ it('worst-case priority perturbation stays negligible', () => {+ // The nonce perturbation tops out at 1001 µlamports (5 + 996).+ const worst = expectedFeeLamports({ selfPay: true, priorityMicrolamports: 1001, cuLimit: RING_CU_LIMIT });+ expect(worst).toBe(5060); // 5000 + floor(1001*60000/1e6=60.06)=60+ expect(worst).toBeLessThanOrEqual(5100); // acceptance bar for a self-paid settle+ });+});++describe('fee-floor regression guard — builders never exceed the ceiling', () => {+ const ceiling = ringMaxFeePerTxLamports(); // 10,000 default+ it('every nonce in a batch keeps a self-paid tx under the ceiling', () => {+ for (let nonce = 0; nonce < 997; nonce++) {+ const fee = expectedFeeLamports({+ selfPay: true,+ priorityMicrolamports: ringPriorityMicrolamports(nonce),+ cuLimit: RING_CU_LIMIT,+ });+ expect(fee).toBeLessThanOrEqual(ceiling);+ expect(fee).toBeLessThanOrEqual(5100); // and under the self-pay acceptance bar+ }+ });+ it('sponsor mode at the baseline priority sits exactly at the ceiling, never above', () => {+ for (let nonce = 0; nonce < 997; nonce++) {+ const fee = expectedFeeLamports({+ selfPay: false,+ priorityMicrolamports: ringPriorityMicrolamports(nonce),+ cuLimit: RING_CU_LIMIT,+ });+ // 10,000 base + up to 60 priority = 10,060 — this is why the ceiling+ // default (10,000) is the SELF-PAY-mode guarantee; sponsor mode is the+ // fallback and its priority is bounded by the facilitator guard instead.+ expect(fee).toBeLessThanOrEqual(10_060);+ }+ });+});++describe('self-pay default — operative for the ring', () => {+ it('defaults to true when X402_RING_SELF_PAY is unset', () => {+ delete process.env.X402_RING_SELF_PAY;+ expect(ringSelfPayDefault()).toBe(true);+ });+ it('honors an explicit false (sponsor mode still selectable)', () => {+ process.env.X402_RING_SELF_PAY = 'false';+ expect(ringSelfPayDefault()).toBe(false);+ process.env.X402_RING_SELF_PAY = 'FALSE';+ expect(ringSelfPayDefault()).toBe(false);+ delete process.env.X402_RING_SELF_PAY;+ });+ it('treats true/1/anything-else as self-pay', () => {+ process.env.X402_RING_SELF_PAY = 'true';+ expect(ringSelfPayDefault()).toBe(true);+ delete process.env.X402_RING_SELF_PAY;+ });+});++describe('self-pay build → facilitator validate roundtrip (zero sponsor)', () => {+ const buyer = Keypair.generate();+ const treasury = Keypair.generate();+ const sponsor = Keypair.generate();+ const blockhash = '11111111111111111111111111111111'; // any valid base58 32-byte-ish+ const accept = {+ network: 'solana:mainnet',+ asset: USDC,+ payTo: treasury.publicKey.toBase58(),+ amount: '1000000', // $1.00+ extra: { feePayer: sponsor.publicKey.toBase58() },+ };+ const requirement = { network: 'solana:mainnet', asset: USDC, payTo: accept.payTo, amount: '1000000' };+ const allowlist = new Set([accept.payTo]);++ it('a self-paid tx validates as self-pay with a 1-signature fee, no sponsor needed', () => {+ const txBase64 = buildPaymentTx({+ accept, buyer, blockhash,+ mintInfo: { decimals: 6 }, receiverAtaExists: true, nonce: 0, selfPay: true,+ });+ const v = validateRingTransaction({+ txBase64, requirement,+ feePayerPubkey: null, // no sponsor advertised — self-pay must not need one+ allowlist,+ });+ expect(v.ok).toBe(true);+ expect(v.decoded.selfPay).toBe(true);+ expect(v.decoded.payer).toBe(buyer.publicKey.toBase58());+ expect(v.decoded.feePayer).toBe(buyer.publicKey.toBase58());+ // 1 signature × 5000 + negligible priority, no ATA create.+ expect(v.decoded.estFeeLamports).toBeLessThanOrEqual(5100);+ expect(v.decoded.estFeeLamports).toBeGreaterThanOrEqual(SIGNATURE_FEE_LAMPORTS);+ });++ it('sponsor mode still validates (the gasless-buyer fallback is intact)', () => {+ const txBase64 = buildPaymentTx({+ accept, buyer, blockhash,+ mintInfo: { decimals: 6 }, receiverAtaExists: true, nonce: 0, selfPay: false,+ });+ const v = validateRingTransaction({+ txBase64, requirement,+ feePayerPubkey: sponsor.publicKey.toBase58(),+ allowlist,+ });+ expect(v.ok).toBe(true);+ expect(v.decoded.selfPay).toBe(false);+ expect(v.decoded.feePayer).toBe(sponsor.publicKey.toBase58());+ expect(v.decoded.estFeeLamports).toBeLessThanOrEqual(10_100);+ });+});++describe('computeFeeEfficiency — the measured numbers', () => {+ it('derives lamports-per-settlement and sol-per-$100 from real totals', () => {+ // 100 settlements, 5,000 lamports each = 500,000 lamports on $100 gross.+ const e = computeFeeEfficiency({+ feesLamports: 500_000, settlements: 100, grossVolumeAtomic: 100_000_000, budgetLamports: 50_000_000,+ });+ expect(e.lamports_per_settlement).toBe(5000);+ expect(e.sol_burned).toBeCloseTo(0.0005, 9);+ // 0.0005 SOL on $100 gross → 0.0005 SOL per $100.+ expect(e.sol_per_100_usd).toBeCloseTo(0.0005, 9);+ expect(e.above_floor).toBe(false);+ expect(e.over_budget).toBe(false);+ });+ it('flags above_floor when per-settlement fee exceeds 1.5× the 1-sig floor', () => {+ const e = computeFeeEfficiency({ feesLamports: 8000 * 10, settlements: 10, grossVolumeAtomic: 10_000_000 });+ expect(e.lamports_per_settlement).toBe(8000);+ expect(e.above_floor).toBe(true); // 8000 > 7500+ });+ it('flags over_budget when daily burn exceeds the budget', () => {+ const e = computeFeeEfficiency({+ feesLamports: 60_000_000, settlements: 10_000, grossVolumeAtomic: 1_000_000_000, budgetLamports: 50_000_000,+ });+ expect(e.over_budget).toBe(true); // 0.06 SOL > 0.05 SOL budget+ });+ it('never divides by zero — no settlements / no volume yields nulls, not NaN', () => {+ const e = computeFeeEfficiency({ feesLamports: 0, settlements: 0, grossVolumeAtomic: 0 });+ expect(e.lamports_per_settlement).toBeNull();+ expect(e.sol_per_100_usd).toBeNull();+ expect(e.above_floor).toBe(false);+ });+});++describe('ATA rent reclaim — SAFETY: never closes a funded or active ATA', () => {+ const payer = solAddr();+ const treasury = solAddr();+ const sponsor = solAddr();+ const activeSet = activeRoleAtas({ mint: USDC, owners: [payer, treasury, sponsor] });++ it('computes exactly the three canonical role ATAs', () => {+ expect(activeSet.size).toBe(3);+ expect(activeSet.has(ataFor(USDC, payer))).toBe(true);+ expect(activeSet.has(ataFor(USDC, treasury))).toBe(true);+ expect(activeSet.has(ataFor(USDC, sponsor))).toBe(true);+ });++ it('NEVER returns an active role ATA even when it is empty', () => {+ const accounts = [+ { pubkey: ataFor(USDC, payer), amount: 0n, mint: USDC }, // active + empty+ { pubkey: ataFor(USDC, treasury), amount: 0n, mint: USDC }, // active + empty+ { pubkey: ataFor(USDC, sponsor), amount: 0n, mint: USDC }, // active + empty+ ];+ const closable = selectClosableAtas({ accounts, activeAtaSet: activeSet, mint: USDC, cap: 5 });+ expect(closable).toEqual([]);+ });++ it('NEVER returns an account with a balance, active or not', () => {+ const funded = solAddr();+ const accounts = [+ { pubkey: ataFor(USDC, funded), amount: 1n, mint: USDC }, // non-role but funded+ { pubkey: ataFor(USDC, payer), amount: 1_000_000n, mint: USDC }, // active + funded+ ];+ const closable = selectClosableAtas({ accounts, activeAtaSet: activeSet, mint: USDC, cap: 5 });+ expect(closable).toEqual([]);+ });++ it('returns ONLY zero-balance, non-role ATAs', () => {+ const stale1 = ataFor(USDC, solAddr());+ const stale2 = ataFor(USDC, solAddr());+ const accounts = [+ { pubkey: stale1, amount: 0n, mint: USDC }, // ✓ closable+ { pubkey: ataFor(USDC, payer), amount: 0n, mint: USDC }, // active — excluded+ { pubkey: stale2, amount: 0n, mint: USDC }, // ✓ closable+ { pubkey: ataFor(USDC, treasury), amount: 500n, mint: USDC }, // active + funded — excluded+ ];+ const closable = selectClosableAtas({ accounts, activeAtaSet: activeSet, mint: USDC, cap: 5 });+ expect(closable.sort()).toEqual([stale1, stale2].sort());+ });++ it('ignores accounts of a different mint', () => {+ const OTHER = solAddr();+ const accounts = [{ pubkey: solAddr(), amount: 0n, mint: OTHER }];+ expect(selectClosableAtas({ accounts, activeAtaSet: activeSet, mint: USDC, cap: 5 })).toEqual([]);+ });++ it('caps the number of closes per run', () => {+ const accounts = Array.from({ length: 12 }, () => ({ pubkey: ataFor(USDC, solAddr()), amount: 0n, mint: USDC }));+ const closable = selectClosableAtas({ accounts, activeAtaSet: activeSet, mint: USDC, cap: FEE_AUDIT.maxClosesPerRun });+ expect(closable.length).toBe(FEE_AUDIT.maxClosesPerRun);+ expect(FEE_AUDIT.maxClosesPerRun).toBe(5);+ });+});diff --git a/tests/x402-ring-floors.test.js b/tests/x402-ring-floors.test.jsnew file mode 100644index 000000000..45f6cc61d--- /dev/null+++ b/tests/x402-ring-floors.test.js@@ -0,0 +1,93 @@+import { describe, it, expect } from 'vitest';++import { ringFloorSpecs, evaluateRingWallet, LAMPORTS_PER_SOL } from '../api/_lib/x402/ring-floors.js';++// Role-appropriate floors for the closed-loop ring wallets. These tests pin the+// exact breach semantics the balance monitor relies on: sponsor/payer have SOL+// floors, the payer has a USDC float floor, the treasury has NO floor (it fills+// and gets swept), and a null (RPC-failed) balance never fabricates a breach.++const SOL_FLOOR = 30_000_000; // 0.03 SOL+const USDC_FLOOR = 5_000_000; // $5++describe('ringFloorSpecs', () => {+ it('gives the sponsor a SOL floor and no USDC floor', () => {+ const [sponsor] = ringFloorSpecs({ solFloorLamports: SOL_FLOOR, payerUsdcFloorAtomic: USDC_FLOOR, selfPay: true });+ expect(sponsor.role).toBe('sponsor');+ expect(sponsor.solFloor).toBe(SOL_FLOOR);+ expect(sponsor.usdcFloor).toBeNull();+ expect(sponsor.watchUsdc).toBe(false);+ });++ it('gives the payer a SOL floor only in self-pay mode', () => {+ const selfPay = ringFloorSpecs({ solFloorLamports: SOL_FLOOR, payerUsdcFloorAtomic: USDC_FLOOR, selfPay: true });+ const sponsored = ringFloorSpecs({ solFloorLamports: SOL_FLOOR, payerUsdcFloorAtomic: USDC_FLOOR, selfPay: false });+ expect(selfPay.find((s) => s.role === 'payer').solFloor).toBe(SOL_FLOOR);+ expect(sponsored.find((s) => s.role === 'payer').solFloor).toBeNull();+ // The payer always has its USDC float floor regardless of fee mode.+ expect(selfPay.find((s) => s.role === 'payer').usdcFloor).toBe(USDC_FLOOR);+ expect(sponsored.find((s) => s.role === 'payer').usdcFloor).toBe(USDC_FLOOR);+ });++ it('gives the treasury no floors — it fills and gets swept', () => {+ const treasury = ringFloorSpecs({ solFloorLamports: SOL_FLOOR, payerUsdcFloorAtomic: USDC_FLOOR, selfPay: true })+ .find((s) => s.role === 'treasury');+ expect(treasury.solFloor).toBeNull();+ expect(treasury.usdcFloor).toBeNull();+ });+});++describe('evaluateRingWallet', () => {+ const [sponsor, payer, treasury] = ringFloorSpecs({ solFloorLamports: SOL_FLOOR, payerUsdcFloorAtomic: USDC_FLOOR, selfPay: true });++ it('flags a sponsor below the SOL floor', () => {+ const r = evaluateRingWallet(sponsor, 'Spon', 10_000_000, null); // 0.01 SOL+ expect(r.sol_low).toBe(true);+ expect(r.sol).toBeCloseTo(0.01);+ expect(r.sol_floor).toBeCloseTo(0.03);+ });++ it('does not flag a sponsor at or above the SOL floor', () => {+ expect(evaluateRingWallet(sponsor, 'Spon', SOL_FLOOR, null).sol_low).toBe(false);+ expect(evaluateRingWallet(sponsor, 'Spon', 50_000_000, null).sol_low).toBe(false);+ });++ it('flags a payer below the USDC float floor', () => {+ const r = evaluateRingWallet(payer, 'Pay', 50_000_000, 3_000_000); // 0.05 SOL, $3+ expect(r.usdc_low).toBe(true);+ expect(r.sol_low).toBe(false);+ expect(r.usdc).toBeCloseTo(3);+ });++ it('does not flag a healthy payer', () => {+ const r = evaluateRingWallet(payer, 'Pay', 50_000_000, 82_000_000); // $82+ expect(r.usdc_low).toBe(false);+ expect(r.sol_low).toBe(false);+ });++ it('never flags the treasury, even at zero', () => {+ const r = evaluateRingWallet(treasury, 'Trez', 0, 0);+ expect(r.sol_low).toBe(false);+ expect(r.usdc_low).toBe(false);+ expect(r.sol_floor).toBeNull();+ expect(r.usdc_floor).toBeNull();+ });++ it('treats a null (RPC-failed) balance as unknown, not a breach', () => {+ const r = evaluateRingWallet(sponsor, 'Spon', null, null);+ expect(r.sol_low).toBe(false);+ expect(r.sol).toBeNull();+ });++ it('reports an unconfigured wallet when the address is missing', () => {+ const r = evaluateRingWallet(sponsor, null, 1, 1);+ expect(r.configured).toBe(false);+ expect(r.address).toBeNull();+ });++ it('converts lamports and atomic USDC to human units', () => {+ const r = evaluateRingWallet(payer, 'Pay', 1 * LAMPORTS_PER_SOL, 12_500_000);+ expect(r.sol).toBe(1);+ expect(r.usdc).toBe(12.5);+ });+});diff --git a/tests/x402-ring-invariants.test.js b/tests/x402-ring-invariants.test.jsnew file mode 100644index 000000000..68ae47d28--- /dev/null+++ b/tests/x402-ring-invariants.test.js@@ -0,0 +1,135 @@+// Tests for the ring spend invariants + controlled-wallet allowlist+// (api/_lib/x402/ring-allowlist.js).+//+// The invariants keep the loop CLOSED: a spend path only runs when external+// spending is off, the charity split is zero, and settlement routes to our own+// facilitator. checkRingInvariants() is pure; assertRingSpendInvariants() adds+// the throttled CRITICAL alert + fail-closed return. ringAllowedAddresses()+// builds the controlled-wallet set the leak scanner classifies against.++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++vi.mock('../api/_lib/alerts.js', () => ({ sendOpsAlert: vi.fn(async () => {}) }));++const {+ checkRingInvariants,+ assertRingSpendInvariants,+ facilitatorResolvesToSelf,+ ringAllowedAddresses,+} = await import('../api/_lib/x402/ring-allowlist.js');+const { sendOpsAlert } = await import('../api/_lib/alerts.js');++const RING_VARS = [+ 'X402_EXTERNAL_ENABLED', 'X402_CHARITY_AUDIT_BPS', 'X402_SELF_FACILITATOR_ENABLED',+ 'X402_FACILITATOR_URL_SOLANA', 'X402_FACILITATOR_URL', 'PUBLIC_APP_ORIGIN',+ 'X402_SEED_SOLANA_SECRET_BASE58', 'X402_AGENT_SOLANA_SECRET_BASE58',+ 'X402_PAY_TO_SOLANA', 'X402_FEE_PAYER_SOLANA', 'X402_SELF_FACILITATOR_PAYTO_ALLOWLIST',+];++function healthyEnv() {+ process.env.X402_EXTERNAL_ENABLED = 'false';+ process.env.X402_CHARITY_AUDIT_BPS = '0';+ process.env.X402_SELF_FACILITATOR_ENABLED = 'true';+ delete process.env.X402_FACILITATOR_URL_SOLANA;+ delete process.env.X402_FACILITATOR_URL;+ delete process.env.PUBLIC_APP_ORIGIN;+}++beforeEach(() => {+ for (const v of RING_VARS) delete process.env[v];+ sendOpsAlert.mockClear();+});+afterEach(() => { for (const v of RING_VARS) delete process.env[v]; });++describe('checkRingInvariants', () => {+ it('passes when all three guards hold', () => {+ healthyEnv();+ const r = checkRingInvariants();+ expect(r.ok).toBe(true);+ expect(r.violations).toHaveLength(0);+ });++ it('flags X402_EXTERNAL_ENABLED when it is not exactly "false"', () => {+ healthyEnv();+ process.env.X402_EXTERNAL_ENABLED = 'true';+ const r = checkRingInvariants();+ expect(r.ok).toBe(false);+ expect(r.violations.map((v) => v.flag)).toContain('X402_EXTERNAL_ENABLED');+ });++ it('flags an unset X402_EXTERNAL_ENABLED (fails CLOSED, not open)', () => {+ healthyEnv();+ delete process.env.X402_EXTERNAL_ENABLED;+ const r = checkRingInvariants();+ expect(r.ok).toBe(false);+ expect(r.violations.map((v) => v.flag)).toContain('X402_EXTERNAL_ENABLED');+ });++ it('flags a non-zero or unset X402_CHARITY_AUDIT_BPS', () => {+ healthyEnv();+ process.env.X402_CHARITY_AUDIT_BPS = '500';+ expect(checkRingInvariants().violations.map((v) => v.flag)).toContain('X402_CHARITY_AUDIT_BPS');+ delete process.env.X402_CHARITY_AUDIT_BPS;+ expect(checkRingInvariants().violations.map((v) => v.flag)).toContain('X402_CHARITY_AUDIT_BPS');+ });++ it('flags settlement routing to an external facilitator', () => {+ healthyEnv();+ process.env.X402_FACILITATOR_URL_SOLANA = 'https://facilitator.payai.network';+ const r = checkRingInvariants();+ expect(r.ok).toBe(false);+ expect(r.violations.some((v) => v.flag.includes('FACILITATOR'))).toBe(true);+ });++ it('flags a disabled self-facilitator', () => {+ healthyEnv();+ process.env.X402_SELF_FACILITATOR_ENABLED = 'false';+ expect(checkRingInvariants().ok).toBe(false);+ });+});++describe('facilitatorResolvesToSelf', () => {+ it('is true for the self-hosted facilitator, false for external', () => {+ healthyEnv();+ expect(facilitatorResolvesToSelf()).toBe(true);+ process.env.X402_FACILITATOR_URL_SOLANA = 'https://facilitator.payai.network';+ expect(facilitatorResolvesToSelf()).toBe(false);+ });+});++describe('assertRingSpendInvariants — fail closed + one throttled alert', () => {+ it('returns ok and fires no alert when guards hold', async () => {+ healthyEnv();+ const r = await assertRingSpendInvariants({ context: 'test' });+ expect(r.ok).toBe(true);+ expect(sendOpsAlert).not.toHaveBeenCalled();+ });++ it('returns ok:false and fires ONE CRITICAL alert naming the flipped flag', async () => {+ healthyEnv();+ process.env.X402_EXTERNAL_ENABLED = 'true';+ const r = await assertRingSpendInvariants({ context: 'x402-ring-tick' });+ expect(r.ok).toBe(false);+ expect(sendOpsAlert).toHaveBeenCalledTimes(1);+ const [title, body, opts] = sendOpsAlert.mock.calls[0];+ expect(title).toMatch(/invariant/i);+ expect(body).toMatch(/X402_EXTERNAL_ENABLED/);+ // dedup signature keys on the sorted flag set so repeated ticks don't flood.+ expect(opts.signature).toContain('ring-invariant:');+ });+});++describe('ringAllowedAddresses', () => {+ it('includes the ring role wallets + explicit extras, degrading without a DB', async () => {+ healthyEnv();+ process.env.X402_PAY_TO_SOLANA = 'RingTreasury11111111111111111111111111111111';+ process.env.X402_FEE_PAYER_SOLANA = 'RingSponsor11111111111111111111111111111111';+ process.env.X402_SELF_FACILITATOR_PAYTO_ALLOWLIST = 'ExtraControlled1111111111111111111111111111';+ // Inject a throwing sql so the DB branch degrades (shrinks, never widens).+ const sql = async () => { throw new Error('no db'); };+ const set = await ringAllowedAddresses({ sql });+ expect(set.has('RingTreasury11111111111111111111111111111111')).toBe(true);+ expect(set.has('RingSponsor11111111111111111111111111111111')).toBe(true);+ expect(set.has('ExtraControlled1111111111111111111111111111')).toBe(true);+ });+});diff --git a/tests/x402-ring-leak-classify.test.js b/tests/x402-ring-leak-classify.test.jsnew file mode 100644index 000000000..657c54afe--- /dev/null+++ b/tests/x402-ring-leak-classify.test.js@@ -0,0 +1,286 @@+// Pure-logic tests for the on-chain leak classifier+// (api/cron/x402-ring-leak-scan.js → classifyWalletDebits).+//+// The classifier decides, for a single parsed transaction, whether each debit+// FROM a ring wallet is internal (counterparty controlled), a network fee, or a+// LEAK (funds left the controlled set) — plus SPL Approve delegation risk. These+// tests feed it synthetic jsonParsed transaction shapes (SYNTHETIC addresses+// only, no real mints or wallets) and assert the six canonical classifications.+//+// Also covers cursor resumption at the scanWallet level (mocked RPC + DB) and+// the fee-divergence helper.++import { describe, it, expect, vi, beforeEach } from 'vitest';++// scanWallet touches db.js (loadCursor/saveCursor/upsertVerdict) and alerts.js.+// Mock both so the cursor-resumption test is deterministic and offline.+const sqlCalls = [];+const sqlQueue = [];+vi.mock('../api/_lib/db.js', () => ({+ sql: vi.fn(async (strings, ...values) => {+ sqlCalls.push({ text: strings.join('?'), values });+ return sqlQueue.length ? sqlQueue.shift() : [];+ }),+}));+vi.mock('../api/_lib/alerts.js', () => ({ sendOpsAlert: vi.fn(async () => {}) }));++const {+ classifyWalletDebits,+ accountKeyStrings,+ feeDivergence,+ scanWallet,+} = await import('../api/cron/x402-ring-leak-scan.js');+const { sendOpsAlert } = await import('../api/_lib/alerts.js');++// ── Synthetic universe ────────────────────────────────────────────────────────+const USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'; // canonical mint the classifier defaults to+const OTHER_MINT = 'OtherMint1111111111111111111111111111111111';+const PAYER = 'RingPayer111111111111111111111111111111111';+const PAYER_ATA = 'RingPayerAta1111111111111111111111111111111';+const TREASURY = 'RingTreasury11111111111111111111111111111111';+const TREASURY_ATA = 'RingTreasuryAta111111111111111111111111111';+const SPONSOR = 'RingSponsor11111111111111111111111111111111';+const UNKNOWN = 'ExternalStranger1111111111111111111111111111';+const UNKNOWN_ATA = 'ExternalStrangerAta11111111111111111111111';+const DELEGATE = 'MaliciousDelegate11111111111111111111111111';++// Everything the platform controls (owners + ATAs). PAYER/TREASURY/SPONSOR are+// internal; UNKNOWN is not.+const ALLOWED = new Set([PAYER, PAYER_ATA, TREASURY, TREASURY_ATA, SPONSOR]);++function baseMeta(overrides = {}) {+ return {+ fee: 5000,+ err: null,+ preBalances: [100_000_000],+ postBalances: [99_995_000], // -5000 = fee only+ preTokenBalances: [],+ postTokenBalances: [],+ innerInstructions: [],+ ...overrides,+ };+}++function tx({ signature = 'sig', keys, instructions = [], meta }) {+ return {+ transaction: {+ signatures: [signature],+ message: { accountKeys: keys.map((pubkey) => ({ pubkey })), instructions },+ },+ meta,+ };+}++describe('classifyWalletDebits — the six canonical cases', () => {+ it('1. internal USDC transfer (payer → treasury) classifies internal, no leak', () => {+ const t = tx({+ keys: [PAYER, PAYER_ATA, TREASURY_ATA],+ instructions: [{+ program: 'spl-token',+ parsed: { type: 'transferChecked', info: { source: PAYER_ATA, destination: TREASURY_ATA, authority: PAYER, mint: USDC, tokenAmount: { amount: '1000000', decimals: 6 } } },+ }],+ meta: baseMeta({+ preTokenBalances: [+ { accountIndex: 1, mint: USDC, owner: PAYER, uiTokenAmount: { amount: '5000000' } },+ { accountIndex: 2, mint: USDC, owner: TREASURY, uiTokenAmount: { amount: '0' } },+ ],+ postTokenBalances: [+ { accountIndex: 1, mint: USDC, owner: PAYER, uiTokenAmount: { amount: '4000000' } },+ { accountIndex: 2, mint: USDC, owner: TREASURY, uiTokenAmount: { amount: '1000000' } },+ ],+ }),+ });+ const r = classifyWalletDebits(t, { wallet: PAYER, allowed: ALLOWED, usdcMint: USDC });+ expect(r.unreadable).toBe(false);+ const leaks = r.events.filter((e) => e.type === 'leak');+ expect(leaks).toHaveLength(0);+ const usdcEvent = r.events.find((e) => e.asset === 'USDC');+ expect(usdcEvent).toMatchObject({ type: 'internal', counterparty: TREASURY, amountAtomic: 1_000_000 });+ });++ it('2. fee-only tx: network fee attributed, no debit events', () => {+ const t = tx({+ keys: [SPONSOR],+ instructions: [{ program: 'spl-memo', parsed: { type: 'memo', info: {} } }],+ meta: baseMeta(), // -5000 lamports = fee exactly+ });+ const r = classifyWalletDebits(t, { wallet: SPONSOR, allowed: ALLOWED, usdcMint: USDC });+ expect(r.fee).toEqual({ lamports: 5000, ours: true });+ expect(r.events).toHaveLength(0);+ });++ it('3. USDC to an unknown address is a LEAK', () => {+ const t = tx({+ keys: [PAYER, PAYER_ATA, UNKNOWN_ATA],+ instructions: [{+ program: 'spl-token',+ parsed: { type: 'transferChecked', info: { source: PAYER_ATA, destination: UNKNOWN_ATA, authority: PAYER, mint: USDC, tokenAmount: { amount: '2000000', decimals: 6 } } },+ }],+ meta: baseMeta({+ preTokenBalances: [+ { accountIndex: 1, mint: USDC, owner: PAYER, uiTokenAmount: { amount: '5000000' } },+ { accountIndex: 2, mint: USDC, owner: UNKNOWN, uiTokenAmount: { amount: '0' } },+ ],+ postTokenBalances: [+ { accountIndex: 1, mint: USDC, owner: PAYER, uiTokenAmount: { amount: '3000000' } },+ { accountIndex: 2, mint: USDC, owner: UNKNOWN, uiTokenAmount: { amount: '2000000' } },+ ],+ }),+ });+ const r = classifyWalletDebits(t, { wallet: PAYER, allowed: ALLOWED, usdcMint: USDC });+ const leak = r.events.find((e) => e.type === 'leak');+ expect(leak).toMatchObject({ asset: 'USDC', counterparty: UNKNOWN, amountAtomic: 2_000_000, reason: 'usdc_to_unknown' });+ });++ it('4. non-USDC token out is a LEAK even to a controlled counterparty', () => {+ const t = tx({+ keys: [PAYER, PAYER_ATA, TREASURY_ATA],+ instructions: [{+ program: 'spl-token',+ parsed: { type: 'transferChecked', info: { source: PAYER_ATA, destination: TREASURY_ATA, authority: PAYER, mint: OTHER_MINT, tokenAmount: { amount: '777', decimals: 0 } } },+ }],+ meta: baseMeta({+ preTokenBalances: [+ { accountIndex: 1, mint: OTHER_MINT, owner: PAYER, uiTokenAmount: { amount: '1000' } },+ { accountIndex: 2, mint: OTHER_MINT, owner: TREASURY, uiTokenAmount: { amount: '0' } },+ ],+ postTokenBalances: [+ { accountIndex: 1, mint: OTHER_MINT, owner: PAYER, uiTokenAmount: { amount: '223' } },+ { accountIndex: 2, mint: OTHER_MINT, owner: TREASURY, uiTokenAmount: { amount: '777' } },+ ],+ }),+ });+ const r = classifyWalletDebits(t, { wallet: PAYER, allowed: ALLOWED, usdcMint: USDC });+ const leak = r.events.find((e) => e.type === 'leak');+ expect(leak).toMatchObject({ asset: OTHER_MINT, amountAtomic: 777, reason: 'non_usdc_token_out' });+ });++ it('5. SPL Approve on a ring ATA raises a delegation alert', () => {+ const t = tx({+ keys: [PAYER, PAYER_ATA, DELEGATE],+ instructions: [{+ program: 'spl-token',+ parsed: { type: 'approve', info: { source: PAYER_ATA, delegate: DELEGATE, owner: PAYER, amount: '1000000' } },+ }],+ meta: baseMeta(),+ });+ const r = classifyWalletDebits(t, { wallet: PAYER, allowed: ALLOWED, usdcMint: USDC });+ const deleg = r.events.find((e) => e.type === 'delegation');+ expect(deleg).toMatchObject({ counterparty: DELEGATE, amountAtomic: 1_000_000, reason: 'spl_approve_on_ring_ata' });+ });+});++describe('classifyWalletDebits — additional leak vectors', () => {+ it('System transfer of SOL to an unknown address is a LEAK', () => {+ const t = tx({+ keys: [PAYER, UNKNOWN],+ instructions: [{ program: 'system', parsed: { type: 'transfer', info: { source: PAYER, destination: UNKNOWN, lamports: 3_000_000 } } }],+ meta: baseMeta({ preBalances: [100_000_000, 0], postBalances: [96_995_000, 3_000_000] }),+ });+ const r = classifyWalletDebits(t, { wallet: PAYER, allowed: ALLOWED, usdcMint: USDC });+ const leak = r.events.find((e) => e.type === 'leak');+ expect(leak).toMatchObject({ asset: 'SOL', counterparty: UNKNOWN, amountAtomic: 3_000_000, reason: 'system_transfer_to_unknown' });+ });++ it('unexplained SOL debit (no instruction) is a LEAK', () => {+ const t = tx({+ keys: [PAYER],+ instructions: [],+ meta: baseMeta({ preBalances: [100_000_000], postBalances: [90_000_000] }), // -10M, fee only 5000+ });+ const r = classifyWalletDebits(t, { wallet: PAYER, allowed: ALLOWED, usdcMint: USDC });+ const leak = r.events.find((e) => e.type === 'leak');+ expect(leak).toMatchObject({ asset: 'SOL', reason: 'unexplained_sol_debit' });+ expect(leak.amountAtomic).toBe(10_000_000 - 5_000);+ });++ it('failed tx (meta.err set) yields the fee only, no debit events', () => {+ const t = tx({+ keys: [PAYER, UNKNOWN],+ instructions: [{ program: 'system', parsed: { type: 'transfer', info: { source: PAYER, destination: UNKNOWN, lamports: 3_000_000 } } }],+ meta: baseMeta({ err: { InstructionError: [0, 'Custom'] } }),+ });+ const r = classifyWalletDebits(t, { wallet: PAYER, allowed: ALLOWED, usdcMint: USDC });+ expect(r.events).toHaveLength(0);+ expect(r.fee.ours).toBe(true);+ });++ it('missing meta → unreadable (retried next run)', () => {+ const r = classifyWalletDebits({ transaction: { signatures: ['s'], message: { accountKeys: [] } }, meta: null }, { wallet: PAYER, allowed: ALLOWED, usdcMint: USDC });+ expect(r.unreadable).toBe(true);+ });+});++describe('accountKeyStrings', () => {+ it('normalizes jsonParsed {pubkey} and raw-string keys', () => {+ expect(accountKeyStrings({ accountKeys: [{ pubkey: 'A' }, 'B'] })).toEqual(['A', 'B']);+ expect(accountKeyStrings({})).toEqual([]);+ });+});++describe('feeDivergence', () => {+ it('is the relative gap, null when a side is unknown or zero', () => {+ expect(feeDivergence(100, 100)).toBe(0);+ expect(feeDivergence(120, 100)).toBeCloseTo(0.1666, 3);+ expect(feeDivergence(100, null)).toBeNull();+ expect(feeDivergence(0, 0)).toBeNull();+ });+});++describe('scanWallet — cursor resumption', () => {+ class FakePublicKey { constructor(v) { this.v = v; } }+ beforeEach(() => {+ sqlCalls.length = 0;+ sqlQueue.length = 0;+ sendOpsAlert.mockClear();+ });++ it('first run passes no `until`; a resumed run passes the stored cursor', async () => {+ // ── Run 1: no cursor. loadCursor → [] (empty).+ const seen = [];+ const conn1 = {+ getSignaturesForAddress: vi.fn(async (_pk, opts) => { seen.push(opts); return [{ signature: 'SIG_NEW', slot: 10, blockTime: 1_700_000_000 }]; }),+ getParsedTransactions: vi.fn(async () => [tx({ signature: 'SIG_NEW', keys: [PAYER], instructions: [], meta: baseMeta() })]),+ };+ sqlQueue.push([]); // loadCursor → no row+ sqlQueue.push([]); // saveCursor upsert+ await scanWallet(conn1, FakePublicKey, PAYER, { allowed: ALLOWED, usdcMint: USDC, runId: 'run-1', feeByDay: new Map() });+ expect(conn1.getSignaturesForAddress).toHaveBeenCalledTimes(1);+ expect(seen[0]).not.toHaveProperty('until');+ // saveCursor persisted the newest signature.+ const savedNew = sqlCalls.find((c) => c.values.includes('SIG_NEW'));+ expect(savedNew).toBeTruthy();++ // ── Run 2: cursor present → getSignaturesForAddress must pass until=SIG_NEW.+ sqlCalls.length = 0;+ const seen2 = [];+ const conn2 = {+ getSignaturesForAddress: vi.fn(async (_pk, opts) => { seen2.push(opts); return []; }),+ getParsedTransactions: vi.fn(async () => []),+ };+ sqlQueue.push([{ last_signature: 'SIG_NEW', scanned_total: 1, leaks_total: 0 }]); // loadCursor+ await scanWallet(conn2, FakePublicKey, PAYER, { allowed: ALLOWED, usdcMint: USDC, runId: 'run-2', feeByDay: new Map() });+ expect(seen2[0]).toMatchObject({ until: 'SIG_NEW' });+ });++ it('a LEAK during scan fires a CRITICAL alert and writes a verdict', async () => {+ sqlCalls.length = 0;+ sqlQueue.push([]); // loadCursor+ const conn = {+ getSignaturesForAddress: vi.fn(async () => [{ signature: 'SIG_LEAK', slot: 5, blockTime: 1_700_000_000 }]),+ getParsedTransactions: vi.fn(async () => [tx({+ signature: 'SIG_LEAK',+ keys: [PAYER, UNKNOWN],+ instructions: [{ program: 'system', parsed: { type: 'transfer', info: { source: PAYER, destination: UNKNOWN, lamports: 4_000_000 } } }],+ meta: baseMeta({ preBalances: [100_000_000, 0], postBalances: [95_995_000, 4_000_000] }),+ })]),+ };+ const summary = await scanWallet(conn, FakePublicKey, PAYER, { allowed: ALLOWED, usdcMint: USDC, runId: 'run-3', feeByDay: new Map() });+ expect(summary.leaks).toBe(1);+ expect(sendOpsAlert).toHaveBeenCalledTimes(1);+ expect(sendOpsAlert.mock.calls[0][0]).toMatch(/LEAK/);+ // A verdict row was upserted into payment_reconciliation with our source.+ const verdict = sqlCalls.find((c) => c.values.includes('x402_ring_onchain'));+ expect(verdict).toBeTruthy();+ });+});diff --git a/tests/x402-ring-tick.test.js b/tests/x402-ring-tick.test.jsnew file mode 100644index 000000000..f871f24c4--- /dev/null+++ b/tests/x402-ring-tick.test.js@@ -0,0 +1,235 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++import {+ ringTickConfig,+ planTick,+ minUsdcForTick,+ dailyRemaining,+ tickBudget,+ assessBackpressure,+ gateOnRingConfig,+} from '../api/_lib/x402/ring-tick-plan.js';+import { CHEAP_ENDPOINTS, RING_SETTLE_ENDPOINT } from '../api/_lib/x402/pipelines/volume-shared.js';+import { warnCapExceeded } from '../api/_lib/x402/pay.js';+import { validateRingConfig } from '../api/_lib/x402/ring-config.js';++// ── Cadence: weighted rotation ─────────────────────────────────────────────────+describe('ring-tick planTick — cadence', () => {+ const CHEAP = CHEAP_ENDPOINTS.length; // 11 in the stock catalog++ // Reproduce the cron's Redis reservation in memory: each tick reserves+ // cheapNeeded indices, advancing a shared cursor.+ function simulate(ticks, { calls = 3, settleEveryN = 5 } = {}) {+ let cursor = 0;+ const out = [];+ for (let seq = 1; seq <= ticks; seq++) {+ const isSettle = settleEveryN > 0 && seq % settleEveryN === 0;+ const cheapNeeded = Math.max(0, calls - (isSettle ? 1 : 0));+ const cheapStart = cursor;+ cursor += cheapNeeded;+ const plan = planTick({ tickSeq: seq, calls, settleEveryN, cheapCount: CHEAP, cheapStart });+ out.push({ seq, ...plan });+ }+ return out;+ }++ it('fires ring-settle on exactly every Nth tick', () => {+ const plans = simulate(20, { settleEveryN: 5 });+ const settleTicks = plans.filter((p) => p.isSettleTick).map((p) => p.seq);+ expect(settleTicks).toEqual([5, 10, 15, 20]);+ });++ it('cheap tips dominate the per-minute count', () => {+ const plans = simulate(10, { calls: 3, settleEveryN: 5 });+ const totalCalls = plans.reduce((n, p) => n + p.cheapIndices.length + (p.isSettleTick ? 1 : 0), 0);+ const settleCalls = plans.filter((p) => p.isSettleTick).length;+ const cheapCalls = totalCalls - settleCalls;+ expect(totalCalls).toBe(30); // 10 ticks × 3 calls+ expect(settleCalls).toBe(2); // ticks 5 and 10+ expect(cheapCalls).toBe(28); // the overwhelming majority+ });++ it('every cheap index is within the catalog and rotates for variety', () => {+ const plans = simulate(12, { calls: 3, settleEveryN: 5 });+ const all = plans.flatMap((p) => p.cheapIndices);+ for (const i of all) {+ expect(Number.isInteger(i)).toBe(true);+ expect(i).toBeGreaterThanOrEqual(0);+ expect(i).toBeLessThan(CHEAP);+ }+ expect(new Set(all).size).toBeGreaterThan(1);+ });++ it('a non-settle tick pays only cheap endpoints', () => {+ const plan = planTick({ tickSeq: 1, calls: 3, settleEveryN: 5, cheapCount: CHEAP, cheapStart: 0 });+ expect(plan.isSettleTick).toBe(false);+ expect(plan.cheapIndices).toHaveLength(3);+ });++ it('a settle tick reserves one slot for ring-settle', () => {+ const plan = planTick({ tickSeq: 5, calls: 3, settleEveryN: 5, cheapCount: CHEAP, cheapStart: 0 });+ expect(plan.isSettleTick).toBe(true);+ expect(plan.cheapIndices).toHaveLength(2);+ expect(RING_SETTLE_ENDPOINT?.key).toBe('ring-settle');+ });++ it('settleEveryN=0 disables the ring-settle carrier', () => {+ const plans = simulate(10, { settleEveryN: 0 });+ expect(plans.every((p) => !p.isSettleTick)).toBe(true);+ });+});++// ── Cap enforcement ─────────────────────────────────────────────────────────────+describe('ring-tick budgets', () => {+ it('tick budget is the smaller of tick cap and daily remaining', () => {+ expect(tickBudget(0, 50_000_000, 1_100_000)).toBe(1_100_000);+ expect(tickBudget(49_500_000, 50_000_000, 1_100_000)).toBe(500_000); // daily nearly spent+ });++ it('daily cap halts the tick (budget 0, never negative)', () => {+ expect(tickBudget(50_000_000, 50_000_000, 1_100_000)).toBe(0);+ expect(tickBudget(60_000_000, 50_000_000, 1_100_000)).toBe(0); // overshoot clamps to 0+ expect(dailyRemaining(60_000_000, 50_000_000)).toBe(0);+ });++ it('minimum payer USDC is the ring-settle price on a settle tick, headroom otherwise', () => {+ expect(minUsdcForTick({ isSettleTick: true, ringSettlePriceAtomic: 1_000_000 })).toBe(1_000_000);+ expect(minUsdcForTick({ isSettleTick: false, ringSettlePriceAtomic: 1_000_000 })).toBe(20_000);+ });+});++// ── Back-pressure ───────────────────────────────────────────────────────────────+describe('ring-tick back-pressure', () => {+ const FLOOR = 20_000_000; // 0.02 SOL+ const MIN_USDC = 1_000_000;++ it('below the SOL floor → clean no-op with sponsor_sol_floor', () => {+ const r = assessBackpressure({ solLamports: 10_000_000, usdcAtomic: 5_000_000, floorLamports: FLOOR, minUsdcAtomic: MIN_USDC });+ expect(r.ok).toBe(false);+ expect(r.reason).toBe('sponsor_sol_floor');+ });++ it('insufficient payer USDC → insufficient_payer_usdc', () => {+ const r = assessBackpressure({ solLamports: 50_000_000, usdcAtomic: 100_000, floorLamports: FLOOR, minUsdcAtomic: MIN_USDC });+ expect(r.ok).toBe(false);+ expect(r.reason).toBe('insufficient_payer_usdc');+ });++ it('an RPC read failure (NaN balance) → rpc_balance_unavailable', () => {+ expect(assessBackpressure({ solLamports: Number.NaN, usdcAtomic: 5_000_000, floorLamports: FLOOR, minUsdcAtomic: MIN_USDC }).reason).toBe('rpc_balance_unavailable');+ expect(assessBackpressure({ solLamports: 50_000_000, usdcAtomic: Number.NaN, floorLamports: FLOOR, minUsdcAtomic: MIN_USDC }).reason).toBe('rpc_balance_unavailable');+ });++ it('healthy balances → tick proceeds', () => {+ const r = assessBackpressure({ solLamports: 50_000_000, usdcAtomic: 5_000_000, floorLamports: FLOOR, minUsdcAtomic: MIN_USDC });+ expect(r.ok).toBe(true);+ expect(r.reason).toBeNull();+ });++ it('the floor is checked before USDC (settlement is paused, so USDC is moot)', () => {+ const r = assessBackpressure({ solLamports: 1, usdcAtomic: 0, floorLamports: FLOOR, minUsdcAtomic: MIN_USDC });+ expect(r.reason).toBe('sponsor_sol_floor');+ });+});++// ── Config gate: run only on a clean (no-error) envelope ────────────────────────+describe('ring-tick config gate', () => {+ it('blocks when any ERROR-severity finding exists', () => {+ const g = gateOnRingConfig([+ { code: 'facilitator_url_external', severity: 'error' },+ { code: 'ring_self_pay_off', severity: 'warn' },+ ]);+ expect(g.blocked).toBe(true);+ expect(g.errors).toHaveLength(1);+ expect(g.warnings).toHaveLength(1);+ });++ it('does NOT block on warn-only findings (sponsor mode still settles in-house)', () => {+ const g = gateOnRingConfig([{ code: 'ring_self_pay_off', severity: 'warn' }]);+ expect(g.blocked).toBe(false);+ expect(g.warnings).toHaveLength(1);+ });++ it('a clean envelope is not blocked', () => {+ expect(gateOnRingConfig([]).blocked).toBe(false);+ });+});++// ── Config knobs + budget separation from the autonomous loop ───────────────────+describe('ringTickConfig', () => {+ const SAVED = {};+ const KEYS = [+ 'X402_RING_TICK_ENABLED', 'X402_RING_TICK_CALLS', 'X402_RING_SETTLE_EVERY_N_TICKS',+ 'X402_RING_TICK_CAP_ATOMIC', 'X402_RING_DAILY_CAP_ATOMIC', 'X402_AUTONOMOUS_DAILY_CAP_ATOMIC',+ ];+ beforeEach(() => { for (const k of KEYS) { SAVED[k] = process.env[k]; delete process.env[k]; } });+ afterEach(() => { for (const k of KEYS) { if (SAVED[k] === undefined) delete process.env[k]; else process.env[k] = SAVED[k]; } });++ it('sensible defaults out of the box', () => {+ const c = ringTickConfig();+ expect(c.enabled).toBe(true);+ expect(c.calls).toBe(3);+ expect(c.settleEveryN).toBe(5);+ expect(c.tickCapAtomic).toBe(1_100_000);+ expect(c.dailyCapAtomic).toBe(50_000_000);+ });++ it('X402_RING_TICK_ENABLED=false disables it; other values keep it on', () => {+ process.env.X402_RING_TICK_ENABLED = 'false';+ expect(ringTickConfig().enabled).toBe(false);+ process.env.X402_RING_TICK_ENABLED = 'true';+ expect(ringTickConfig().enabled).toBe(true);+ });++ it('the ring tick daily cap is SEPARATE from the autonomous loop cap', () => {+ process.env.X402_RING_DAILY_CAP_ATOMIC = '50000000';+ process.env.X402_AUTONOMOUS_DAILY_CAP_ATOMIC = '999';+ // Reading the ring tick config never picks up the autonomous loop's cap.+ expect(ringTickConfig().dailyCapAtomic).toBe(50_000_000);+ });++ it('rejects garbage numeric env, falling back to the default', () => {+ process.env.X402_RING_TICK_CALLS = 'not-a-number';+ expect(ringTickConfig().calls).toBe(3);+ });+});++// ── Price-vs-cap contradiction is impossible to hit silently ────────────────────+describe('price-vs-cap coherence', () => {+ const SAVED = {};+ const KEYS = ['X402_PRICE_RING_SETTLE', 'X402_VOLUME_PER_RUN_CAP_ATOMIC'];+ beforeEach(() => { for (const k of KEYS) { SAVED[k] = process.env[k]; delete process.env[k]; } });+ afterEach(() => { for (const k of KEYS) { if (SAVED[k] === undefined) delete process.env[k]; else process.env[k] = SAVED[k]; } });++ it('validateRingConfig flags ring_price_exceeds_run_cap when price > cap', () => {+ process.env.X402_PRICE_RING_SETTLE = '1000000'; // $1.00+ process.env.X402_VOLUME_PER_RUN_CAP_ATOMIC = '50000'; // $0.05 (the old, broken pairing)+ const codes = validateRingConfig().map((f) => f.code);+ expect(codes).toContain('ring_price_exceeds_run_cap');+ });++ it('no contradiction once the cap accommodates the price (stock defaults)', () => {+ process.env.X402_PRICE_RING_SETTLE = '1000000'; // $1.00+ process.env.X402_VOLUME_PER_RUN_CAP_ATOMIC = '1100000'; // $1.10 (the new default)+ const codes = validateRingConfig().map((f) => f.code);+ expect(codes).not.toContain('ring_price_exceeds_run_cap');+ });++ it('warnCapExceeded logs loudly and throttles per (url,cap) signature', () => {+ const spy = vi.spyOn(console, 'warn').mockImplementation(() => {});+ try {+ warnCapExceeded('https://three.ws/api/x402/ring-settle', 1_000_000, 50_000);+ expect(spy).toHaveBeenCalledTimes(1);+ expect(spy.mock.calls[0][0]).toMatch(/SKIPPED/);+ expect(spy.mock.calls[0][0]).toMatch(/ring-settle/);+ // Same signature again within the hour is throttled.+ warnCapExceeded('https://three.ws/api/x402/ring-settle', 1_000_000, 50_000);+ expect(spy).toHaveBeenCalledTimes(1);+ // A different cap is a different signature — logs again.+ warnCapExceeded('https://three.ws/api/x402/ring-settle', 1_000_000, 60_000);+ expect(spy).toHaveBeenCalledTimes(2);+ } finally {+ spy.mockRestore();+ }+ });+});diff --git a/tests/x402-ring-wallet-monitor.test.js b/tests/x402-ring-wallet-monitor.test.jsnew file mode 100644index 000000000..a8bbcf886--- /dev/null+++ b/tests/x402-ring-wallet-monitor.test.js@@ -0,0 +1,123 @@+import { describe, it, expect, beforeAll, afterEach } from 'vitest';+import { Keypair } from '@solana/web3.js';+import bs58 from 'bs58';++// checkRingWallets reads the three ring wallets on-chain and alerts on a role-+// floor breach. These tests inject a fake balance reader + alert sink (the+// function's DI seams) so no RPC, spl-token, or Redis is touched — we assert the+// breach → alert wiring and the treasury's deliberate exemption.++let checkRingWallets;+let SPONSOR;+let PAYER;+let TREASURY;++beforeAll(async () => {+ // Synthetic, matched keypairs. The payer address is derived from the seed+ // secret exactly as production's loadSeedKeypair() does.+ const payerKp = Keypair.generate();+ const treasuryKp = Keypair.generate();+ const sponsorKp = Keypair.generate();+ PAYER = payerKp.publicKey.toBase58();+ TREASURY = treasuryKp.publicKey.toBase58();+ SPONSOR = sponsorKp.publicKey.toBase58();++ process.env.X402_SEED_SOLANA_SECRET_BASE58 = bs58.encode(payerKp.secretKey);+ process.env.X402_PAY_TO_SOLANA = TREASURY;+ process.env.X402_FEE_PAYER_SOLANA = SPONSOR;+ process.env.X402_SPONSOR_SOL_FLOOR_LAMPORTS = '20000000'; // 0.02 SOL → 0.03 watch floor+ process.env.X402_RING_PAYER_USDC_FLOOR_ATOMIC = '5000000'; // $5+ process.env.X402_RING_SELF_PAY = 'true';++ ({ checkRingWallets } = await import('../api/_lib/x402/wallet-balance-monitor.js'));+});++afterEach(() => {+ process.env.X402_RING_SELF_PAY = 'true';+});++// Build a fake on-chain reader from a { address: { lamports, usdcAtomic } } map.+function reader(balances) {+ return async (address) => balances[address] || { lamports: null, usdcAtomic: null };+}++function alertCollector() {+ const calls = [];+ return { fn: async (title, detail, opts) => calls.push({ title, detail, opts }), calls };+}++describe('checkRingWallets', () => {+ it('alerts when the sponsor SOL is below floor', async () => {+ const alerts = alertCollector();+ const res = await checkRingWallets({+ sendAlert: alerts.fn,+ readBalance: reader({+ [SPONSOR]: { lamports: 10_000_000, usdcAtomic: null }, // 0.01 SOL < 0.03+ [PAYER]: { lamports: 100_000_000, usdcAtomic: 82_000_000 },+ [TREASURY]: { lamports: 0, usdcAtomic: 0 },+ }),+ });+ expect(res.configured).toBe(true);+ expect(res.breaches.some((b) => b.startsWith('sponsor SOL'))).toBe(true);+ expect(alerts.calls.some((c) => c.title.includes('sponsor low on SOL'))).toBe(true);+ });++ it('alerts when the payer USDC float is below floor', async () => {+ const alerts = alertCollector();+ const res = await checkRingWallets({+ sendAlert: alerts.fn,+ readBalance: reader({+ [SPONSOR]: { lamports: 100_000_000, usdcAtomic: null },+ [PAYER]: { lamports: 100_000_000, usdcAtomic: 3_000_000 }, // $3 < $5+ [TREASURY]: { lamports: 0, usdcAtomic: 0 },+ }),+ });+ expect(res.breaches.some((b) => b.startsWith('payer USDC'))).toBe(true);+ expect(alerts.calls.some((c) => c.title.includes('payer low on USDC'))).toBe(true);+ });++ it('never alerts on the treasury, even at zero balance', async () => {+ const alerts = alertCollector();+ const res = await checkRingWallets({+ sendAlert: alerts.fn,+ readBalance: reader({+ [SPONSOR]: { lamports: 100_000_000, usdcAtomic: null },+ [PAYER]: { lamports: 100_000_000, usdcAtomic: 82_000_000 },+ [TREASURY]: { lamports: 0, usdcAtomic: 0 },+ }),+ });+ expect(res.breaches).toEqual([]);+ expect(alerts.calls).toEqual([]);+ const treasury = res.wallets.find((w) => w.role === 'treasury');+ expect(treasury.sol_low).toBe(false);+ expect(treasury.usdc_low).toBe(false);+ });++ it('does not flag the payer SOL when self-pay is off', async () => {+ process.env.X402_RING_SELF_PAY = 'false';+ const alerts = alertCollector();+ const res = await checkRingWallets({+ sendAlert: alerts.fn,+ readBalance: reader({+ [SPONSOR]: { lamports: 100_000_000, usdcAtomic: null },+ [PAYER]: { lamports: 1_000, usdcAtomic: 82_000_000 }, // near-zero SOL, but sponsor pays+ [TREASURY]: { lamports: 0, usdcAtomic: 0 },+ }),+ });+ expect(res.breaches.some((b) => b.startsWith('payer SOL'))).toBe(false);+ });++ it('does not fabricate a breach from a null (RPC-failed) balance', async () => {+ const alerts = alertCollector();+ const res = await checkRingWallets({+ sendAlert: alerts.fn,+ readBalance: reader({+ [SPONSOR]: { lamports: null, usdcAtomic: null },+ [PAYER]: { lamports: null, usdcAtomic: null },+ [TREASURY]: { lamports: null, usdcAtomic: null },+ }),+ });+ expect(res.breaches).toEqual([]);+ expect(alerts.calls).toEqual([]);+ });+});diff --git a/three-ws-club-ambience.wav b/three-ws-club-ambience.wavdeleted file mode 100644index b244fbf65..000000000Binary files a/three-ws-club-ambience.wav and /dev/null differdiff --git a/three-ws-club-music.wav b/three-ws-club-music.wavdeleted file mode 100644index a1de6bad9..000000000Binary files a/three-ws-club-music.wav and /dev/null differdiff --git a/three.mp3 b/three.mp3deleted file mode 100644index 9ae9b3ee9..000000000Binary files a/three.mp3 and /dev/null differdiff --git a/vercel.json b/vercel.jsonindex 25f89f529..4c8945122 100644--- a/vercel.json+++ b/vercel.json@@ -15,7 +15,7 @@"api/cron/treasury-topup.js": {"maxDuration": 120},- "api/cron/economy-reconcile.js": {+ "{api/cron/economy-reconcile,api/cron/x402-ring-leak-scan}.js": {"maxDuration": 300},"{api/strategies,api/cron/payment-session-sweep,api/cron/three-market-refresh}.js": {@@ -27,7 +27,7 @@"api/tournaments/[id].js": {"maxDuration": 120},- "{api/agents/networth,api/avatars/from-forge,api/pay/execute,api/cron/launcher-claimer,api/seed/synthesize}.js": {+ "{api/agents/networth,api/avatars/from-forge,api/pay/execute,api/cron/launcher-claimer,api/seed/synthesize,api/cron/x402-ring-tick}.js": {"maxDuration": 60},"{api/club/tips-stream,api/feed-stream,api/pump/trades-stream,api/oracle/stream,api/oracle/action-stream,api/sniper/stream,api/sniper/radar-stream,api/agent-screen-stream}.js": {@@ -216,6 +216,14 @@"src": "/admin/seeder/","dest": "/admin/seeder.html"},+ {+ "src": "/admin/ring",+ "dest": "/admin/ring.html"+ },+ {+ "src": "/admin/ring/",+ "dest": "/admin/ring.html"+ },{"src": "/aws-marketplace/welcome","dest": "/aws-marketplace/welcome.html"@@ -2056,6 +2064,10 @@"src": "/api/agents/x402/manifest","dest": "/api/agents/x402/[action]?action=manifest"},+ {+ "src": "/api/x402-facilitator/([^/]+)",+ "dest": "/api/x402-facilitator/[action]?action=$1"+ },{"src": "/api/agents/([^/]+)/wallet/([^/]+)","dest": "/api/agents/[id]"@@ -4873,6 +4885,10 @@"path": "/api/cron/x402-autonomous-loop","schedule": "*/5 * * * *"},+ {+ "path": "/api/cron/x402-ring-tick",+ "schedule": "* * * * *"+ },{"path": "/api/cron/avatar-thumbnail-render","schedule": "*/10 * * * *"@@ -4916,6 +4932,10 @@{"path": "/api/cron/economy-reconcile","schedule": "*/30 * * * *"+ },+ {+ "path": "/api/cron/x402-ring-leak-scan",+ "schedule": "*/10 * * * *"}]}diff --git a/vite.config.js b/vite.config.jsindex 497d93636..ba17b223b 100644--- a/vite.config.js+++ b/vite.config.js@@ -386,6 +386,7 @@ const appConfig = {deployments: resolve(__dirname, 'pages/deployments.html'),'admin-launcher': resolve(__dirname, 'pages/admin/launcher.html'),'admin-seeder': resolve(__dirname, 'pages/admin/seeder.html'),+ 'admin-ring': resolve(__dirname, 'pages/admin/ring.html'),launcher: resolve(__dirname, 'pages/launcher.html'),'launch-detail': resolve(__dirname, 'pages/launch-detail.html'),watchlist: resolve(__dirname, 'pages/watchlist.html'),@@ -861,6 +862,8 @@ support: resolve(__dirname, 'pages/support.html'),'/admin/launcher/': resolve(root, 'pages/admin/launcher.html'),'/admin/seeder': resolve(root, 'pages/admin/seeder.html'),'/admin/seeder/': resolve(root, 'pages/admin/seeder.html'),+ '/admin/ring': resolve(root, 'pages/admin/ring.html'),+ '/admin/ring/': resolve(root, 'pages/admin/ring.html'),'/launcher': resolve(root, 'pages/launcher.html'),'/launcher/': resolve(root, 'pages/launcher.html'),'/clash': resolve(root, 'pages/clash.html'),