Skip to content

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.

fix(vaults): reserve the rolling 24h buy budget atomically instead of read-then-write

nirholas9c140c201e66
diff --git a/api/_lib/vault-store.js b/api/_lib/vault-store.js
index 02238abd2..f3a01a43c 100644
--- a/api/_lib/vault-store.js
+++ b/api/_lib/vault-store.js
@@ -198,18 +198,83 @@ export async function listVaultEvents(vaultId, { limit = 50, beforeId = null, ty
`;
}
-/** Rolling 24h confirmed buy spend (USDC atomics) — the daily-budget denominator. */
+/**
+ * Rolling 24h buy spend (USDC atomics) — the daily-budget denominator.
+ *
+ * Counts settled AND in-flight buys. A buy that has been claimed but not yet
+ * confirmed on-chain has already committed the vault's capital, so leaving it out
+ * (as this did until the 2026-08-06 review, L5) let two concurrent buys read the
+ * same pre-spend total and both pass a budget only one of them fit in. The
+ * authoritative gate is claimVaultBuyBudget below, which reserves under a lock;
+ * this read is for display and for the pre-flight message.
+ */
export async function getDailyTradeSpend(vaultId) {
const [r] = await sql`
SELECT COALESCE(SUM((meta->>'usdc_in')::numeric), 0) AS spent
FROM vault_events
- WHERE vault_id = ${vaultId} AND type = 'trade' AND status = 'ok'
+ WHERE vault_id = ${vaultId} AND type = 'trade' AND status IN ('ok', 'pending')
AND (meta->>'side') = 'buy'
AND created_at > now() - interval '24 hours'
`;
return r?.spent ?? '0';
}
+/**
+ * Atomically claim rolling-24h budget headroom for a buy AND reserve its pending
+ * ledger row, under a per-vault advisory lock.
+ *
+ * Check-then-insert was two statements, so two owner buys racing on one vault
+ * could both read the same pre-spend total, both clear the budget, and both
+ * settle: a $X/day ceiling became $X + one trade. Here the sum and the insert are
+ * one statement behind `pg_advisory_xact_lock`, mirroring reserveSpendUsd in
+ * agent-trade-guards.js, so the second buy sees the first one's pending row.
+ *
+ * @returns {Promise<{ ok: true, claimId: number, spentBefore: string }
+ * | { ok: false, reason: 'daily_budget'|'in_flight', spentBefore?: string }>}
+ */
+export async function claimVaultBuyBudget({
+ vaultId, userId, idempotencyKey, usdcInAtomics, dailyBudgetAtomics, reason, meta,
+}) {
+ const amount = String(usdcInAtomics);
+ // A non-positive budget means "no ceiling configured" (same reading as
+ // tradeExceedsDailyBudget), so the claim only has to clear idempotency.
+ const budget = String(dailyBudgetAtomics ?? 0);
+ const rows = await sql`
+ WITH locked AS (
+ SELECT pg_advisory_xact_lock(hashtextextended(${String(vaultId)}, 0))
+ ),
+ spent AS (
+ SELECT COALESCE(SUM((meta->>'usdc_in')::numeric), 0) AS s
+ FROM vault_events
+ WHERE vault_id = ${vaultId} AND type = 'trade' AND status IN ('ok', 'pending')
+ AND (meta->>'side') = 'buy'
+ AND created_at > now() - interval '24 hours'
+ )
+ INSERT INTO vault_events
+ (vault_id, type, user_id, atomics_delta, status, reason, idempotency_key, meta)
+ SELECT ${vaultId}, 'trade', ${userId ?? null}, ${`-${amount}`}, 'pending', ${reason ?? null},
+ ${idempotencyKey ?? null}, ${JSON.stringify(meta ?? {})}::jsonb
+ FROM spent, locked
+ WHERE ${budget}::numeric <= 0
+ OR spent.s + ${amount}::numeric <= ${budget}::numeric
+ ON CONFLICT (vault_id, idempotency_key) WHERE idempotency_key IS NOT NULL DO NOTHING
+ RETURNING id, (SELECT s FROM spent)::text AS spent_before
+ `;
+ if (rows.length) {
+ return { ok: true, claimId: Number(rows[0].id), spentBefore: rows[0].spent_before ?? '0' };
+ }
+ // No row: either the budget rejected it or this idempotency key already claimed
+ // one. Distinguish the two so the caller reports the real reason.
+ if (idempotencyKey) {
+ const [dupe] = await sql`
+ SELECT id FROM vault_events
+ WHERE vault_id = ${vaultId} AND idempotency_key = ${idempotencyKey} LIMIT 1
+ `;
+ if (dupe) return { ok: false, reason: 'in_flight' };
+ }
+ return { ok: false, reason: 'daily_budget', spentBefore: await getDailyTradeSpend(vaultId) };
+}
+
/** Upsert a backer's position after a deposit (mint shares) or redemption (burn). */
export async function applyBackerDelta({ vaultId, userId, backerAgentId, sharesDelta, basisDelta, depositedDelta = 0n, redeemedDelta = 0n, realizedGainDelta = 0n, feesPaidDelta = 0n }) {
const [row] = await sql`
diff --git a/api/_lib/vault-trade.js b/api/_lib/vault-trade.js
index d262f17bf..5acf15bd4 100644
--- a/api/_lib/vault-trade.js
+++ b/api/_lib/vault-trade.js
@@ -19,7 +19,7 @@ import { confirmOrThrow } from './solana/confirm.js';
import { logAudit } from './audit.js';
import { explorerTxUrl } from './avatar-wallet.js';
import {
- getVaultWithSecret, getOpenPositions, getDailyTradeSpend,
+ getVaultWithSecret, getOpenPositions, getDailyTradeSpend, claimVaultBuyBudget,
recordVaultEvent, updateVaultEvent, applyVaultShareDelta, setVaultStatus,
upsertPosition, reducePosition,
} from './vault-store.js';
@@ -148,6 +148,8 @@ export async function vaultTrade({ vaultId, userId, side, mint, usdcInAtomics, a
if (tradeExceedsPerTrade(amount, vault.max_per_trade_atomics)) {
return blocked('per_trade_cap', 'exceeds the vault per-trade ceiling', { max_per_trade_atomics: String(vault.max_per_trade_atomics) });
}
+ // Pre-flight only, for a fast and specific rejection. The binding check is
+ // the atomic claim below, which reserves the headroom under a per-vault lock.
const spent = await getDailyTradeSpend(vault.id);
if (tradeExceedsDailyBudget(spent, amount, vault.daily_budget_atomics)) {
return blocked('daily_budget', 'exceeds the vault rolling 24h budget', { spent_atomics: String(spent), daily_budget_atomics: String(vault.daily_budget_atomics) });
@@ -184,14 +186,36 @@ export async function vaultTrade({ vaultId, userId, side, mint, usdcInAtomics, a
price_impact_pct: q.priceImpactPct,
...(side === 'buy' ? { usdc_in: String(toBig(usdcInAtomics)), expected_out_raw: String(q.expectedOutRaw) } : { sell_raw: String(sellRaw), expected_usdc_out: String(q.expectedOutAtomics) }),
};
- const claimId = await recordVaultEvent({
- vaultId: vault.id, type: 'trade', userId,
- atomicsDelta: side === 'buy' ? String(-toBig(usdcInAtomics)) : null,
- signature: null, status: 'pending', reason: `trade_${side}`,
- idempotencyKey, meta: claimMeta,
- });
- if (claimId == null) {
- return { status: 'failed', code: 'in_flight', message: 'a trade with this id is already recorded — check the ledger before retrying' };
+ let claimId;
+ if (side === 'buy') {
+ // A buy claims daily-budget headroom and its ledger row in ONE statement,
+ // so two concurrent buys can never both pass on the same stale 24h total.
+ const claim = await claimVaultBuyBudget({
+ vaultId: vault.id, userId, idempotencyKey,
+ usdcInAtomics: toBig(usdcInAtomics),
+ dailyBudgetAtomics: vault.daily_budget_atomics,
+ reason: `trade_${side}`, meta: claimMeta,
+ });
+ if (!claim.ok) {
+ if (claim.reason === 'in_flight') {
+ return { status: 'failed', code: 'in_flight', message: 'a trade with this id is already recorded, check the ledger before retrying' };
+ }
+ return blocked('daily_budget', 'exceeds the vault rolling 24h budget', {
+ spent_atomics: String(claim.spentBefore ?? '0'),
+ daily_budget_atomics: String(vault.daily_budget_atomics),
+ });
+ }
+ claimId = claim.claimId;
+ } else {
+ claimId = await recordVaultEvent({
+ vaultId: vault.id, type: 'trade', userId,
+ atomicsDelta: null,
+ signature: null, status: 'pending', reason: `trade_${side}`,
+ idempotencyKey, meta: claimMeta,
+ });
+ if (claimId == null) {
+ return { status: 'failed', code: 'in_flight', message: 'a trade with this id is already recorded, check the ledger before retrying' };
+ }
}
// ── Sign + submit the real swap ─────────────────────────────────────────────
diff --git a/docs/vaults.md b/docs/vaults.md
index 9a3928b53..6b627adce 100644
--- a/docs/vaults.md
+++ b/docs/vaults.md
@@ -165,7 +165,7 @@ Guards run **before the key is ever decrypted**, in this order:
1. Vault status must be `open` (`vault_not_open`; a paused vault must be resumed first).
2. The mint must be a real, readable mint on this network, and not USDC itself (`invalid_mint`).
3. Buy size must not exceed the per-trade ceiling (`per_trade_cap`).
-4. Buy size plus the rolling 24h spend must not exceed the daily budget (`daily_budget`).
+4. Buy size plus the rolling 24h spend must not exceed the daily budget (`daily_budget`). The 24h total counts settled AND in-flight buys, and a buy reserves its headroom in the same statement that writes its ledger row, under a per-vault lock, so two trades fired at once can never both fit into headroom only one of them had.
5. The vault must actually hold that much USDC on-chain (`insufficient_usdc`).
6. The vault must hold enough SOL for fees and account rent (`insufficient_sol_for_fees`).
7. A route must exist and be priceable (`no_route`, `quote_failed`).