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
feat: implement closeAllPositions function for manual token selling and strategy wind down
nirholasae0daffae752
diff --git a/api/pump/strategy-close-all.js b/api/pump/strategy-close-all.jsnew file mode 100644index 000000000..d7cf9dea4--- /dev/null+++ b/api/pump/strategy-close-all.js@@ -0,0 +1,73 @@+// POST /api/pump/strategy-close-all+//+// Body:+// agentId: string required+// network: 'mainnet' | 'devnet' default 'mainnet'+// mints?: string[] optional: only close these mints+// simulate?: boolean dry-run; emit intended sells+//+// Loads the agent's hot wallet, enumerates SPL holdings, and sells each+// position 100% via pump-fun-trade.sellToken. Returns per-mint result.++import { sql } from '../_lib/db.js';+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';+import { cors, json, method, wrap, error, readJson } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { makeRuntime } from '../_lib/skill-runtime.js';+import { loadWallet } from '../_lib/solana-wallet.js';++const RPC = {+ mainnet: process.env.SOLANA_MAINNET_RPC || 'https://api.mainnet-beta.solana.com',+ devnet: process.env.SOLANA_DEVNET_RPC || 'https://api.devnet.solana.com',+};++async function resolveAuth(req) {+ const session = await getSessionUser(req);+ if (session) return { userId: session.id };+ const bearer = await authenticateBearer(extractBearer(req));+ if (bearer) return { userId: bearer.userId };+ return null;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const auth = await resolveAuth(req);+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');++ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const body = await readJson(req);+ if (!body?.agentId) return error(res, 400, 'validation_error', 'agentId required');+ const network = body.network === 'devnet' ? 'devnet' : 'mainnet';++ const [row] = await sql`+ SELECT user_id, meta FROM agent_identities+ WHERE id = ${body.agentId} AND deleted_at IS NULL+ `;+ if (!row) return error(res, 404, 'not_found', 'agent not found');+ if (row.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');+ const enc = row.meta?.encrypted_solana_secret;+ if (!enc) return error(res, 409, 'conflict', 'agent has no solana wallet');++ const wallet = await loadWallet(enc);+ const rt = makeRuntime({+ wallet,+ agentId: body.agentId,+ signerAddress: wallet.publicKey.toBase58(),+ configOverrides: {+ 'pump-fun-trade': { rpc: RPC[network] },+ 'solana-wallet': { rpc: RPC[network] },+ },+ });++ const { closeAllPositions } = await import('../../examples/skills/pump-fun-strategy/handlers.js');+ const result = await closeAllPositions(+ { mints: body.mints, simulate: !!body.simulate },+ { skills: { invoke: rt.invoke }, wallet, memory: { note: () => {} } },+ );+ if (!result.ok) return error(res, 400, 'sell_failed', result.error);+ return json(res, 200, { data: result.data });+});diff --git a/api/pump/strategy-run.js b/api/pump/strategy-run.jsindex 69778e020..64a1bbcb6 100644--- a/api/pump/strategy-run.js+++ b/api/pump/strategy-run.js@@ -26,6 +26,7 @@ import { cors, method, error, readJson } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { makeRuntime } from '../_lib/skill-runtime.js';import { loadWallet } from '../_lib/solana-wallet.js';+import { checkBuyAllowed } from '../_lib/agent-spend-policy.js';const RPC = {mainnet: process.env.SOLANA_MAINNET_RPC || 'https://api.mainnet-beta.solana.com',@@ -50,7 +51,7 @@ async function loadAgentWallet(agentId, userId) {const enc = row.meta?.encrypted_solana_secret;if (!enc) throw Object.assign(new Error('agent has no solana wallet — provision via /api/agents/:id/solana'), { status: 409 });const wallet = await loadWallet(enc);- return { wallet, address: wallet.publicKey.toBase58() };+ return { wallet, address: wallet.publicKey.toBase58(), meta: row.meta };}export default async function handler(req, res) {@@ -69,7 +70,7 @@ export default async function handler(req, res) {const mode = body.mode === 'live' ? 'live' : 'simulate';const network = body.network === 'devnet' ? 'devnet' : 'mainnet';- let wallet = null, walletAddress = null;+ let wallet = null, walletAddress = null, agentMeta = null;if (mode === 'live') {const auth = await resolveAuth(req);if (!auth) return error(res, 401, 'unauthorized', 'sign in required for live mode');@@ -78,6 +79,7 @@ export default async function handler(req, res) {const r = await loadAgentWallet(body.agentId, auth.userId);wallet = r.wallet;walletAddress = r.address;+ agentMeta = r.meta;} catch (e) {return error(res, e.status ?? 500, e.status === 409 ? 'conflict' : 'unauthorized', e.message);}@@ -117,6 +119,16 @@ export default async function handler(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 abortController = new AbortController();+ req.on('close', () => abortController.abort());+try {const result = await runStrategy({@@ -124,6 +136,8 @@ export default async function handler(req, res) {durationSec,simulate: mode === 'simulate',onLog: (entry) => { if (!aborted) send('log', entry); },+ policyGuard,+ abortSignal: abortController.signal,},ctx,);diff --git a/examples/skills/pump-fun-strategy/handlers.js b/examples/skills/pump-fun-strategy/handlers.jsindex 2fcf0842d..733939d39 100644--- a/examples/skills/pump-fun-strategy/handlers.js+++ b/examples/skills/pump-fun-strategy/handlers.js@@ -286,5 +286,64 @@ export async function backtestStrategy(args, ctx) {};}+// ── Manual position close ───────────────────────────────────────────────────+// Sell every SPL holding the agent currently has on-chain. Use to wind down+// a strategy on demand or as a kill-switch when something goes wrong.+//+// Args:+// mints?: string[] - if provided, only sell these mints; else sell all+// positive-balance SPL holdings the wallet owns+// simulate?: boolean - dry-run; emit intended sells but skip signing+// onLog?: (e) => void+//+// Requires ctx.wallet (uses solana-wallet.getSplBalances under the hood).++export async function closeAllPositions(args, ctx) {+ const onLog = typeof args?.onLog === 'function' ? args.onLog : () => {};+ const simulate = !!args?.simulate;+ const log = [];+ const emit = (e) => { log.push(e); try { onLog(e); } catch {} };++ if (!ctx?.wallet?.publicKey && !simulate) {+ return { ok: false, error: 'closeAllPositions requires ctx.wallet (or simulate:true)' };+ }++ let targets;+ if (Array.isArray(args?.mints) && args.mints.length) {+ targets = args.mints.map((mint) => ({ mint }));+ } else {+ const r = await ctx.skills.invoke('solana-wallet.getSplBalances', {});+ if (!r?.ok) return { ok: false, error: `getSplBalances failed: ${r?.error}` };+ targets = (r.data?.balances ?? []).filter((b) => (b.amount ?? 0) > 0);+ }++ let sold = 0, errors = 0;+ for (const t of targets) {+ try {+ if (simulate) {+ emit({ mint: t.mint, action: 'simulate-sell', amount: t.amount });+ sold++;+ continue;+ }+ const r = await ctx.skills.invoke('pump-fun-trade.sellToken', {+ mint: t.mint,+ percent: 100,+ });+ if (r?.ok) {+ emit({ mint: t.mint, action: 'sold', sig: r.data.sig });+ sold++;+ } else {+ emit({ mint: t.mint, action: 'sell-error', error: r?.error });+ errors++;+ }+ } catch (e) {+ emit({ mint: t.mint, action: 'sell-error', error: e.message });+ errors++;+ }+ }++ return { ok: true, data: { sold, errors, total: targets.length, simulate, log } };+}+// Re-exported for tests.export { parsePredicate, evalPredicate, buildView, compileStrategy };diff --git a/examples/skills/pump-fun-strategy/tools.json b/examples/skills/pump-fun-strategy/tools.jsonindex da7c40da7..800e00821 100644--- a/examples/skills/pump-fun-strategy/tools.json+++ b/examples/skills/pump-fun-strategy/tools.json@@ -23,6 +23,17 @@"required": ["strategy", "durationSec"]}},+ {+ "name": "closeAllPositions",+ "description": "Sell every open SPL position the agent's wallet holds. Use to wind down a strategy or as a kill switch.",+ "input_schema": {+ "type": "object",+ "properties": {+ "mints": { "type": "array", "items": { "type": "string" }, "description": "Optional: only close these mints. Default: every positive-balance SPL holding." },+ "simulate": { "type": "boolean" }+ }+ }+ },{"name": "backtestStrategy","description": "Replay a strategy against historical token trade history. No signing, no RPC. Returns per-trade PnL and aggregate stats (win rate, total return, max drawdown).",diff --git a/public/strategy-lab.html b/public/strategy-lab.htmlindex 1c33d4690..1aa48fabc 100644--- a/public/strategy-lab.html+++ b/public/strategy-lab.html@@ -156,7 +156,10 @@<section class="panel" style="margin-top:1rem"><div class="row" style="justify-content:space-between; margin:0"><h2 style="margin:0">Portfolio</h2>- <button id="refreshPortfolio">Refresh</button>+ <div class="row" style="margin:0">+ <button id="refreshPortfolio">Refresh</button>+ <button id="closeAll" class="danger">Stop & sell all</button>+ </div></div><div id="portfolio"><p class="muted">Pick an agent above to load on-chain holdings.</p></div></section>