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
feat(x402-ring): rotate the payer pool through funded wallets only and grow it to 2,000
qhqf450f373602f1
diff --git a/api/_lib/migrations/20260922230000_x402_ring_pool_balances.sql b/api/_lib/migrations/20260922230000_x402_ring_pool_balances.sqlnew file mode 100644index 000000000..4dba68028--- /dev/null+++ b/api/_lib/migrations/20260922230000_x402_ring_pool_balances.sql@@ -0,0 +1,20 @@+-- x402 ring payer pool: last recorded on-chain balances per wallet, so the tick's+-- rotation only ever claims a wallet that can pay. The funder (ring-pool-fund)+-- reads every pool wallet's SOL + USDC each run and records it here; the claim+-- (claimNextPayer) requires recorded SOL over its floor, recorded USDC over the+-- price of the call, and a record no older than its freshness window. NULL means+-- never read, which the claim treats as unfunded. A freshly minted pool is all+-- NULL, so growing the pool never hands the tick an empty wallet again (the first+-- 20 claims from the 2,000-wallet pool minted on 2026-09-22 all paid nothing).+-- api/_lib/x402/pool.js ensurePoolSchema() applies the same ALTERs idempotently.++ALTER TABLE x402_ring_pool ADD COLUMN IF NOT EXISTS last_sol_lamports bigint;+ALTER TABLE x402_ring_pool ADD COLUMN IF NOT EXISTS last_usdc_atomic bigint;+ALTER TABLE x402_ring_pool ADD COLUMN IF NOT EXISTS balances_checked_at timestamptz;++COMMENT ON COLUMN x402_ring_pool.last_sol_lamports IS+ 'SOL (lamports) the funder last read for this wallet, debited by a fee estimate on each claim. NULL = never read = unfunded.';+COMMENT ON COLUMN x402_ring_pool.last_usdc_atomic IS+ 'USDC (6dp atomics) the funder last read for this wallet, debited by the call price on each claim. NULL = never read = unfunded.';+COMMENT ON COLUMN x402_ring_pool.balances_checked_at IS+ 'When the funder last recorded balances. The claim ignores records older than X402_RING_POOL_BALANCE_MAX_AGE_MINUTES (default 30).';diff --git a/api/_lib/x402/pipelines/ring-pool-fund.js b/api/_lib/x402/pipelines/ring-pool-fund.jsindex 2cd9265be..635ccc882 100644--- a/api/_lib/x402/pipelines/ring-pool-fund.js+++ b/api/_lib/x402/pipelines/ring-pool-fund.js@@ -36,7 +36,7 @@ import { logger } from '../../usage.js';import { solanaConnection } from '../../solana/connection.js';import { blockhashKey, getRecentBlockhashInfo, mintDecimals } from '../../solana/read-guards.js';import { USDC_MINT } from '../pay.js';-import { ringPoolEnabled, listEnabledPubkeys, recoverPoolKeypair, poolCount } from '../pool.js';+import { ringPoolEnabled, listEnabledPubkeys, recoverPoolKeypair, poolCount, recordPoolBalances } from '../pool.js';import { ringAllowedAddresses } from '../ring-allowlist.js';const log = logger('x402-ring-pool-fund');@@ -50,6 +50,16 @@ export function poolUsdcTargetAtomic() { return num(process.env.X402_RING_POOL_Uexport function poolUsdcCeilingAtomic() { return num(process.env.X402_RING_POOL_USDC_CEIL_ATOMIC, 4_000_000); } // $4.00export function poolFundMaxPerRun() { return Math.max(1, num(process.env.X402_RING_POOL_FUND_MAX_PER_RUN, 60)); }+/**+ * SOL the sponsor/master keeps out of pool funding. Defaults to the facilitator's+ * own settle floor so a funding run can never park the fee wallet under the line+ * that pauses settlement (the 2026-07-27 failure mode, in pool form).+ */+export function funderReserveLamports() { return num(process.env.X402_SPONSOR_SOL_FLOOR_LAMPORTS, 20_000_000); }++const ATA_RENT_LAMPORTS = 2_039_280; // rent-exempt minimum for a new SPL token account+const TRANSFER_FEE_LAMPORTS = 5_000; // one signature's base fee, budgeted per transfer+const SOL_TRANSFERS_PER_TX = 14; // System transfers batched per funding txconst USDC_TRANSFERS_PER_TX = 6; // (idempotent-create + transferChecked) pairs per txconst ACCOUNTS_PER_READ = 100; // getMultipleAccountsInfo hard limit@@ -108,10 +118,67 @@ export function planPoolFunding({ pubkeys, solByPubkey, usdcByPubkey, allowed, freturn { solNeed, usdcNeed, usdcSweep };}+/**+ * Trim a funding plan to what the funders can actually pay THIS run. A transfer+ * the funder cannot cover fails simulation, and with a 2,000-wallet pool an empty+ * master would otherwise burn 40 doomed transactions every two minutes. SOL for+ * top-ups, new-ATA rent and every tx fee comes out of one budget (the sponsor's+ * balance above its reserve); USDC comes out of the treasury's ATA. Both plans+ * keep their neediest-first order, so trimming drops the tail, never the head.+ *+ * @param {{ solNeed:{pk:string,add:number}[], usdcNeed:{pk:string,add:bigint}[], ataExists?:Set<string>,+ * funderLamports:number, treasuryUsdcAtomic:bigint|number, reserveLamports:number,+ * ataRentLamports?:number, feeLamports?:number }} args+ */+export function trimToFunderCapacity({+ solNeed, usdcNeed, ataExists, funderLamports, treasuryUsdcAtomic, reserveLamports,+ ataRentLamports = ATA_RENT_LAMPORTS, feeLamports = TRANSFER_FEE_LAMPORTS,+}) {+ let solBudget = Math.max(0, Number(funderLamports || 0) - Number(reserveLamports || 0));+ const solKept = [];+ for (const w of solNeed) {+ const cost = Math.floor(w.add) + feeLamports;+ if (cost > solBudget) break;+ solBudget -= cost;+ solKept.push(w);+ }+ let usdcBudget = BigInt(treasuryUsdcAtomic ?? 0);+ const usdcKept = [];+ for (const w of usdcNeed) {+ const solCost = (ataExists?.has(w.pk) ? 0 : ataRentLamports) + feeLamports;+ if (solCost > solBudget || BigInt(w.add) > usdcBudget) break;+ solBudget -= solCost;+ usdcBudget -= BigInt(w.add);+ usdcKept.push(w);+ }+ return {+ solNeed: solKept,+ usdcNeed: usdcKept,+ skipped: { sol: solNeed.length - solKept.length, usdc: usdcNeed.length - usdcKept.length },+ };+}++/**+ * The balances to record after a run: the fresh on-chain reads plus what this+ * run just moved, so the claim never waits a whole funder cycle to see a wallet+ * it just funded. Pure; the funder feeds it the lists of moves that landed.+ *+ * @returns {{ pubkey:string, solLamports:number, usdcAtomic:bigint }[]}+ */+export function applyFundingMoves({ pubkeys, solByPubkey, usdcByPubkey, solFunded = [], usdcFunded = [], usdcSwept = [] }) {+ const sol = new Map(solByPubkey);+ const usdc = new Map(usdcByPubkey);+ for (const w of solFunded) sol.set(w.pk, Number(sol.get(w.pk) ?? 0) + Math.floor(w.add));+ for (const w of usdcFunded) usdc.set(w.pk, BigInt(usdc.get(w.pk) ?? 0n) + BigInt(w.add));+ for (const w of usdcSwept) usdc.set(w.pk, BigInt(usdc.get(w.pk) ?? 0n) - BigInt(w.take));+ return pubkeys.map((pk) => ({ pubkey: pk, solLamports: Number(sol.get(pk) ?? 0), usdcAtomic: BigInt(usdc.get(pk) ?? 0n) }));+}+async function readBalances(conn, pubkeys, mint) {const solByPubkey = new Map();const usdcByPubkey = new Map();const ataByPubkey = new Map();+ const ataExists = new Set();for (const pk of pubkeys) {ataByPubkey.set(pk, getAssociatedTokenAddressSync(mint, new PublicKey(pk), false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID));}@@ -126,9 +193,12 @@ async function readBalances(conn, pubkeys, mint) {for (let i = 0; i < ataList.length; i += ACCOUNTS_PER_READ) {const chunk = ataList.slice(i, i + ACCOUNTS_PER_READ);const infos = await conn.getMultipleAccountsInfo(chunk.map((c) => c.ata), 'confirmed');- chunk.forEach((c, j) => usdcByPubkey.set(c.pk, infos[j] ? tokenAmountFromAccountData(infos[j].data) : 0n));+ chunk.forEach((c, j) => {+ usdcByPubkey.set(c.pk, infos[j] ? tokenAmountFromAccountData(infos[j].data) : 0n);+ if (infos[j]) ataExists.add(c.pk);+ });}- return { solByPubkey, usdcByPubkey, ataByPubkey };+ return { solByPubkey, usdcByPubkey, ataByPubkey, ataExists };}async function sendIxs(conn, feePayer, signers, instructions) {@@ -187,9 +257,9 @@ export async function run(ctx = {}) {const treasuryAta = getAssociatedTokenAddressSync(mint, treasury.publicKey, false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID);const pubkeys = await listEnabledPubkeys(sql);- const { solByPubkey, usdcByPubkey, ataByPubkey } = await readBalances(conn, pubkeys, mint);+ const { solByPubkey, usdcByPubkey, ataByPubkey, ataExists } = await readBalances(conn, pubkeys, mint);- const { solNeed, usdcNeed, usdcSweep } = planPoolFunding({+ const planned = planPoolFunding({pubkeys, solByPubkey, usdcByPubkey, allowed,floors: {solFloor: poolSolFloorLamports(), solTarget: poolSolTargetLamports(),@@ -198,8 +268,34 @@ export async function run(ctx = {}) {},});- const moves = { sol_funded: 0, usdc_funded: 0, usdc_swept: 0, sigs: [] };+ // Only submit what the funders can pay: read the sponsor's SOL and the+ // treasury's USDC once, then cut the plan to fit (see trimToFunderCapacity).+ let funderLamports = 0;+ let treasuryUsdcAtomic = 0n;+ try { funderLamports = await conn.getBalance(solFunder.publicKey, 'confirmed'); } catch { funderLamports = 0; }+ try {+ const info = await conn.getAccountInfo(treasuryAta, 'confirmed');+ treasuryUsdcAtomic = info ? tokenAmountFromAccountData(info.data) : 0n;+ } catch { treasuryUsdcAtomic = 0n; }+ const { solNeed, usdcNeed, skipped } = trimToFunderCapacity({+ solNeed: planned.solNeed, usdcNeed: planned.usdcNeed, ataExists,+ funderLamports, treasuryUsdcAtomic, reserveLamports: funderReserveLamports(),+ });+ const usdcSweep = planned.usdcSweep;+ if (skipped.sol || skipped.usdc) {+ log.warn('pool_fund_underfunded', {+ total, need_sol: planned.solNeed.length, need_usdc: planned.usdcNeed.length,+ skipped_sol: skipped.sol, skipped_usdc: skipped.usdc,+ funder: solFunder.publicKey.toBase58(), funder_sol: funderLamports / 1e9,+ treasury_usdc: Number(treasuryUsdcAtomic) / 1e6,+ });+ }++ const moves = { sol_funded: 0, usdc_funded: 0, usdc_swept: 0, sigs: [], recorded: 0 };const ledgerRows = [];+ const solFunded = [];+ const usdcFunded = [];+ const usdcSwept = [];// ── SOL top-ups (batched System transfers, funded by the sponsor/master) ──────for (let i = 0; i < solNeed.length; i += SOL_TRANSFERS_PER_TX) {@@ -211,6 +307,7 @@ export async function run(ctx = {}) {const res = await sendIxs(conn, solFunder, [solFunder], ixs);if (res.ok) {moves.sol_funded += chunk.length; moves.sigs.push(res.signature);+ solFunded.push(...chunk);for (const w of chunk) ledgerRows.push({ from: solFunder.publicKey.toBase58(), to: w.pk, amount: 0, sig: res.signature });} else {log.warn('pool_sol_fund_failed', { count: chunk.length, err: res.err });@@ -234,6 +331,7 @@ export async function run(ctx = {}) {const res = await sendIxs(conn, solFunder, signers, ixs);if (res.ok) {moves.usdc_funded += chunk.length; moves.sigs.push(res.signature);+ usdcFunded.push(...chunk);for (const w of chunk) ledgerRows.push({ from: treasury.publicKey.toBase58(), to: w.pk, amount: Number(w.add), sig: res.signature });} else {log.warn('pool_usdc_fund_failed', { count: chunk.length, err: res.err });@@ -256,6 +354,7 @@ export async function run(ctx = {}) {const res = await sendIxs(conn, solFunder, signers, ixs);if (res.ok) {moves.usdc_swept += 1; moves.sigs.push(res.signature);+ usdcSwept.push(w);ledgerRows.push({ from: w.pk, to: treasury.publicKey.toBase58(), amount: Number(w.take), sig: res.signature });} else {log.warn('pool_sweep_failed', { pubkey: w.pk, err: res.err });@@ -270,10 +369,25 @@ export async function run(ctx = {}) {} catch (err) { log.warn('pool_fund_ledger_write_failed', { message: err?.message }); }}- log.info('ring_pool_funded', { total, ...moves, sigs: moves.sigs.length });+ // Record what every wallet holds now (reads + this run's moves), so the tick's+ // claim rotates through funded wallets only. A failed write leaves the previous+ // record in place, which the claim's freshness window ages out on its own.+ try {+ moves.recorded = await recordPoolBalances(+ applyFundingMoves({ pubkeys, solByPubkey, usdcByPubkey, solFunded, usdcFunded, usdcSwept }),+ sql,+ );+ } catch (err) {+ log.warn('pool_balance_record_failed', { message: err?.message });+ }++ log.info('ring_pool_funded', { total, ...moves, sigs: moves.sigs.length, skipped_sol: skipped.sol, skipped_usdc: skipped.usdc });return {success: true, amountAtomic: 0,- note: `pool_fund sol=${moves.sol_funded} usdc=${moves.usdc_funded} swept=${moves.usdc_swept}`,- moves: { sol_funded: moves.sol_funded, usdc_funded: moves.usdc_funded, usdc_swept: moves.usdc_swept, tx_count: moves.sigs.length },+ note: `pool_fund sol=${moves.sol_funded} usdc=${moves.usdc_funded} swept=${moves.usdc_swept} recorded=${moves.recorded} underfunded=${skipped.sol + skipped.usdc}`,+ moves: {+ sol_funded: moves.sol_funded, usdc_funded: moves.usdc_funded, usdc_swept: moves.usdc_swept,+ tx_count: moves.sigs.length, recorded: moves.recorded, skipped_sol: skipped.sol, skipped_usdc: skipped.usdc,+ },};}diff --git a/api/_lib/x402/pool.js b/api/_lib/x402/pool.jsindex 17f04a09e..76f566663 100644--- a/api/_lib/x402/pool.js+++ b/api/_lib/x402/pool.js@@ -19,6 +19,14 @@// • Secrets never live in env. Each key is secret-box-encrypted at rest// (WALLET_ENCRYPTION_KEY + random per-record salt), decrypted only in-process// for the moment it signs.+// • Funded-only rotation. The funder (pipelines/ring-pool-fund.js) records every+// wallet's last on-chain SOL + USDC here on each run, and claimNextPayer()+// only draws a wallet whose recorded balances cover the call it is about to+// pay. A freshly minted pool is all zeros, so until the funder has moved+// money the claim returns null and the tick keeps paying from the seed payer.+// Without this gate, growing the pool to 2,000 wallets on 2026-09-22 handed+// the tick empty wallets on its first 20 claims and every one of those+// settles failed simulation.import { Keypair } from '@solana/web3.js';import { encryptSecret, decryptSecret } from '../secret-box.js';@@ -27,6 +35,29 @@ import { logger } from '../usage.js';const log = logger('x402-ring-pool');+const num = (v, d) => { const n = Number(v); return Number.isFinite(n) && n >= 0 ? n : d; };++/**+ * SOL a claim assumes the settle will burn. A 1-signature self-pay settle costs+ * ~5k lamports base + priority fee (the ledger averages ~6.7k), so 10k leaves a+ * margin without over-reserving; the funder's next balance read corrects it.+ */+export const CLAIM_FEE_ESTIMATE_LAMPORTS = 10_000;++/**+ * Floors a pool wallet must clear to be handed to the tick as a payer.+ * minSolLamports: enough for a few self-pay settles, not just one.+ * maxBalanceAgeMinutes: a recorded balance older than this is not trusted;+ * the funder refreshes every run (120s cooldown), so a+ * stale row means the funder has not been running.+ */+export function poolClaimFloors() {+ return {+ minSolLamports: Math.floor(num(process.env.X402_RING_POOL_CLAIM_MIN_SOL_LAMPORTS, 20_000)),+ maxBalanceAgeMinutes: Math.max(1, Math.floor(num(process.env.X402_RING_POOL_BALANCE_MAX_AGE_MINUTES, 30))),+ };+}+/** True when the ring should rotate through the payer pool. Off by default. */export function ringPoolEnabled() {return String(process.env.X402_RING_POOL_ENABLED || '').trim().toLowerCase() === 'true';@@ -62,6 +93,11 @@ export async function ensurePoolSchema(sql = defaultSql) {)`;await sql`CREATE INDEX IF NOT EXISTS x402_ring_pool_rotationON x402_ring_pool (enabled, last_used_at NULLS FIRST, pubkey)`;+ // Last recorded on-chain balances (migration 20260922230000). NULL = never+ // read, which the claim treats as unfunded.+ await sql`ALTER TABLE x402_ring_pool ADD COLUMN IF NOT EXISTS last_sol_lamports bigint`;+ await sql`ALTER TABLE x402_ring_pool ADD COLUMN IF NOT EXISTS last_usdc_atomic bigint`;+ await sql`ALTER TABLE x402_ring_pool ADD COLUMN IF NOT EXISTS balances_checked_at timestamptz`;_schemaReady = true;}@@ -72,6 +108,57 @@ export async function poolCount(sql = defaultSql) {return rows[0]?.n ?? 0;}+/**+ * Count of enabled pool wallets whose recorded balances would clear a claim for+ * `minUsdcAtomic` right now. This is the number that says whether the rotation+ * has anything to rotate through, which `poolCount` alone does not.+ */+export async function poolFundedCount(sql = defaultSql, { minUsdcAtomic = 0 } = {}) {+ await ensurePoolSchema(sql);+ const { minSolLamports, maxBalanceAgeMinutes } = poolClaimFloors();+ const minUsdc = Math.max(0, Math.floor(Number(minUsdcAtomic) || 0));+ const rows = await sql`+ SELECT count(*)::int AS n FROM x402_ring_pool+ WHERE enabled = true+ AND last_sol_lamports >= ${minSolLamports}::bigint+ AND last_usdc_atomic >= ${minUsdc}::bigint+ AND balances_checked_at > now() - (${maxBalanceAgeMinutes}::int * interval '1 minute')`;+ return rows[0]?.n ?? 0;+}++/**+ * Record fresh on-chain balances for a batch of pool wallets in ONE round trip+ * (unnest, the same array-parameter shape agent-embeddings uses). The funder+ * calls this with every wallet it read, after applying the moves it just made,+ * so the claim always sees a balance at most one funder run old.+ *+ * @param {{ pubkey:string, solLamports:number|bigint, usdcAtomic:number|bigint }[]} entries+ * @returns {Promise<number>} rows updated+ */+export async function recordPoolBalances(entries, sql = defaultSql) {+ if (!entries?.length) return 0;+ await ensurePoolSchema(sql);+ const pubkeys = entries.map((e) => e.pubkey);+ const sols = entries.map((e) => clampAtomic(e.solLamports));+ const usdcs = entries.map((e) => clampAtomic(e.usdcAtomic));+ const rows = await sql`+ UPDATE x402_ring_pool p+ SET last_sol_lamports = v.sol::bigint,+ last_usdc_atomic = v.usdc::bigint,+ balances_checked_at = now()+ FROM unnest(${pubkeys}::text[], ${sols}::text[], ${usdcs}::text[]) AS v(pubkey, sol, usdc)+ WHERE p.pubkey = v.pubkey+ RETURNING p.pubkey`;+ return rows.length;+}++// A balance as a non-negative integer string, whatever numeric shape it arrived in.+function clampAtomic(v) {+ let b;+ try { b = typeof v === 'bigint' ? v : BigInt(Math.floor(Number(v) || 0)); } catch { b = 0n; }+ return (b < 0n ? 0n : b).toString();+}+/** All enabled pool pubkeys (for the funding pipeline's batched balance reads). */export async function listEnabledPubkeys(sql = defaultSql) {await ensurePoolSchema(sql);@@ -147,19 +234,35 @@ export async function growPoolToTarget({ target, sql = defaultSql } = {}) {/*** Atomically claim the next payer wallet on a least-recently-used rotation, bump* its usage cursor, and return its decrypted Keypair. Concurrent ticks never pick- * the same wallet (FOR UPDATE SKIP LOCKED). Returns null when the pool is empty —- * the caller falls back to the seed payer so the ring never stalls.+ * the same wallet (FOR UPDATE SKIP LOCKED). Only a FUNDED wallet is eligible: its+ * last recorded SOL must clear the claim floor, its last recorded USDC must cover+ * `minUsdcAtomic` (the price of the call about to be paid), and that record must+ * be fresh. The claim debits the recorded balances by the call price and a fee+ * estimate so a wallet is not handed out again before the funder re-reads it.+ * Returns null when no wallet qualifies (empty pool, unfunded pool, or a funder+ * that has stopped running); the caller falls back to the seed payer so the ring+ * never stalls.*+ * @param {Function} [sql]+ * @param {{ minUsdcAtomic?: number }} [opts]* @returns {Promise<{ keypair: Keypair, pubkey: string } | null>}*/-export async function claimNextPayer(sql = defaultSql) {+export async function claimNextPayer(sql = defaultSql, { minUsdcAtomic = 0 } = {}) {await ensurePoolSchema(sql);+ const { minSolLamports, maxBalanceAgeMinutes } = poolClaimFloors();+ const minUsdc = Math.max(0, Math.floor(Number(minUsdcAtomic) || 0));const rows = await sql`UPDATE x402_ring_pool- SET last_used_at = now(), use_count = use_count + 1+ SET last_used_at = now(),+ use_count = use_count + 1,+ last_usdc_atomic = last_usdc_atomic - ${minUsdc}::bigint,+ last_sol_lamports = last_sol_lamports - ${CLAIM_FEE_ESTIMATE_LAMPORTS}::bigintWHERE pubkey = (SELECT pubkey FROM x402_ring_poolWHERE enabled = true+ AND last_sol_lamports >= ${minSolLamports}::bigint+ AND last_usdc_atomic >= ${minUsdc}::bigint+ AND balances_checked_at > now() - (${maxBalanceAgeMinutes}::int * interval '1 minute')ORDER BY last_used_at NULLS FIRST, pubkeyLIMIT 1FOR UPDATE SKIP LOCKEDdiff --git a/api/cron/x402-ring-tick.js b/api/cron/x402-ring-tick.jsindex a5b7b5f65..c9c35463c 100644--- a/api/cron/x402-ring-tick.js+++ b/api/cron/x402-ring-tick.js@@ -448,10 +448,23 @@ export default wrapCron(async (req, res) => {// never stalls. Pool wallets are inside ringAllowedAddresses(), so the onAccept// allowlist gate and the leak scanner classify them internal.const usePool = ringPoolEnabled();+ let poolClaims = 0;+ let poolFallbacks = 0;const payCtx = {buyer: payer, conn, blockhash, mintInfo,...(usePool- ? { buyerFor: async () => { const c = await claimNextPayer(sql).catch(() => null); return c?.keypair || payer; } }+ ? {+ buyerFor: async (ep) => {+ // The claim only hands back a wallet whose recorded balances cover+ // THIS call, so an unfunded pool falls through to the seed payer+ // instead of producing settles that fail simulation.+ const minUsdcAtomic = ep === RING_SETTLE_ENDPOINT ? ringSettlePriceAtomic : CHEAP_RESERVATION_ATOMIC;+ const c = await claimNextPayer(sql, { minUsdcAtomic }).catch(() => null);+ if (c?.keypair) { poolClaims += 1; return c.keypair; }+ poolFallbacks += 1;+ return payer;+ },+ }: {}),};// Bounded-concurrency execution (ring-tick-exec.js): the settle carrier runs@@ -492,12 +505,14 @@ export default wrapCron(async (req, res) => {run_id: runId, tick_seq: tickSeq, settle_tick: plan.isSettleTick,degraded: pbp.degraded, calls, paid, errors, spent_usdc: (spent / 1e6).toFixed(4),payer: payer.publicKey.toBase58(),+ pool_enabled: usePool, pool_claims: poolClaims, pool_fallbacks: poolFallbacks,});return json(res, 200, {ok: true,run_id: runId,tick_seq: tickSeq,+ pool: { enabled: usePool, claims: poolClaims, fallbacks: poolFallbacks },settle_tick: plan.isSettleTick,...(pbp.degraded ? { degraded: true, reason: 'settle_unaffordable' } : {}),calls,diff --git a/api/x402-ring.js b/api/x402-ring.jsindex 869d4c5b1..962932f21 100644--- a/api/x402-ring.js+++ b/api/x402-ring.js@@ -27,6 +27,8 @@ import { solPriceUsd } from './_lib/sol-price.js';import { loadSeedKeypair, USDC_MINT } from './_lib/x402/pay.js';import { SELF_FACILITATOR_ENABLED, SPONSOR_SOL_FLOOR_LAMPORTS } from './_lib/x402/self-facilitator.js';import { validateRingConfig, warnIfRingRoutesExternal } from './_lib/x402/ring-config.js';+import { ringPoolEnabled, ringPoolTargetSize, poolCount, poolFundedCount } from './_lib/x402/pool.js';+import { priceFor } from './_lib/x402-prices.js';const PERIOD_HOURS = { '24h': 24, '7d': 168, '30d': 720 };// 'all' is the documented lifetime window; every other key is a windowed report.@@ -188,6 +190,24 @@ export default wrap(async (req, res) => {warnIfRingRoutesExternal('x402-ring');const configWarnings = validateRingConfig();+ // Payer pool: how many distinct wallets the rotation can actually draw from.+ // `total` is what was minted; the funded counts are what the claim will hand+ // out right now (recorded balances covering a cheap call / a full settle).+ let pool = { enabled: ringPoolEnabled(), target: ringPoolTargetSize(), total: null, funded_for_cheap_call: null, funded_for_settle: null };+ if (dbOk) {+ try {+ const settlePrice = Number(priceFor('ring-settle', '1000000'));+ const [total, cheap, settle] = await Promise.all([+ poolCount(sql),+ poolFundedCount(sql, { minUsdcAtomic: 20_000 }),+ poolFundedCount(sql, { minUsdcAtomic: settlePrice }),+ ]);+ pool = { ...pool, total, funded_for_cheap_call: cheap, funded_for_settle: settle };+ } catch (err) {+ if (!isDbUnavailableError(err)) throw err;+ }+ }+return json(res, 200, {ok: true,self_hosted_facilitator: SELF_FACILITATOR_ENABLED,@@ -209,6 +229,7 @@ export default wrap(async (req, res) => {below_floor: sponsorSol != null ? sponsorSol < sol(SPONSOR_SOL_FLOOR_LAMPORTS) : null,},},+ pool,net: {ring_float_usdc: ringFloat,gross_volume_usdc: settlements.gross_usdc,diff --git a/data/changelog.json b/data/changelog.jsonindex 2867b1fa4..901840d84 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -28679,6 +28679,15 @@"fix"],"link": "/club"+ },+ {+ "date": "2026-09-22",+ "title": "The agent economy now pays from thousands of distinct wallets, and only from ones that hold funds",+ "summary": "The x402 ring, the closed loop where three.ws agents pay each other for services, has a pool of 2,000 payer wallets to rotate through instead of a single seed wallet, so on-chain activity reflects many participants rather than one cron. Rotation now checks each wallet's recorded SOL and USDC before handing it a payment and falls back to the seed payer when nothing in the pool can cover the call, so a freshly minted or thinly funded pool never produces failed payments. The funder that keeps the pool topped up only submits transfers its own wallets can pay for, and the ring status endpoint reports how many pool wallets are minted and how many are ready to pay.",+ "tags": [+ "infra",+ "improvement"+ ]}]}diff --git a/docs/x402-ring-economy.md b/docs/x402-ring-economy.mdindex 1a7933662..07577a382 100644--- a/docs/x402-ring-economy.md+++ b/docs/x402-ring-economy.md@@ -929,10 +929,22 @@ one-time, reclaimable ATA rent.`treasury-sweepback` never enumerates them. This is the same class of bug thatused to close the treasury's USDC ATA every run (see the box below) — it cannotrecur across 1,000 pool wallets because they are never in the sweepback set.-- **Rotation.** `claimNextPayer()` atomically claims the least-recently-used enabled- wallet (`FOR UPDATE SKIP LOCKED`, so concurrent ticks never collide), and the ring- tick passes it per-settle via the shared driver's `buyerFor` hook. An empty or- unavailable pool falls back to the seed payer, so the ring never stalls.+- **Rotation, funded wallets only.** `claimNextPayer()` atomically claims the+ least-recently-used enabled wallet (`FOR UPDATE SKIP LOCKED`, so concurrent ticks+ never collide), and the ring tick passes it per-call via the shared driver's+ `buyerFor` hook together with the price of that call. A wallet is eligible only+ when its **last recorded balances** cover it: SOL at or above+ `X402_RING_POOL_CLAIM_MIN_SOL_LAMPORTS` (default 20,000, a few self-pay settles),+ USDC at or above the call price (the ring-settle price for the carrier, the+ $0.02 cheap-call reservation otherwise), and a record no older than+ `X402_RING_POOL_BALANCE_MAX_AGE_MINUTES` (default 30). The claim debits the+ record by the price plus a fee estimate so a wallet is not handed out twice+ before the funder re-reads it. A pool with no eligible wallet (empty, freshly+ minted, or a funder that has stopped running) returns nothing and the tick pays+ from the seed payer, so the ring never stalls and never submits a settle from a+ wallet that cannot pay. That gate exists because growing the pool to 2,000 fresh+ wallets on 2026-09-22 with the old balance-blind claim handed the tick empty+ wallets on its first 20 claims, and every one of those settles failed simulation.- **Funding.** `ring-pool-fund` (120s cooldown) reads all pool balances in**batches** (`getMultipleAccountsInfo`, ≤100/call) and tops up in **batched**transactions: SOL from the sponsor/master, USDC from the treasury, each below a@@ -940,7 +952,20 @@ one-time, reclaimable ATA rent.a handful of transactions per run, not one per wallet. Recirculation, not spend —it never consumes the daily cap. The pure decision is `planPoolFunding()`(unit-tested); the effectful execution batches and records each move to- `x402_ring_ledger` as `kind='fund'`.+ `x402_ring_ledger` as `kind='fund'`. Two more things every run does:+ it **trims the plan to what the funders can pay** (`trimToFunderCapacity()`,+ pure and unit-tested: SOL top-ups, new-ATA rent and tx fees share the sponsor's+ balance above `X402_SPONSOR_SOL_FLOOR_LAMPORTS`, USDC comes from the treasury's+ ATA, and the neediest-first head is kept while the tail is skipped and logged as+ `pool_fund_underfunded`), so an empty master never burns doomed transactions;+ and it **records every wallet's balances** (`recordPoolBalances()`, one+ `unnest` round trip for the whole pool, applied after this run's moves) into+ `x402_ring_pool.last_sol_lamports` / `last_usdc_atomic` /+ `balances_checked_at` (migration `20260922230000`), which is what the claim+ above reads. `node scripts/x402-ring-pool-setup.mjs --status` prints the minted+ count and the funded count side by side, and `GET /api/x402-ring?action=status`+ exposes the same under `pool` (`total`, `funded_for_cheap_call`,+ `funded_for_settle`).**Turning it on.**@@ -960,7 +985,8 @@ gcloud run services update three-ws-api --region us-central1 \(target), `X402_RING_POOL_SOL_FLOOR_LAMPORTS` / `_TARGET_LAMPORTS` (default0.008 / 0.012 SOL), `X402_RING_POOL_USDC_FLOOR_ATOMIC` / `_TARGET_ATOMIC` /`_CEIL_ATOMIC` (default $0.50 / $2 / $4), `X402_RING_POOL_FUND_MAX_PER_RUN`-(default 60).+(default 60), `X402_RING_POOL_CLAIM_MIN_SOL_LAMPORTS` (default 20,000) and+`X402_RING_POOL_BALANCE_MAX_AGE_MINUTES` (default 30) for the funded-only claim.> ### Fixed 2026-07-17 — the treasury-sweepback rent churn>diff --git a/scripts/x402-ring-pool-setup.mjs b/scripts/x402-ring-pool-setup.mjsindex fb0e31b44..6517633a2 100644--- a/scripts/x402-ring-pool-setup.mjs+++ b/scripts/x402-ring-pool-setup.mjs@@ -35,9 +35,9 @@ const opt = (n, d) => { const p = args.find((a) => a.startsWith(`--${n}=`)); retconst size = Number(opt('size', process.env.X402_RING_POOL_SIZE || 0)) || 0;async function main() {- const { poolCount, growPoolToTarget, ringPoolTargetSize } = await import('../api/_lib/x402/pool.js');+ const { poolCount, poolFundedCount, poolClaimFloors, growPoolToTarget, ringPoolTargetSize } = await import('../api/_lib/x402/pool.js');const {- poolSolTargetLamports, poolUsdcTargetAtomic,+ poolSolTargetLamports, poolUsdcTargetAtomic, poolUsdcFloorAtomic,} = await import('../api/_lib/x402/pipelines/ring-pool-fund.js');const target = size > 0 ? size : ringPoolTargetSize();@@ -63,7 +63,12 @@ async function main() {const before = await poolCount();if (flag('status')) {- console.log(`ring pool: ${before} enabled wallet(s). target=${target || '(unset)'}.`);+ // "funded" is what the tick's claim would actually hand out: recorded SOL+ // over the claim floor, recorded USDC over the pool floor, read recently.+ const floors = poolClaimFloors();+ const funded = await poolFundedCount(undefined, { minUsdcAtomic: poolUsdcFloorAtomic() });+ console.log(`ring pool: ${before} enabled wallet(s), ${funded} funded (>= ${floors.minSolLamports} lamports and >= ${(poolUsdcFloorAtomic() / 1e6).toFixed(2)} USDC, balances read within ${floors.maxBalanceAgeMinutes} min). target=${target || '(unset)'}.`);+ if (before && !funded) console.log('No wallet is claimable yet: the ring keeps paying from the seed payer until ring-pool-fund has moved SOL + USDC into the pool.');return;}diff --git a/tests/x402-ring-pool.test.js b/tests/x402-ring-pool.test.jsindex afee9389b..578137b9e 100644--- a/tests/x402-ring-pool.test.js+++ b/tests/x402-ring-pool.test.js@@ -100,3 +100,93 @@ describe('planPoolFunding (pure)', () => {expect(usdcNeed).toHaveLength(10);});});++// ── Funded-only rotation (2026-09-22) ─────────────────────────────────────────+// The claim only hands out wallets whose recorded balances cover the call, the+// funder only submits what its funders can pay, and it records post-move+// balances so the claim sees a just-funded wallet without waiting a cycle.++import { poolClaimFloors, CLAIM_FEE_ESTIMATE_LAMPORTS } from '../api/_lib/x402/pool.js';+import { trimToFunderCapacity, applyFundingMoves, funderReserveLamports } from '../api/_lib/x402/pipelines/ring-pool-fund.js';++describe('claim floors', () => {+ const keys = ['X402_RING_POOL_CLAIM_MIN_SOL_LAMPORTS', 'X402_RING_POOL_BALANCE_MAX_AGE_MINUTES', 'X402_SPONSOR_SOL_FLOOR_LAMPORTS'];+ const saved = {};+ beforeEach(() => { for (const k of keys) saved[k] = process.env[k]; });+ afterEach(() => { for (const k of keys) { if (saved[k] === undefined) delete process.env[k]; else process.env[k] = saved[k]; } });++ it('defaults to a few settles of SOL and a 30-minute freshness window', () => {+ for (const k of keys) delete process.env[k];+ expect(poolClaimFloors()).toEqual({ minSolLamports: 20_000, maxBalanceAgeMinutes: 30 });+ expect(poolClaimFloors().minSolLamports).toBeGreaterThan(CLAIM_FEE_ESTIMATE_LAMPORTS);+ expect(funderReserveLamports()).toBe(20_000_000);+ });++ it('honors env overrides and never accepts a zero-minute window', () => {+ process.env.X402_RING_POOL_CLAIM_MIN_SOL_LAMPORTS = '50000';+ process.env.X402_RING_POOL_BALANCE_MAX_AGE_MINUTES = '0';+ process.env.X402_SPONSOR_SOL_FLOOR_LAMPORTS = '2000000';+ expect(poolClaimFloors()).toEqual({ minSolLamports: 50_000, maxBalanceAgeMinutes: 1 });+ expect(funderReserveLamports()).toBe(2_000_000);+ });+});++describe('trimToFunderCapacity (pure)', () => {+ const solNeed = [{ pk: 'a', add: 12_000_000 }, { pk: 'b', add: 12_000_000 }, { pk: 'c', add: 12_000_000 }];+ const usdcNeed = [{ pk: 'a', add: 2_000_000n }, { pk: 'b', add: 2_000_000n }, { pk: 'c', add: 2_000_000n }];++ it('keeps the neediest-first head and drops the tail the sponsor cannot pay', () => {+ // 30M lamports, 5M reserve: 25M spendable covers two 12M top-ups (+5k fee each), not three.+ const r = trimToFunderCapacity({ solNeed, usdcNeed: [], funderLamports: 30_000_000, treasuryUsdcAtomic: 0n, reserveLamports: 5_000_000 });+ expect(r.solNeed.map((w) => w.pk)).toEqual(['a', 'b']);+ expect(r.skipped).toEqual({ sol: 1, usdc: 0 });+ });++ it('submits nothing from an empty sponsor and reports every skip', () => {+ const r = trimToFunderCapacity({ solNeed, usdcNeed, funderLamports: 7_800_000, treasuryUsdcAtomic: 10_000_000n, reserveLamports: 20_000_000 });+ expect(r.solNeed).toEqual([]);+ expect(r.usdcNeed).toEqual([]);+ expect(r.skipped).toEqual({ sol: 3, usdc: 3 });+ });++ it('bounds USDC by the treasury and charges ATA rent only for wallets without one', () => {+ const ataExists = new Set(['a']);+ // Treasury holds $4: covers two $2 top-ups. SOL budget 2.04M: 'a' needs only a fee,+ // 'b' needs rent (2,039,280) + fee = 2,044,280 > remaining, so 'b' is cut.+ const r = trimToFunderCapacity({ solNeed: [], usdcNeed, ataExists, funderLamports: 2_040_000, treasuryUsdcAtomic: 4_000_000n, reserveLamports: 0 });+ expect(r.usdcNeed.map((w) => w.pk)).toEqual(['a']);+ expect(r.skipped).toEqual({ sol: 0, usdc: 2 });+ const rich = trimToFunderCapacity({ solNeed: [], usdcNeed, ataExists, funderLamports: 10_000_000, treasuryUsdcAtomic: 4_000_000n, reserveLamports: 0 });+ expect(rich.usdcNeed.map((w) => w.pk)).toEqual(['a', 'b']);+ expect(rich.skipped).toEqual({ sol: 0, usdc: 1 });+ });++ it('shares one SOL budget between top-ups and USDC-leg rent', () => {+ // 12,005,000 lamports exactly funds one SOL top-up; nothing is left for rent.+ const r = trimToFunderCapacity({ solNeed: [solNeed[0]], usdcNeed: [usdcNeed[1]], ataExists: new Set(), funderLamports: 12_005_000, treasuryUsdcAtomic: 9_000_000n, reserveLamports: 0 });+ expect(r.solNeed.map((w) => w.pk)).toEqual(['a']);+ expect(r.usdcNeed).toEqual([]);+ });+});++describe('applyFundingMoves (pure)', () => {+ it('records reads plus this run\'s moves for every wallet, funded or not', () => {+ const pubkeys = ['a', 'b', 'c'];+ const solByPubkey = new Map([['a', 1_000], ['b', 15_000_000], ['c', 0]]);+ const usdcByPubkey = new Map([['a', 0n], ['b', 5_000_000n], ['c', 100n]]);+ const out = applyFundingMoves({+ pubkeys, solByPubkey, usdcByPubkey,+ solFunded: [{ pk: 'a', add: 11_999_000 }],+ usdcFunded: [{ pk: 'a', add: 2_000_000n }],+ usdcSwept: [{ pk: 'b', take: 3_000_000n }],+ });+ expect(out).toEqual([+ { pubkey: 'a', solLamports: 12_000_000, usdcAtomic: 2_000_000n },+ { pubkey: 'b', solLamports: 15_000_000, usdcAtomic: 2_000_000n },+ { pubkey: 'c', solLamports: 0, usdcAtomic: 100n },+ ]);+ // Inputs are not mutated: the funder's read maps stay the on-chain truth.+ expect(solByPubkey.get('a')).toBe(1_000);+ expect(usdcByPubkey.get('b')).toBe(5_000_000n);+ });+});