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): implement payer pool for distinct wallet usage in ring economy
nirholas2c5653d88c91
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4bc6b5f57..b1b593c0e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Avatars you generate now come out truly animation-ready** — We rebuilt the auto-rigging engine that turns a generated 3D character into a living avatar. Rigging now finishes in seconds instead of stalling for 20 minutes, produces a full standard skeleton with fingers that our entire animation library (walk, wave, dance, emotes) can drive immediately, keeps the model's original textures perfectly intact, and adds the 52 facial expression shapes used for emotions and lip-sync. Every piece of the new pipeline is MIT-licensed open source, so it works for everyone, everywhere. (`/forge`) `[feature, improvement, fix]`- **Creator profile pages work again, plus a site-wide reliability sweep** — A full automated sweep of every page and API endpoint on the site caught a bug that replaced creator profile pages (three.ws/u/yourname) with an error message. That is fixed. The sweep also repaired the login captcha for rate-limited sign-ins, fixed dead links in the dashboard and two blog posts, and added two dozen previously unlisted pages to the site index so search engines and the sitemap can find them. The audit now runs with deeper checks (blank-page detection, visible error detection, and link crawling) so regressions like these get caught before anyone hits them. (`/changelog`) `[fix, improvement]`+- **The agent-to-agent payment economy runs far cheaper and now cycles hundreds of distinct payers** — Two improvements to the closed-loop x402 agent economy that dogfoods every paid endpoint on the platform. First, a fix: a background wallet-consolidation job was quietly closing the ring's payment account after every settlement, forcing the next one to recreate it and pay account rent each time. That single bug had pushed the real fee cost to roughly a hundred times where it should be. With it fixed and single-signature settlement turned on, each settlement is back to the network floor of a few thousandths of a cent, and the ring's working balance stays in the loop instead of leaking away. Second, a new capability: the ring can now cycle payments through a reusable pool of hundreds to a thousand distinct wallets instead of one, so the economy reads as many participants rather than a single account, with no extra cost per payment. The pool is off until funded and activated, and every wallet in it stays clearly labeled internal dogfooding, not organic demand. (`/admin/ring`) `[fix, improvement, infra]`- **Your models now look studio-quality everywhere, not just in the Forge** — The viewer page that opens when someone follows a shared model link now renders with the same rich lighting, tone mapping, and exposure as the Forge studio where the model was created, so what you share is what they see. The copy-paste embed snippet ships those same settings, meaning models dropped onto your own site no longer look flat compared to the preview. Avatars in agent embed cards now cast a soft ground shadow instead of floating, and the homepage 3D showcase stops burning your battery when it is scrolled out of view or in a background tab. (`/viewer`) `[improvement]`## 2026-07-16diff --git a/STRUCTURE.md b/STRUCTURE.mdindex de871e271..1a74cb9d3 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -91,6 +91,7 @@ bottom.| Agent Skills pack | [.agents/skills/](.agents/skills) → manifest [.agents/skills/SKILLS.md](.agents/skills/SKILLS.md), [.agents/skills/skills-pack.json](.agents/skills/skills-pack.json) | In-repo; bundled in the `three-ws-core` [plugin](.claude-plugin/marketplace.json) | 40 portable `SKILL.md` folders (Agent Skills open standard) for any Claude surface — 3d/creative (cross-platform-safe), wallet/payments, intel/trading. Regenerate manifest: `node scripts/build-skills-pack.mjs`. Docs: [docs/agent-skills.md](docs/agent-skills.md) || SNS naming + pay-by-name | [api/sns.js](api/sns.js), [api/sns-subdomain.js](api/sns-subdomain.js), [api/threews/subdomain.js](api/threews/subdomain.js), [api/x402/pay-by-name.js](api/x402/pay-by-name.js), [src/solana/sns-subdomain.js](src/solana/sns-subdomain.js), [pages/threews-claim.html](pages/threews-claim.html) | In-repo | `*.threews.sol` subdomain mint, x402 payments addressed by name. Env: `THREEWS_SOL_PARENT_SECRET_BASE58` || Self-hosted x402 facilitator + ring economy | [api/x402-facilitator/[action].js](api/x402-facilitator/[action].js), [api/_lib/x402/self-facilitator.js](api/_lib/x402/self-facilitator.js), [api/x402/ring-settle.js](api/x402/ring-settle.js), [api/_lib/x402/pipelines/ring-rebalance.js](api/_lib/x402/pipelines/ring-rebalance.js), [api/x402-ring.js](api/x402-ring.js), [scripts/x402-ring-setup.mjs](scripts/x402-ring-setup.mjs) | In-repo (off by default) | Closed-loop agent-to-agent x402: platform wallets pay platform endpoints, settled in-house (no external facilitator). Fee-minimized, SOL-floor guarded, internal-labeled. Env: `X402_SELF_FACILITATOR_ENABLED`, `X402_FEE_PAYER_SECRET_BASE58`, `X402_TREASURY_SECRET_BASE58`. See [docs/x402-ring-economy.md](docs/x402-ring-economy.md) |+| Ring payer pool (many distinct payers) | [api/_lib/x402/pool.js](api/_lib/x402/pool.js), [api/_lib/x402/pipelines/ring-pool-fund.js](api/_lib/x402/pipelines/ring-pool-fund.js), [scripts/x402-ring-pool-setup.mjs](scripts/x402-ring-pool-setup.mjs), migration [api/_lib/migrations/2026-07-17-x402-ring-pool.sql](api/_lib/migrations/2026-07-17-x402-ring-pool.sql) | In-repo (off by default) | Reused rotating payer wallets (500–1,000) the ring tick cycles through so the closed loop shows many distinct, attributed payers at 1 tx/settle. Keys secret-box-encrypted in `x402_ring_pool`; pubkeys mirrored into `x402_ring_wallets(role='pool')` so they join the controlled set automatically; NOT in solana-signers.js so sweepback never touches them. LRU rotation (`claimNextPayer`), batched threshold funding (`ring-pool-fund`). Env: `X402_RING_POOL_ENABLED`, `X402_RING_POOL_SIZE`. See [docs/x402-ring-economy.md](docs/x402-ring-economy.md#payer-pool--many-distinct-payers-one-reused-set-of-wallets) || Ring economy operator dashboard | [pages/admin/ring.html](pages/admin/ring.html) + [src/admin-ring.js](src/admin-ring.js) `→ /admin/ring`, backend [api/admin/ring-dashboard.js](api/admin/ring-dashboard.js) | In-repo (admin, noindex) | Live eyes on the closed-loop x402 ring: per-minute settlement pulse (green/amber/red heartbeat), loop diagram with live wallet balances + floors, streaming activity feed (agent attribution, Solscan links, skip/fail reasons), fee-burn vs daily budget, integrity (leak scan + reconciliation), per-endpoint coverage. One aggregate read model composes [/api/x402-ring](api/x402-ring.js); admin/Bearer-secret authed. Labels volume as internal dogfooding. See [docs/x402-ring-economy.md](docs/x402-ring-economy.md#watching-it--the-operator-dashboard) || Economy funding root (master wallet) | [api/_lib/economy-master.js](api/_lib/economy-master.js), cron [api/cron/treasury-topup.js](api/cron/treasury-topup.js), registry [api/_lib/solana-signers.js](api/_lib/solana-signers.js) | In-repo (inert until keyed) | One master wallet (`WwwuGbq…T3WwW`, `ECONOMY_MASTER_SECRET_BASE58`) auto-tops-up every other Solana engine below its floor. Funder-only — never trades/settles; reserve/per-engine/per-run guarded; allowlisted to registry wallets; fee-minimized. See [docs/economy-master.md](docs/economy-master.md) + the signer registry [api/_lib/solana-signers.js](api/_lib/solana-signers.js) || Economy master audit ledger + breach monitor | ledger [api/_lib/economy-ledger.js](api/_lib/economy-ledger.js) ([schema](api/_lib/migrations/20260702010000_economy_master_ledger.sql)), reconcile cron [api/cron/economy-reconcile.js](api/cron/economy-reconcile.js), export [scripts/economy-ledger-export.mjs](scripts/economy-ledger-export.mjs) | In-repo | Tamper-evident (SHA-256 hash-chained) accounting book of every SOL movement from the master, with running balance + USD-at-transfer-time. The reconcile cron checks it every 30 min for tamper, unrecorded on-chain outbound (breach/key-compromise), and on-chain integrity; findings land in `payment_reconciliation`. Accounting CSV/JSON export. See [docs/economy-master.md](docs/economy-master.md#audit-accounting--breach-monitoring) |diff --git a/api/_lib/x402/autonomous-registry.js b/api/_lib/x402/autonomous-registry.jsindex bf5bab49b..87f47bd1b 100644--- a/api/_lib/x402/autonomous-registry.js+++ b/api/_lib/x402/autonomous-registry.js@@ -46,6 +46,7 @@ import { run as sniperIntelEnrich } from './pipelines/sniper-intel-enrich.js';import { run as volumeBootstrapLoop } from './pipelines/volume-bootstrap-loop.js';import { run as datapointVolumeSweep } from './pipelines/datapoint-volume-sweep.js';import { run as ringRebalance, floatTopUp as ringFloatTopUp } from './pipelines/ring-rebalance.js';+import { run as ringPoolFund } from './pipelines/ring-pool-fund.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';@@ -2772,6 +2773,27 @@ const SELF_ENDPOINTS = [run: (ctx) => ringFloatTopUp(ctx),},+ // ── Ring Payer-Pool Funding ─────────────────────────────────────────────────+ // Threshold top-up for the reused payer POOL (api/_lib/x402/pool.js): batched+ // SOL from the sponsor/master and USDC from the treasury keep every rotating+ // wallet above its floor, and overfull wallets are swept back to the treasury.+ // No-op until X402_RING_POOL_ENABLED=true and the pool is provisioned. Balances+ // are read in batches (getMultipleAccountsInfo) and top-ups batched into few+ // transactions, so funding 500-1,000 wallets is a handful of tx per run.+ // Recirculation, not spend — returns amountAtomic:0, never consumes the cap.+ {+ id: 'ring-pool-fund',+ name: 'Ring Payer-Pool Funding',+ path: '/api/x402/ring-settle',+ method: 'POST',+ body: null,+ cooldown_s: 120,+ priority: 22,+ pipeline: 'agents',+ enabled: true,+ run: (ctx) => ringPoolFund(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/pipelines/ring-pool-fund.js b/api/_lib/x402/pipelines/ring-pool-fund.jsnew file mode 100644index 000000000..9295c9677--- /dev/null+++ b/api/_lib/x402/pipelines/ring-pool-fund.js@@ -0,0 +1,272 @@+// api/_lib/x402/pipelines/ring-pool-fund.js+//+// Keeps the ring payer POOL (api/_lib/x402/pool.js) topped up so every rotating+// wallet can settle: a little SOL for its own 1-signature self-pay fee, and a+// small recirculating USDC float. This is the threshold-based "top up when low"+// funder the pool needs — the economy master's treasury-topup only funds+// solana-signers.js entries, and pool wallets are deliberately NOT signers.+//+// Efficiency: balances are read in BATCHES (getMultipleAccountsInfo, ≤100/call)+// and top-ups are BATCHED into few transactions (many SystemProgram transfers per+// SOL tx; several USDC transfers per USDC tx), so funding 500–1,000 wallets costs a+// handful of transactions per run, not one per wallet. Bounded by+// X402_RING_POOL_FUND_MAX_PER_RUN so a single run can never fan out unboundedly.+//+// Closed-loop invariants:+// • SOL comes from the sponsor/master fee wallet (X402_FEE_PAYER_SECRET_BASE58);+// USDC comes from the treasury (X402_TREASURY_SECRET_BASE58). Both are inside+// ringAllowedAddresses(); every recipient is a pool wallet, also inside the set.+// • Recirculation, not spend: returns amountAtomic:0, never consumes the daily+// cap. Overfull wallets are swept back to the treasury to keep the float flat.+// • Every move is recorded in x402_ring_ledger as kind='fund'.++import bs58 from 'bs58';+import {+ PublicKey, Keypair, SystemProgram, TransactionMessage, VersionedTransaction, ComputeBudgetProgram,+} from '@solana/web3.js';+import {+ getAssociatedTokenAddressSync, getMint,+ createTransferCheckedInstruction, createAssociatedTokenAccountIdempotentInstruction,+ TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID,+} from '@solana/spl-token';++import { sql as defaultSql } from '../../db.js';+import { env } from '../../env.js';+import { logger } from '../../usage.js';+import { solanaConnection } from '../../solana/connection.js';+import { USDC_MINT } from '../pay.js';+import { ringPoolEnabled, listEnabledPubkeys, recoverPoolKeypair, poolCount } from '../pool.js';+import { ringAllowedAddresses } from '../ring-allowlist.js';++const log = logger('x402-ring-pool-fund');++// ── Tunable floors/targets (lamports for SOL, USDC atomics for USDC) ──────────+const num = (v, d) => { const n = Number(v); return Number.isFinite(n) && n >= 0 ? n : d; };+export function poolSolFloorLamports() { return num(process.env.X402_RING_POOL_SOL_FLOOR_LAMPORTS, 8_000_000); } // 0.008 SOL+export function poolSolTargetLamports() { return num(process.env.X402_RING_POOL_SOL_TARGET_LAMPORTS, 12_000_000); } // 0.012 SOL+export function poolUsdcFloorAtomic() { return num(process.env.X402_RING_POOL_USDC_FLOOR_ATOMIC, 500_000); } // $0.50+export function poolUsdcTargetAtomic() { return num(process.env.X402_RING_POOL_USDC_TARGET_ATOMIC, 2_000_000); } // $2.00+export function poolUsdcCeilingAtomic() { return num(process.env.X402_RING_POOL_USDC_CEIL_ATOMIC, 4_000_000); } // $4.00+export function poolFundMaxPerRun() { return Math.max(1, num(process.env.X402_RING_POOL_FUND_MAX_PER_RUN, 60)); }++const SOL_TRANSFERS_PER_TX = 14; // System transfers batched per funding tx+const USDC_TRANSFERS_PER_TX = 6; // (idempotent-create + transferChecked) pairs per tx+const ACCOUNTS_PER_READ = 100; // getMultipleAccountsInfo hard limit++function loadKp(secret) {+ const s = String(secret || '').trim();+ if (!s) throw new Error('empty secret');+ try { const b = bs58.decode(s); if (b.length === 64) return Keypair.fromSecretKey(b); } catch { /* try base64 */ }+ const b = Buffer.from(s, 'base64');+ if (b.length === 64) return Keypair.fromSecretKey(Uint8Array.from(b));+ throw new Error(`secret decodes to ${b.length} bytes, expected 64`);+}++async function confirmSignature(conn, signature, timeoutMs = 30_000) {+ const deadline = Date.now() + timeoutMs;+ while (Date.now() < deadline) {+ const st = await conn.getSignatureStatuses([signature]).catch(() => null);+ const v = st?.value?.[0];+ if (v?.err) return { confirmed: false, err: JSON.stringify(v.err) };+ if (v && (v.confirmationStatus === 'confirmed' || v.confirmationStatus === 'finalized')) return { confirmed: true };+ await new Promise((r) => setTimeout(r, 1500));+ }+ return { confirmed: false, err: 'timeout' };+}++// SPL token account layout: `amount` is a little-endian u64 at byte offset 64.+export function tokenAmountFromAccountData(data) {+ if (!data || data.length < 72) return 0n;+ return data.readBigUInt64LE(64);+}++/**+ * PURE — decide the funding work for a pass. Given each wallet's SOL (lamports) and+ * USDC (atomic) balances plus the floors/targets, return the wallets that need SOL,+ * need USDC, or are overfull (sweep back), each capped at `maxPerRun`. No I/O, no+ * signing — unit-tested independently of the chain.+ *+ * @returns {{ solNeed:Array<{pk,add}>, usdcNeed:Array<{pk,add:bigint}>, usdcSweep:Array<{pk,take:bigint}> }}+ */+export function planPoolFunding({ pubkeys, solByPubkey, usdcByPubkey, allowed, floors }) {+ const { solFloor, solTarget, usdcFloor, usdcTarget, usdcCeil, maxPerRun } = floors;+ const solNeed = [];+ const usdcNeed = [];+ const usdcSweep = [];+ for (const pk of pubkeys) {+ if (allowed && !allowed.has(pk)) continue; // defence-in-depth: only fund controlled wallets+ const sol = Number(solByPubkey.get(pk) ?? 0);+ if (sol < solFloor) solNeed.push({ pk, add: solTarget - sol });+ const usdc = BigInt(usdcByPubkey.get(pk) ?? 0n);+ if (usdc < BigInt(usdcFloor)) usdcNeed.push({ pk, add: BigInt(usdcTarget) - usdc });+ else if (usdc > BigInt(usdcCeil)) usdcSweep.push({ pk, take: usdc - BigInt(usdcTarget) });+ }+ solNeed.splice(maxPerRun);+ usdcNeed.splice(maxPerRun);+ usdcSweep.splice(maxPerRun);+ return { solNeed, usdcNeed, usdcSweep };+}++async function readBalances(conn, pubkeys, mint) {+ const solByPubkey = new Map();+ const usdcByPubkey = new Map();+ const ataByPubkey = new Map();+ for (const pk of pubkeys) {+ ataByPubkey.set(pk, getAssociatedTokenAddressSync(mint, new PublicKey(pk), false, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID));+ }+ // SOL: read the wallet accounts themselves.+ for (let i = 0; i < pubkeys.length; i += ACCOUNTS_PER_READ) {+ const chunk = pubkeys.slice(i, i + ACCOUNTS_PER_READ);+ const infos = await conn.getMultipleAccountsInfo(chunk.map((p) => new PublicKey(p)), 'confirmed');+ chunk.forEach((pk, j) => solByPubkey.set(pk, infos[j] ? infos[j].lamports : 0));+ }+ // USDC: read each wallet's ATA (absent ATA → 0 balance, top-up creates it).+ const ataList = pubkeys.map((pk) => ({ pk, ata: ataByPubkey.get(pk) }));+ 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));+ }+ return { solByPubkey, usdcByPubkey, ataByPubkey };+}++async function sendIxs(conn, feePayer, signers, instructions) {+ const { blockhash } = await conn.getLatestBlockhash('confirmed');+ const msg = new TransactionMessage({ payerKey: feePayer.publicKey, recentBlockhash: blockhash, instructions }).compileToV0Message();+ const vtx = new VersionedTransaction(msg);+ vtx.sign(signers);+ const signature = await conn.sendRawTransaction(vtx.serialize(), { skipPreflight: false, maxRetries: 5 });+ const conf = await confirmSignature(conn, signature);+ if (!conf.confirmed) return { ok: false, signature, err: conf.err };+ return { ok: true, signature };+}++/**+ * Run one pool-funding pass. Conforms to the run()-style registry contract.+ * @param {{ sql?:Function, conn?:object, runId?:string }} ctx+ */+export async function run(ctx = {}) {+ const sql = ctx.sql || defaultSql;+ const runId = ctx.runId || null;++ if (!ringPoolEnabled()) return { success: true, skipped: true, amountAtomic: 0, note: 'pool_disabled' };+ if (!USDC_MINT) return { success: true, skipped: true, amountAtomic: 0, note: 'usdc_mint_unset' };++ const treasurySecret = process.env.X402_TREASURY_SECRET_BASE58;+ const solFunderSecret = process.env.X402_FEE_PAYER_SECRET_BASE58 || treasurySecret;+ if (!treasurySecret) return { success: true, skipped: true, amountAtomic: 0, note: 'treasury_secret_unset' };+ if (!solFunderSecret) return { success: true, skipped: true, amountAtomic: 0, note: 'sol_funder_secret_unset' };++ let treasury, solFunder;+ try { treasury = loadKp(treasurySecret); solFunder = loadKp(solFunderSecret); }+ catch (err) { return { success: false, amountAtomic: 0, errorMsg: `bad_funder_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' };+ }++ const total = await poolCount(sql);+ if (total === 0) return { success: true, skipped: true, amountAtomic: 0, note: 'pool_empty' };++ const allowed = await ringAllowedAddresses({ sql });+ // Fail closed: both funders must be inside the controlled set.+ if (!allowed.has(treasury.publicKey.toBase58()) || !allowed.has(solFunder.publicKey.toBase58())) {+ return { success: false, amountAtomic: 0, errorMsg: 'funder_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 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 { solNeed, usdcNeed, usdcSweep } = planPoolFunding({+ pubkeys, solByPubkey, usdcByPubkey, allowed,+ floors: {+ solFloor: poolSolFloorLamports(), solTarget: poolSolTargetLamports(),+ usdcFloor: poolUsdcFloorAtomic(), usdcTarget: poolUsdcTargetAtomic(),+ usdcCeil: poolUsdcCeilingAtomic(), maxPerRun: poolFundMaxPerRun(),+ },+ });++ const moves = { sol_funded: 0, usdc_funded: 0, usdc_swept: 0, sigs: [] };+ const ledgerRows = [];++ // ── SOL top-ups (batched System transfers, funded by the sponsor/master) ──────+ for (let i = 0; i < solNeed.length; i += SOL_TRANSFERS_PER_TX) {+ const chunk = solNeed.slice(i, i + SOL_TRANSFERS_PER_TX);+ const ixs = [ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 5 })];+ for (const w of chunk) {+ ixs.push(SystemProgram.transfer({ fromPubkey: solFunder.publicKey, toPubkey: new PublicKey(w.pk), lamports: Math.floor(w.add) }));+ }+ const res = await sendIxs(conn, solFunder, [solFunder], ixs);+ if (res.ok) {+ moves.sol_funded += chunk.length; moves.sigs.push(res.signature);+ 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 });+ }+ }++ // ── USDC top-ups: USDC moves treasury→wallet, but ALL SOL (each pool wallet's+ // new-ATA rent + the tx fee) is paid by the sponsor/master fee wallet, so an+ // operator funds SOL in exactly ONE place. The treasury only signs as the token+ // transfer authority; the sponsor is fee payer + ATA-create funder.+ const solFunderIsTreasury = solFunder.publicKey.equals(treasury.publicKey);+ for (let i = 0; i < usdcNeed.length; i += USDC_TRANSFERS_PER_TX) {+ const chunk = usdcNeed.slice(i, i + USDC_TRANSFERS_PER_TX);+ const ixs = [ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 5 })];+ for (const w of chunk) {+ const ata = ataByPubkey.get(w.pk);+ ixs.push(createAssociatedTokenAccountIdempotentInstruction(solFunder.publicKey, ata, new PublicKey(w.pk), mint, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID));+ ixs.push(createTransferCheckedInstruction(treasuryAta, mint, ata, treasury.publicKey, BigInt(w.add), mintInfo.decimals, [], TOKEN_PROGRAM_ID));+ }+ const signers = solFunderIsTreasury ? [treasury] : [solFunder, treasury];+ const res = await sendIxs(conn, solFunder, signers, ixs);+ if (res.ok) {+ moves.usdc_funded += chunk.length; moves.sigs.push(res.signature);+ 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 });+ }+ }++ // ── Overfull sweeps (pool wallet → treasury). The sponsor pays the SOL fee, so a+ // pool wallet never needs SOL beyond its own settle fees; the pool wallet signs+ // only as the token transfer authority.+ for (const w of usdcSweep) {+ const kp = await recoverPoolKeypair(w.pk, sql);+ if (!kp) { log.warn('pool_sweep_key_unavailable', { pubkey: w.pk }); continue; }+ const fromAta = ataByPubkey.get(w.pk);+ const ixs = [+ ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 5 }),+ createAssociatedTokenAccountIdempotentInstruction(solFunder.publicKey, treasuryAta, treasury.publicKey, mint, TOKEN_PROGRAM_ID, ASSOCIATED_TOKEN_PROGRAM_ID),+ createTransferCheckedInstruction(fromAta, mint, treasuryAta, kp.publicKey, w.take, mintInfo.decimals, [], TOKEN_PROGRAM_ID),+ ];+ const signers = solFunder.publicKey.equals(kp.publicKey) ? [kp] : [solFunder, kp];+ const res = await sendIxs(conn, solFunder, signers, ixs);+ if (res.ok) {+ moves.usdc_swept += 1; moves.sigs.push(res.signature);+ 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 });+ }+ }++ // Record every move to x402_ring_ledger as kind='fund' (recirculation).+ for (const r of ledgerRows) {+ try {+ await sql`INSERT INTO x402_ring_ledger (kind, from_wallet, to_wallet, mint, amount_atomic, tx_sig, run_id)+ VALUES ('fund', ${r.from}, ${r.to}, ${USDC_MINT}, ${r.amount}, ${r.sig}, ${runId})`;+ } catch (err) { log.warn('pool_fund_ledger_write_failed', { message: err?.message }); }+ }++ log.info('ring_pool_funded', { total, ...moves, sigs: moves.sigs.length });+ 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 },+ };+}diff --git a/api/_lib/x402/pipelines/volume-shared.js b/api/_lib/x402/pipelines/volume-shared.jsindex 9bd8753d3..71943a926 100644--- a/api/_lib/x402/pipelines/volume-shared.js+++ b/api/_lib/x402/pipelines/volume-shared.js@@ -219,13 +219,23 @@ export async function settleAndRecord({const endpointUrl = `${origin}${ep.path}`;const t0 = Date.now();+ // Per-call payer rotation: when the caller supplies ctx.buyerFor (the ring tick+ // does this once the payer pool is enabled), each settle draws a DISTINCT pool+ // wallet on a least-recently-used rotation. Falls back to the shared ctx.buyer+ // whenever the resolver returns nothing, so the ring never stalls on an empty or+ // briefly-unavailable pool. The resolver is async and its throw is non-fatal.+ let buyer = ctx.buyer;+ if (typeof ctx.buyerFor === 'function') {+ try { buyer = (await ctx.buyerFor(ep)) || ctx.buyer; } catch { buyer = ctx.buyer; }+ }+let result;try {result = await payFn({url: endpointUrl,method: ep.method || 'POST',body: ep.body,- buyer: ctx.buyer,+ buyer,conn: ctx.conn,blockhash: ctx.blockhash,mintInfo: ctx.mintInfo,@@ -258,6 +268,10 @@ export async function settleAndRecord({endpoint_key: ep.key,paid: result.paid === true,amount_atomic: paidAmount,+ // The wallet that actually paid this call — the rotating pool wallet when+ // ctx.buyerFor is active, else the shared buyer. Gives the dashboard true+ // per-call payer attribution across the whole pool.+ payer_address: (() => { try { return buyer?.publicKey?.toBase58?.() || null; } catch { return null; } })(),liveness: summarizeResponse(result.responseBody),...(metric ? {cumulative_calls: Number(metric.call_count),diff --git a/api/_lib/x402/pool.js b/api/_lib/x402/pool.jsnew file mode 100644index 000000000..17f04a09e--- /dev/null+++ b/api/_lib/x402/pool.js@@ -0,0 +1,176 @@+// x402 ring payer-wallet POOL — a reused set of custodial payer wallets the ring+// tick rotates through so the closed-loop economy presents many distinct,+// attributed payers instead of one seed wallet, at NO extra per-settle cost.+//+// Design (see docs/x402-ring-economy.md "Payer pool"):+// • REUSED, not throwaway. A fresh wallet per call would add a funding hop plus+// ~0.00204 SOL of USDC-ATA rent EVERY settle and still cluster on-chain to the+// one float that funds them. A reused pool pays that rent once per wallet, keeps+// the settle on the 1-signature self-pay hot path, and rotates least-recently-+// used-first so a few hundred wallets yield unlimited distinct-payer sequences.+// • Membership is automatic. generatePoolWallets() mirrors every pubkey into+// x402_ring_wallets(role='pool'), so ringAllowedAddresses() (the controlled+// set), the on-chain leak scanner (classifies them INTERNAL), and the+// facilitator allowlist all pick them up with no extra wiring.+// • Sweepback-safe by construction. Pool wallets are NOT in solana-signers.js, so+// the excess-mode treasury-sweepback never enumerates them — the exact bug that+// was closing the treasury's USDC ATA and churning ~2.04M lamports of rent per+// settle cannot recur across 1,000 pool wallets.+// • 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.++import { Keypair } from '@solana/web3.js';+import { encryptSecret, decryptSecret } from '../secret-box.js';+import { sql as defaultSql } from '../db.js';+import { logger } from '../usage.js';++const log = logger('x402-ring-pool');++/** 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';+}++/** Target pool size (number of reused payer wallets). 0 disables growth. */+export function ringPoolTargetSize() {+ const n = Number(process.env.X402_RING_POOL_SIZE || 0);+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : 0;+}++/**+ * Hard cap on how many wallets a single generate call will mint — a runaway-loop+ * backstop far above any real target. Env-tunable for an unusually large pool.+ */+export function ringPoolMaxGenerate() {+ const n = Number(process.env.X402_RING_POOL_MAX_GENERATE || 2000);+ return Number.isFinite(n) && n > 0 ? Math.floor(n) : 2000;+}++let _schemaReady = false;+/** Idempotent DDL guard (mirrors the migration; keeps standalone runs self-sufficient). */+export async function ensurePoolSchema(sql = defaultSql) {+ if (_schemaReady) return;+ await sql`+ CREATE TABLE IF NOT EXISTS x402_ring_pool (+ pubkey text PRIMARY KEY,+ encrypted_secret text NOT NULL,+ enabled boolean NOT NULL DEFAULT true,+ last_used_at timestamptz,+ use_count bigint NOT NULL DEFAULT 0,+ created_at timestamptz NOT NULL DEFAULT now()+ )`;+ await sql`CREATE INDEX IF NOT EXISTS x402_ring_pool_rotation+ ON x402_ring_pool (enabled, last_used_at NULLS FIRST, pubkey)`;+ _schemaReady = true;+}++/** Count of enabled pool wallets. */+export async function poolCount(sql = defaultSql) {+ await ensurePoolSchema(sql);+ const rows = await sql`SELECT count(*)::int AS n FROM x402_ring_pool WHERE enabled = true`;+ return rows[0]?.n ?? 0;+}++/** All enabled pool pubkeys (for the funding pipeline's batched balance reads). */+export async function listEnabledPubkeys(sql = defaultSql) {+ await ensurePoolSchema(sql);+ const rows = await sql`SELECT pubkey FROM x402_ring_pool WHERE enabled = true ORDER BY pubkey`;+ return rows.map((r) => r.pubkey);+}++/** Recover a single pool keypair by pubkey (used by the funding pipeline to sweep an overfull wallet). */+export async function recoverPoolKeypair(pubkey, sql = defaultSql) {+ await ensurePoolSchema(sql);+ const rows = await sql`SELECT encrypted_secret FROM x402_ring_pool WHERE pubkey = ${pubkey} AND enabled = true LIMIT 1`;+ if (!rows[0]?.encrypted_secret) return null;+ return decodeKeypair(await decryptSecret(rows[0].encrypted_secret));+}++// Decode a base64-encoded 64-byte secret key into a Keypair.+function decodeKeypair(secretB64) {+ const raw = Buffer.from(secretB64, 'base64');+ if (raw.length !== 64) throw new Error(`pool key decode: expected 64 bytes, got ${raw.length}`);+ return Keypair.fromSecretKey(Uint8Array.from(raw));+}++/**+ * Generate `count` NEW pool wallets, encrypt each secret at rest, insert them into+ * x402_ring_pool, and mirror each pubkey into x402_ring_wallets(role='pool') so it+ * joins the controlled set immediately. Idempotent per pubkey (fresh keypairs never+ * collide, but the upsert is ON CONFLICT-safe). Returns the created pubkeys.+ *+ * @param {{ count:number, sql?:Function }} args+ */+export async function generatePoolWallets({ count, sql = defaultSql } = {}) {+ const n = Math.max(0, Math.min(Math.floor(Number(count) || 0), ringPoolMaxGenerate()));+ if (n === 0) return { created: [], total: await poolCount(sql) };+ await ensurePoolSchema(sql);++ const created = [];+ for (let i = 0; i < n; i++) {+ const kp = Keypair.generate();+ const pubkey = kp.publicKey.toBase58();+ const encrypted = await encryptSecret(Buffer.from(kp.secretKey).toString('base64'));+ // Insert the pool row and register membership in ONE round-trip pair. Both are+ // ON CONFLICT DO NOTHING so a re-run never duplicates or overwrites a wallet.+ await sql`+ INSERT INTO x402_ring_pool (pubkey, encrypted_secret)+ VALUES (${pubkey}, ${encrypted})+ ON CONFLICT (pubkey) DO NOTHING`;+ await sql`+ INSERT INTO x402_ring_wallets (pubkey, label, role, enabled, note)+ VALUES (${pubkey}, ${'ring-pool'}, ${'pool'}, ${true},+ ${'reused rotating ring payer (x402_ring_pool)'})+ ON CONFLICT (pubkey) DO UPDATE SET role = 'pool', enabled = true`;+ created.push(pubkey);+ }+ const total = await poolCount(sql);+ log.info('ring_pool_generated', { created: created.length, total });+ return { created, total };+}++/**+ * Grow the pool up to `target` (default X402_RING_POOL_SIZE), minting only the+ * shortfall. Safe to call every provisioning run — it never shrinks or re-keys.+ */+export async function growPoolToTarget({ target, sql = defaultSql } = {}) {+ const want = Number.isFinite(target) && target > 0 ? Math.floor(target) : ringPoolTargetSize();+ if (want <= 0) return { created: [], total: await poolCount(sql), target: 0 };+ const current = await poolCount(sql);+ const shortfall = Math.max(0, want - current);+ if (shortfall === 0) return { created: [], total: current, target: want };+ const { created, total } = await generatePoolWallets({ count: shortfall, sql });+ return { created, total, target: want };+}++/**+ * 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.+ *+ * @returns {Promise<{ keypair: Keypair, pubkey: string } | null>}+ */+export async function claimNextPayer(sql = defaultSql) {+ await ensurePoolSchema(sql);+ const rows = await sql`+ UPDATE x402_ring_pool+ SET last_used_at = now(), use_count = use_count + 1+ WHERE pubkey = (+ SELECT pubkey FROM x402_ring_pool+ WHERE enabled = true+ ORDER BY last_used_at NULLS FIRST, pubkey+ LIMIT 1+ FOR UPDATE SKIP LOCKED+ )+ RETURNING pubkey, encrypted_secret`;+ if (!rows[0]) return null;+ try {+ const keypair = decodeKeypair(await decryptSecret(rows[0].encrypted_secret));+ return { keypair, pubkey: rows[0].pubkey };+ } catch (err) {+ log.warn('ring_pool_claim_decrypt_failed', { pubkey: rows[0].pubkey, message: err?.message });+ return null;+ }+}diff --git a/api/cron/x402-ring-tick.js b/api/cron/x402-ring-tick.jsindex 506a04628..a698ed94b 100644--- a/api/cron/x402-ring-tick.js+++ b/api/cron/x402-ring-tick.js@@ -52,6 +52,7 @@ 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 { ringPoolEnabled, claimNextPayer } from '../_lib/x402/pool.js';import { validateRingConfig } from '../_lib/x402/ring-config.js';import { assertRingSpendInvariants } from '../_lib/x402/ring-allowlist.js';import {@@ -321,7 +322,18 @@ export default wrapCron(async (req, res) => {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 };+ // Payer pool: when enabled, each settle draws a DISTINCT least-recently-used+ // pool wallet (self-pays its own 1-sig fee, so no shared fee wallet). The seed+ // payer stays the fallback whenever the pool is empty/unavailable, so the ring+ // never stalls. Pool wallets are inside ringAllowedAddresses(), so the onAccept+ // allowlist gate and the leak scanner classify them internal.+ const usePool = ringPoolEnabled();+ const payCtx = {+ buyer: payer, conn, blockhash, mintInfo,+ ...(usePool+ ? { buyerFor: async () => { const c = await claimNextPayer(sql).catch(() => null); return c?.keypair || payer; } }+ : {}),+ };const results = [];let paid = 0, calls = 0, errors = 0, spent = 0, lastTxSig = null;let floorHit = false;diff --git a/data/changelog.json b/data/changelog.jsonindex 7e7b7129e..b1206868f 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,17 @@{"$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-17",+ "title": "The agent-to-agent payment economy runs far cheaper and now cycles hundreds of distinct payers",+ "summary": "Two improvements to the closed-loop x402 agent economy that dogfoods every paid endpoint on the platform. First, a fix: a background wallet-consolidation job was quietly closing the ring's payment account after every settlement, forcing the next one to recreate it and pay account rent each time. That single bug had pushed the real fee cost to roughly a hundred times where it should be. With it fixed and single-signature settlement turned on, each settlement is back to the network floor of a few thousandths of a cent, and the ring's working balance stays in the loop instead of leaking away. Second, a new capability: the ring can now cycle payments through a reusable pool of hundreds to a thousand distinct wallets instead of one, so the economy reads as many participants rather than a single account, with no extra cost per payment. The pool is off until funded and activated, and every wallet in it stays clearly labeled internal dogfooding, not organic demand.",+ "tags": [+ "fix",+ "improvement",+ "infra"+ ],+ "link": "/admin/ring"+ },{"date": "2026-07-16","title": "Forge now waits out long full-quality generations and shows queue state",diff --git a/docs/ops/gcp-credits-plan.md b/docs/ops/gcp-credits-plan.mdindex c74db681f..587d98747 100644--- a/docs/ops/gcp-credits-plan.md+++ b/docs/ops/gcp-credits-plan.md@@ -28,17 +28,21 @@ Four warm instances against a quota of 3 means the fleet is permanently at its c### The escape hatch that is ALREADY GRANTED: RTX PRO 6000-`NvidiaRtxPro6000GpuAllocNoZonalRedundancyPerProjectRegion` is granted at-**1000** for us-central1 (preference `rtx-pro-6000-uscentral1-3dpbr`). Cloud-Run deploys with `--gpu-type=nvidia-rtx-pro-6000` there today (validated-2026-07-17 with a live probe service); platform minimums for the type are-**20 CPU / 80 Gi memory** per instance. Blackwell is compute capability 12.0,-so images built for the L4 (cu121/cu124 stacks) do NOT run on it; a worker-needs a CUDA 12.8 + torch 2.7 (cu128) rebuild. First mover:-`workers/model-hunyuan3d/Dockerfile.hunyuan21rtx` (service-`model-hunyuan3d-21-rtx`, warm min 1 / max 4). When an L4 lane needs headroom-before the L4 grant lands, port it the same way rather than parking work on-the quota.+The preference `rtx-pro-6000-uscentral1-3dpbr` shows+`NvidiaRtxPro6000GpuAllocNoZonalRedundancyPerProjectRegion` granted at+**1000** for us-central1, BUT live deploy enforcement allows **1** RTX GPU+(2026-07-17, deploy error: "requested: 4 allowed: 1"); treat the preference+number as aspirational until a multi-instance deploy succeeds. Cloud Run does+deploy with `--gpu-type=nvidia-rtx-pro-6000` there today (validated live);+platform minimums for the type are **20 CPU / 80 Gi memory** per instance.+Blackwell is compute capability 12.0, so images built for the L4 (cu121/cu124+stacks) do NOT run on it; a worker needs a CUDA 12.8 + torch 2.7 (cu128)+rebuild. First mover: `workers/model-hunyuan3d/Dockerfile.hunyuan21rtx`+(service `model-hunyuan3d-21-rtx`, warm min 1 / max 1). One warm RTX PRO 6000+(96 GB VRAM) still beats what the whole L4 pool could give the 2.1 PBR lane:+the L4 build cannot even load (see the fleet table). When an L4 lane needs+headroom before the L4 grant lands, port it the same way rather than parking+work on the quota.- **When granted ≥ 8, execute immediately (no owner input needed):**```shgcloud run services update model-trellis --region us-central1 --max-instances=3diff --git a/docs/x402-ring-economy.md b/docs/x402-ring-economy.mdindex 1a7251f6e..bd539d2bd 100644--- a/docs/x402-ring-economy.md+++ b/docs/x402-ring-economy.md@@ -457,6 +457,91 @@ daily volume is an env change (`X402_PRICE_RING_SETTLE`,— in July 2026 a defaults-only lift to $35/settle put every tick intoback-pressure and flat-lined the visible ring economy for hours.+## Payer pool — many distinct payers, one reused set of wallets++By default the ring pays from a single seed wallet. The **payer pool** lets it pay+from hundreds-to-thousands of distinct, attributed wallets **at no extra per-settle+cost**, so the economy reads as many participants instead of one cron. It is+[api/_lib/x402/pool.js](../api/_lib/x402/pool.js) + the+[ring-pool-fund](../api/_lib/x402/pipelines/ring-pool-fund.js) pipeline, off by+default (`X402_RING_POOL_ENABLED`).++**Reused, not throwaway — the efficiency call.** A fresh wallet per call would add+a funding hop **and** a one-time USDC-ATA rent (~0.00204 SOL ≈ $0.15) on *every*+settle, roughly tripling the per-settle cost, and the wallets would still cluster+on-chain in one hop (they are all funded from the same float, the textbook cluster+signature). A **reused pool** pays that rent once per wallet, keeps each settle on+the 1-signature self-pay hot path (**1 tx/settle**, same as the single payer), and+rotates least-recently-used-first so a few hundred wallets produce effectively+unlimited distinct-payer sequences. 1,000 reused wallets rotating at the stock+cadence means each pays only a few times a day — genuinely distinct — for ~$150 of+one-time, reclaimable ATA rent.++**How it wires in.**++- **Storage.** Each wallet's key is secret-box-encrypted at rest (same scheme as+ custodial agent wallets, `WALLET_ENCRYPTION_KEY`) in `x402_ring_pool`. A+ 500–1,000-wallet pool can't live in env vars, so the three role wallets stay in+ env and the pool lives in the DB.+- **Membership is automatic.** The generator mirrors every pool pubkey into+ `x402_ring_wallets(role='pool')`, so `ringAllowedAddresses()` (the controlled+ set), the on-chain leak scanner (classifies them **internal**), and the+ facilitator allowlist all pick them up with no extra wiring. Pool wallets stay+ labeled internal — they are dogfooding payers, never presented as organic demand.+- **Sweepback-safe by construction.** Pool wallets are deliberately **not** in+ [api/_lib/solana-signers.js](../api/_lib/solana-signers.js), so the excess-mode+ `treasury-sweepback` never enumerates them. This is the same class of bug that+ used to close the treasury's USDC ATA every run (see the box below) — it cannot+ recur 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.+- **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+ floor up to a target, sweeping overfull wallets back. Funding 500–1,000 wallets is+ 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'`.++**Turning it on.**++```bash+# 1. Mint the pool (encrypts + stores keys, registers membership — no funding).+node scripts/x402-ring-pool-setup.mjs --grow --size=750++# 2. See exactly what to fund.+node scripts/x402-ring-pool-setup.mjs --funding-plan --size=750++# 3. Enable rotation + set the size on the service (config-only, pre-approved).+gcloud run services update three-ws-api --region us-central1 \+ --update-env-vars X402_RING_POOL_ENABLED=true,X402_RING_POOL_SIZE=750+```++**Env knobs:** `X402_RING_POOL_ENABLED` (off by default), `X402_RING_POOL_SIZE`+(target), `X402_RING_POOL_SOL_FLOOR_LAMPORTS` / `_TARGET_LAMPORTS` (default+0.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).++> ### Fixed 2026-07-17 — the treasury-sweepback rent churn+>+> The ring treasury (`wwwww…ccrU`, `X402_PAY_TO_SOLANA`) is the **same physical+> wallet** as the `pump-x402-launcher` signer (`PUMP_X402_LAUNCHER_SECRET_KEY_B64`+> → secret `wallet-x402-treasury-b64`). That registry entry lacked `holdsTokens`,+> so the excess-mode `treasury-sweepback` consolidated the treasury's USDC up to+> the economy master **and closed its USDC ATA every run**. Every following ring+> settle then had to recreate the ATA at **2,039,280 lamports** of rent — which+> dragged the measured per-settle fee to ~570,000 lamports (114× the 5,000-lamport+> self-pay floor) and quietly drained the closed loop's float into the master (why+> `sweeps=0` on the rebalancer: the treasury was emptied before it could+> recirculate). The fix is one line — `holdsTokens: true` on that registry entry —+> so excess-mode sweepback never touches the ring float again; only an explicit+> drain still consolidates it. Pair it with `X402_RING_SELF_PAY=true` (1 signature,+> not 2) and the per-settle fee returns to the ~5,000-lamport floor.+## Agents in the ring — buyers with names, not a cronThe cadence above keeps volume flowing, but volume alone still reads as "a crondiff --git a/public/changelog.json b/public/changelog.jsonindex 784d051ad..37750cdbb 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-17T06:48:03.813Z",+ "generated_at": "2026-07-17T06:55:51.169Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -29,6 +29,18 @@"improvement"]},+ {+ "date": "2026-07-17",+ "type": "update",+ "title": "The agent-to-agent payment economy runs far cheaper and now cycles hundreds of distinct payers",+ "summary": "Two improvements to the closed-loop x402 agent economy that dogfoods every paid endpoint on the platform. First, a fix: a background wallet-consolidation job was quietly closing the ring's payment account after every settlement, forcing the next one to recreate it and pay account rent each time. That single bug had pushed the real fee cost to roughly a hundred times where it should be. With it fixed and single-signature settlement turned on, each settlement is back to the network floor of a few thousandths of a cent, and the ring's working balance stays in the loop instead of leaking away. Second, a new capability: the ring can now cycle payments through a reusable pool of hundreds to a thousand distinct wallets instead of one, so the economy reads as many participants rather than a single account, with no extra cost per payment. The pool is off until funded and activated, and every wallet in it stays clearly labeled internal dogfooding, not organic demand.",+ "link": "/admin/ring",+ "tags": [+ "fix",+ "improvement",+ "infra"+ ]+ },{"date": "2026-07-17","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex aa06af4d4..7e2779e5b 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -22,6 +22,14 @@<category>fix</category><description>A full automated sweep of every page and API endpoint on the site caught a bug that replaced creator profile pages (three.ws/u/yourname) with an error message. That is fixed. The sweep also repaired the login captcha for rate-limited sign-ins, fixed dead links in the dashboard and two blog posts, and added two dozen previously unlisted pages to the site index so search engines and the sitemap can find them. The audit now runs with deeper checks (blank-page detection, visible error detection, and link crawling) so regressions like these get caught before anyone hits them.</description></item>+ <item>+ <title>The agent-to-agent payment economy runs far cheaper and now cycles hundreds of distinct payers</title>+ <link>https://three.ws/admin/ring</link>+ <guid isPermaLink="false">2026-07-17:The agent-to-agent payment economy runs far cheaper and now cycles hundreds of distinct payers</guid>+ <pubDate>Fri, 17 Jul 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>Two improvements to the closed-loop x402 agent economy that dogfoods every paid endpoint on the platform. First, a fix: a background wallet-consolidation job was quietly closing the ring's payment account after every settlement, forcing the next one to recreate it and pay account rent each time. That single bug had pushed the real fee cost to roughly a hundred times where it should be. With it fixed and single-signature settlement turned on, each settlement is back to the network floor of a few thousandths of a cent, and the ring's working balance stays in the loop instead of leaking away. Second, a new capability: the ring can now cycle payments through a reusable pool of hundreds to a thousand distinct wallets instead of one, so the economy reads as many participants rather than a single account, with no extra cost per payment. The pool is off until funded and activated, and every wallet in it stays clearly labeled internal dogfooding, not organic demand.</description>+ </item><item><title>Your models now look studio-quality everywhere, not just in the Forge</title><link>https://three.ws/viewer</link>diff --git a/public/features.json b/public/features.jsonindex c74e8cb33..437335778 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-17T06:48:03.747Z",+ "generated_at": "2026-07-17T06:55:51.157Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/scripts/x402-ring-pool-setup.mjs b/scripts/x402-ring-pool-setup.mjsnew file mode 100644index 000000000..fb0e31b44--- /dev/null+++ b/scripts/x402-ring-pool-setup.mjs@@ -0,0 +1,87 @@+#!/usr/bin/env node+// scripts/x402-ring-pool-setup.mjs+//+// Provision (and inspect) the x402 ring PAYER POOL — the reused set of custodial+// payer wallets the ring tick rotates through so the closed-loop economy shows+// many distinct, attributed payers at no extra per-settle cost.+//+// What it does:+// • Generates the shortfall up to the target size (default X402_RING_POOL_SIZE),+// encrypts each secret at rest (secret-box, WALLET_ENCRYPTION_KEY), stores it in+// x402_ring_pool, and registers each pubkey in x402_ring_wallets(role='pool') so+// it joins the controlled set (allowlist + leak-scanner internal) automatically.+// • NEVER funds anything and NEVER re-keys an existing wallet. Funding the pool+// with SOL + USDC is the ring-pool-fund pipeline's job once the pool is enabled;+// the initial float is a deliberate manual top-up (see --funding-plan).+//+// Requires DATABASE_URL + WALLET_ENCRYPTION_KEY in the environment.+//+// Usage:+// node scripts/x402-ring-pool-setup.mjs --status # counts only, no writes+// node scripts/x402-ring-pool-setup.mjs --grow # mint up to X402_RING_POOL_SIZE+// node scripts/x402-ring-pool-setup.mjs --grow --size=750 # mint up to 750+// node scripts/x402-ring-pool-setup.mjs --funding-plan --size=750 # print exact SOL/USDC to send+//+// After --grow, set X402_RING_POOL_ENABLED=true (and X402_RING_POOL_SIZE) on the+// Cloud Run service to switch rotation on; the ring-pool-fund pipeline then keeps+// every wallet topped up from the treasury/sponsor.++import process from 'node:process';++const args = process.argv.slice(2);+const flag = (n) => args.includes(`--${n}`);+const opt = (n, d) => { const p = args.find((a) => a.startsWith(`--${n}=`)); return p ? p.slice(n.length + 3) : d; };++const 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 {+ poolSolTargetLamports, poolUsdcTargetAtomic,+ } = await import('../api/_lib/x402/pipelines/ring-pool-fund.js');++ const target = size > 0 ? size : ringPoolTargetSize();++ if (flag('funding-plan')) {+ const n = target || (await poolCount());+ if (!n) { console.error('No pool size given. Pass --size=<n> or set X402_RING_POOL_SIZE.'); process.exit(1); }+ const solEach = poolSolTargetLamports() / 1e9;+ const usdcEach = poolUsdcTargetAtomic() / 1e6;+ // Not every wallet is hot at once; a conservative plan funds ~60% of the pool+ // to target with SOL and USDC, the rest fills on demand as they rotate in.+ const hot = Math.ceil(n * 0.6);+ const solTotal = hot * solEach;+ const usdcTotal = hot * usdcEach;+ const rentSol = n * 0.00203928; // one-time USDC-ATA rent per wallet+ console.log(`\nFunding plan for a ${n}-wallet pool (targets: ${solEach} SOL, $${usdcEach} USDC each):`);+ console.log(` • USDC float → send ~$${usdcTotal.toFixed(2)} USDC to the TREASURY (X402_PAY_TO_SOLANA); it distributes on demand.`);+ console.log(` • SOL fees → send ~${(solTotal + rentSol).toFixed(3)} SOL to the SPONSOR/master fee wallet (X402_FEE_PAYER_SOLANA)`);+ console.log(` (${solTotal.toFixed(3)} SOL fee float for ~${hot} hot wallets + ${rentSol.toFixed(3)} SOL one-time ATA rent for all ${n}).`);+ console.log(` Both are RECOVERABLE float — the USDC recirculates and the ATA rent is reclaimable.\n`);+ return;+ }++ const before = await poolCount();+ if (flag('status')) {+ console.log(`ring pool: ${before} enabled wallet(s). target=${target || '(unset)'}.`);+ return;+ }++ if (flag('grow')) {+ if (!target) { console.error('No target size. Pass --size=<n> or set X402_RING_POOL_SIZE.'); process.exit(1); }+ if (!process.env.WALLET_ENCRYPTION_KEY) { console.error('WALLET_ENCRYPTION_KEY is required to encrypt pool secrets.'); process.exit(1); }+ console.log(`Growing pool ${before} → ${target} …`);+ const { created, total } = await growPoolToTarget({ target });+ console.log(`Done. Minted ${created.length} new wallet(s); pool now ${total}.`);+ if (created.length) {+ console.log('Sample new pubkeys:', created.slice(0, 3).join(', '), created.length > 3 ? `(+${created.length - 3} more)` : '');+ console.log('\nNext: set X402_RING_POOL_ENABLED=true + X402_RING_POOL_SIZE=' + target + ' on the service,');+ console.log('then run: node scripts/x402-ring-pool-setup.mjs --funding-plan --size=' + target);+ }+ return;+ }++ console.log('Nothing to do. Pass --status, --grow, or --funding-plan. See the header for usage.');+}++main().catch((e) => { console.error('pool setup failed:', e?.message || e); process.exit(1); });diff --git a/tests/x402-ring-pool.test.js b/tests/x402-ring-pool.test.jsnew file mode 100644index 000000000..afee9389b--- /dev/null+++ b/tests/x402-ring-pool.test.js@@ -0,0 +1,102 @@+// Tests for the x402 ring PAYER POOL — the reused rotating payer wallets+// (api/_lib/x402/pool.js) and their threshold funder (pipelines/ring-pool-fund.js).+// Pure logic only; no DB, no chain, no network.+//+// What these lock down:+// • config gates — enable flag + target size parse exactly, off by default.+// • balance decode — the SPL token-account amount is read from the right offset.+// • funding planner — the pure decision (who needs SOL/USDC, who is overfull) is+// correct, respects the controlled-set gate, and honors the per-run cap.++import { describe, it, expect, beforeEach, afterEach } from 'vitest';++import { ringPoolEnabled, ringPoolTargetSize, ringPoolMaxGenerate } from '../api/_lib/x402/pool.js';+import { planPoolFunding, tokenAmountFromAccountData } from '../api/_lib/x402/pipelines/ring-pool-fund.js';++const FLOORS = {+ solFloor: 8_000_000, solTarget: 12_000_000,+ usdcFloor: 500_000, usdcTarget: 2_000_000, usdcCeil: 4_000_000,+ maxPerRun: 60,+};++describe('ring pool config gates', () => {+ const saved = {};+ beforeEach(() => { for (const k of ['X402_RING_POOL_ENABLED', 'X402_RING_POOL_SIZE', 'X402_RING_POOL_MAX_GENERATE']) saved[k] = process.env[k]; });+ afterEach(() => { for (const k of Object.keys(saved)) { if (saved[k] === undefined) delete process.env[k]; else process.env[k] = saved[k]; } });++ it('is disabled by default and only "true" enables it', () => {+ delete process.env.X402_RING_POOL_ENABLED;+ expect(ringPoolEnabled()).toBe(false);+ process.env.X402_RING_POOL_ENABLED = '1';+ expect(ringPoolEnabled()).toBe(false);+ process.env.X402_RING_POOL_ENABLED = 'TRUE';+ expect(ringPoolEnabled()).toBe(true);+ });++ it('parses target size, rejecting junk and negatives', () => {+ delete process.env.X402_RING_POOL_SIZE;+ expect(ringPoolTargetSize()).toBe(0);+ process.env.X402_RING_POOL_SIZE = '750';+ expect(ringPoolTargetSize()).toBe(750);+ process.env.X402_RING_POOL_SIZE = '-5';+ expect(ringPoolTargetSize()).toBe(0);+ process.env.X402_RING_POOL_SIZE = 'abc';+ expect(ringPoolTargetSize()).toBe(0);+ });++ it('caps a single generate call (default 2000)', () => {+ delete process.env.X402_RING_POOL_MAX_GENERATE;+ expect(ringPoolMaxGenerate()).toBe(2000);+ process.env.X402_RING_POOL_MAX_GENERATE = '500';+ expect(ringPoolMaxGenerate()).toBe(500);+ });+});++describe('SPL token amount decode', () => {+ it('reads the u64 amount at byte offset 64, little-endian', () => {+ const data = Buffer.alloc(165); // SPL token account size+ data.writeBigUInt64LE(1_234_567n, 64);+ expect(tokenAmountFromAccountData(data)).toBe(1_234_567n);+ });+ it('treats a too-short / missing buffer as zero', () => {+ expect(tokenAmountFromAccountData(null)).toBe(0n);+ expect(tokenAmountFromAccountData(Buffer.alloc(10))).toBe(0n);+ });+});++describe('planPoolFunding (pure)', () => {+ const allowed = new Set(['A', 'B', 'C', 'D']);++ it('funds SOL below floor up to target', () => {+ const sol = new Map([['A', 1_000_000], ['B', 9_000_000]]); // A low, B fine+ const usdc = new Map([['A', 2_000_000n], ['B', 2_000_000n]]);+ const { solNeed } = planPoolFunding({ pubkeys: ['A', 'B'], solByPubkey: sol, usdcByPubkey: usdc, allowed, floors: FLOORS });+ expect(solNeed).toEqual([{ pk: 'A', add: 11_000_000 }]);+ });++ it('funds USDC below floor up to target and sweeps overfull back', () => {+ const sol = new Map([['A', 12_000_000], ['B', 12_000_000], ['C', 12_000_000]]);+ const usdc = new Map([['A', 100_000n], ['B', 2_000_000n], ['C', 5_000_000n]]); // A low, B fine, C overfull+ const { usdcNeed, usdcSweep } = planPoolFunding({ pubkeys: ['A', 'B', 'C'], solByPubkey: sol, usdcByPubkey: usdc, allowed, floors: FLOORS });+ expect(usdcNeed).toEqual([{ pk: 'A', add: 1_900_000n }]);+ expect(usdcSweep).toEqual([{ pk: 'C', take: 3_000_000n }]);+ });++ it('never funds a wallet outside the controlled set', () => {+ const sol = new Map([['A', 0], ['X', 0]]);+ const usdc = new Map([['A', 0n], ['X', 0n]]);+ const { solNeed, usdcNeed } = planPoolFunding({ pubkeys: ['A', 'X'], solByPubkey: sol, usdcByPubkey: usdc, allowed, floors: FLOORS });+ expect(solNeed.map((w) => w.pk)).toEqual(['A']);+ expect(usdcNeed.map((w) => w.pk)).toEqual(['A']);+ });++ it('honors the per-run cap', () => {+ const pks = Array.from({ length: 100 }, (_, i) => `w${i}`);+ const allowAll = new Set(pks);+ const sol = new Map(pks.map((p) => [p, 0]));+ const usdc = new Map(pks.map((p) => [p, 0n]));+ const { solNeed, usdcNeed } = planPoolFunding({ pubkeys: pks, solByPubkey: sol, usdcByPubkey: usdc, allowed: allowAll, floors: { ...FLOORS, maxPerRun: 10 } });+ expect(solNeed).toHaveLength(10);+ expect(usdcNeed).toHaveLength(10);+ });+});diff --git a/workers/model-hunyuan3d/README.md b/workers/model-hunyuan3d/README.mdindex 604d5a139..cc0ec1398 100644--- a/workers/model-hunyuan3d/README.md+++ b/workers/model-hunyuan3d/README.md@@ -44,7 +44,8 @@ applies there). Deploy with[`cloudbuild.hunyuan21rtx.yaml`](./cloudbuild.hunyuan21rtx.yaml) (BuildKit,inline layer cache); platform minimums for the GPU type are 20 CPU / 80 Gi,which also clears wall 1 with room to spare. The RTX service runs warm (min 1,-max 4) as the 2.1 primary. Making the L4 build genuinely loadable (stage one+max 1: the quota preference reads granted 1000, but live deploy enforcement+allows exactly 1 RTX GPU in us-central1) as the 2.1 primary. Making the L4 build genuinely loadable (stage oneweight subtree at a time and delete each after its `from_pretrained`) is theopen follow-up if an L4 fallback for 2.1 is ever needed; until then the 2.0lane is the fallback.