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(sniper): close each coin's token account after a full exit so trade rent returns to the wallet
nirholase0ad5e812bd9
diff --git a/package.json b/package.jsonindex 0d31b4bda..5af59ea26 100644--- a/package.json+++ b/package.json@@ -299,6 +299,7 @@"ui:review": "node scripts/ui-review.mjs","agent:vitals": "node scripts/agent-vitals.mjs","bots:report": "node scripts/trading-bot-report.mjs",+ "sniper:reclaim-rent": "node --env-file-if-exists=.env.local scripts/sniper-reclaim-rent.mjs","logs": "node scripts/gcp-logs.mjs","logs:tail": "node scripts/gcp-logs.mjs --follow","gpu": "node scripts/gpu-capacity.mjs",diff --git a/scripts/sniper-reclaim-rent.mjs b/scripts/sniper-reclaim-rent.mjsnew file mode 100644index 000000000..1125a3466--- /dev/null+++ b/scripts/sniper-reclaim-rent.mjs@@ -0,0 +1,139 @@+#!/usr/bin/env node+// Reclaim the rent stranded in sniper wallets' empty token accounts.+//+// Every sniper buy opened a token account and, until the worker learned to close+// it on exit (workers/agent-sniper/rent-reclaim.js), no sell ever closed it. This+// sweeps the backlog: for every wallet that has a sniper strategy, it lists the+// token accounts, keeps only the ones whose raw balance is exactly zero, and+// closes them with the rent returned to that same wallet. Nothing is sent to any+// other address, and an account holding even one base unit is never touched.+//+// DRY RUN BY DEFAULT: without --apply it only reads and prints what it would+// reclaim. --apply signs close transactions from each agent wallet, which is an+// owner-approved action (CLAUDE.md gate 1).+//+// Usage:+// npm run sniper:reclaim-rent # plan, all sniper wallets+// node --env-file=.env.local scripts/sniper-reclaim-rent.mjs --agent <id> # plan, one agent+// node --env-file=.env.local scripts/sniper-reclaim-rent.mjs --apply # sign and close+//+// Reads need an RPC that serves getTokenAccountsByOwner with a programId filter+// (public mainnet-beta and several free lanes reject it). Resolution order:+// --rpc <url>, SOLANA_RPC_URL, then Helius via HELIUS_API_KEY. --apply also needs+// WALLET_ENCRYPTION_KEY to recover the agent keys; both live on the agent-sniper+// Cloud Run service (node scripts/read-service-env.mjs '^NAME$' --raw).++import { Connection, PublicKey } from '@solana/web3.js';+import { sql } from '../api/_lib/db.js';+import { planCloses, buildCloseInstructions } from '../workers/agent-sniper/rent-reclaim.js';+import { TOKEN_PROGRAMS } from '../workers/agent-sniper/reconcile.js';++const args = process.argv.slice(2);+const flag = (name) => args.includes(name);+const opt = (name) => (args.includes(name) ? args[args.indexOf(name) + 1] : null);++const APPLY = flag('--apply');+const ONLY_AGENT = opt('--agent');+const RPC = opt('--rpc')+ || process.env.SOLANA_RPC_URL+ || (process.env.HELIUS_API_KEY ? `https://mainnet.helius-rpc.com/?api-key=${process.env.HELIUS_API_KEY}` : null);++if (!RPC) {+ console.error('No RPC: pass --rpc <url> or set SOLANA_RPC_URL / HELIUS_API_KEY.');+ process.exit(2);+}+const connection = new Connection(RPC, 'confirmed');++// Owner-wide token scans are the heaviest read a free or shared Helius plan+// serves; spacing wallets out and retrying once keeps a 429 burst from reading as+// a wallet that could not be scanned.+const WALLET_PACING_MS = 1_500;+const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));++async function listTokenAccountsWithRetry(owner) {+ try {+ return await listTokenAccounts(owner);+ } catch {+ await pause(WALLET_PACING_MS * 4);+ return listTokenAccounts(owner);+ }+}++async function listTokenAccounts(owner) {+ const out = [];+ for (const programId of TOKEN_PROGRAMS) {+ const res = await connection.getParsedTokenAccountsByOwner(new PublicKey(owner), { programId: new PublicKey(programId) });+ for (const { pubkey, account } of res.value) {+ out.push({+ pubkey: pubkey.toBase58(),+ programId,+ amount: account.data?.parsed?.info?.tokenAmount?.amount ?? null,+ lamports: account.lamports,+ });+ }+ }+ return out;+}++const agents = await sql`+ SELECT DISTINCT ON (s.agent_id) s.agent_id, s.user_id, a.name, a.meta->>'solana_address' AS address+ FROM agent_sniper_strategies s+ JOIN agent_identities a ON a.id = s.agent_id AND a.deleted_at IS NULL+ WHERE s.network = 'mainnet'+ AND a.meta->>'solana_address' IS NOT NULL+ AND (${ONLY_AGENT}::uuid IS NULL OR s.agent_id = ${ONLY_AGENT}::uuid)+ ORDER BY s.agent_id+`;++let ctx = null;+let signAndSend = null;+let loadAgentKeypair = null;+if (APPLY) {+ const tradeClient = await import('../workers/agent-sniper/trade-client.js');+ ctx = await tradeClient.getTradeCtx('mainnet');+ signAndSend = tradeClient.signAndSend;+ ({ loadAgentKeypair } = await import('../workers/agent-sniper/keys.js'));+}++let totalAccounts = 0;+let totalRent = 0;+let totalReclaimed = 0;+let readErrors = 0;++console.log(`${APPLY ? 'APPLY' : 'DRY RUN'}: ${agents.length} sniper wallet(s)\n`);+for (const a of agents) {+ let accounts;+ await pause(WALLET_PACING_MS);+ try {+ accounts = await listTokenAccountsWithRetry(a.address);+ } catch (err) {+ readErrors += 1;+ console.log(` ${a.name.padEnd(28)} ${a.address} read failed: ${err.message}`);+ continue;+ }+ const plan = planCloses(accounts);+ totalAccounts += plan.closable;+ totalRent += plan.rentLamports;+ console.log(` ${a.name.padEnd(28)} ${a.address} ${String(accounts.length).padStart(4)} accounts, ${String(plan.closable).padStart(4)} empty, ${(plan.rentLamports / 1e9).toFixed(4)} SOL reclaimable`);+ if (!APPLY || plan.closable === 0) continue;++ const loaded = await loadAgentKeypair(a.agent_id, a.user_id, 'sniper_rent_reclaim');+ if (!loaded || loaded.address !== a.address) {+ console.log(` skipped: signing key does not resolve to ${a.address}`);+ continue;+ }+ for (const batch of plan.batches) {+ try {+ const sig = await signAndSend(ctx, loaded.keypair, buildCloseInstructions(ctx, loaded.keypair.publicKey, batch), 60_000);+ const rent = batch.reduce((s, x) => s + x.lamports, 0);+ totalReclaimed += rent;+ console.log(` closed ${batch.length}, +${(rent / 1e9).toFixed(4)} SOL ${sig}`);+ } catch (err) {+ console.log(` batch of ${batch.length} failed (left for the next run): ${err.message}`);+ }+ }+}++console.log(`\n${totalAccounts} empty account(s), ${(totalRent / 1e9).toFixed(4)} SOL reclaimable${APPLY ? `, ${(totalReclaimed / 1e9).toFixed(4)} SOL reclaimed` : ''}`);+if (readErrors) console.log(`${readErrors} wallet(s) could not be read; rerun with an RPC that serves getTokenAccountsByOwner by programId.`);+process.exit(readErrors ? 2 : 0);diff --git a/tests/sniper-rent-reclaim.test.js b/tests/sniper-rent-reclaim.test.jsnew file mode 100644index 000000000..2458f2f8f--- /dev/null+++ b/tests/sniper-rent-reclaim.test.js@@ -0,0 +1,37 @@+import { describe, it, expect } from 'vitest';+import { planCloses, MAX_CLOSES_PER_TX } from '../workers/agent-sniper/rent-reclaim.js';+import { TOKEN_PROGRAMS } from '../workers/agent-sniper/reconcile.js';++const [TOKEN, TOKEN_2022] = TOKEN_PROGRAMS;+const acct = (n, amount, programId = TOKEN_2022, lamports = 2_039_280) => ({ pubkey: `acct${n}`, programId, amount, lamports });++describe('planCloses', () => {+ it('closes only accounts whose raw balance is exactly zero', () => {+ const plan = planCloses([acct(1, '0'), acct(2, '1'), acct(3, '0', TOKEN), acct(4, 0n)]);+ expect(plan.closable).toBe(3);+ expect(plan.batches.flat().map((a) => a.pubkey)).toEqual(['acct1', 'acct3', 'acct4']);+ expect(plan.rentLamports).toBe(3 * 2_039_280);+ });++ it('never treats an unreadable balance as empty', () => {+ const plan = planCloses([acct(1, null), acct(2, undefined), acct(3, 'not-a-number')]);+ expect(plan.closable).toBe(0);+ expect(plan.batches).toEqual([]);+ });++ it('ignores accounts owned by any program other than the two token programs', () => {+ const plan = planCloses([acct(1, '0', '11111111111111111111111111111111')]);+ expect(plan.closable).toBe(0);+ });++ it('batches so no transaction carries more than the per-tx cap', () => {+ const many = Array.from({ length: MAX_CLOSES_PER_TX * 2 + 3 }, (_, i) => acct(i, '0'));+ const plan = planCloses(many);+ expect(plan.batches.map((b) => b.length)).toEqual([MAX_CLOSES_PER_TX, MAX_CLOSES_PER_TX, 3]);+ });++ it('returns an empty plan for empty or missing input', () => {+ expect(planCloses([]).closable).toBe(0);+ expect(planCloses(null).closable).toBe(0);+ });+});diff --git a/workers/agent-sniper/executor.js b/workers/agent-sniper/executor.jsindex 11fc52473..c65ca0fef 100644--- a/workers/agent-sniper/executor.js+++ b/workers/agent-sniper/executor.js@@ -28,6 +28,7 @@ import { assessTradeSafety, recordFirewallDecision, criticalFirewallReason } froimport { recordDecision } from '../../api/_lib/reasoning-ledger.js';import { screenPush } from './screen-push.js';import { buildAgentTradeFee } from '../../api/_lib/pump-platform-fee.js';+import { reclaimMintRent } from './rent-reclaim.js';// Self-rated conviction for a snipe entry, 0..1. Lower price impact and a clean// firewall verdict raise it; a warned verdict and heavy impact lower it. This is@@ -859,6 +860,16 @@ export async function executeSell({ cfg, position, reason, fraction = 1, recover},);notifySell({ agentName: position.agent_name || position.agent_id, symbol: position.symbol, mint: position.mint, pnlSol, pnlPct, exitReason: reason, mode: cfg.mode, sig, chatId: position.telegram_chat_id || null });+ // A full exit leaves the coin's token account empty; close it so its rent+ // (~0.0015-0.002 SOL, as much as a whole small position) returns to the+ // wallet. Separate tx, not awaited: the exit is already booked and a failed+ // close must never hold the agent lock or touch the sell.+ if (cfg.mode === 'live' && !retainsMoonbag) {+ void reclaimMintRent({+ ctx, keypair, mint: position.mint, tag,+ sendTx: (ixs) => signAndSend(ctx, keypair, ixs, cfg.confirmTimeoutMs),+ });+ }return { status: 'closed', sig, pnl: pnl.toString(), venue, moonbagBase: keptBase.toString() };} catch (err) {// A failed sell must NOT terminate the position — leave it 'open' so thediff --git a/workers/agent-sniper/rent-reclaim.js b/workers/agent-sniper/rent-reclaim.jsnew file mode 100644index 000000000..f25606f19--- /dev/null+++ b/workers/agent-sniper/rent-reclaim.js@@ -0,0 +1,109 @@+// agent-sniper: recover the rent a trade's token account locks up.+//+// Every buy opens an associated token account for the coin (~0.0015-0.002 SOL of+// rent) and the sell path never closed it. Measured on 2026-10-01 across the 11+// sniper wallets: 1,377 token accounts holding 2.61 SOL of rent, 1,162 of them+// already empty (2.20 SOL), against a realized trading loss of 0.54 SOL. At+// 0.002 SOL per trade the unclosed rent alone needed a ~79% move to break even,+// and it is what drained most arms dry. See docs/ops/sniper-fleet-review-2026-10-01.md.+//+// The close is deliberately a SEPARATE transaction sent after the exit confirms,+// never an instruction inside the sell: a close fails on any non-zero balance, and+// bundling it would let a few leftover base units abort a stop-loss sell. Here a+// failed close costs nothing but the attempt, and the account is retried by the+// next exit on the same wallet or by scripts/sniper-reclaim-rent.mjs.+//+// Only accounts that read EXACTLY zero on-chain are closed, and the rent always+// goes back to the owning wallet itself, so this can never move value anywhere.++import { createCloseAccountInstruction } from '@solana/spl-token';+import { log } from './log.js';+import { deriveTokenAccounts, TOKEN_PROGRAMS } from './reconcile.js';++/** Closes per transaction. Each close is ~3 accounts; 20 stays far under the size cap. */+export const MAX_CLOSES_PER_TX = 20;++/**+ * Pick the token accounts that are safe to close and batch them. Pure.+ *+ * A row qualifies only when its program is a known token program and its raw+ * amount is exactly zero. Unknown amounts (null, unparseable) never qualify: an+ * unreadable balance is not an empty one.+ *+ * @param {Array<{pubkey:string, programId:string, amount:string|bigint|null, lamports?:number}>} accounts+ * @param {{maxPerTx?:number}} [opts]+ * @returns {{batches:Array<Array<{pubkey:string, programId:string, lamports:number}>>, closable:number, rentLamports:number}}+ */+export function planCloses(accounts, { maxPerTx = MAX_CLOSES_PER_TX } = {}) {+ const known = new Set(TOKEN_PROGRAMS);+ const closable = [];+ for (const a of accounts || []) {+ if (!a || !known.has(a.programId)) continue;+ let amount;+ try { amount = a.amount == null ? null : BigInt(a.amount); } catch { amount = null; }+ if (amount !== 0n) continue;+ closable.push({ pubkey: a.pubkey, programId: a.programId, lamports: Number(a.lamports) || 0 });+ }+ const size = Math.max(1, Math.floor(maxPerTx));+ const batches = [];+ for (let i = 0; i < closable.length; i += size) batches.push(closable.slice(i, i + size));+ return { batches, closable: closable.length, rentLamports: closable.reduce((s, a) => s + a.lamports, 0) };+}++/**+ * Build the close instructions for one batch. Rent returns to the owner.+ *+ * @param {object} ctx getTradeCtx() result (for web3)+ * @param {import('@solana/web3.js').PublicKey} ownerPk+ * @param {Array<{pubkey:string, programId:string}>} batch+ */+export function buildCloseInstructions(ctx, ownerPk, batch) {+ return batch.map((a) => createCloseAccountInstruction(+ new ctx.web3.PublicKey(a.pubkey),+ ownerPk,+ ownerPk,+ [],+ new ctx.web3.PublicKey(a.programId),+ ));+}++/**+ * Read the owner's token accounts for one mint, with exact raw amounts.+ * Returns null when any read fails, so a degraded RPC never reads as "empty".+ */+async function readMintAccounts(ctx, ownerPk, mint) {+ const out = [];+ for (const ata of deriveTokenAccounts(ctx, ownerPk, new ctx.web3.PublicKey(mint))) {+ let info;+ try { info = await ctx.connection.getAccountInfo(ata); } catch { return null; }+ if (!info) continue;+ let amount;+ try { amount = (await ctx.connection.getTokenAccountBalance(ata))?.value?.amount ?? null; } catch { return null; }+ out.push({ pubkey: ata.toBase58(), programId: info.owner.toBase58(), amount, lamports: info.lamports });+ }+ return out;+}++/**+ * After a full exit, close the coin's now-empty token account(s) so the rent+ * returns to the agent wallet. Best effort: never throws, and a balance that is+ * not provably zero is left alone.+ *+ * @param {{ctx:object, keypair:import('@solana/web3.js').Keypair, mint:string, sendTx:Function, tag?:object}} args+ * sendTx(instructions) broadcasts and resolves to a signature.+ * @returns {Promise<{closed:number, rentLamports:number, sig?:string, skipped?:string}>}+ */+export async function reclaimMintRent({ ctx, keypair, mint, sendTx, tag = {} }) {+ try {+ const accounts = await readMintAccounts(ctx, keypair.publicKey, mint);+ if (accounts == null) return { closed: 0, rentLamports: 0, skipped: 'balance_unreadable' };+ const plan = planCloses(accounts);+ if (plan.closable === 0) return { closed: 0, rentLamports: 0, skipped: accounts.length ? 'not_empty' : 'no_account' };+ const sig = await sendTx(buildCloseInstructions(ctx, keypair.publicKey, plan.batches[0]));+ log.trade('rent-reclaim', { ...tag, mint, closed: plan.closable, rent_sol: plan.rentLamports / 1e9, sig });+ return { closed: plan.closable, rentLamports: plan.rentLamports, sig };+ } catch (err) {+ log.warn('rent reclaim failed (account left for the next sweep)', { ...tag, mint, err: err?.message });+ return { closed: 0, rentLamports: 0, skipped: 'send_failed' };+ }+}