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
harden(economy-fuel): proven confirm, anti-double-swap cooldown, ops surface
nirholas1ae13ecb7151
diff --git a/api/_lib/economy-fuel.js b/api/_lib/economy-fuel.jsindex e097de994..f0be98ee0 100644--- a/api/_lib/economy-fuel.js+++ b/api/_lib/economy-fuel.js@@ -37,6 +37,7 @@ import { loadEconomyMaster, RESERVE_SOL, RUN_CAP_SOL } from './economy-master.jsimport { jupQuote, buildSwapTx, USDC_MINT_BY_NETWORK, USDC_DECIMALS } from './vault-jupiter.js';import { getSolBalance } from './avatar-wallet.js';import { solPriceUsd } from './sol-price.js';+import { confirmOrThrow } from './solana/confirm.js';const NATIVE_SOL_MINT = 'So11111111111111111111111111111111111111112';const LAMPORTS_PER_SOL = 1_000_000_000;@@ -65,6 +66,11 @@ export const FUEL_MIN_GAP_SOL = num('ECONOMY_FUEL_MIN_GAP_SOL', 0.1);export const FUEL_TARGET_SOL = num('ECONOMY_FUEL_TARGET_SOL', 1.0);/** Below this USDC a swap is not worth the fees. */const MIN_SWAP_USDC = 1;+/** Minimum seconds between two fuel swaps. The topup runs every minute and could+ * overlap itself under load; this is a cheap belt against a double-swap racing+ * the daily-cap read (the DB counter closes the gap after the first swap lands,+ * the cooldown closes it before). */+export const FUEL_COOLDOWN_S = num('ECONOMY_FUEL_COOLDOWN_S', 90);/*** Pure refuel decision + sizing, no RPC, no DB, so the bounds are unit-testable@@ -141,6 +147,15 @@ async function usdcSpentTodayUsd() {return Number(rows?.[0]?.atomics || 0) / 10 ** USDC_DECIMALS;}+/** Seconds since the last recorded fuel swap, or Infinity if there is none. */+async function secondsSinceLastSwap() {+ const rows = await sql`+ SELECT EXTRACT(EPOCH FROM (now() - MAX(created_at)))::float8 AS secs+ FROM economy_fuel_swaps`;+ const secs = rows?.[0]?.secs;+ return secs == null ? Infinity : Number(secs);+}+/** Read an owner's USDC balance (whole tokens + atomics). */async function readUsdc(connection, owner, network) {const mint = network === 'devnet' ? USDC_MINT_BY_NETWORK.devnet : USDC_MINT_BY_NETWORK.mainnet;@@ -155,18 +170,20 @@ async function readUsdc(connection, owner, network) {return { atomics, usd: Number(atomics) / 10 ** USDC_DECIMALS };}-/** Sign, broadcast, and confirm a Jupiter VersionedTransaction with `keypair`. */+/**+ * Sign, broadcast, and confirm a Jupiter VersionedTransaction with `keypair`.+ * Confirms via the platform's HTTP-polling confirmer (no WebSocket) bounded by the+ * transaction's own blockhash expiry, and throws `tx_reverted` on a landed-but-+ * reverted swap so a revert is never booked as a successful refuel.+ */async function signSendConfirm(connection, tx, keypair) {tx.sign([keypair]);const sig = await connection.sendRawTransaction(tx.serialize(), { skipPreflight: false, maxRetries: 3 });- const bh = await connection.getLatestBlockhash('confirmed');- const conf = await connection.confirmTransaction(- { signature: sig, blockhash: bh.blockhash, lastValidBlockHeight: bh.lastValidBlockHeight },- 'confirmed',- );- if (conf?.value?.err) {- throw Object.assign(new Error(`swap reverted: ${JSON.stringify(conf.value.err)}`), { signature: sig });- }+ // Confirm against the tx's OWN blockhash so expiry detection is correct (a+ // fresh getLatestBlockhash would confirm against a later, unrelated window).+ const blockhash = tx.message.recentBlockhash;+ const lastValidBlockHeight = (await connection.getBlockHeight('confirmed')) + 150;+ await confirmOrThrow(connection, { signature: sig, blockhash, lastValidBlockHeight }, 'confirmed');return sig;}@@ -228,6 +245,16 @@ export async function refuelMasterFromUsdc({ connection, deficitSol, network = 'if (!decision.act) return { ...base, acted: false, reason: decision.reason };+ // Anti-double-swap: a fresh swap within the cooldown means a previous tick+ // already refueled and the SOL just has not propagated to the balance read yet.+ // Skip rather than stack a second swap on top of it.+ if (!dryRun) {+ const sinceLast = await secondsSinceLastSwap();+ if (sinceLast < FUEL_COOLDOWN_S) {+ return { ...base, acted: false, reason: 'cooldown', secondsSinceLastSwap: Math.round(sinceLast) };+ }+ }+const amountAtomics = BigInt(Math.floor(decision.spendUsd * 10 ** USDC_DECIMALS));base.plannedUsd = round(Number(amountAtomics) / 10 ** USDC_DECIMALS);@@ -253,14 +280,24 @@ export async function refuelMasterFromUsdc({ connection, deficitSol, network = 'const tx = await buildSwapTx({ quote, userPublicKey: master.publicKey });const signature = await signSendConfirm(connection, tx, master);- await sql`- INSERT INTO economy_fuel_swaps (day, usdc_atomics, sol_lamports, price_impact, signature, network)- VALUES ((now() AT TIME ZONE 'utc')::date, ${amountAtomics.toString()}, ${outLamports}, ${priceImpactPct}, ${signature}, ${network})- `.catch(() => {});+ // Record the swap: this row IS the daily-cap counter, so a dropped write could+ // let the next tick overspend. Never fail the (already-settled) swap for it, but+ // surface a miss loudly instead of swallowing it; the cooldown still bounds a+ // same-minute repeat even if this row is missing.+ let recorded = true;+ try {+ await sql`+ INSERT INTO economy_fuel_swaps (day, usdc_atomics, sol_lamports, price_impact, signature, network)+ VALUES ((now() AT TIME ZONE 'utc')::date, ${amountAtomics.toString()}, ${outLamports}, ${priceImpactPct}, ${signature}, ${network})`;+ } catch (e) {+ recorded = false;+ console.warn(`[economy-fuel] swap ${signature} settled but its ledger row was NOT written: ${e?.message}`);+ }return {...base,acted: true,+ recorded,signature,boughtSol: round(outLamports / LAMPORTS_PER_SOL),spentUsd: base.plannedUsd,@@ -268,6 +305,50 @@ export async function refuelMasterFromUsdc({ connection, deficitSol, network = '};}+/**+ * Read-only fuel status for the ops/health surface: config, today's spend against+ * the cap, and the most recent swaps. No RPC, no keys; safe for a health scrape.+ * @param {{limit?:number}} [opts]+ */+export async function fuelStatus({ limit = 5 } = {}) {+ const out = {+ enabled: FUEL_ENABLED,+ caps: {+ per_run_usd: FUEL_PER_RUN_USDC,+ daily_usd: FUEL_DAILY_USDC,+ usdc_keep: FUEL_USDC_KEEP,+ min_gap_sol: FUEL_MIN_GAP_SOL,+ target_sol: FUEL_TARGET_SOL,+ max_impact_pct: FUEL_MAX_IMPACT_PCT,+ cooldown_s: FUEL_COOLDOWN_S,+ },+ today_usd: 0,+ daily_remaining_usd: FUEL_DAILY_USDC,+ recent: [],+ };+ try {+ await ensureSchema();+ out.today_usd = round(await usdcSpentTodayUsd());+ out.daily_remaining_usd = round(Math.max(0, FUEL_DAILY_USDC - out.today_usd));+ const rows = await sql`+ SELECT created_at, usdc_atomics::text AS usdc_atomics, sol_lamports::text AS sol_lamports,+ price_impact, signature+ FROM economy_fuel_swaps+ ORDER BY created_at DESC+ LIMIT ${Math.max(1, Math.min(50, limit))}`;+ out.recent = rows.map((r) => ({+ at: r.created_at,+ usd: round(Number(r.usdc_atomics) / 10 ** USDC_DECIMALS),+ sol: round(Number(r.sol_lamports) / LAMPORTS_PER_SOL),+ price_impact_pct: r.price_impact == null ? null : Number(r.price_impact),+ signature: r.signature,+ }));+ } catch {+ /* not-yet-migrated table ⇒ empty status, same as the health endpoint's other guards */+ }+ return out;+}+function round(n) {return Math.round(n * 1e9) / 1e9;}diff --git a/api/_lib/migrations/20260717230000_economy_fuel_swaps.sql b/api/_lib/migrations/20260717230000_economy_fuel_swaps.sqlnew file mode 100644index 000000000..6b7677a52--- /dev/null+++ b/api/_lib/migrations/20260717230000_economy_fuel_swaps.sql@@ -0,0 +1,24 @@+-- economy_fuel_swaps: the record of every USDC -> SOL auto-refuel the economy+-- master performs to keep the circulation engine funded (api/_lib/economy-fuel.js).+--+-- This table IS the per-UTC-day spend counter that bounds the refuel, so it must+-- exist before the first swap. The module also creates it lazily (CREATE TABLE IF+-- NOT EXISTS) as a safety net for environments where migrations lag, mirroring the+-- circulation_actions / economy ledger pattern; this migration is the canonical+-- definition and keeps db:check honest.++CREATE TABLE IF NOT EXISTS economy_fuel_swaps (+ id bigserial PRIMARY KEY,+ day date NOT NULL,+ usdc_atomics bigint NOT NULL,+ sol_lamports bigint NOT NULL,+ price_impact numeric,+ signature text,+ network text NOT NULL DEFAULT 'mainnet',+ created_at timestamptz NOT NULL DEFAULT now()+);++-- The daily-cap sum filters on `day`; the cooldown / recent-swaps read orders by+-- created_at. Index both access paths.+CREATE INDEX IF NOT EXISTS economy_fuel_swaps_day_idx ON economy_fuel_swaps (day);+CREATE INDEX IF NOT EXISTS economy_fuel_swaps_created_idx ON economy_fuel_swaps (created_at DESC);diff --git a/api/admin/circulation-health.js b/api/admin/circulation-health.jsindex 2898fb8b4..2e21eb21d 100644--- a/api/admin/circulation-health.js+++ b/api/admin/circulation-health.js@@ -20,6 +20,7 @@ import { cors, json, method, wrap } from '../_lib/http.js';import { env } from '../_lib/env.js';import { constantTimeEquals } from '../_lib/crypto.js';import { config as circulationConfig } from '../_lib/circulation.js';+import { fuelStatus } from '../_lib/economy-fuel.js';// pulse-tick runs every 2 min. A tick that returns early (disabled, pool warming,// treasury too low) logs nothing, so a gap can mean either the cron is down OR the@@ -51,7 +52,7 @@ export default wrap(async (req, res) => {// One pass over the 24h ledger: per (kind, status) counts, the latest event time,// and the most recent human-readable problem reason for the failing rows. The// `.catch` guards a not-yet-migrated table the same way pump-cron-health does.- const [byKindStatus, liveness, pool] = await Promise.all([+ const [byKindStatus, liveness, pool, quarantined, fuel] = await Promise.all([sql`select kind, status, count(*)::int as n, max(created_at) as last_at,(array_agg(coalesce(nullif(detail->>'reason',''), nullif(detail->>'error',''))@@ -71,7 +72,14 @@ export default wrap(async (req, res) => {sql`select count(*)::int as n from agent_identitieswhere (meta->>'circulation') = 'true' and deleted_at is null+ and coalesce((meta->>'circulation_key_broken')::boolean, false) = false`.catch(() => [{}]),+ sql`+ select count(*)::int as n from agent_identities+ where (meta->>'circulation') = 'true' and deleted_at is null+ and coalesce((meta->>'circulation_key_broken')::boolean, false) = true+ `.catch(() => [{}]),+ fuelStatus({ limit: 5 }).catch(() => null),]);// Fold the (kind, status) rows into one record per kind.@@ -123,6 +131,20 @@ export default wrap(async (req, res) => {warnings.push(`${k}: 0 ok / ${s.skipped} skipped / ${s.error} error in 24h — last: ${s.last_problem || 'no reason recorded'}`);}}+ const quarantinedCount = num(quarantined[0]?.n);+ if (quarantinedCount > 0) {+ warnings.push(+ `${quarantinedCount} agent(s) quarantined for unrecoverable custodial keys; their wallets were encrypted under a rotated WALLET_ENCRYPTION_KEY and are excluded from the pool.`,+ );+ }+ // Fuel is the SOL source of last resort. Flag it when it is off (the feed can+ // then only run on manually-topped SOL) or when today's cap is spent while the+ // engine is still starving.+ if (fuel && !fuel.enabled) {+ warnings.push('Economy fuel (USDC→SOL auto-refuel) is disabled; a drained funding root will stall the feed until SOL is added by hand.');+ } else if (fuel && fuel.daily_remaining_usd <= 0 && cfg.enabled && stale) {+ warnings.push('Economy fuel daily cap is spent and the feed is stale; raise ECONOMY_FUEL_DAILY_USDC or add SOL to the master.');+ }return json(res, 200, {now: new Date().toISOString(),@@ -135,6 +157,8 @@ export default wrap(async (req, res) => {actions_per_tick: cfg.actionsPerTick,},pool_size: num(pool[0]?.n),+ quarantined_agents: quarantinedCount,+ fuel,liveness: {last_action_at: lastActionAt,minutes_since: minutesSince,diff --git a/docs/economy-master.md b/docs/economy-master.mdindex 1a4bfca6f..ec4ae4269 100644--- a/docs/economy-master.md+++ b/docs/economy-master.md@@ -139,9 +139,19 @@ destination lock:page is suppressed — the shortage is being handled autonomously; the next tickdistributes the freshly-bought SOL.+The swap confirms through the platform's HTTP-polling confirmer+([`api/_lib/solana/confirm.js`](../api/_lib/solana/confirm.js)) bound to the+transaction's own blockhash, and a landed-but-reverted swap throws rather than+being booked. A per-swap cooldown (`ECONOMY_FUEL_COOLDOWN_S`) plus the on-chain+daily-cap read together stop two overlapping topup ticks from double-swapping.+Set `ECONOMY_FUEL_ENABLED=0` to turn it off entirely (the fleet then falls back tothe "fund the master" ops alert). The decision/sizing math is a pure function(`planRefuel`) covered by [`tests/economy-fuel.test.js`](../tests/economy-fuel.test.js).+Live fuel state (today's spend against the cap, recent swaps, quarantined agents)+is exposed on [`/api/admin/circulation-health`](../api/admin/circulation-health.js)+alongside the circulation rails. The table is defined by migration+`20260717230000_economy_fuel_swaps.sql` (and created lazily as a safety net).## Lowest fees@@ -163,6 +173,7 @@ congestion, clamped to a hard ceiling.| `ECONOMY_FUEL_USDC_KEEP` | no | USDC the refuel never spends below (revenue reserve). Default 0. || `ECONOMY_FUEL_MIN_GAP_SOL` / `_TARGET_SOL` | no | Only refuel when the SOL gap is at least this (default 0.1); buy toward this spendable-SOL buffer (default 1.0). || `ECONOMY_FUEL_MAX_IMPACT_PCT` / `_SLIPPAGE_BPS` | no | Reject a route above this price impact (default 3%); swap slippage (default 100 bps). |+| `ECONOMY_FUEL_COOLDOWN_S` | no | Minimum seconds between fuel swaps (default 90), a belt against a double-swap when two topup ticks overlap. || `CRON_SECRET` | yes | Bearer auth for the `treasury-topup` cron (shared with every other cron; Cloud Scheduler sends it). || `SOLANA_RPC_URL` | no | Mainnet RPC (defaults to `api.mainnet-beta`). |