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): bounded-concurrency ring tick for ~94 paid calls/minute
nirholasd65085c0d7eb
diff --git a/api/_lib/x402/ring-tick-exec.js b/api/_lib/x402/ring-tick-exec.jsnew file mode 100644index 000000000..31e504f5c--- /dev/null+++ b/api/_lib/x402/ring-tick-exec.js@@ -0,0 +1,131 @@+// Bounded-concurrency executor for the ring tick's paid calls.+//+// The sequential for-loop in x402-ring-tick.js topped out around 15-20 paid+// calls per 60 s tick (each call is a full 402 dance + on-chain settle ++// confirm). Scaling the ring to ~94 calls/minute (the $100/day fee budget the+// owner approved 2026-07-25) needs the cheap calls in flight together.+//+// Budget safety under concurrency works by RESERVATION: before a call+// launches, a worst-case slice of the remaining tick budget is reserved and+// passed to the call as its own remainingCap — payX402 refuses to pay any+// challenge above that cap, so the sum of all in-flight spends can never+// exceed the reservations, and the reservations never exceed the tick budget.+// When a call finishes, the unspent part of its reservation is refunded.+//+// The ring-settle carrier (the $1.00 volume call) still runs ALONE first: it+// is the big-ticket item, and running it before the swarm keeps the old+// degrade semantics (settle unaffordable → cheap-only tick) observable.+//+// Floor back-pressure: the first result carrying a facilitator SOL-floor+// signal stops all further launches; in-flight calls drain, nothing new fires.+//+// Pure orchestration — no network, no DB, no solana imports. The caller+// injects `pay(ep, capForCall)` (the settleAndRecord closure) and+// `isFloorSignal(result)`. Unit-tested in tests/x402-ring-tick-exec.test.js.++/**+ * @param {object} opts+ * @param {Array<object>} opts.picks ordered endpoints; a settle-tick's ring-settle is picks[0]+ * @param {number} opts.remaining tick budget still available (USDC atomics)+ * @param {number} opts.concurrency max cheap calls in flight (>=1)+ * @param {boolean} opts.settleFirst picks[0] is the ring-settle carrier — run it alone first+ * @param {number} opts.ringSettlePriceAtomic reservation for the settle carrier+ * @param {number} opts.worstCaseCheapAtomic reservation per cheap call (must cover the priciest cheap endpoint)+ * @param {(ep: object, capForCall: number) => Promise<{result: object, paidAmount: number}>} opts.pay+ * @param {(result: object) => boolean} opts.isFloorSignal+ * @returns {Promise<{results: Array<object>, calls: number, paid: number, errors: number,+ * spent: number, remaining: number, lastTxSig: string|null,+ * floorHit: boolean, capReached: boolean}>}+ */+export async function runTickPicks({+ picks,+ remaining,+ concurrency,+ settleFirst,+ ringSettlePriceAtomic,+ worstCaseCheapAtomic,+ pay,+ isFloorSignal,+}) {+ const state = {+ results: new Array(picks.length),+ calls: 0,+ paid: 0,+ errors: 0,+ spent: 0,+ remaining: Math.max(0, remaining),+ lastTxSig: null,+ floorHit: false,+ capReached: false,+ };++ const settleOne = async (index, reservation) => {+ const ep = picks[index];+ state.remaining -= reservation;+ state.calls += 1;+ let outcome;+ try {+ outcome = await pay(ep, reservation);+ } catch (err) {+ outcome = {+ result: { success: false, paid: false, errorMsg: err?.message || 'pay_failed' },+ paidAmount: 0,+ };+ }+ const { result, paidAmount } = outcome;+ // Refund the unspent slice. payX402 enforces paidAmount <= reservation+ // (remainingCap), so the refund is never negative; clamp anyway.+ state.remaining += Math.max(0, reservation - (paidAmount || 0));+ if (!result.success) state.errors += 1;+ if (result.paid) {+ state.paid += 1;+ state.spent += paidAmount || 0;+ if (result.txSig) state.lastTxSig = result.txSig;+ }+ if (!result.success && isFloorSignal(result)) state.floorHit = true;+ state.results[index] = {+ key: ep.key,+ paid: result.paid === true,+ success: result.success,+ status: result.status,+ amount_usdc: (paidAmount || 0) / 1e6,+ };+ };++ let next = 0;++ // The ring-settle carrier runs alone, reserving its full price (clamped to+ // what is left — payX402 then refuses cleanly if that cannot cover it,+ // matching the old sequential behavior).+ if (settleFirst && picks.length > 0) {+ const reservation = Math.min(state.remaining, Math.max(0, ringSettlePriceAtomic));+ await settleOne(0, reservation);+ next = 1;+ }++ // Cheap swarm: N workers pull from the shared cursor. A worker stops when+ // picks run out, the budget cannot cover another worst-case reservation, or+ // a floor signal appeared.+ const worker = async () => {+ while (true) {+ if (state.floorHit) return;+ if (state.remaining < worstCaseCheapAtomic) {+ if (next < picks.length) state.capReached = true;+ return;+ }+ const index = next;+ if (index >= picks.length) return;+ next += 1;+ await settleOne(index, worstCaseCheapAtomic);+ }+ };++ const workers = [];+ const lanes = Math.max(1, Math.floor(concurrency) || 1);+ for (let i = 0; i < lanes; i++) workers.push(worker());+ await Promise.all(workers);++ // Drop unfilled slots (calls never launched because of cap/floor stops).+ state.results = state.results.filter(Boolean);+ return state;+}diff --git a/api/_lib/x402/ring-tick-plan.js b/api/_lib/x402/ring-tick-plan.jsindex 2099e608d..ca6e5ffc4 100644--- a/api/_lib/x402/ring-tick-plan.js+++ b/api/_lib/x402/ring-tick-plan.js@@ -41,6 +41,11 @@ export function ringTickConfig(e = process.env) {// SPONSOR_SOL_FLOOR_LAMPORTS default (0.02 SOL) — below it, settlement is// paused, so we skip the tick rather than fire calls that will 502.solFloorLamports: num(e.X402_SPONSOR_SOL_FLOOR_LAMPORTS, 20_000_000),+ // Cheap calls in flight at once (ring-tick-exec.js worker lanes). The+ // settle carrier always runs alone first. 12 lanes clears ~94 calls in+ // well under the 60 s tick window at typical 1-3 s per settle; 1 restores+ // the old strictly-sequential behavior.+ concurrency: Math.max(1, Math.floor(num(e.X402_RING_TICK_CONCURRENCY, 12))),};}diff --git a/api/cron/x402-ring-tick.js b/api/cron/x402-ring-tick.jsindex a698ed94b..f4e384262 100644--- a/api/cron/x402-ring-tick.js+++ b/api/cron/x402-ring-tick.js@@ -69,11 +69,16 @@ import {tickBudget,gateOnRingConfig,} from '../_lib/x402/ring-tick-plan.js';+import { runTickPicks } from '../_lib/x402/ring-tick-exec.js';const log = logger('x402-ring-tick');const ORIGIN = () => env.APP_ORIGIN || 'https://three.ws';const RING_SETTLE_DEFAULT_PRICE = '1000000'; // $1.00 — mirrors ring-settle.js (RING_SETTLE_DEFAULT_PRICE_ATOMICS)+// Worst-case budget reservation per cheap call (atomics). Must cover the+// priciest CHEAP_ENDPOINTS entry ($0.001–$0.01 today) — a cheap call whose 402+// challenge exceeds its reservation is refused by payX402, not overspent.+const CHEAP_RESERVATION_ATOMIC = 20_000; // $0.02// Redis keys: a monotonic per-minute tick counter and the cheap-rotation cursor.// Independent of the volume loop's cursor so the two drivers rotate separately.@@ -334,30 +339,29 @@ export default wrapCron(async (req, res) => {? { 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;-- for (const ep of picks) {- if (remaining <= 0) {- log.info('ring_tick_cap_reached', { endpoint: ep.key, spent_atomic: spent });- break;- }- const { result, paidAmount } = await settleAndRecord({- sql, runId, ep, origin, remaining, ctx: payCtx,- pipeline: 'ring-tick', namePrefix: 'Ring', payFn: payX402, log,- });- calls += 1;- if (!result.success) errors += 1;- if (result.paid) {- paid += 1; spent += paidAmount; remaining -= paidAmount;- if (result.txSig) lastTxSig = result.txSig;- }- results.push({ key: ep.key, paid: result.paid === true, success: result.success, status: result.status, amount_usdc: paidAmount / 1e6 });-- // Mid-tick back-pressure: the floor was crossed after pre-flight. Stop the- // tick (don't keep firing settles that will fail) and alert once.- if (!result.success && isFloorSignal(result)) { floorHit = true; break; }+ // Bounded-concurrency execution (ring-tick-exec.js): the settle carrier runs+ // alone first, then the cheap calls fan out across cfg.concurrency worker+ // lanes. Budget safety holds under concurrency because every launch reserves+ // a worst-case slice of `remaining` and passes it as that call's own+ // remainingCap — payX402 refuses any challenge above it. Mid-tick floor+ // signals stop further launches; in-flight calls drain.+ const exec = await runTickPicks({+ picks,+ remaining,+ concurrency: cfg.concurrency,+ settleFirst: plan.isSettleTick,+ ringSettlePriceAtomic,+ worstCaseCheapAtomic: CHEAP_RESERVATION_ATOMIC,+ pay: (ep, capForCall) =>+ settleAndRecord({+ sql, runId, ep, origin, remaining: capForCall, ctx: payCtx,+ pipeline: 'ring-tick', namePrefix: 'Ring', payFn: payX402, log,+ }),+ isFloorSignal,+ });+ const { results, calls, paid, errors, spent, lastTxSig, floorHit } = exec;+ if (exec.capReached) {+ log.info('ring_tick_cap_reached', { spent_atomic: spent, launched: calls, picks: picks.length });}if (floorHit) {diff --git a/docs/x402-ring-economy.md b/docs/x402-ring-economy.mdindex 042f448d3..e3fe54f53 100644--- a/docs/x402-ring-economy.md+++ b/docs/x402-ring-economy.md@@ -404,6 +404,24 @@ independently, so the ring tick never consumes the autonomous loop's| `X402_PRICE_RING_SETTLE` | $1.00 | the volume carrier's per-call size || `X402_RING_TICK_CAP_ATOMIC` | $1.10 | per-tick spend ceiling (fits one settle + its cheap co-riders) || `X402_RING_DAILY_CAP_ATOMIC` | $50.00 | ring-tick daily ceiling (separate budget) |+| `X402_RING_TICK_CONCURRENCY` | 12 | cheap calls in flight at once (1 = strictly sequential) |++### Scaling up: concurrency and reservations++The tick's paid calls run through a bounded-concurrency executor+([api/_lib/x402/ring-tick-exec.js](../api/_lib/x402/ring-tick-exec.js)): the+ring-settle carrier runs alone first, then the cheap calls fan out across+`X402_RING_TICK_CONCURRENCY` worker lanes, which is what lets a tick clear+~90+ calls inside its 60 s window. Budget safety holds under concurrency by+reservation: each launch reserves a worst-case slice ($0.02) of the remaining+tick budget and gets that slice as its own `remainingCap`, which `payX402`+enforces against the live 402 challenge, so concurrent calls can never+collectively overspend the tick cap. Unspent slices are refunded as calls+finish; a mid-tick SOL-floor signal stops further launches and drains what is+in flight. Fee math when scaling: fees track *transaction count*, not USDC+size — ~10,001 lamports per settle, so ~94 calls/min ≈ 135k tx/day ≈ 1.35+SOL/day. Raise `X402_RING_DAILY_FEE_BUDGET_LAMPORTS`, the daily cap, and payer+funding together (see the funding table in "Turning it on").At 3 calls/min the **traffic shape** is:diff --git a/tests/x402-ring-tick-exec.test.js b/tests/x402-ring-tick-exec.test.jsnew file mode 100644index 000000000..a6fcf0eca--- /dev/null+++ b/tests/x402-ring-tick-exec.test.js@@ -0,0 +1,202 @@+import { describe, it, expect } from 'vitest';+import { runTickPicks } from '../api/_lib/x402/ring-tick-exec.js';+import { ringTickConfig } from '../api/_lib/x402/ring-tick-plan.js';++// ── Helpers ──────────────────────────────────────────────────────────────────++const pick = (key) => ({ key, path: `/api/x402/${key}`, method: 'POST' });+const picks = (n, withSettle = false) => {+ const out = withSettle ? [pick('ring-settle')] : [];+ for (let i = out.length; i < n; i++) out.push(pick(`cheap-${i}`));+ return out;+};++const paidResult = (amount, txSig = 'sig') => ({+ result: { success: true, paid: true, status: 200, txSig },+ paidAmount: amount,+});+const failedResult = (errorMsg = 'boom') => ({+ result: { success: false, paid: false, status: 502, errorMsg },+ paidAmount: 0,+});++const FLOOR = (r) => /sol_floor/.test(r?.errorMsg || '');+const CHEAP_PRICE = 1_000; // $0.001+const RESERVE = 20_000; // $0.02 worst case+const SETTLE_PRICE = 1_000_000; // $1.00++// ── runTickPicks ─────────────────────────────────────────────────────────────++describe('runTickPicks', () => {+ it('runs the settle carrier first, then all cheap picks, and accounts spend', async () => {+ const order = [];+ const out = await runTickPicks({+ picks: picks(5, true),+ remaining: 2_000_000,+ concurrency: 4,+ settleFirst: true,+ ringSettlePriceAtomic: SETTLE_PRICE,+ worstCaseCheapAtomic: RESERVE,+ isFloorSignal: FLOOR,+ pay: async (ep) => {+ order.push(ep.key);+ return paidResult(ep.key === 'ring-settle' ? SETTLE_PRICE : CHEAP_PRICE, `tx-${ep.key}`);+ },+ });+ expect(order[0]).toBe('ring-settle');+ expect(out.calls).toBe(5);+ expect(out.paid).toBe(5);+ expect(out.errors).toBe(0);+ expect(out.spent).toBe(SETTLE_PRICE + 4 * CHEAP_PRICE);+ expect(out.remaining).toBe(2_000_000 - out.spent);+ expect(out.lastTxSig).toMatch(/^tx-/);+ expect(out.results).toHaveLength(5);+ expect(out.results[0].key).toBe('ring-settle');+ });++ it('never spends beyond the budget when calls consume their full reservation', async () => {+ // Budget fits exactly 3 worst-case reservations and every call spends the+ // whole slice — no refunds, so exactly 3 launch.+ const out = await runTickPicks({+ picks: picks(10),+ remaining: 3 * RESERVE,+ concurrency: 8,+ settleFirst: false,+ ringSettlePriceAtomic: SETTLE_PRICE,+ worstCaseCheapAtomic: RESERVE,+ isFloorSignal: FLOOR,+ pay: async () => paidResult(RESERVE),+ });+ expect(out.calls).toBe(3);+ expect(out.capReached).toBe(true);+ expect(out.spent).toBe(3 * RESERVE);+ expect(out.remaining).toBe(0);+ expect(out.results).toHaveLength(3);+ });++ it('recycles refunded reservations into more launches without exceeding the budget', async () => {+ // Same tight budget, but calls spend only $0.001 of each $0.02 slice —+ // refunds flow back, all 10 picks fire, and spend stays under budget.+ const out = await runTickPicks({+ picks: picks(10),+ remaining: 3 * RESERVE,+ concurrency: 8,+ settleFirst: false,+ ringSettlePriceAtomic: SETTLE_PRICE,+ worstCaseCheapAtomic: RESERVE,+ isFloorSignal: FLOOR,+ pay: async () => paidResult(CHEAP_PRICE),+ });+ expect(out.calls).toBe(10);+ expect(out.spent).toBe(10 * CHEAP_PRICE);+ expect(out.spent).toBeLessThanOrEqual(3 * RESERVE);+ expect(out.remaining).toBe(3 * RESERVE - 10 * CHEAP_PRICE);+ });++ it('passes each call its own reservation as the cap', async () => {+ const caps = [];+ await runTickPicks({+ picks: picks(2),+ remaining: 10 * RESERVE,+ concurrency: 1,+ settleFirst: false,+ ringSettlePriceAtomic: SETTLE_PRICE,+ worstCaseCheapAtomic: RESERVE,+ isFloorSignal: FLOOR,+ pay: async (_ep, cap) => { caps.push(cap); return paidResult(CHEAP_PRICE); },+ });+ expect(caps).toEqual([RESERVE, RESERVE]);+ });++ it('clamps the settle reservation to the remaining budget', async () => {+ const caps = [];+ const out = await runTickPicks({+ picks: picks(1, true),+ remaining: 300_000, // less than the $1.00 settle+ concurrency: 2,+ settleFirst: true,+ ringSettlePriceAtomic: SETTLE_PRICE,+ worstCaseCheapAtomic: RESERVE,+ isFloorSignal: FLOOR,+ pay: async (_ep, cap) => { caps.push(cap); return failedResult('cap_exceeded'); },+ });+ expect(caps).toEqual([300_000]);+ expect(out.errors).toBe(1);+ expect(out.remaining).toBe(300_000); // full refund on an unpaid call+ });++ it('stops launching after a floor signal and drains in-flight work', async () => {+ let launched = 0;+ const out = await runTickPicks({+ picks: picks(20),+ remaining: 10_000_000,+ concurrency: 1, // deterministic: floor on the first call+ settleFirst: false,+ ringSettlePriceAtomic: SETTLE_PRICE,+ worstCaseCheapAtomic: RESERVE,+ isFloorSignal: FLOOR,+ pay: async () => { launched += 1; return failedResult('sponsor sol_floor crossed'); },+ });+ expect(launched).toBe(1);+ expect(out.floorHit).toBe(true);+ expect(out.calls).toBe(1);+ expect(out.results).toHaveLength(1);+ });++ it('bounds in-flight calls to the concurrency lanes', async () => {+ let inFlight = 0;+ let maxInFlight = 0;+ const out = await runTickPicks({+ picks: picks(24),+ remaining: 100_000_000,+ concurrency: 6,+ settleFirst: false,+ ringSettlePriceAtomic: SETTLE_PRICE,+ worstCaseCheapAtomic: RESERVE,+ isFloorSignal: FLOOR,+ pay: async () => {+ inFlight += 1;+ maxInFlight = Math.max(maxInFlight, inFlight);+ await new Promise((r) => setTimeout(r, 5));+ inFlight -= 1;+ return paidResult(CHEAP_PRICE);+ },+ });+ expect(out.calls).toBe(24);+ expect(maxInFlight).toBeLessThanOrEqual(6);+ expect(maxInFlight).toBeGreaterThan(1);+ });++ it('counts a throwing pay() as an error and refunds its reservation', async () => {+ const out = await runTickPicks({+ picks: picks(2),+ remaining: 10 * RESERVE,+ concurrency: 2,+ settleFirst: false,+ ringSettlePriceAtomic: SETTLE_PRICE,+ worstCaseCheapAtomic: RESERVE,+ isFloorSignal: FLOOR,+ pay: async (ep) => {+ if (ep.key === 'cheap-0') throw new Error('network down');+ return paidResult(CHEAP_PRICE);+ },+ });+ expect(out.calls).toBe(2);+ expect(out.errors).toBe(1);+ expect(out.paid).toBe(1);+ expect(out.remaining).toBe(10 * RESERVE - CHEAP_PRICE);+ });+});++// ── ringTickConfig concurrency knob ──────────────────────────────────────────++describe('ringTickConfig concurrency', () => {+ it('defaults to 12 lanes', () => {+ expect(ringTickConfig({}).concurrency).toBe(12);+ });+ it('reads X402_RING_TICK_CONCURRENCY and floors at 1', () => {+ expect(ringTickConfig({ X402_RING_TICK_CONCURRENCY: '20' }).concurrency).toBe(20);+ expect(ringTickConfig({ X402_RING_TICK_CONCURRENCY: '0' }).concurrency).toBe(1);+ expect(ringTickConfig({ X402_RING_TICK_CONCURRENCY: 'junk' }).concurrency).toBe(12);+ });+});