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
fix(agora): hold a citizen's daily spend headroom before the escrow, not after
nirholase69ec6ff0cc3
diff --git a/api/_lib/agora-policy.js b/api/_lib/agora-policy.jsindex f5d879d52..a31006641 100644--- a/api/_lib/agora-policy.js+++ b/api/_lib/agora-policy.js@@ -131,12 +131,23 @@ async function dailySpentAtomic(citizenId, rewardMint, windowHours = 24) {}}+// How long a pre-chain hold counts against the cap. Long enough to cover the+// slowest escrow round trip (register + fund + createTask on a congested+// cluster), short enough that a process killed mid-post frees the citizen's+// headroom on its own. Nothing sweeps these: the cap sum simply ignores older+// held rows, so expiry needs no cron to be correct.+const HOLD_TTL_MINUTES = 10;+/*** Check whether a citizen may escrow `amountAtomic` for a new bounty/hire under* their per-user policy on `cluster`. Returns { ok: true, caps, spentAtomic } or- * { ok: false, status, code, message, detail } — the caller maps the failure+ * { ok: false, status, code, message, detail }: the caller maps the failure* straight to an HTTP error. Never throws for a policy decision; only a DB error* propagates.+ *+ * This is the READ-ONLY check, used for previews and for the fast rejection path.+ * A post that is about to touch the chain must use reservePostSpend() instead,+ * which takes a hold in the same statement that sums the window.*/export async function checkPostSpend({ citizenId, cluster, amountAtomic, requestedCluster }) {// Mainnet must be explicitly enabled. If the caller asked for mainnet but the@@ -183,3 +194,105 @@ export async function checkPostSpend({ citizenId, cluster, amountAtomic, requestreturn { ok: true, caps, spentAtomic: spent.toString() };}++/**+ * Reserve daily-cap headroom for a post/hire BEFORE the on-chain escrow, and+ * return the hold. Same policy decisions as checkPostSpend (mainnet gate,+ * per-task cap, rolling daily cap), but the daily check and the hold are ONE+ * statement under a per-citizen advisory lock, which is what closes the race+ * checkPostSpend alone left open (security review L6): the projection it meters+ * against is written after the chain call, so two concurrent posts could both+ * read a pre-spend total neither of them was any longer entitled to.+ *+ * The caller MUST resolve the hold: settlePostSpend() once the activity row is+ * projected (the projection then counts it), or releasePostSpend() if the escrow+ * never happened. An unresolved hold expires on its own after HOLD_TTL_MINUTES.+ *+ * @returns {Promise<{ ok: true, caps, spentAtomic: string, reservationId: string }+ * | { ok: false, status, code, message, detail? }>}+ */+export async function reservePostSpend({ citizenId, cluster, amountAtomic, requestedCluster }) {+ const pre = await checkPostSpend({ citizenId, cluster, amountAtomic, requestedCluster });+ if (!pre.ok) return pre;++ const caps = pre.caps;+ const amount = BigInt(amountAtomic).toString();+ const daily = caps.dailyAtomic.toString();+ const mint = caps.rewardMint;+ const rows = await sql`+ with locked as (+ select pg_advisory_xact_lock(hashtextextended(${String(citizenId)}, 0))+ ),+ spent as (+ select coalesce(sum(amount_atomic), 0) as s+ from agora_activity+ where citizen_id = ${citizenId}+ and kind in ('posted_task', 'hired')+ and reward_mint is not distinct from ${mint}+ and created_at > now() - interval '24 hours'+ ),+ held as (+ select coalesce(sum(amount_atomic), 0) as s+ from agora_spend_reservations+ where citizen_id = ${citizenId}+ and reward_mint is not distinct from ${mint}+ and state = 'held'+ and created_at > now() - (${HOLD_TTL_MINUTES} * interval '1 minute')+ )+ insert into agora_spend_reservations (citizen_id, amount_atomic, reward_mint)+ select ${citizenId}, ${amount}::numeric, ${mint}+ from spent, held, locked+ where spent.s + held.s + ${amount}::numeric <= ${daily}::numeric+ returning id, ((select s from spent) + (select s from held))::text as committed_before+ `;++ if (!rows.length) {+ return {+ ok: false,+ status: 403,+ code: 'daily_cap',+ message: `This would exceed your rolling 24h Agora spend cap of ${caps.daily} ${caps.asset}.`,+ detail: { daily: caps.daily, asset: caps.asset, cluster },+ };+ }+ return {+ ok: true,+ caps,+ spentAtomic: rows[0].committed_before ?? '0',+ reservationId: rows[0].id,+ };+}++/**+ * Mark a hold as settled once its activity row exists. Call it AFTER+ * projectActivity, never before: while both rows exist the spend is counted+ * twice, which is the conservative direction, whereas settling first opens a gap+ * where a concurrent post sees neither.+ */+export async function settlePostSpend(reservationId, { taskPda = null, txSignature = null } = {}) {+ if (!reservationId) return;+ await sql`+ update agora_spend_reservations+ set state = 'settled', resolved_at = now(),+ task_pda = coalesce(${taskPda}, task_pda),+ tx_signature = coalesce(${txSignature}, tx_signature)+ where id = ${reservationId} and state = 'held'+ `.catch((err) => {+ // The hold expires on its own, so a failed settle costs the citizen a few+ // minutes of headroom, never correctness. Log it rather than failing a post+ // whose escrow already landed on-chain.+ console.warn('[agora-policy] settle hold failed', { reservationId, reason: err?.message || String(err) });+ });+}++/** Release a hold whose escrow never happened, freeing the headroom immediately. */+export async function releasePostSpend(reservationId) {+ if (!reservationId) return;+ await sql`+ update agora_spend_reservations+ set state = 'released', resolved_at = now()+ where id = ${reservationId} and state = 'held'+ `.catch((err) => {+ console.warn('[agora-policy] release hold failed', { reservationId, reason: err?.message || String(err) });+ });+}diff --git a/api/_lib/migrations/20260806120000_agora_spend_reservations.sql b/api/_lib/migrations/20260806120000_agora_spend_reservations.sqlnew file mode 100644index 000000000..c4421d086--- /dev/null+++ b/api/_lib/migrations/20260806120000_agora_spend_reservations.sql@@ -0,0 +1,40 @@+-- Agora: pre-chain spend holds, so the rolling 24h cap cannot be raced.+--+-- checkPostSpend metered a citizen against agora_activity, which is the+-- PROJECTION written AFTER the on-chain escrow succeeds. Between the check and+-- that write there was a window (an RPC round trip wide) in which a second post+-- read the same total and also passed: two concurrent posts by one citizen could+-- each clear a cap only one of them fit under.+--+-- A reservation is taken BEFORE the chain call, inside the same statement that+-- sums the window, under a per-citizen advisory lock. It counts toward the cap+-- while held, is marked settled once the activity row lands (and the projection+-- takes over the counting), and is released when the escrow fails.+--+-- Holds also expire: the cap sum only counts rows younger than the hold TTL, so a+-- process that dies between reserving and settling parks a citizen's headroom for+-- minutes, never permanently, and no sweeper is required for correctness.++create table if not exists agora_spend_reservations (+ id uuid primary key default gen_random_uuid(),+ citizen_id uuid not null references agora_citizens(id) on delete cascade,+ -- The reward being escrowed, in the cluster's atomic units (lamports on+ -- devnet, $THREE atomics on mainnet).+ amount_atomic numeric not null check (amount_atomic > 0),+ -- Matches agora_activity.reward_mint: '$THREE' on mainnet, null (native SOL)+ -- on devnet, so a devnet hold never eats a mainnet cap.+ reward_mint text,+ -- held: counting against the cap. settled: the activity row now counts it.+ -- released: the escrow never happened.+ state text not null default 'held' check (state in ('held', 'settled', 'released')),+ -- What it turned into, for the audit trail. Set on settle.+ task_pda text,+ tx_signature text,+ created_at timestamptz not null default now(),+ resolved_at timestamptz+);++-- The cap sum: held rows for one citizen in one asset, newest window only.+create index if not exists agora_spend_reservations_open+ on agora_spend_reservations (citizen_id, reward_mint, created_at)+ where state = 'held';diff --git a/api/agora/act.js b/api/agora/act.jsindex a25fc8623..253de4d0b 100644--- a/api/agora/act.js+++ b/api/agora/act.js@@ -30,7 +30,7 @@ import {PROFESSION_BITS, THREE_ATOMICS_PER_TOKEN, rewardLabel, proofHashFor,sendOnchainAttestation, explorerTx,} from '../_lib/agora-human.js';-import { resolveCluster, checkPostSpend } from '../_lib/agora-policy.js';+import { resolveCluster, reservePostSpend, settlePostSpend, releasePostSpend } from '../_lib/agora-policy.js';import { redactUrlSecrets as redactSecrets } from '../_lib/scrub-secrets.js';const LAMPORTS_PER_SOL = 1_000_000_000n;@@ -173,100 +173,118 @@ async function postTaskCore({ user, body, requestedCluster, hire }) {// Per-user spend policy + mainnet gate (server-side, ledger-backed).const { citizen } = await ensureHumanCitizen({ user, cluster });- const policy = await checkPostSpend({ citizenId: citizen.id, cluster, amountAtomic, requestedCluster });+ // Reserve the daily-cap headroom BEFORE the chain call. The projection this+ // cap meters against is only written after the escrow lands, so a plain check+ // left a window in which two concurrent posts could both spend the same+ // headroom (security review L6). The hold counts until the projection takes+ // over, and the finally below frees it on every path that never escrows.+ const policy = await reservePostSpend({ citizenId: citizen.id, cluster, amountAtomic, requestedCluster });if (!policy.ok) return { err: [policy.status, policy.code, policy.message, policy.detail] };-- // Register on-chain (lazy) + fund the reward escrow on devnet.- const reg = await ensureRegistered({ citizen, cluster });- const { PublicKey } = await import('@solana/web3.js');-- const createArgs = {- creatorAgentId: reg.agentId,- requiredCapabilities: professionToCapabilityBits(profession),- description: description || title,- rewardAmount: amountAtomic,- maxWorkers: 1,- deadline: Math.floor(Date.now() / 1000) + Math.max(1, Math.min(720, Number(body.deadlineHours) || 24)) * 3600,- taskType: 'Exclusive',- minReputation,- };-- if (cluster === 'mainnet') {- const { getAssociatedTokenAddressSync } = await import('@solana/spl-token');- createArgs.rewardMint = new PublicKey(TOKEN_MINT);- createArgs.creatorTokenAccount = getAssociatedTokenAddressSync(new PublicKey(TOKEN_MINT), reg.signer.publicKey, false);- // Real money: check the $THREE the escrow will actually debit before we- // sign, so "you don't hold enough $THREE" is a designed state and not an- // SPL transfer failure surfaced as a 502.- const held = await citizenBalances(citizen, cluster).catch(() => ({ three: null }));- const needThree = Number(amountAtomic) / Number(THREE_ATOMICS_PER_TOKEN);- if (held.three != null && held.three < needThree) {- return {- err: [409, 'insufficient_funds',- `This bounty escrows ${rewardLabel(amountAtomic, cluster)} and your Agora wallet holds ${held.three.toLocaleString('en-US')} $THREE. Send $THREE to your wallet address, then post again.`,- { walletAddress: held.address, asset: '$THREE', cluster, needed: needThree, have: held.three }],- };- }- } else {- // Devnet native-SOL escrow: top up, then gate on the real balance so a- // throttled faucet reads as "fund this address", not a 500.- const needLamports = Number(amountAtomic) + 10_000_000;- await ensureDevnetBalance(reg.client.connection, reg.signer, needLamports);- await requireFunded({- connection: reg.client.connection, address: reg.signer.publicKey,- neededLamports: needLamports, cluster, purpose: 'escrow this bounty',- });- }-- const { createAgenCTask } = await import('@three-ws/solana-agent');- let created;+ const hold = policy.reservationId;+ let settled = false;try {- created = await createAgenCTask(reg.client, createArgs);- } catch (e) {- return { err: [502, 'escrow_failed', 'the bounty was not posted — no funds moved'], cause: e };- }-- const taskPda = created.taskPda.toBase58();- const taskIdHex = Buffer.from(created.taskId).toString('hex');- const label = rewardLabel(amountAtomic, cluster);- const mintLabel = cluster === 'mainnet' ? '$THREE' : null;-- const narrative = hire- ? `${citizen.display_name} hired ${target.display_name} for a ${profession} task — ${label}.`- : `${citizen.display_name} posted a ${profession} bounty — ${label}.`;+ // Register on-chain (lazy) + fund the reward escrow on devnet.+ const reg = await ensureRegistered({ citizen, cluster });+ const { PublicKey } = await import('@solana/web3.js');++ const createArgs = {+ creatorAgentId: reg.agentId,+ requiredCapabilities: professionToCapabilityBits(profession),+ description: description || title,+ rewardAmount: amountAtomic,+ maxWorkers: 1,+ deadline: Math.floor(Date.now() / 1000) + Math.max(1, Math.min(720, Number(body.deadlineHours) || 24)) * 3600,+ taskType: 'Exclusive',+ minReputation,+ };++ if (cluster === 'mainnet') {+ const { getAssociatedTokenAddressSync } = await import('@solana/spl-token');+ createArgs.rewardMint = new PublicKey(TOKEN_MINT);+ createArgs.creatorTokenAccount = getAssociatedTokenAddressSync(new PublicKey(TOKEN_MINT), reg.signer.publicKey, false);+ // Real money: check the $THREE the escrow will actually debit before we+ // sign, so "you don't hold enough $THREE" is a designed state and not an+ // SPL transfer failure surfaced as a 502.+ const held = await citizenBalances(citizen, cluster).catch(() => ({ three: null }));+ const needThree = Number(amountAtomic) / Number(THREE_ATOMICS_PER_TOKEN);+ if (held.three != null && held.three < needThree) {+ return {+ err: [409, 'insufficient_funds',+ `This bounty escrows ${rewardLabel(amountAtomic, cluster)} and your Agora wallet holds ${held.three.toLocaleString('en-US')} $THREE. Send $THREE to your wallet address, then post again.`,+ { walletAddress: held.address, asset: '$THREE', cluster, needed: needThree, have: held.three }],+ };+ }+ } else {+ // Devnet native-SOL escrow: top up, then gate on the real balance so a+ // throttled faucet reads as "fund this address", not a 500.+ const needLamports = Number(amountAtomic) + 10_000_000;+ await ensureDevnetBalance(reg.client.connection, reg.signer, needLamports);+ await requireFunded({+ connection: reg.client.connection, address: reg.signer.publicKey,+ neededLamports: needLamports, cluster, purpose: 'escrow this bounty',+ });+ }- await projectActivity({- citizenId: citizen.id,- kind: hire ? 'hired' : 'posted_task',- taskPda, taskId: taskIdHex, profession,- counterpartyCitizenId: hire ? target.id : null,- amountAtomic: amountAtomic.toString(), rewardMint: mintLabel, rewardLabel: label,- txSignature: created.txSignature, narrative,- worldX: citizen.home_x, worldZ: citizen.home_z,- meta: { minReputation, maxWorkers: 1 },- });- await bumpCitizenStats(citizen.id, { incPosted: 1, status: 'idle' });+ const { createAgenCTask } = await import('@three-ws/solana-agent');+ let created;+ try {+ created = await createAgenCTask(reg.client, createArgs);+ } catch (e) {+ return { err: [502, 'escrow_failed', 'the bounty was not posted — no funds moved'], cause: e };+ }- const { publishFeedEvent } = await import('../_lib/feed.js');- publishFeedEvent({- type: hire ? 'agora-hired' : 'agora-task-posted',- actor: citizen.display_name.slice(0, 32),- taskPda, profession, rewardLabel: label, minReputation, cluster,- }).catch(() => {});+ const taskPda = created.taskPda.toBase58();+ const taskIdHex = Buffer.from(created.taskId).toString('hex');+ const label = rewardLabel(amountAtomic, cluster);+ const mintLabel = cluster === 'mainnet' ? '$THREE' : null;++ const narrative = hire+ ? `${citizen.display_name} hired ${target.display_name} for a ${profession} task — ${label}.`+ : `${citizen.display_name} posted a ${profession} bounty — ${label}.`;++ await projectActivity({+ citizenId: citizen.id,+ kind: hire ? 'hired' : 'posted_task',+ taskPda, taskId: taskIdHex, profession,+ counterpartyCitizenId: hire ? target.id : null,+ amountAtomic: amountAtomic.toString(), rewardMint: mintLabel, rewardLabel: label,+ txSignature: created.txSignature, narrative,+ worldX: citizen.home_x, worldZ: citizen.home_z,+ meta: { minReputation, maxWorkers: 1 },+ });+ // The projection now carries this spend, so the hold can stop counting.+ // Settled AFTER the write, never before: overlapping for a moment+ // overcounts, which is the safe direction, while settling first would+ // leave a gap a racing post could slip through.+ await settlePostSpend(hold, { taskPda, txSignature: created.txSignature });+ settled = true;+ await bumpCitizenStats(citizen.id, { incPosted: 1, status: 'idle' });++ const { publishFeedEvent } = await import('../_lib/feed.js');+ publishFeedEvent({+ type: hire ? 'agora-hired' : 'agora-task-posted',+ actor: citizen.display_name.slice(0, 32),+ taskPda, profession, rewardLabel: label, minReputation, cluster,+ }).catch(() => {});- return {- ok: true,- body: {+ return {ok: true,- taskPda, taskId: taskIdHex,- txSignature: created.txSignature,- explorerUrl: explorerTx(created.txSignature, cluster),- reward: { amountAtomic: amountAtomic.toString(), label, mint: mintLabel },- profession, minReputation, cluster,- routedTo: hire ? { citizenId: target.id, name: target.display_name } : null,- taskUrl: `/api/agenc/get-task?taskPda=${taskPda}&cluster=${cluster}&lifecycle=1`,- },- };+ body: {+ ok: true,+ taskPda, taskId: taskIdHex,+ txSignature: created.txSignature,+ explorerUrl: explorerTx(created.txSignature, cluster),+ reward: { amountAtomic: amountAtomic.toString(), label, mint: mintLabel },+ profession, minReputation, cluster,+ routedTo: hire ? { citizenId: target.id, name: target.display_name } : null,+ taskUrl: `/api/agenc/get-task?taskPda=${taskPda}&cluster=${cluster}&lifecycle=1`,+ },+ };+ } finally {+ // Anything that returned or threw without escrowing gives the headroom back+ // immediately rather than waiting for the hold to age out.+ if (!settled) await releasePostSpend(hold);+ }}// ── action handlers ───────────────────────────────────────────────────────────diff --git a/docs/agora.md b/docs/agora.mdindex 918e6e552..a9b13b4fc 100644--- a/docs/agora.md+++ b/docs/agora.md@@ -310,7 +310,10 @@ simulation).[api/_lib/agora-policy.js](../api/_lib/agora-policy.js), the `src/agora/me-hud.js`+ `post-form.js` + `actions.js` HUD). Every action is server-side, authenticated,input-validated, idempotent, and spend-capped; mainnet $THREE stays gated behind- explicit opt-in. A matching **Verify** offers a **one-click vouch** for the+ explicit opt-in. The rolling 24h cap is enforced by a pre-chain hold+ (`agora_spend_reservations`): the sum and the hold are one statement under a+ per-citizen lock, so two posts fired at once cannot both spend headroom only+ one of them had, and an abandoned hold ages out on its own. A matching **Verify** offers a **one-click vouch** for thecitizen who produced the deliverable (verify.js → `agora:vouch-prompt` → the HUD'sreal on-chain attestation) — you can only attest to work you actually confirmed.diff --git a/tests/agora-humans.test.js b/tests/agora-humans.test.jsindex f3ea18430..c28c8e479 100644--- a/tests/agora-humans.test.js+++ b/tests/agora-humans.test.js@@ -10,7 +10,7 @@import { describe, it, expect, beforeEach, afterEach } from 'vitest';import {- resolveCluster, mainnetEnabled, spendCaps, checkPostSpend,+ resolveCluster, mainnetEnabled, spendCaps, checkPostSpend, reservePostSpend,} from '../api/_lib/agora-policy.js';import {professionToCapabilityBits, PROFESSION_BITS, rewardLabel, proofHashFor,@@ -97,6 +97,36 @@ describe('agora-policy: checkPostSpend boundary rejections (no DB)', () => {});});+describe('agora-policy: reservePostSpend rejects before it ever holds (no DB)', () => {+ const saved = process.env.AGORA_MAINNET_ENABLED;+ afterEach(() => { process.env.AGORA_MAINNET_ENABLED = saved; });++ // The hold is the thing that makes the daily cap race-proof, so a rejected+ // post must be rejected by the SAME rules as the read-only check and must+ // never reach the insert (these cases return before any DB call, which is+ // exactly what lets them run without DATABASE_URL).+ it('applies the mainnet gate before reserving', async () => {+ delete process.env.AGORA_MAINNET_ENABLED;+ const r = await reservePostSpend({ citizenId: 'c1', cluster: 'devnet', amountAtomic: 1n, requestedCluster: 'mainnet' });+ expect(r.ok).toBe(false);+ expect(r.code).toBe('mainnet_disabled');+ });++ it('applies the per-task cap before reserving', async () => {+ delete process.env.AGORA_MAINNET_ENABLED;+ const r = await reservePostSpend({ citizenId: 'c1', cluster: 'devnet', amountAtomic: LAMPORTS_PER_SOL, requestedCluster: 'devnet' });+ expect(r.ok).toBe(false);+ expect(r.code).toBe('per_task_cap');+ });++ it('rejects a non-positive reward before reserving', async () => {+ delete process.env.AGORA_MAINNET_ENABLED;+ const r = await reservePostSpend({ citizenId: 'c1', cluster: 'devnet', amountAtomic: 0n, requestedCluster: 'devnet' });+ expect(r.ok).toBe(false);+ expect(r.code).toBe('validation_error');+ });+});+describe('agora-human: profession bitmap (open registry, mirrors docs)', () => {it('maps each profession to its documented bit', () => {expect(professionToCapabilityBits('fetcher')).toBe(1n); // bit 0