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(spend): reserve strategy-run buys atomically so concurrent runs cannot both pass the daily SOL cap
nirholasbf3b376ca095
diff --git a/api/_lib/agent-spend-policy.js b/api/_lib/agent-spend-policy.jsindex 3571555fc..db931dba8 100644--- a/api/_lib/agent-spend-policy.js+++ b/api/_lib/agent-spend-policy.js@@ -169,3 +169,34 @@ export async function releaseSpend(reservationId) {DELETE FROM agent_actions WHERE id = ${reservationId}`.catch((e) => console.error('[spend-policy] release failed', e));}++// Per-run spend guard for strategy-run live buys. `guard` reserves the buy+// atomically (reserveSpend) before the trade; `settle` finalizes the reservation+// with the signature when the buy lands, or releases it when it fails. The+// reserved row is the buy's agent_actions record, so the runtime must not+// persist a second pumpfun.buy row for the same trade.+export function createStrategySpendGuard({ agentId, meta }) {+ const open = new Map();+ return {+ async guard({ mint, amountSol }) {+ const r = await reserveSpend({+ agentId,+ meta,+ mint,+ solAmount: amountSol,+ type: 'pumpfun.buy',+ payload: { source: 'strategy_run', amountSol: Number(amountSol) || 0 },+ });+ if (!r.ok) return { code: r.code, msg: r.msg };+ open.set(mint, r.reservationId);+ return null;+ },+ async settle({ mint, ok, sig }) {+ const id = open.get(mint);+ if (!id) return;+ open.delete(mint);+ if (ok) await finalizeSpend(id, { mint, sig: sig ?? null });+ else await releaseSpend(id);+ },+ };+}diff --git a/api/_lib/skill-runtime.js b/api/_lib/skill-runtime.jsindex ed84f217a..7c8f0d403 100644--- a/api/_lib/skill-runtime.js+++ b/api/_lib/skill-runtime.js@@ -109,11 +109,12 @@ async function serverFetch(input, init) {* @param {(event: object) => void} [opts.onEvent] - notified on every memory.note call* @param {object} [opts.fetch] - fetch impl (defaults to serverFetch: in-process for /api/pump-fun-mcp, APP_ORIGIN for other relative paths)* @param {string} [opts.agentId] - if set, every memory.note is persisted to agent_actions+ * @param {(skillName: string, tag: string) => boolean} [opts.shouldPersist] - return false to skip persisting a note (caller records it itself)* @param {string} [opts.signerAddress] - persisted with each agent_actions row when agentId is set* @param {Record<string, { skill_id: string, author_id: string }>} [opts.skillMeta] - DB-sourced royalty metadata keyed by skill name*/export function makeRuntime(opts = {}) {- const { configOverrides = {}, wallet, onEvent, fetch = serverFetch, agentId, signerAddress, skillMeta = {} } = opts;+ const { configOverrides = {}, wallet, onEvent, fetch = serverFetch, agentId, signerAddress, skillMeta = {}, shouldPersist = null } = opts;let _sql;// Map skill-internal tags to canonical action types so existing// aggregations (spend-policy, portfolio cost-basis) keep working.@@ -129,6 +130,7 @@ export function makeRuntime(opts = {}) {async function persistAction(skillName, tag, value) {if (!agentId) return;+ if (shouldPersist && !shouldPersist(skillName, tag)) return;try {if (!_sql) _sql = (await import('./db.js')).sql;await _sql`diff --git a/api/pump/[action].js b/api/pump/[action].jsindex b7dc8e4d4..fe061f369 100644--- a/api/pump/[action].js+++ b/api/pump/[action].js@@ -137,7 +137,7 @@ import { makeRuntime } from '../_lib/skill-runtime.js';import { loadWallet } from '../_lib/solana-wallet.js';import { requireRealFundsAgreement, currentSignatureFor } from '../_lib/real-funds-agreement.js';import {- checkBuyAllowed,+ createStrategySpendGuard,reserveSpend,finalizeSpend,releaseSpend,@@ -3842,10 +3842,15 @@ async function handleStrategyRun(req, res) {aborted = true;});+ const spendGuard =+ mode === 'live' ? createStrategySpendGuard({ agentId: body.agentId, meta: agentMeta }) : null;const rt = makeRuntime({wallet,agentId: mode === 'live' ? body.agentId : undefined,signerAddress: walletAddress,+ // Live buys are recorded by the spend reservation (finalizeSpend), so the+ // runtime must not persist a second pumpfun.buy row for the same trade.+ shouldPersist: (skillName, tag) => !(spendGuard && skillName === 'pump-fun-trade' && tag === 'pump-fun-trade:buy'),configOverrides: {'pump-fun-trade': { rpc: RPC[network] },'solana-wallet': { rpc: RPC[network] },@@ -3863,18 +3868,8 @@ async function handleStrategyRun(req, res) {wallet,};- const policyGuard =- mode === 'live'- ? async ({ mint, amountSol }) => {- const block = await checkBuyAllowed({- agentId: body.agentId,- meta: agentMeta,- mint,- solAmount: amountSol,- });- return block ? { code: block.code, msg: block.msg } : null;- }- : null;+ const policyGuard = spendGuard ? spendGuard.guard : null;+ const policySettle = spendGuard ? spendGuard.settle : null;const abortController = new AbortController();req.on('close', () => abortController.abort());@@ -3889,6 +3884,7 @@ async function handleStrategyRun(req, res) {if (!aborted) send('log', entry);},policyGuard,+ policySettle,abortSignal: abortController.signal,},ctx,diff --git a/examples/skills/pump-fun-strategy/handlers.js b/examples/skills/pump-fun-strategy/handlers.jsindex 6bb90b799..556216eb5 100644--- a/examples/skills/pump-fun-strategy/handlers.js+++ b/examples/skills/pump-fun-strategy/handlers.js@@ -154,6 +154,7 @@ export async function runStrategy(args, ctx) {const onLog = typeof args.onLog === 'function' ? args.onLog : () => {};// Optional async guard: returns null to allow, or { code, msg } to block.const policyGuard = typeof args.policyGuard === 'function' ? args.policyGuard : null;+ const policySettle = typeof args.policySettle === 'function' ? args.policySettle : null;// Optional abort signal: when set, the loop terminates at the next safe point.const abortSignal = args.abortSignal ?? null;@@ -218,6 +219,7 @@ export async function runStrategy(args, ctx) {}try {const buy = await maybeBuy(ctx, simulate, mint, perTrade);+ if (policySettle && !simulate) await policySettle({ mint, ok: true, sig: buy.sig });spent += perTrade;positions.set(mint, {amountTokens: buy.amountTokens ?? 0,@@ -227,6 +229,7 @@ export async function runStrategy(args, ctx) {emit({ mint, action: 'enter', sig: buy.sig, spent, entryPriceSol: snap.curve?.priceSol ?? 0 });if (spent + perTrade > cap) break;} catch (e) {+ if (policySettle && !simulate) await policySettle({ mint, ok: false }).catch(() => {});emit({ mint, action: 'enter-error', error: e.message });}}diff --git a/tests/spend-policy-strategy-reserve.test.js b/tests/spend-policy-strategy-reserve.test.jsnew file mode 100644index 000000000..fe691ee37--- /dev/null+++ b/tests/spend-policy-strategy-reserve.test.js@@ -0,0 +1,69 @@+// Regression: strategy-run live buys must reserve against the daily SOL cap+// atomically. The old read-only checkBuyAllowed gate let two concurrent runs+// both read the same 24h total and both pass. No funds move here: PGlite only.++import { beforeAll, describe, it, expect, vi } from 'vitest';+import { createPgliteSql } from './_helpers/pglite-sql.js';++const holder = vi.hoisted(() => ({ db: null }));++vi.mock('../api/_lib/db.js', async (importActual) => {+ const actual = await importActual();+ const sql = (...args) => holder.db.sql(...args);+ sql.transaction = async (queries) => {+ const out = [];+ for (const q of queries) out.push(await q);+ return out;+ };+ return { ...actual, sql };+});++process.env.DATABASE_URL ||= 'postgres://pglite.test/db';++const AGENT = '00000000-0000-0000-0000-000000000031';+const META = { spend_policy: { max_sol_per_tx: 4, daily_sol_cap: 5 } };++async function rows() {+ return holder.db.query(+ `select type, payload from agent_actions where agent_id = $1 order by created_at`,+ [AGENT],+ );+}++beforeAll(async () => {+ holder.db = createPgliteSql();+ await holder.db.exec(`create table agent_actions (+ id uuid primary key default gen_random_uuid(), agent_id uuid, type text, payload jsonb,+ source_skill text, signature text, signer_address text, created_at timestamptz default now());`);+});++describe('strategy spend guard reserves atomically', () => {+ it('lets only one of two concurrent 3 SOL buys through a 5 SOL daily cap', async () => {+ const { createStrategySpendGuard } = await import('../api/_lib/agent-spend-policy.js');+ const a = createStrategySpendGuard({ agentId: AGENT, meta: META });+ const b = createStrategySpendGuard({ agentId: AGENT, meta: META });+ const [ra, rb] = await Promise.all([+ a.guard({ mint: 'THREEsyntheticMintA', amountSol: 3 }),+ b.guard({ mint: 'THREEsyntheticMintB', amountSol: 3 }),+ ]);+ const blocked = [ra, rb].filter(Boolean);+ expect(blocked).toHaveLength(1);+ expect(blocked[0].code).toBe('daily_cap_exceeded');+ expect((await rows()).length).toBe(1);+ });++ it('finalizes the reservation on success and releases it on failure', async () => {+ const { createStrategySpendGuard } = await import('../api/_lib/agent-spend-policy.js');+ await holder.db.query(`delete from agent_actions`);+ const g = createStrategySpendGuard({ agentId: AGENT, meta: META });+ expect(await g.guard({ mint: 'THREEsyntheticMintC', amountSol: 2 })).toBeNull();+ expect(await g.guard({ mint: 'THREEsyntheticMintD', amountSol: 2 })).toBeNull();+ await g.settle({ mint: 'THREEsyntheticMintC', ok: true, sig: 'sigC' });+ await g.settle({ mint: 'THREEsyntheticMintD', ok: false });+ const r = await rows();+ expect(r).toHaveLength(1);+ expect(r[0].type).toBe('pumpfun.buy');+ expect(r[0].payload.status).toBe('confirmed');+ expect(r[0].payload.sig).toBe('sigC');+ });+});