Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
Fix the agent economy's self-funding loop and scale the daily caps
nirholasa4311b227722
diff --git a/.env.example b/.env.exampleindex c3672d75d..ae5f1c9f6 100644--- a/.env.example+++ b/.env.example@@ -525,6 +525,13 @@ X402_RING_DAILY_CAP_ATOMIC=50000000# 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+# Revenue share of every treasury sweep routed to the economy master wallet, in+# basis points (default 2000 = 20%; 0 disables the leg). This is the ONE inflow+# that keeps the funding root's USDC stocked so economy-fuel can convert it to+# SOL and treasury-topup can hold every engine (circulation treasury, ring+# sponsor) above its floor. Ledgered as kind='revshare' in x402_ring_ledger and+# verified per-leg by the ring reconciler.+X402_RING_MASTER_REVSHARE_BPS=2000# Hard per-payment network-fee ceiling (lamports). payX402 refuses to broadcast# a ring payment whose fee configuration could exceed it. Default 10000 —# double the 1-signature self-pay floor, so both modes fit with headroom.@@ -885,6 +892,16 @@ APP_ORIGIN=https://three.ws# Generate: openssl rand -base64 32CRON_SECRET=+# ── PumpPortal (pump.fun data websocket) ─────────────────────────────────────+# PumpPortal gates subscribeTokenTrade / subscribeAccountTrade behind an API key+# whose linked wallet holds at least 0.02 SOL. Without it, per-coin trade+# streams are refused: the intel watcher then only ever sees each coin's dev+# buy, smart-money rollups stay empty, and Oracle conviction plateaus below the+# actionable tiers (no Lean/Strong/Prime, no calls, no win rate). Create a key+# at pumpportal.fun, fund its wallet, and set it on three-ws-api AND the+# agent-sniper worker. subscribeNewToken still works without a key.+PUMPPORTAL_API_KEY=+# ── Database retention (/api/cron/db-retention) ──────────────────────────────# Keeps the Neon branch under its project-size cap. The pump.fun intel firehose# (pump_coin_intel + its mint-keyed satellites) ingests tens of thousands of rowsdiff --git a/api/_lib/x402/autonomous-registry.js b/api/_lib/x402/autonomous-registry.jsindex 87f47bd1b..598429aa0 100644--- a/api/_lib/x402/autonomous-registry.js+++ b/api/_lib/x402/autonomous-registry.js@@ -2720,6 +2720,9 @@ const SELF_ENDPOINTS = [priority: 20,pipeline: 'volume',enabled: true,+ // Reserved-slot maintenance: recirculation must never compete with (and+ // lose to) paid entries for tick slots — see the loop's selection step.+ maintenance: true,run: (ctx) => ringRebalance(ctx),},@@ -2770,6 +2773,7 @@ const SELF_ENDPOINTS = [priority: 22,pipeline: 'agents',enabled: true,+ maintenance: true,run: (ctx) => ringFloatTopUp(ctx),},@@ -2791,6 +2795,7 @@ const SELF_ENDPOINTS = [priority: 22,pipeline: 'agents',enabled: true,+ maintenance: true,run: (ctx) => ringPoolFund(ctx),},diff --git a/api/_lib/x402/pipelines/ring-rebalance.js b/api/_lib/x402/pipelines/ring-rebalance.jsindex 4d2c387d1..f75c40ff5 100644--- a/api/_lib/x402/pipelines/ring-rebalance.js+++ b/api/_lib/x402/pipelines/ring-rebalance.js@@ -34,6 +34,7 @@ import { env } from '../../env.js';import { logger } from '../../usage.js';import { solanaConnection } from '../../solana/connection.js';import { loadSeedKeypair, USDC_MINT } from '../pay.js';+import { ECONOMY_MASTER_ADDRESS } from '../../economy-master.js';const log = logger('x402-ring-rebalance');@@ -50,6 +51,32 @@ const TREASURY_BUFFER_ATOMIC = BigInt(process.env.X402_RING_TREASURY_BUFFER_ATOM// 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);+// Revenue share routed to the economy master on every sweep, in basis points.+// The master's fuel module (economy-fuel.js) was built on the assumption that+// "the master accumulates USDC revenue (x402, marketplace)" — but nothing ever+// delivered that revenue, so the funding root could never refuel SOL and every+// engine below it starved. This cut closes the loop: treasury → master USDC →+// fuel swap → SOL → treasury-topup → circulation/sponsor floors. Still wallet-+// to-wallet inside the controlled set (master is a SOLANA_SIGNERS role, so the+// leak scanner classifies it internal). 0 disables the leg entirely.+const MASTER_REVSHARE_BPS = (() => {+ const v = Number(process.env.X402_RING_MASTER_REVSHARE_BPS);+ return Number.isFinite(v) && v >= 0 && v <= 10_000 ? Math.floor(v) : 2_000;+})();+// Don't bother with a dust-sized master leg (default $0.10).+const MIN_REVSHARE_ATOMIC = 100_000n;++/**+ * Pure split of a sweep amount into { payerCut, masterCut } per the revshare+ * bps, with the dust floor applied to the master leg.+ * @param {bigint} sweep total atomic USDC being swept+ * @param {number} [bps] override for tests; defaults to the env-derived cut+ */+export function splitSweep(sweep, bps = MASTER_REVSHARE_BPS) {+ let masterCut = (sweep * BigInt(bps)) / 10_000n;+ if (masterCut < MIN_REVSHARE_ATOMIC) masterCut = 0n;+ return { payerCut: sweep - masterCut, masterCut };+}async function confirmSignature(conn, signature, timeoutMs = 30_000) {const deadline = Date.now() + timeoutMs;@@ -128,13 +155,19 @@ export async function run(ctx = {}) {}}+ // Split the sweep: a bounded revenue share funds the economy master (the SOL+ // fuel source for every engine floor), the rest recycles to the payer float.+ const split = splitSweep(sweep);+ let masterCut = split.masterCut;+ const payerCut = split.payerCut;+const payerAta = getAssociatedTokenAddressSync(mint, payerPub, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID);const payerAtaInfo = await conn.getAccountInfo(payerAta).catch(() => null);const mintInfo = await getMint(conn, mint);const { blockhash } = await conn.getLatestBlockhash('confirmed');const ixs = [- ComputeBudgetProgram.setComputeUnitLimit({ units: 60_000 }),+ ComputeBudgetProgram.setComputeUnitLimit({ units: 90_000 }),ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 5 }),];if (!payerAtaInfo) {@@ -142,9 +175,24 @@ export async function run(ctx = {}) {feePayerKp.publicKey, payerAta, payerPub, mint, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,));}- ixs.push(createTransferCheckedInstruction(- treasuryAta, mint, payerAta, treasury.publicKey, sweep, mintInfo.decimals, [], TOKEN_PROGRAM_ID,- ));+ if (payerCut > 0n) {+ ixs.push(createTransferCheckedInstruction(+ treasuryAta, mint, payerAta, treasury.publicKey, payerCut, mintInfo.decimals, [], TOKEN_PROGRAM_ID,+ ));+ }+ let masterPub = null;+ if (masterCut > 0n && ECONOMY_MASTER_ADDRESS) {+ masterPub = new PublicKey(ECONOMY_MASTER_ADDRESS);+ const masterAta = getAssociatedTokenAddressSync(mint, masterPub, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID);+ ixs.push(createAssociatedTokenAccountIdempotentInstruction(+ feePayerKp.publicKey, masterAta, masterPub, mint, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,+ ));+ ixs.push(createTransferCheckedInstruction(+ treasuryAta, mint, masterAta, treasury.publicKey, masterCut, mintInfo.decimals, [], TOKEN_PROGRAM_ID,+ ));+ } else {+ masterCut = 0n;+ }const msg = new TransactionMessage({payerKey: feePayerKp.publicKey,@@ -170,17 +218,28 @@ export async function run(ctx = {}) {}try {- await sql`- INSERT INTO x402_ring_ledger (kind, from_wallet, to_wallet, mint, amount_atomic, tx_sig, run_id)- VALUES ('sweep', ${treasury.publicKey.toBase58()}, ${payerPub.toBase58()},- ${USDC_MINT}, ${Number(sweep)}, ${signature}, ${runId})- `;+ if (payerCut > 0n) {+ await sql`+ INSERT INTO x402_ring_ledger (kind, from_wallet, to_wallet, mint, amount_atomic, tx_sig, run_id)+ VALUES ('sweep', ${treasury.publicKey.toBase58()}, ${payerPub.toBase58()},+ ${USDC_MINT}, ${Number(payerCut)}, ${signature}, ${runId})+ `;+ }+ if (masterCut > 0n && masterPub) {+ await sql`+ INSERT INTO x402_ring_ledger (kind, from_wallet, to_wallet, mint, amount_atomic, tx_sig, run_id)+ VALUES ('revshare', ${treasury.publicKey.toBase58()}, ${masterPub.toBase58()},+ ${USDC_MINT}, ${Number(masterCut)}, ${signature}, ${runId})+ `;+ }} catch (err) {log.warn('sweep_ledger_write_failed', { message: err?.message });}log.info('ring_rebalance_swept', {amount_atomic: Number(sweep),+ payer_cut_atomic: Number(payerCut),+ master_cut_atomic: Number(masterCut),to: payerPub.toBase58(),tx: signature,});@@ -189,7 +248,8 @@ export async function run(ctx = {}) {success: true,amountAtomic: 0, // recirculation, not spend — cap-neutraltxSig: signature,- note: `swept ${Number(sweep) / 1e6} USDC treasury→payer`,+ note: `swept ${Number(payerCut) / 1e6} USDC treasury→payer`+ + (masterCut > 0n ? ` + ${Number(masterCut) / 1e6} USDC treasury→master` : ''),};}diff --git a/api/_lib/x402/ring-reconciliation.js b/api/_lib/x402/ring-reconciliation.jsindex 3ea91bf15..bcacc4238 100644--- a/api/_lib/x402/ring-reconciliation.js+++ b/api/_lib/x402/ring-reconciliation.js@@ -189,9 +189,9 @@ async function loadSettleRows(db) {async function loadSweepRows(db) {try {return await db`- SELECT id, ts, from_wallet, to_wallet, mint, amount_atomic, tx_sig+ SELECT id, ts, kind, from_wallet, to_wallet, mint, amount_atomic, tx_sigFROM x402_ring_ledger- WHERE kind = 'sweep'+ WHERE kind IN ('sweep', 'revshare')AND ts > now() - (${LOOKBACK_HOURS} || ' hours')::intervalORDER BY ts DESCLIMIT ${MAX_SWEEP_ROWS}@@ -283,9 +283,14 @@ export function verifySettleAmount(row, parsedTx) {}// Prove one confirmed sweep moved amount_atomic of mint from_wallet → to_wallet,-// and that the source is the configured treasury (treasury→payer is the ONLY-// legal sweep direction). Pure; exported for tests.-export function verifySweepMovement(row, parsedTx, treasuryAddress) {+// and that the source is the configured treasury (treasury→payer and+// treasury→master revshare are the only legal directions). A single sweep tx+// may carry MULTIPLE ledger legs (payer sweep + master revshare), so the+// treasury's total on-chain delta is checked against `txTotalAtomic` — the sum+// of every ledger row sharing this tx_sig (defaults to the row's own amount for+// the single-leg case). The recipient check stays per-row. Pure; exported for+// tests.+export function verifySweepMovement(row, parsedTx, treasuryAddress, txTotalAtomic = null) {const mint = row.mint || ASSET;if (treasuryAddress && row.from_wallet !== treasuryAddress) {return { ok: false, reason: `sweep_source_not_treasury:${row.from_wallet}` };@@ -293,9 +298,10 @@ export function verifySweepMovement(row, parsedTx, treasuryAddress) {const deltas = tokenDeltasByOwner(parsedTx, mint);if (deltas === null) return { ok: false, reason: 'tx_unparseable', soft: true };const amount = BigInt(row.amount_atomic ?? 0);+ const txTotal = BigInt(txTotalAtomic ?? row.amount_atomic ?? 0);const sent = deltas.get(row.from_wallet) ?? 0n;const received = deltas.get(row.to_wallet) ?? 0n;- if (sent !== -amount) return { ok: false, reason: `treasury_delta_${sent}_expected_${-amount}` };+ if (sent !== -txTotal) return { ok: false, reason: `treasury_delta_${sent}_expected_${-txTotal}` };if (received !== amount) return { ok: false, reason: `payer_delta_${received}_expected_${amount}` };return { ok: true };}@@ -429,6 +435,13 @@ export async function run(ctx = {}) {// each sweep moves the entire float, so full verification of every sweep// outranks sampling one more settle.const treasuryAddress = env.X402_PAY_TO_SOLANA || process.env.X402_PAY_TO_SOLANA || null;+ // A split sweep (payer leg + master revshare leg) shares one tx_sig; the+ // treasury's on-chain delta must match the SUM of its legs, not each row.+ const sweepTxTotals = new Map();+ for (const row of sweeps) {+ if (!row.tx_sig) continue;+ sweepTxTotals.set(row.tx_sig, (sweepTxTotals.get(row.tx_sig) ?? 0n) + BigInt(row.amount_atomic ?? 0));+ }for (const row of sweeps) {const ref = String(row.id);if (!row.tx_sig) {@@ -471,7 +484,7 @@ export async function run(ctx = {}) {});continue;}- const check = verifySweepMovement(row, tx, treasuryAddress);+ const check = verifySweepMovement(row, tx, treasuryAddress, sweepTxTotals.get(row.tx_sig));if (!check.ok && !check.soft) {summary.sweep_mismatches += 1;critical.push({ kind: 'x402_ring_sweep_mismatch', ref, sig: row.tx_sig, reason: check.reason });diff --git a/api/cron/x402-autonomous-loop.js b/api/cron/x402-autonomous-loop.jsindex 495545678..9f6f827fe 100644--- a/api/cron/x402-autonomous-loop.js+++ b/api/cron/x402-autonomous-loop.js@@ -314,11 +314,19 @@ export default wrapCron(async (req, res) => {return { entry, ready: !cooling };}),);- const ready = readyChecks- .filter((e) => e.ready)- .map((e) => e.entry)- .sort((a, b) => (b.priority || 0) - (a.priority || 0))- .slice(0, MAX_PER_TICK);+ // Maintenance entries (recirculation: treasury→payer sweep, agent float+ // top-up, pool funding) get RESERVED slots outside MAX_PER_TICK. They move+ // zero net spend, are cooldown-gated at 120s, and are the only thing keeping+ // the payer float alive — when they competed on priority alone, a wave of+ // failing high-priority paid entries starved them for days and the whole+ // ring drained (July 2026 flat-line).+ const readyAll = readyChecks.filter((e) => e.ready).map((e) => e.entry);+ const byPriority = (a, b) => (b.priority || 0) - (a.priority || 0);+ const maintenance = readyAll.filter((e) => e.maintenance).sort(byPriority);+ const ready = [+ ...maintenance,+ ...readyAll.filter((e) => !e.maintenance).sort(byPriority).slice(0, MAX_PER_TICK),+ ];if (ready.length === 0) {return json(res, 200, { ok: true, skipped: true, reason: 'all_cooling_down', run_id: runId });@@ -486,16 +494,19 @@ export default wrapCron(async (req, res) => {if (!accept) {errorMsg = 'no_solana_accept';results.push({ id: entry.id, status: 'skip', reason: errorMsg });+ await setCooldown(redis, entry); // endpoint misconfigured — don't re-probe every tickcontinue;}if (!USDC_MINT || accept.asset !== USDC_MINT) {errorMsg = `unexpected_asset:${accept.asset}`;results.push({ id: entry.id, status: 'skip', reason: errorMsg });+ await setCooldown(redis, entry);continue;}if (!accept.extra?.feePayer) {errorMsg = 'missing_fee_payer';results.push({ id: entry.id, status: 'skip', reason: errorMsg });+ await setCooldown(redis, entry);continue;}@@ -503,6 +514,7 @@ export default wrapCron(async (req, res) => {if (amountAtomic > remainingCap) {log.info('autonomous_cap_would_exceed', { id: entry.id, amount: amountAtomic, remaining: remainingCap });results.push({ id: entry.id, status: 'skip', reason: 'cap_would_exceed' });+ await setCooldown(redis, entry); // cap headroom won't appear mid-cooldown; stop re-probingcontinue;}// Can't pay what we don't hold. Skip BEFORE building/signing/POSTing a@@ -569,12 +581,18 @@ export default wrapCron(async (req, res) => {await runStoreValue(entry, { sql, redis, responseBody, signalData, runId, targetUrl, targetContext, endpointUrl, origin, durationMs: Date.now() - t0, success, amountAtomic, txSig });} else {errorMsg = `http_${paidRes.status}`;+ // Failure MUST cool down too. Without this a failing paid entry+ // retried every tick forever: 12k+ settle-502 rows/day, all 8 tick+ // slots pinned by the same broken entries, and the maintenance+ // pipelines starved out of the rotation entirely.+ await setCooldown(redis, entry);}results.push({ id: entry.id, status: success ? 'paid' : 'error', amount_usdc: amountAtomic / 1e6, tx: txSig });} catch (err) {errorMsg = err?.message || 'unknown_error';results.push({ id: entry.id, status: 'error', reason: errorMsg });+ await setCooldown(redis, entry);}await recordLog(runId, entry, {diff --git a/data/changelog.json b/data/changelog.jsonindex d0dcc32f9..b504d71d0 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,27 @@{"$comment": "Curated changelog entries for three.ws, 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-19",+ "title": "Agent economy self-funding fixed and scaled up",+ "summary": "The agent economy's money loops are back at full speed. We found and fixed the scheduling bug that let failing paid calls hog the autonomous loop and starve the recirculation pipelines, wired a revenue share from the x402 ring treasury into the economy's funding root so it can refuel its own SOL, and raised the daily activity caps. Tips, agent-to-agent payments, trades, and marketplace purchases on the Money Pulse all flow again, and the ring's audit trail now verifies every leg of the new split sweeps.",+ "tags": [+ "fix",+ "improvement",+ "infra"+ ],+ "link": "/pulse"+ },+ {+ "date": "2026-07-19",+ "title": "First autonomous agent trade, fully documented",+ "summary": "A platform agent closed its first fully autonomous trade: it sniped a brand-new pump.fun launch from its own wallet and exited at +42.38 percent, with every decision recorded on its hash-chained ledger. We published the complete postmortem: a blog post with the on-chain receipts, a deep-dive doc on the sniper architecture (entry gates, the simulate-the-sell trade firewall, the exit ladder), and a tutorial for arming a sniper on your own agent, including the take-profit lesson this trade taught us.",+ "tags": [+ "feature",+ "docs"+ ],+ "link": "/blog/first-autonomous-trade"+ },{"date": "2026-07-19","title": "TradingView charts on every coin page",diff --git a/docs/x402-ring-economy.md b/docs/x402-ring-economy.mdindex 353432fc0..a3b7cf017 100644--- a/docs/x402-ring-economy.md+++ b/docs/x402-ring-economy.md@@ -418,6 +418,33 @@ principal recirculates (the rebalancer sweeps treasury→payer, now on a **120s*cooldown to keep up with the faster float), a higher daily cap raises *gross volume*without raising real cost — cost is only the SOL fees above.+### The master revenue share: how the ring fuels the rest of the economy++Every treasury sweep routes a bounded cut (`X402_RING_MASTER_REVSHARE_BPS`,+default 20%) to the **economy master wallet** instead of the payer. That cut is+the funding root's only USDC inflow: `economy-fuel.js` converts it to SOL (a+self-swap, per-run and per-day capped) and `treasury-topup` distributes that SOL+to every engine below its floor — the circulation treasury that drives the+Money Pulse (tips, trades, agent-to-agent payments), the ring sponsor whose SOL+floor gates settlement, and the rest of `SOLANA_SIGNERS`. Without this leg the+master starves, the sponsor slips under its floor, settles 502, and the pulse+flat-lines (July 2026 incident). Both legs of a split sweep land in+`x402_ring_ledger` (`kind='sweep'` payer leg, `kind='revshare'` master leg,+same `tx_sig`) and the reconciler verifies the treasury's on-chain delta+against the *sum* of the legs, each recipient against its own row.++Two scheduling guarantees keep the recirculation alive regardless of what else+the autonomous loop is doing:++1. **Reserved maintenance slots** — registry entries tagged `maintenance: true`+ (ring-rebalance, ring-float-topup, ring-pool-fund) are selected *outside*+ `X402_AUTONOMOUS_MAX_PER_TICK`, so a wave of failing high-priority paid+ entries can never starve them out of the rotation.+2. **Cooldown on failure** — a paid entry that errors now backs off for its full+ cooldown exactly like a success. Before this, a failing entry retried every+ tick forever, pinning all tick slots and generating thousands of junk+ settle-502 rows per day.+### Coherence: no silent skipsThe old failure — ring-settle silently dropped because its price exceeded thediff --git a/tests/x402-ring-reconciliation.test.js b/tests/x402-ring-reconciliation.test.jsindex 3cd64fb6b..7d44cc995 100644--- a/tests/x402-ring-reconciliation.test.js+++ b/tests/x402-ring-reconciliation.test.js@@ -143,6 +143,38 @@ describe('ring-reconciliation — pure helpers', () => {expect(r.ok).toBe(false);});+ it('verifySweepMovement verifies each leg of a split sweep (payer + master revshare) via txTotal', () => {+ const MASTER = 'MasterWallet1111111111111111111111111111111';+ // One tx: treasury sends 1.0 USDC total — 0.8 to payer, 0.2 to master.+ const tx = {+ meta: {+ preTokenBalances: [+ { owner: TREASURY, mint: MINT, uiTokenAmount: { amount: '1000000' } },+ { owner: PAYER, mint: MINT, uiTokenAmount: { amount: '0' } },+ { owner: MASTER, mint: MINT, uiTokenAmount: { amount: '0' } },+ ],+ postTokenBalances: [+ { owner: TREASURY, mint: MINT, uiTokenAmount: { amount: '0' } },+ { owner: PAYER, mint: MINT, uiTokenAmount: { amount: '800000' } },+ { owner: MASTER, mint: MINT, uiTokenAmount: { amount: '200000' } },+ ],+ },+ };+ const payerLeg = verifySweepMovement(+ { from_wallet: TREASURY, to_wallet: PAYER, mint: MINT, amount_atomic: 800_000 }, tx, TREASURY, 1_000_000,+ );+ const masterLeg = verifySweepMovement(+ { from_wallet: TREASURY, to_wallet: MASTER, mint: MINT, amount_atomic: 200_000 }, tx, TREASURY, 1_000_000,+ );+ expect(payerLeg.ok).toBe(true);+ expect(masterLeg.ok).toBe(true);+ // A leg claiming more than its on-chain credit still fails.+ const inflated = verifySweepMovement(+ { from_wallet: TREASURY, to_wallet: MASTER, mint: MINT, amount_atomic: 300_000 }, tx, TREASURY, 1_000_000,+ );+ expect(inflated.ok).toBe(false);+ });+it('feeDivergence: null when no audit figure, 0 when both zero, ratio otherwise', () => {expect(feeDivergence(100, null)).toBeNull();expect(feeDivergence(0, 0)).toBe(0);diff --git a/tests/x402-ring-revshare.test.js b/tests/x402-ring-revshare.test.jsnew file mode 100644index 000000000..a94281e18--- /dev/null+++ b/tests/x402-ring-revshare.test.js@@ -0,0 +1,54 @@+// The treasury sweep's master revenue share: split math and the registry's+// reserved maintenance slots (the two halves of the July 2026 starvation fix).+import { describe, it, expect } from 'vitest';+import { splitSweep } from '../api/_lib/x402/pipelines/ring-rebalance.js';+import { getFullRegistry } from '../api/_lib/x402/autonomous-registry.js';++describe('splitSweep', () => {+ it('routes the configured bps to the master and the rest to the payer', () => {+ const { payerCut, masterCut } = splitSweep(100_000_000n, 2_000);+ expect(masterCut).toBe(20_000_000n);+ expect(payerCut).toBe(80_000_000n);+ expect(payerCut + masterCut).toBe(100_000_000n);+ });++ it('drops a dust-sized master leg entirely', () => {+ const { payerCut, masterCut } = splitSweep(400_000n, 2_000); // 20% = $0.08 < $0.10 floor+ expect(masterCut).toBe(0n);+ expect(payerCut).toBe(400_000n);+ });++ it('bps=0 disables the master leg', () => {+ const { payerCut, masterCut } = splitSweep(50_000_000n, 0);+ expect(masterCut).toBe(0n);+ expect(payerCut).toBe(50_000_000n);+ });++ it('bps=10000 sends the full sweep to the master', () => {+ const { payerCut, masterCut } = splitSweep(50_000_000n, 10_000);+ expect(masterCut).toBe(50_000_000n);+ expect(payerCut).toBe(0n);+ });++ it('never loses atomics to rounding', () => {+ const { payerCut, masterCut } = splitSweep(1_234_567n, 3_333);+ expect(payerCut + masterCut).toBe(1_234_567n);+ });+});++describe('autonomous registry maintenance slots', () => {+ it('marks every recirculation pipeline as maintenance so the loop reserves it a slot', () => {+ const registry = getFullRegistry();+ const byId = Object.fromEntries(registry.map((e) => [e.id, e]));+ for (const id of ['ring-rebalance', 'ring-float-topup', 'ring-pool-fund']) {+ expect(byId[id], `${id} present`).toBeTruthy();+ expect(byId[id].maintenance, `${id}.maintenance`).toBe(true);+ }+ });++ it('keeps maintenance a small reserved set, not a backdoor around MAX_PER_TICK', () => {+ const maint = getFullRegistry().filter((e) => e.maintenance);+ expect(maint.length).toBeLessThanOrEqual(5);+ for (const e of maint) expect(typeof e.run).toBe('function');+ });+});