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
// api/_lib/x402/wallet-fee-governor.js
//
// Pure decision logic for the WALLET-level fee governor — the shared-wallet
// counterpart of the ring tick's governedCalls() (ring-tick-plan.js).
//
// Why this exists: governedCalls() throttles the ring tick, but the fee-paying
// wallets are shared by roughly a dozen other paid pipelines (health, volume,
// oracle, sniper, datapoint, 3d, ring-agents, …) that spend ungoverned.
// Measured 2026-07-27: in one 20-minute window the ring tick was throttled to
// 2 paid calls while co-tenant pipelines completed ~200 through the same
// wallet. A governor that throttles one tenant while others drain the same
// runway protects nothing under real scarcity — it just decides WHICH pipeline
// gets starved.
//
// This module meters the WALLET instead: every settle that a given wallet pays
// the SOL fee for — regardless of which pipeline initiated it — draws from one
// daily fee budget derived from that wallet's live spendable SOL. Enforcement
// happens at the one choke point every platform payment passes through, the
// self-hosted facilitator's settle path (self-facilitator.js `feeMeter` hook,
// wired by api/x402-facilitator/[action].js via wallet-fee-meter.js). That also
// answers the "watch the wallet that actually pays" gap: the metered wallet is
// the transaction's real fee payer (decoded.feePayer), so sponsor-mode settles
// debit the sponsor's budget and self-pay settles debit the payer's.
//
// No network, no DB — every function is deterministic given its inputs
// (tests/x402-wallet-fee-governor.test.js). The I/O (spent-today ledger read,
// controlled-wallet scoping, caching) lives in wallet-fee-meter.js.
// ── Config knobs ────────────────────────────────────────────────────────────────
export function walletFeeGovernorConfig(e = process.env) {
const num = (v, d) => {
const n = Number(v);
return Number.isFinite(n) && n >= 0 ? n : d;
};
return {
// Kill switch: default ON. Only an explicit "false" disables the meter.
enabled: String(e.X402_WALLET_FEE_GOVERNOR_ENABLED ?? '').trim().toLowerCase() !== 'false',
// How long the wallet's spendable SOL must last at the governed burn rate.
// Mirrors the ring tick's X402_RING_TARGET_RUNWAY_DAYS default.
runwayDays: Math.max(0.5, num(e.X402_WALLET_FEE_RUNWAY_DAYS, 3)),
// Heartbeat floor: the daily fee budget never drops below this, so the
// economy keeps a minimum pulse while the wallet is above its hard SOL
// floor. Same rationale as the ring heartbeat (X402_RING_MIN_CALLS): the
// hard floor is the real protection, and a wallet that does nothing cannot
// restart the economy from its own balances. Default 0.01 SOL/day ≈ ~2,000
// self-pay settles.
minBudgetLamports: Math.floor(num(e.X402_WALLET_FEE_MIN_BUDGET_LAMPORTS, 10_000_000)),
// How long wallet-fee-meter.js may serve a cached spent-today read before
// re-summing the facilitator log. Bounds multi-instance undercount to one
// cache window of settles per instance.
spentCacheMs: Math.max(1_000, Math.floor(num(e.X402_WALLET_FEE_SPENT_CACHE_MS, 20_000))),
// Release the daily budget gradually across the UTC day instead of all of
// it at 00:00. OPT-IN: only an explicit "true" enables it.
//
// Off by default on purpose. Pacing changes which gate refuses a starved
// wallet first (the governor rather than the hard SOL floor), and the floor
// vs governor distinction is the diagnostic the runway lab exists to make
// visible. Flipping it silently on a live money rail would trade a real
// diagnostic for an availability gain that does not, by itself, settle one
// extra payment. Enable it with a config-only env update once an operator
// wants the smoother shape.
paceDay: String(e.X402_WALLET_FEE_PACE_DAY ?? '').trim().toLowerCase() === 'true',
// The slice of budget unlocked at the very top of the day, so a paced
// wallet is never dead for the first minutes after the reset.
paceMinSliceLamports: Math.floor(num(e.X402_WALLET_FEE_PACE_MIN_SLICE_LAMPORTS, 200_000)),
};
}
// ── Daily budget ────────────────────────────────────────────────────────────────
// The lamports of fee burn this wallet may spend per UTC day: its spendable SOL
// (balance minus the untouchable floor) spread over `runwayDays`, never below
// the heartbeat floor. Funding IS the throttle: top the wallet up and every
// tenant speeds up together; let it drain and they all taper together instead
// of racing each other to the floor.
export function walletDailyFeeBudgetLamports({
solLamports, floorLamports, runwayDays, minBudgetLamports = 0,
}) {
if (!Number.isFinite(solLamports)) return 0;
const spendable = Math.max(0, solLamports - Math.max(0, floorLamports || 0));
const runwayBudget = Math.floor(spendable / Math.max(0.5, runwayDays));
return Math.max(Math.max(0, Math.floor(minBudgetLamports)), runwayBudget);
}
// ── Intraday pacing ─────────────────────────────────────────────────────────────
// Fraction of the current UTC day already elapsed, 0 at 00:00 and approaching 1
// at 23:59. Kept here (not in the meter) so the pacing math stays pure and the
// caller owns the clock.
export function utcDayElapsedFraction(now = Date.now()) {
const ms = Number(now);
if (!Number.isFinite(ms)) return 1;
const dayMs = 86_400_000;
const intoDay = ((ms % dayMs) + dayMs) % dayMs;
return intoDay / dayMs;
}
// How much of today's budget has been unlocked so far.
//
// Why this exists: the daily budget used to be spendable in full the moment the
// UTC day rolled over, so a wallet near its floor burned the entire allowance in
// a morning burst and then refused every settle for the rest of the day.
// Measured on production 2026-08-01: 1,002 settles paid before midday against a
// 10,000,000 lamport budget, then roughly 3,500 `fee_runway_exhausted` rejects
// per hour for the following sixteen hours, each one a wasted round trip that
// surfaced to callers as a 502. Spreading the same budget across the day turns
// that burst-then-flatline into the steady pulse the heartbeat floor was always
// meant to provide. It does not grant a wallet one extra lamport per day.
export function pacedFeeBudgetLamports({
budgetLamports, dayElapsedFraction, minSliceLamports = 0,
}) {
const budget = Math.max(0, Math.floor(Number(budgetLamports) || 0));
const fraction = Number(dayElapsedFraction);
// An unreadable clock must not throttle anything: fall back to the full budget.
if (!Number.isFinite(fraction)) return budget;
const clamped = Math.min(1, Math.max(0, fraction));
const unlocked = Math.floor(budget * clamped);
const floor = Math.max(0, Math.floor(Number(minSliceLamports) || 0));
return Math.min(budget, Math.max(unlocked, floor));
}
// ── Admission decision ──────────────────────────────────────────────────────────
// Admit the next settle only if its estimated fee still fits in today's budget.
// An unknown spend (ledger unreadable) fails OPEN — the SOL floor in the settle
// path remains the hard protection; the meter is pacing, not the last line of
// defense. Pure: same inputs → same verdict.
export function assessWalletFeeBudget({ spentTodayLamports, budgetLamports, nextFeeLamports = 0 }) {
if (!Number.isFinite(spentTodayLamports)) return { ok: true, reason: null };
const next = Math.max(0, Number(nextFeeLamports) || 0);
if (spentTodayLamports + next > budgetLamports) {
return {
ok: false,
reason: `fee_runway_exhausted:${spentTodayLamports}+${next}>${budgetLamports}`,
};
}
return { ok: true, reason: null };
}
// ── Batch sizing ────────────────────────────────────────────────────────────────
// How many settles of `feeLamports` each still fit in today's budget, after
// leaving `keepLamports` of headroom untouched for other tenants of the wallet.
//
// assessWalletFeeBudget() answers yes/no for ONE settle. A batch caller (the x402
// seed cron fires up to 120 sponsor-mode payments in parallel) needs the count,
// and asking one at a time is how it used to fire 60 when the budget funded one:
// measured on production 2026-09-29, 3,600 of 3,660 seed payments in two hours
// were refused at the facilitator with `fee_runway_exhausted` after each had
// paid for a signed transfer and a simulated verify. Same arithmetic as the
// single-settle verdict, so the two can never disagree about the boundary:
// `n` settles are admitted exactly when spent + n*fee <= budget - keep.
//
// Unknown spend (ledger unreadable) returns `max`, the same fail-open contract as
// assessWalletFeeBudget: the settle path's SOL floor stays the hard protection.
export function admissibleSettleCount({
spentTodayLamports, budgetLamports, feeLamports, keepLamports = 0, max = Infinity,
}) {
const cap = Math.max(0, Math.floor(Number(max)));
const ceiling = Number.isFinite(cap) ? cap : Infinity;
if (!Number.isFinite(spentTodayLamports)) return ceiling;
const fee = Math.max(0, Number(feeLamports) || 0);
const keep = Math.max(0, Number(keepLamports) || 0);
const headroom = Number(budgetLamports) - spentTodayLamports - keep;
if (!(headroom >= 0)) return 0;
// A zero fee cannot exhaust anything; the caller's own cap is the only limit.
if (fee === 0) return ceiling;
return Math.min(ceiling, Math.floor(headroom / fee));
}