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: add custodial and self-custodial wallet adapters
qbdz7a9d5adc54da
diff --git a/packages/agent-sniper/bin/agent-sniper.js b/packages/agent-sniper/bin/agent-sniper.jsnew file mode 100644index 000000000..77d5bfdee--- /dev/null+++ b/packages/agent-sniper/bin/agent-sniper.js@@ -0,0 +1,408 @@+#!/usr/bin/env node+// agent-sniper — command-line entry for @three-ws/agent-sniper.+//+// One binary, five faces: `run` (live/simulate trade loop), `mcp` (stdio MCP+// server), `serve` (x402 paid HTTP API), `arm` (strategy template/validator,+// no network), and `status` (local config or a remote /status probe). The hard+// dependencies are the local package + Node builtins only — the arg parser is+// hand-rolled and the heavier faces (mcp/api/sqlite) are imported lazily so a+// minimal `arm`/`help` run never touches them.+//+// SAFETY: the default mode is `simulate`. `live` trades REAL funds from the+// agent wallet and must be opted into explicitly with `--mode live`.++import fs from 'node:fs';+import path from 'node:path';+import process from 'node:process';+import { fileURLToPath } from 'node:url';+import { LAMPORTS_PER_SOL } from '@solana/web3.js';++import {+ presets,+ loadConfig,+ createSelfCustodyWallet,+ createMemoryStore,+} from '../src/index.js';++const HERE = path.dirname(fileURLToPath(import.meta.url));++// ── tiny flag parser ────────────────────────────────────────────────────────+// Hand-rolled so the binary stays zero-dep. Supports `--flag value`,+// `--flag=value`, and bare boolean `--flag`. First non-flag token is the+// command; everything else is collected by key.+function parseArgv(argv) {+ const flags = {};+ let command = null;+ for (let i = 0; i < argv.length; i++) {+ const tok = argv[i];+ if (tok === '--help' || tok === '-h') { flags.help = true; continue; }+ if (tok.startsWith('--')) {+ const body = tok.slice(2);+ const eq = body.indexOf('=');+ if (eq !== -1) { flags[body.slice(0, eq)] = body.slice(eq + 1); continue; }+ const next = argv[i + 1];+ if (next != null && !next.startsWith('--')) { flags[body] = next; i++; }+ else flags[body] = true;+ continue;+ }+ if (command == null) command = tok;+ }+ return { command, flags };+}++// ── small helpers ───────────────────────────────────────────────────────────++// Expected, user-facing failures throw this so main() can print a clean line+// instead of a raw Node stack trace.+class CliError extends Error {}++function fail(msg) { throw new CliError(msg); }++function readFileMaybe(p) {+ try { return fs.readFileSync(p, 'utf8'); } catch { return null; }+}++// A --keypair value can be a base58/json secret OR a path to a file holding one.+// Resolve to the raw secret string the wallet adapter knows how to decode.+function resolveKeypairSecret(value) {+ if (value == null || value === true) return null;+ const s = String(value).trim();+ // Looks like a filesystem path (and exists)? read it.+ if (!s.startsWith('[') && !s.startsWith('0x') && (s.includes('/') || s.includes('\\') || s.endsWith('.json'))) {+ const body = readFileMaybe(s);+ if (body == null) fail(`--keypair file not found: ${s}`);+ return body.trim();+ }+ if (fs.existsSync(s) && fs.statSync(s).isFile()) return readFileMaybe(s)?.trim() || s;+ return s;+}++// --strategy is a JSON string, a path to a .json file (one strategy or an array),+// or, when absent, the SNIPER_STRATEGIES env. Always returns an array.+function loadStrategiesFlag(value) {+ const src = value === true || value == null ? (process.env.SNIPER_STRATEGIES || '') : String(value);+ if (!src.trim()) return [];++ let text = src;+ // A path to a .json file rather than inline JSON?+ if (!src.trim().startsWith('{') && !src.trim().startsWith('[')) {+ const body = readFileMaybe(src);+ if (body == null) fail(`--strategy file not found: ${src}`);+ text = body;+ }+ let parsed;+ try { parsed = JSON.parse(text); }+ catch (err) { fail(`--strategy is not valid JSON: ${err.message}`); }+ const arr = Array.isArray(parsed) ? parsed : [parsed];+ if (!arr.length) fail('--strategy resolved to an empty list');+ return arr;+}++// SOL → lamports for the human-friendly amount fields. Strategies are stored in+// lamports; users think in SOL. Convert here so the engine sees what it expects.+function solToLamports(sol) {+ return BigInt(Math.round(Number(sol) * LAMPORTS_PER_SOL));+}++// Take an author-friendly strategy (per_trade_sol / daily_budget_sol) and emit+// the lamport-denominated shape the engine reads. Already-lamport fields pass+// through untouched. stop_loss_pct is mandatory — the engine drops strategies+// without it, so we reject early rather than silently no-op.+function normalizeStrategy(s, idx = 0) {+ if (!s || typeof s !== 'object') fail(`strategy #${idx} is not an object`);+ if (s.stop_loss_pct == null) fail(`strategy #${idx} (${s.id || 'unnamed'}) is missing stop_loss_pct — a stop-loss is mandatory`);++ const out = { ...s };+ out.id = s.id || `cli_${idx}_${Date.now().toString(36)}`;+ out.agent_id = s.agent_id || 'default';+ out.enabled = s.enabled !== false; // default armed unless explicitly disabled+ out.trigger = s.trigger || 'new_mint';++ if (out.per_trade_lamports == null) {+ if (s.per_trade_sol == null) fail(`strategy #${idx} needs per_trade_sol or per_trade_lamports`);+ out.per_trade_lamports = solToLamports(s.per_trade_sol).toString();+ } else {+ out.per_trade_lamports = String(out.per_trade_lamports);+ }+ delete out.per_trade_sol;++ if (out.daily_budget_lamports == null) {+ if (s.daily_budget_sol == null) fail(`strategy #${idx} needs daily_budget_sol or daily_budget_lamports`);+ out.daily_budget_lamports = solToLamports(s.daily_budget_sol).toString();+ } else {+ out.daily_budget_lamports = String(out.daily_budget_lamports);+ }+ delete out.daily_budget_sol;++ return out;+}++// The documented template `arm` prints when invoked without --strategy.+const STRATEGY_TEMPLATE = {+ id: 'my-first-snipe',+ agent_id: 'default',+ enabled: true,+ network: 'mainnet',+ trigger: 'new_mint', // new_mint | intel_confirmed | first_claim | manual+ per_trade_sol: 0.05, // SOL committed per snipe (→ per_trade_lamports)+ daily_budget_sol: 1.0, // SOL/day ceiling (→ daily_budget_lamports)+ max_concurrent_positions: 3,+ slippage_bps: 500, // 5.00%+ max_price_impact_pct: 10, // entry circuit breaker+ mev_tip_mode: 'off', // off | economy | turbo+ firewall_level: 'block', // block | warn | off+ take_profit_pct: 80,+ stop_loss_pct: 35, // MANDATORY — engine drops strategies without it+ trailing_stop_pct: 20,+ max_hold_seconds: 1800,+ require_socials: false,+};++// ── shared sniper construction (run / mcp / serve) ──────────────────────────+async function buildSniper(flags, { screen = false } = {}) {+ const network = flags.network || process.env.SNIPER_NETWORK || 'mainnet';+ const mode = flags.mode || process.env.SNIPER_MODE || 'simulate';+ if (mode !== 'simulate' && mode !== 'live') fail(`--mode must be simulate|live, got "${mode}"`);+ const rpcUrl = flags.rpc || process.env.SOLANA_RPC_URL || null;++ // A single default keypair drives one-agent runs; multi-agent runs resolve+ // per-agent secrets from SNIPER_WALLET_<AGENTID> env or the sqlite store.+ const keypairSecret = resolveKeypairSecret(flags.keypair);++ const rawStrategies = loadStrategiesFlag(flags.strategy);+ const strategies = rawStrategies.map((s, i) => normalizeStrategy(s, i));++ // Durable store on request; otherwise process-memory.+ let store = null;+ if (flags.sqlite || flags.db) {+ const dbPath = typeof flags.db === 'string' ? flags.db+ : typeof flags.sqlite === 'string' ? flags.sqlite+ : undefined;+ const { createSqliteStore } = await import('../src/adapters/store/sqlite.js');+ store = createSqliteStore({ path: dbPath });+ if (typeof store.addStrategy === 'function') for (const s of strategies) store.addStrategy(s);+ } else {+ store = createMemoryStore({ strategies });+ }++ const hooks = {};+ if (screen) {+ // Pretty per-event line to stderr so stdout stays clean for piping.+ hooks.onScreen = ({ text, kind }) => {+ const tag = ({ trade: 'TRADE', activity: 'LIVE', alert: 'ALERT' }[kind] || 'INFO').padEnd(5);+ process.stderr.write(`\x1b[2m${new Date().toISOString().slice(11, 19)}\x1b[0m ${tag} ${text}\n`);+ };+ }++ // presets.local builds the wallet/solana/executor/feed wiring; we override the+ // wallet so the resolved default secret is honored without env round-trips.+ const wallet = createSelfCustodyWallet(keypairSecret ? { defaultSecret: keypairSecret } : {});++ // presets.local takes a config-ish object; re-create the wiring it does but+ // with our store + wallet so we control persistence and key resolution.+ const { createPumpClient, createWeb3Executor, createPumpPortalFeed, createSniper } = await import('../src/index.js');+ const solana = await createPumpClient({ network, rpcUrl });+ const sniper = createSniper({+ config: { network, mode, rpcUrl },+ store,+ wallet,+ solana,+ executor: createWeb3Executor(),+ feed: createPumpPortalFeed({ network }),+ hooks,+ });++ return { sniper, store, wallet, strategies, network, mode, keypairSecret };+}++// ── commands ────────────────────────────────────────────────────────────────++async function cmdRun(flags) {+ const { sniper, wallet, strategies, network, mode } = await buildSniper(flags, { screen: true });++ let walletAddr = null;+ if (strategies.length === 1 || flags.keypair) {+ const loaded = await wallet.loadKeypair(strategies[0]?.agent_id || 'default').catch(() => null);+ walletAddr = loaded?.address || null;+ }++ // ── startup banner ──+ const line = (l) => process.stderr.write(l + '\n');+ line('');+ line(' \x1b[1magent-sniper\x1b[0m — pump.fun sniper engine');+ line(` network ${network}`);+ line(` mode ${mode}${mode === 'live' ? ' \x1b[31m(LIVE — trading REAL funds)\x1b[0m' : ' (simulate — no funds at risk)'}`);+ line(` strategies ${strategies.length}`);+ if (walletAddr) line(` wallet ${walletAddr}`);+ if (mode === 'live') line(' \x1b[33m⚠ live mode: every snipe spends SOL from the agent wallet. Ctrl-C to stop.\x1b[0m');+ line('');++ await sniper.start();++ let stopping = false;+ const shutdown = async (sig) => {+ if (stopping) return;+ stopping = true;+ line(`\n ${sig} — draining and stopping…`);+ try { await sniper.stop(); } catch { /* best-effort */ }+ process.exit(0);+ };+ process.on('SIGINT', () => shutdown('SIGINT'));+ process.on('SIGTERM', () => shutdown('SIGTERM'));++ // Keep the process alive; the feed + timers do the work.+ return new Promise(() => {});+}++async function cmdMcp(flags) {+ const { sniper, store } = await buildSniper(flags, { screen: false });+ let mod;+ try {+ mod = await import('../src/faces/mcp.js');+ } catch (err) {+ if (err?.code === 'ERR_MODULE_NOT_FOUND' || /Cannot find module/.test(err?.message || '')) {+ fail('mcp face not available');+ }+ throw err;+ }+ if (typeof mod.startStdio !== 'function') fail('mcp face not available');+ await mod.startStdio({ sniper, store });+}++async function cmdServe(flags) {+ const { sniper, store } = await buildSniper(flags, { screen: false });+ const port = Number(flags.port) || 8787;+ let mod;+ try {+ mod = await import('../src/faces/api.js');+ } catch (err) {+ if (err?.code === 'ERR_MODULE_NOT_FOUND' || /Cannot find module/.test(err?.message || '')) {+ fail('api face not available');+ }+ throw err;+ }+ const serve = mod.serve || mod.default;+ if (typeof serve !== 'function') fail('api face not available');+ await serve({ sniper, store, port });+ process.stderr.write(`agent-sniper x402 API listening on :${port}\n`);+}++async function cmdArm(flags) {+ // No --strategy: print the fill-in template.+ if (flags.strategy == null && !process.env.SNIPER_STRATEGIES) {+ process.stderr.write('// Fill in this template and pass it via --strategy (JSON string or file path).\n');+ process.stderr.write('// stop_loss_pct is mandatory; per_trade_sol / daily_budget_sol convert to lamports.\n');+ process.stdout.write(JSON.stringify(STRATEGY_TEMPLATE, null, 2) + '\n');+ return;+ }+ // --strategy given: validate + emit the normalized, lamport-converted shape.+ const raw = loadStrategiesFlag(flags.strategy);+ const normalized = raw.map((s, i) => normalizeStrategy(s, i));+ process.stdout.write(JSON.stringify(normalized.length === 1 ? normalized[0] : normalized, null, 2) + '\n');+}++async function cmdStatus(flags) {+ if (flags.url) {+ const base = String(flags.url).replace(/\/+$/, '');+ const res = await fetch(`${base}/status`).catch((err) => fail(`could not reach ${base}/status: ${err.message}`));+ if (!res.ok) fail(`status endpoint returned HTTP ${res.status}`);+ const body = await res.json().catch(() => fail('status endpoint did not return JSON'));+ process.stdout.write(JSON.stringify(body, null, 2) + '\n');+ return;+ }+ // Local: resolve config from env + flags and print it.+ const cfg = loadConfig({+ network: typeof flags.network === 'string' ? flags.network : undefined,+ mode: typeof flags.mode === 'string' ? flags.mode : undefined,+ rpcUrl: typeof flags.rpc === 'string' ? flags.rpc : undefined,+ });+ process.stdout.write(JSON.stringify(cfg, null, 2) + '\n');+}++function cmdHelp() {+ const out = `+agent-sniper — embeddable pump.fun sniper engine (@three-ws/agent-sniper)++USAGE+ agent-sniper <command> [flags]++COMMANDS+ run Start the live/simulate trade loop and keep running.+ mcp Run the stdio MCP server face (for AI agents / MCP clients).+ serve Start the x402 paid HTTP API (default port 8787).+ arm Print or validate a strategy. No network. Helper for authoring.+ status Show local config, or probe a running server's /status (--url).+ help Show this help.++FLAGS+ --network <mainnet|devnet> Target cluster. (env SNIPER_NETWORK)+ --mode <simulate|live> Trade mode. (env SNIPER_MODE)+ --rpc <url> Solana RPC endpoint. (env SOLANA_RPC_URL)+ --keypair <base58|path|json> Default agent wallet secret (single-agent runs).+ --strategy <json|file> Strategy JSON, or path to a .json file (one or+ an array). (env SNIPER_STRATEGIES)+ --sqlite [path] Use the durable SQLite store instead of memory.+ --db <path> Same as --sqlite with an explicit DB path.+ --port <n> HTTP port for 'serve'. (default 8787)+ --url <url> Remote base URL for 'status'.++SAFETY+ Default mode is SIMULATE — no funds are ever moved. Pass '--mode live' to+ trade REAL SOL from the agent wallet. There is no confirmation prompt; live+ means live. A mandatory stop_loss_pct is enforced on every armed strategy.++WALLETS+ Single agent: --keypair <secret> (or SOLANA_SECRET_KEY).+ Multi-agent: set SNIPER_WALLET_<AGENTID> env vars, or use --sqlite/--db so+ each agent_id resolves its own self-custody key.++EXAMPLES+ # Print a strategy template to fill in+ agent-sniper arm++ # Validate a strategy file and see the lamport-normalized result+ agent-sniper arm --strategy ./my-strategy.json++ # Dry-run (simulate) against devnet with one inline strategy+ agent-sniper run --network devnet \\+ --strategy '{"id":"s1","agent_id":"a1","stop_loss_pct":35,"per_trade_sol":0.05,"daily_budget_sol":1}'++ # LIVE on mainnet with a durable store and a wallet file+ agent-sniper run --mode live --rpc https://your-rpc \\+ --keypair ./agent.json --strategy ./strategies.json --sqlite ./sniper.db++ # Run the MCP server / x402 API faces+ agent-sniper mcp --strategy ./strategies.json+ agent-sniper serve --port 8787 --sqlite ./sniper.db++ # Inspect local config or a running server+ agent-sniper status+ agent-sniper status --url http://localhost:8787+`;+ process.stdout.write(out + '\n');+}++// ── entrypoint ──────────────────────────────────────────────────────────────+async function main() {+ const { command, flags } = parseArgv(process.argv.slice(2));++ if (!command || command === 'help' || flags.help) { cmdHelp(); return; }++ switch (command) {+ case 'run': await cmdRun(flags); break;+ case 'mcp': await cmdMcp(flags); break;+ case 'serve': await cmdServe(flags); break;+ case 'arm': await cmdArm(flags); break;+ case 'status': await cmdStatus(flags); break;+ default:+ process.stderr.write(`agent-sniper: unknown command "${command}"\n\n`);+ cmdHelp();+ process.exit(1);+ }+}++main().catch((err) => {+ // Expected (CliError) → clean one-liner. Unexpected → message only, no stack.+ process.stderr.write(`agent-sniper: ${err?.message || err}\n`);+ process.exit(1);+});diff --git a/packages/agent-sniper/package.json b/packages/agent-sniper/package.jsonindex bf63c5e46..539ae3c34 100644--- a/packages/agent-sniper/package.json+++ b/packages/agent-sniper/package.json@@ -58,6 +58,7 @@"@modelcontextprotocol/sdk": "^1.29.0","@pump-fun/pump-sdk": "^1.36.0","@pump-fun/pump-swap-sdk": "^1.17.0",+ "@three-ws/agent-payments": "^3.2.0","@solana/spl-token": "^0.4.14","@solana/web3.js": "^1.98.4","@three-ws/x402-server": "^0.1.0",diff --git a/packages/agent-sniper/src/adapters/feed/pumpportal.js b/packages/agent-sniper/src/adapters/feed/pumpportal.jsnew file mode 100644index 000000000..544f42ef7--- /dev/null+++ b/packages/agent-sniper/src/adapters/feed/pumpportal.js@@ -0,0 +1,247 @@+// agent-sniper — PumpPortal new-token Feed adapter.+//+// Streams pump.fun launches off the public PumpPortal WebSocket+// (wss://pumpportal.fun/api/data) and maps each new-token event into the+// engine's Candidate shape. No auth, no RPC, no Redis — just a socket.+//+// This is the standalone-package twin of three.ws's api/_lib/pumpfun-ws-feed.js,+// rewritten with ZERO three.ws imports so the published @three-ws/agent-sniper+// package carries no internal coupling. It depends only on `ws` (already a+// package dependency) and Node >=20 built-ins.+//+// Contract (src/types.js): a Feed is `{ start(onEvent) => Promise<stopFn> }`.+// `onEvent` receives `{ kind: 'mint', data: Candidate }`. `Candidate.mint` is+// the only required field; we map everything else PumpPortal gives us and omit+// what it doesn't, rather than inventing values.++import WebSocket from 'ws';++const DEFAULT_URL = 'wss://pumpportal.fun/api/data';++// Reconnect backoff: start fast (a transient blip recovers in ~1s), grow+// geometrically so a sustained upstream outage doesn't hammer the endpoint, and+// cap so we never wait absurdly long once it heals.+const RECONNECT_BASE_MS = 1_000;+const RECONNECT_MAX_MS = 30_000;++// Watchdog: PumpPortal occasionally drops a subscription silently — the socket+// stays open but stops delivering events. If we see no message for this long we+// re-send the subscribe payload (and, failing that, the close handler below+// will cycle the socket). 3 min is well past any quiet stretch on a live feed.+const DEFAULT_WATCHDOG_MS = 180_000;++// Solana mainnet quote mints. PumpPortal exposes a quote/pool field on v2 coins;+// only an explicit USDC quote flips `is_usdc_pair`. Anything else (or absent) is+// treated as the native SOL pair, matching the bonding-curve default.+const WSOL_MINT = 'So11111111111111111111111111111111111111112';+const USDC_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';++/**+ * Decide whether a launch is USDC-paired from whatever quote signal the event+ * carries. PumpPortal isn't fully consistent across coin versions, so we probe+ * the handful of fields it has historically used (quoteMint / quote_mint, and+ * the `pool` label on AMM-migrated coins). Returns true only on a positive USDC+ * match — we never guess USDC from absence.+ *+ * @param {object} d raw PumpPortal new-token message+ * @returns {boolean}+ */+function deriveUsdcPair(d) {+ const quoteMint = d.quoteMint || d.quote_mint || null;+ if (quoteMint) return quoteMint === USDC_MINT;+ // Some AMM-pool labels encode the quote asset in the pool name.+ if (typeof d.pool === 'string' && /usdc/i.test(d.pool)) return true;+ return false;+}++/**+ * Map a raw PumpPortal new-token (`txType === 'create'`) message to a Candidate.+ * We only set fields PumpPortal actually delivers on the create event; richer+ * enrichment (creator history, socials) belongs to the engine's intel hooks, not+ * the firehose. `entry_trigger` is always 'mint' here.+ *+ * @param {object} d raw PumpPortal message+ * @returns {import('../../types.js').Candidate}+ */+function toCandidate(d) {+ /** @type {import('../../types.js').Candidate} */+ const c = { mint: d.mint, entry_trigger: 'mint' };++ // Symbol / name — trim and drop empties so the scorer never sees "".+ if (typeof d.symbol === 'string' && d.symbol.trim()) c.symbol = d.symbol.trim();+ if (typeof d.name === 'string' && d.name.trim()) c.name = d.name.trim();++ // PumpPortal reports market cap in SOL (`marketCapSol`); the Candidate field+ // is USD. We have no SOL price on the firehose path here, so we omit+ // market_cap_usd rather than ship an unconverted SOL figure as if it were+ // dollars — a wrong unit is worse than an absent field for the scorer.+ // (The three.ws build enriches with a price feed; the standalone package+ // leaves USD conversion to a price-aware Solana adapter / hook.)++ // The dev's opening buy, in SOL — present on most create events.+ const initialBuy = d.initialBuy ?? d.solAmount;+ if (typeof initialBuy === 'number' && Number.isFinite(initialBuy)) {+ c.initial_buy_sol = initialBuy;+ }++ c.is_usdc_pair = deriveUsdcPair(d);++ return c;+}++/**+ * Create a PumpPortal-backed Feed.+ *+ * @param {object} [opts]+ * @param {'mainnet'|'devnet'} [opts.network='mainnet'] PumpPortal only streams+ * mainnet; kept for parity with the Feed surface and forward compatibility.+ * @param {string} [opts.url] WebSocket URL (default wss://pumpportal.fun/api/data).+ * @param {number} [opts.watchdogMs=180000] re-subscribe if no message arrives in+ * this window.+ * @returns {import('../../types.js').Feed}+ */+export function createPumpPortalFeed(opts = {}) {+ const url = opts.url || DEFAULT_URL;+ const watchdogMs = Number.isFinite(opts.watchdogMs) && opts.watchdogMs > 0+ ? opts.watchdogMs+ : DEFAULT_WATCHDOG_MS;++ return {+ /**+ * @param {(e: { kind: string, data: import('../../types.js').Candidate }) => void} onEvent+ * @returns {Promise<() => void>} stop function+ */+ async start(onEvent) {+ // `active` gates every async continuation. Once stop() flips it false,+ // late socket events and pending reconnect timers become no-ops, so the+ // feed can't resurrect itself after teardown.+ let active = true;+ let ws = null;+ let reconnectAttempt = 0;+ let reconnectTimer = null;+ let watchdogTimer = null;+ let lastMessageAt = Date.now();++ // Per-feed mint dedupe. PumpPortal can redeliver an event after a WS+ // hiccup or a watchdog re-subscribe; the engine also expects to claim+ // each (agent, mint) slot once, so suppressing duplicates here keeps the+ // buy path clean. Bounded so a long-lived feed never leaks memory.+ const seen = new Set();+ const SEEN_LIMIT = 5_000;+ function firstSight(mint) {+ if (!mint || seen.has(mint)) return false;+ seen.add(mint);+ if (seen.size > SEEN_LIMIT) {+ // Drop the oldest ~20% — Set preserves insertion order.+ const it = seen.values();+ for (let i = 0; i < SEEN_LIMIT / 5; i++) seen.delete(it.next().value);+ }+ return true;+ }++ function sendSubscribe() {+ // Same payload the three.ws feed uses; PumpPortal's documented+ // new-token subscription method.+ try { ws?.send(JSON.stringify({ method: 'subscribeNewToken' })); } catch { /* socket not open */ }+ }++ function armWatchdog() {+ clearInterval(watchdogTimer);+ watchdogTimer = setInterval(() => {+ if (!active) return;+ if (Date.now() - lastMessageAt < watchdogMs) return;+ // Silent stall: nudge the subscription. If the socket is actually+ // dead, the send throws / no-ops and the close path recycles it.+ console.error('[agent-sniper:pumpportal] watchdog: no events, re-subscribing');+ lastMessageAt = Date.now(); // reset so we don't re-fire every tick+ sendSubscribe();+ }, watchdogMs);+ watchdogTimer.unref?.();+ }++ function scheduleReconnect() {+ if (!active) return;+ const delay = Math.min(RECONNECT_BASE_MS * 2 ** reconnectAttempt, RECONNECT_MAX_MS);+ reconnectAttempt++;+ clearTimeout(reconnectTimer);+ reconnectTimer = setTimeout(connect, delay);+ reconnectTimer.unref?.();+ }++ function connect() {+ if (!active) return;+ try {+ ws = new WebSocket(url);+ } catch (err) {+ // Constructor can throw on a malformed URL — treat as a connection+ // failure and back off rather than crashing start().+ console.error('[agent-sniper:pumpportal] socket construct failed:', err?.message);+ scheduleReconnect();+ return;+ }++ ws.on('open', () => {+ if (!active) { try { ws.close(); } catch { /* noop */ } return; }+ reconnectAttempt = 0; // healthy connection — reset backoff+ lastMessageAt = Date.now();+ sendSubscribe();+ });++ ws.on('message', (raw) => {+ if (!active) return;+ lastMessageAt = Date.now();+ let msg;+ try { msg = JSON.parse(raw.toString()); } catch { return; }+ if (msg.message) return; // subscription ack, not a token event+ if (msg.txType !== 'create' || !msg.mint) return;+ if (!firstSight(msg.mint)) return;+ const data = toCandidate(msg);+ // Never let a consumer throw bubble up and kill the socket loop.+ try { onEvent({ kind: 'mint', data }); } catch (err) {+ console.error('[agent-sniper:pumpportal] onEvent threw:', err?.message);+ }+ });++ ws.on('error', (err) => {+ // During teardown a mid-handshake socket emits a benign "closed+ // before the connection was established" error — stay quiet for it.+ if (!active) return;+ console.error('[agent-sniper:pumpportal] socket error:', err?.message);+ // `error` is typically followed by `close`; the reconnect is driven+ // from there so we don't double-schedule.+ });++ ws.on('close', () => {+ if (!active) return;+ scheduleReconnect();+ });+ }++ connect();+ armWatchdog();++ // stop(): idempotent teardown. Flip `active` first so no in-flight event+ // or timer can re-arm anything, then clear timers and close the socket.+ return function stop() {+ if (!active) return;+ active = false;+ clearTimeout(reconnectTimer);+ clearInterval(watchdogTimer);+ const sock = ws;+ ws = null;+ if (!sock) return;+ try {+ // Drop listeners so the impending close/error from our own teardown+ // doesn't reschedule or log. terminate() is the hard, immediate kill;+ // fall back to close() if the ws build lacks it.+ sock.removeAllListeners?.('open');+ sock.removeAllListeners?.('message');+ sock.removeAllListeners?.('close');+ sock.removeAllListeners?.('error');+ sock.on?.('error', () => {});+ (sock.terminate ?? sock.close).call(sock);+ } catch { /* already closed */ }+ };+ },+ };+}diff --git a/packages/agent-sniper/src/adapters/solana/executor-web3.js b/packages/agent-sniper/src/adapters/solana/executor-web3.jsnew file mode 100644index 000000000..cb8a5a184--- /dev/null+++ b/packages/agent-sniper/src/adapters/solana/executor-web3.js@@ -0,0 +1,148 @@+// agent-sniper — default Executor: MEV-aware web3.js broadcast.+//+// The one place a signed transaction hits the network. Builds a v0 tx with a+// dynamic priority fee, optionally simulates, sends, and confirms with bounded+// adaptive retry (fresh blockhash + escalating fee per attempt). When tipMode is+// 'economy'|'turbo' it appends a Jito tip transfer and routes the tx through the+// Jito block engine for bundle inclusion, falling back to the normal RPC path+// (reported honestly via fallbackReason) if Jito is unreachable.+//+// Returns full landing telemetry so callers can persist route / tip / fee /+// landed_ms. No external Jito SDK — the block engine speaks plain JSON-RPC.++import {+ ComputeBudgetProgram, SystemProgram, PublicKey,+ TransactionMessage, VersionedTransaction,+} from '@solana/web3.js';++// Jito mainnet tip accounts (public, rotate by random pick). Block engine routes+// a tx to a validator running Jito when it pays one of these.+const JITO_TIP_ACCOUNTS = [+ '96gYZGLnJYVFmbjzopPSU6QiEV5fGqZNyN9nmNhvrZU5',+ 'HFqU5x63VTqvQss8hp11i4wVV8bD44PvwucfZ2bU7gRe',+ 'Cw8CFyM9FkoMi7K7Crf6HNQqf4uEMzpKw6QNghp5HJ8L',+ 'ADaUMid9yfUytqMBgopwjb2DTLSokTSzL1zt6iGPaS49',+ 'DfXygSm4jCyNCybVYYK6DwvWqjKee8pbDmJGcLWNDXjh',+ 'ADuUkR4vqLUMWXxW9gh6D6L8pMSawimctcNZ5pGwDcEt',+ 'DttWaMuVvTiduZRnguLF7jNxTgiMBZ1hyAumKUiL2KRL',+ '3AVi9Tg9Uo68tJfuvoKvqKNWKkC5wPdSSdeBnizKZ6jT',+];+const JITO_BLOCK_ENGINE = 'https://mainnet.block-engine.jito.wtf/api/v1/transactions';++const TIP_LAMPORTS = { economy: 100_000n, turbo: 1_000_000n }; // 0.0001 / 0.001 SOL+const PRIORITY_FEE_MICROLAMPORTS = { base: 50_000, turbo: 500_000 };++function pickTipAccount(seed) {+ return JITO_TIP_ACCOUNTS[Math.abs(seed) % JITO_TIP_ACCOUNTS.length];+}++async function buildSigned({ connection, payer, instructions, microLamports, tipIx }) {+ const cuPrice = ComputeBudgetProgram.setComputeUnitPrice({ microLamports });+ const cuLimit = ComputeBudgetProgram.setComputeUnitLimit({ units: 600_000 });+ const ixs = [cuPrice, cuLimit, ...instructions];+ if (tipIx) ixs.push(tipIx);+ const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash('confirmed');+ const msg = new TransactionMessage({ payerKey: payer.publicKey, recentBlockhash: blockhash, instructions: ixs }).compileToV0Message();+ const tx = new VersionedTransaction(msg);+ tx.sign([payer]);+ return { tx, blockhash, lastValidBlockHeight };+}++async function sendViaJito(rawBase64) {+ const res = await fetch(JITO_BLOCK_ENGINE, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'sendTransaction', params: [rawBase64, { encoding: 'base64' }] }),+ });+ if (!res.ok) throw new Error(`jito ${res.status}`);+ const body = await res.json();+ if (body.error) throw new Error(`jito ${body.error.message || 'rejected'}`);+ return body.result; // signature+}++/**+ * @param {object} [opts]+ * @param {number} [opts.maxAttempts] default 3+ * @param {boolean} [opts.simulate] pre-simulate before first send (default true)+ * @returns {import('../../types.js').Executor}+ */+export function createWeb3Executor(opts = {}) {+ const maxAttempts = Math.max(1, opts.maxAttempts ?? 3);+ const simulate = opts.simulate !== false;++ return {+ async submit({ connection, payer, instructions, confirmTimeoutMs, tipMode = 'off', onTip }) {+ const start = Date.now();+ let useJito = tipMode === 'economy' || tipMode === 'turbo';+ let tipLamports = 0n;+ let tipIx = null;+ if (useJito) {+ tipLamports = TIP_LAMPORTS[tipMode] || TIP_LAMPORTS.economy;+ // Invoke the spend-guard veto with the real tip amount BEFORE it leaves+ // the wallet. A throw drops us to the untipped standard route.+ if (typeof onTip === 'function') {+ try { await onTip(tipLamports, 'jito'); }+ catch { tipLamports = 0n; tipIx = null; useJito = false; return await sendStandard(); }+ }+ tipIx = SystemProgram.transfer({+ fromPubkey: payer.publicKey,+ toPubkey: new PublicKey(pickTipAccount(payer.publicKey.toBuffer()[0])),+ lamports: Number(tipLamports),+ });+ }++ let fallbackReason = null;++ async function attemptSend(microLamports, viaJito) {+ const { tx, blockhash, lastValidBlockHeight } = await buildSigned({ connection, payer, instructions, microLamports, tipIx: viaJito ? tipIx : null });+ if (simulate) {+ const sim = await connection.simulateTransaction(tx, { sigVerify: false, replaceRecentBlockhash: true });+ if (sim.value.err) throw Object.assign(new Error(`simulation failed: ${JSON.stringify(sim.value.err)}`), { code: 'sim_failed', logs: sim.value.logs });+ }+ const raw = Buffer.from(tx.serialize());+ let signature;+ if (viaJito) {+ signature = await sendViaJito(raw.toString('base64'));+ } else {+ signature = await connection.sendRawTransaction(raw, { skipPreflight: true, maxRetries: 0 });+ }+ await connection.confirmTransaction({ signature, blockhash, lastValidBlockHeight }, 'confirmed');+ return signature;+ }++ async function sendStandard() {+ let lastErr;+ for (let i = 0; i < maxAttempts; i++) {+ const fee = PRIORITY_FEE_MICROLAMPORTS.base * (i + 1);+ try {+ const signature = await Promise.race([+ attemptSend(fee, false),+ timeout(confirmTimeoutMs),+ ]);+ return { signature, route: 'standard', tipLamports: 0n, priorityFeeMicroLamports: fee, attempts: i + 1, landedMs: Date.now() - start, fallbackReason };+ } catch (err) { lastErr = err; }+ }+ throw lastErr;+ }++ if (!useJito || !tipIx) return await sendStandard();++ // Jito path first; on any failure fall back to the standard RPC route.+ const fee = tipMode === 'turbo' ? PRIORITY_FEE_MICROLAMPORTS.turbo : PRIORITY_FEE_MICROLAMPORTS.base;+ try {+ const signature = await Promise.race([attemptSend(fee, true), timeout(confirmTimeoutMs)]);+ return { signature, route: 'jito', tipLamports, priorityFeeMicroLamports: fee, attempts: 1, landedMs: Date.now() - start, fallbackReason: null };+ } catch (err) {+ fallbackReason = `jito_failed:${err?.message || 'error'}`.slice(0, 120);+ tipIx = null; // don't pay a tip on the non-Jito fallback+ return await sendStandard();+ }+ },+ };+}++function timeout(ms) {+ return new Promise((_, reject) => setTimeout(() => reject(Object.assign(new Error('confirm timeout'), { code: 'confirm_timeout' })), ms).unref?.());+}++export default createWeb3Executor;diff --git a/packages/agent-sniper/src/adapters/solana/pump-client.js b/packages/agent-sniper/src/adapters/solana/pump-client.jsnew file mode 100644index 000000000..cded6fc4d--- /dev/null+++ b/packages/agent-sniper/src/adapters/solana/pump-client.js@@ -0,0 +1,70 @@+// agent-sniper — default SolanaClient: pump.fun bonding-curve trades.+//+// Wraps @three-ws/agent-payments' PumpTradeClient (an Anchor-backed client over+// the official pump.fun program) so quotes + instruction builds use the same+// battle-tested bonding-curve math the three.ws platform runs in production —+// rather than a re-derivation that could be subtly, expensively wrong.+//+// This is the ONLY adapter that knows pump.fun specifics. Implement the+// SolanaClient contract yourself to route through Jupiter, Raydium, a custom+// program, or a mock for tests.++import { Connection, PublicKey } from '@solana/web3.js';+import BN from 'bn.js';++const RPC = {+ mainnet: () => process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com',+ devnet: () => process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com',+};+const WSOL = 'So11111111111111111111111111111111111111112';+const toBN = (v) => new BN(BigInt(v).toString());++/**+ * @param {object} [opts]+ * @param {'mainnet'|'devnet'} [opts.network]+ * @param {string} [opts.rpcUrl] overrides the network default+ * @param {Connection} [opts.connection] bring your own+ * @returns {Promise<import('../../types.js').SolanaClient>}+ */+export async function createPumpClient(opts = {}) {+ const network = opts.network || 'mainnet';+ const { PumpTradeClient } = await import('@three-ws/agent-payments');+ const url = opts.rpcUrl || (network === 'devnet' ? RPC.devnet() : RPC.mainnet());+ const connection = opts.connection || new Connection(url, 'confirmed');+ const client = new PumpTradeClient(connection);++ return {+ connection,++ async quoteForBuy({ mint, quoteLamports, slippagePct }) {+ const q = await client.quoteForBuy({ mint, quoteAmount: toBN(quoteLamports), slippagePct });+ return {+ priceImpactPct: Number(q.priceImpactPct ?? 0),+ quoteMint: q.quoteMint || new PublicKey(WSOL),+ };+ },++ async buildBuyInstructions({ mint, user, quoteLamports, slippagePct }) {+ const built = await client.buildBuyInstructions({ mint, user, quoteAmount: toBN(quoteLamports), slippagePct });+ return {+ instructions: built.instructions,+ expectedBaseTokens: BigInt(built.expectedBaseTokens.toString()),+ };+ },++ async quoteForSell({ mint, baseAmount, slippagePct }) {+ const q = await client.quoteForSell({ mint, baseAmount: toBN(baseAmount), slippagePct });+ return { priceImpactPct: Number(q.priceImpactPct ?? 0), expectedQuoteOut: BigInt(q.expectedQuoteOut.toString()) };+ },++ async buildSellInstructions({ mint, user, baseAmount, slippagePct }) {+ const built = await client.buildSellInstructions({ mint, user, baseAmount: toBN(baseAmount), slippagePct });+ return {+ instructions: built.instructions,+ expectedQuoteOut: built.expectedQuoteOut != null ? BigInt(built.expectedQuoteOut.toString()) : undefined,+ };+ },+ };+}++export default createPumpClient;diff --git a/packages/agent-sniper/src/adapters/store/memory.js b/packages/agent-sniper/src/adapters/store/memory.jsnew file mode 100644index 000000000..2cb21abaf--- /dev/null+++ b/packages/agent-sniper/src/adapters/store/memory.js@@ -0,0 +1,134 @@+// agent-sniper — in-memory Store.+//+// The reference Store implementation and the zero-config default. Holds+// strategies + positions in process memory; nothing survives a restart. Perfect+// for simulate mode, tests, and single-run CLI sessions. For durable multi-run+// state use the sqlite store (./sqlite.js) — it implements the same contract.+//+// claimPosition is atomic by construction: JS is single-threaded, so the+// check-then-insert on (agent_id, mint, network) can't interleave.++let _seq = 0;+const nextId = () => `pos_${Date.now().toString(36)}_${(++_seq).toString(36)}`;++const startOfUtcDay = (ms) => {+ const d = new Date(ms);+ return Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate());+};++/**+ * @param {object} [seed]+ * @param {import('../../types.js').Strategy[]} [seed.strategies]+ * @returns {import('../../types.js').Store & { addStrategy: Function, _positions: Map, _spend: any[] }}+ */+export function createMemoryStore(seed = {}) {+ /** @type {Map<string, import('../../types.js').Strategy>} */+ const strategies = new Map();+ /** @type {Map<string, import('../../types.js').Position>} */+ const positions = new Map();+ /** @type {Array<{ agentId: string, network: string, amountLamports: bigint, at: number, category: string }>} */+ const spend = [];++ for (const s of seed.strategies || []) strategies.set(s.id, { ...s });++ const slotKey = (agentId, mint, network) => `${agentId}::${mint}::${network}`;++ return {+ addStrategy(s) { strategies.set(s.id, { ...s }); return s; },+ removeStrategy(id) { return strategies.delete(id); },+ _positions: positions,+ _spend: spend,++ async getArmedStrategies(network) {+ const out = [];+ for (const s of strategies.values()) {+ if (!s.enabled || s.kill_switch) continue;+ if ((s.network || 'mainnet') !== network) continue;+ if (s.stop_loss_pct == null) continue; // mandatory stop-loss+ out.push({ ...s });+ }+ return out;+ },++ async countOpenPositions(agentId, network) {+ let n = 0;+ for (const p of positions.values()) {+ if (p.agent_id === agentId && p.network === network && (p.status === 'open' || p.status === 'opening')) n++;+ }+ return n;+ },++ async getDailySpendLamports(agentId, network) {+ const dayStart = startOfUtcDay(Date.now());+ let total = 0n;+ for (const e of spend) {+ if (e.agentId === agentId && e.network === network && e.at >= dayStart) total += BigInt(e.amountLamports);+ }+ return total;+ },++ async claimPosition({ strategy, candidate, network }) {+ const key = slotKey(strategy.agent_id, candidate.mint, network);+ for (const p of positions.values()) {+ if (slotKey(p.agent_id, p.mint, p.network) === key && p.status !== 'closed' && p.status !== 'failed') {+ return null; // slot already held+ }+ }+ const pos = {+ id: nextId(),+ strategy_id: strategy.id,+ agent_id: strategy.agent_id,+ user_id: strategy.user_id,+ wallet: 'pending',+ network,+ mint: candidate.mint,+ symbol: candidate.symbol || null,+ name: candidate.name || null,+ status: 'opening',+ entry_trigger: candidate.entry_trigger || strategy.trigger || 'new_mint',+ trigger_ref: candidate.trigger_ref || null,+ slippage_bps: strategy.slippage_bps ?? 500,+ take_profit_pct: strategy.take_profit_pct ?? null,+ stop_loss_pct: strategy.stop_loss_pct,+ trailing_stop_pct: strategy.trailing_stop_pct ?? null,+ max_hold_seconds: strategy.max_hold_seconds ?? 1800,+ created_at_ms: Date.now(),+ };+ positions.set(pos.id, pos);+ return { ...pos };+ },++ async updatePosition(id, patch) {+ const cur = positions.get(id);+ if (!cur) return;+ positions.set(id, { ...cur, ...patch });+ },++ async getOpenPositions(network) {+ const out = [];+ for (const p of positions.values()) {+ if (p.network !== network) continue;+ if (p.status === 'open' || p.status === 'closing') out.push({ ...p });+ }+ return out;+ },++ async recordSpend(e) {+ spend.push({ agentId: e.agentId, network: e.network, amountLamports: BigInt(e.amountLamports), at: Date.now(), category: e.category });+ },++ /** Convenience for faces (MCP/API/CLI): list positions for an agent. */+ async listPositions({ agentId, network, status } = {}) {+ const out = [];+ for (const p of positions.values()) {+ if (agentId && p.agent_id !== agentId) continue;+ if (network && p.network !== network) continue;+ if (status && p.status !== status) continue;+ out.push({ ...p });+ }+ return out;+ },+ };+}++export default createMemoryStore;diff --git a/packages/agent-sniper/src/adapters/store/sqlite.js b/packages/agent-sniper/src/adapters/store/sqlite.jsnew file mode 100644index 000000000..923b75881--- /dev/null+++ b/packages/agent-sniper/src/adapters/store/sqlite.js@@ -0,0 +1,393 @@+// agent-sniper — durable SQLite Store.+//+// A drop-in, durable replacement for the in-memory store (./memory.js): it+// implements the exact same Store contract, so the engine can't tell them apart.+// State survives restarts, which is what multi-run CLI sessions and long-lived+// MCP/API servers need. Backed by better-sqlite3 (an OPTIONAL dependency) —+// synchronous under the hood, wrapped so every method still returns a Promise.+//+// claimPosition is atomic by construction here too: a PARTIAL UNIQUE INDEX on+// (agent_id, mint, network) over non-terminal positions makes the reserving+// INSERT fail on a held slot, so two concurrent processes can't double-buy.+//+// Lamport amounts are bigint in the contract but SQLite has no 64-bit-safe+// integer bind for values > 2^53, and better-sqlite3 throws if you hand it a+// BigInt. So every *_lamports / amount value is stored as TEXT and read back+// with BigInt() / Number() at the boundary.++import { createRequire } from 'node:module';++// better-sqlite3 is a CJS native addon; pull it in via a module-scoped require+// rather than `import` so the dependency stays optional and load failures are+// catchable inside the factory.+const require = createRequire(import.meta.url);++let _seq = 0;+const nextId = () => `pos_${Date.now().toString(36)}_${(++_seq).toString(36)}`;++const startOfUtcDay = (ms) => {+ const d = new Date(ms);+ return Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate());+};++// better-sqlite3 rejects BigInt binds outright and silently lossy-casts large+// Numbers — funnel every lamport-ish value through here on the way in.+const asText = (v) => (v == null ? null : String(v));+const asInt = (v) => (v == null ? null : Number(v));+const asBool = (v) => (v == null ? null : v ? 1 : 0);++// Known position columns (TEXT-stored lamport fields flagged so updatePosition+// and claimPosition coerce them consistently). Anything not here lands in `data`.+const POSITION_LAMPORT_COLS = new Set([+ 'entry_quote_lamports',+ 'base_amount',+ 'peak_value_lamports',+ 'last_value_lamports',+ 'realized_pnl_lamports',+]);+const POSITION_INT_COLS = new Set([+ 'slippage_bps',+ 'take_profit_pct',+ 'stop_loss_pct',+ 'trailing_stop_pct',+ 'max_hold_seconds',+ 'realized_pnl_pct',+ 'opened_at_ms',+ 'created_at_ms',+ 'closed_at_ms',+]);+const POSITION_TEXT_COLS = new Set([+ 'strategy_id',+ 'agent_id',+ 'user_id',+ 'wallet',+ 'network',+ 'mint',+ 'symbol',+ 'name',+ 'status',+ 'entry_trigger',+ 'trigger_ref',+ 'error',+ 'exit_reason',+ 'buy_sig',+ 'sell_sig',+]);+const POSITION_COLS = new Set([+ 'id',+ ...POSITION_TEXT_COLS,+ ...POSITION_LAMPORT_COLS,+ ...POSITION_INT_COLS,+]);++// Reassemble a Position object from its row: typed columns + spread `data`.+function rowToPosition(row) {+ if (!row) return null;+ const extra = row.data ? JSON.parse(row.data) : {};+ const pos = { ...extra };+ pos.id = row.id;+ for (const c of POSITION_TEXT_COLS) if (row[c] != null) pos[c] = row[c];+ for (const c of POSITION_LAMPORT_COLS) if (row[c] != null) pos[c] = BigInt(row[c]);+ for (const c of POSITION_INT_COLS) if (row[c] != null) pos[c] = Number(row[c]);+ return pos;+}++// Strategy round-trips through the `data` column verbatim so unknown/forward+// fields survive; the indexed columns exist only for the armed-set query.+function rowToStrategy(row) {+ if (!row) return null;+ return row.data ? JSON.parse(row.data) : null;+}++function strategyIndexValues(s) {+ return {+ id: s.id,+ agent_id: s.agent_id,+ network: s.network || 'mainnet',+ enabled: asBool(s.enabled),+ kill_switch: asBool(s.kill_switch),+ stop_loss_pct: s.stop_loss_pct == null ? null : Number(s.stop_loss_pct),+ trigger: s.trigger || null,+ data: JSON.stringify(s),+ };+}++/**+ * Durable SQLite-backed Store. Same contract as createMemoryStore().+ *+ * @param {object} [opts]+ * @param {string} [opts.path] db file path (default $SNIPER_DB_PATH || './agent-sniper.db')+ * @param {import('../../types.js').Strategy[]} [opts.strategies] seed strategies (upserted)+ * @returns {import('../../types.js').Store & { addStrategy: Function, removeStrategy: Function, close: Function, _db: any }}+ */+export function createSqliteStore(opts = {}) {+ const dbPath = opts.path || process.env.SNIPER_DB_PATH || './agent-sniper.db';++ // Lazy + optional: the package ships without better-sqlite3 by default.+ let Database;+ try {+ Database = require('better-sqlite3');+ } catch {+ throw new Error(+ 'better-sqlite3 is required for the sqlite store — install it or use createMemoryStore()'+ );+ }++ const db = new Database(dbPath);+ db.pragma('journal_mode = WAL');+ db.pragma('foreign_keys = ON');++ db.exec(`+ CREATE TABLE IF NOT EXISTS strategies (+ id TEXT PRIMARY KEY,+ agent_id TEXT NOT NULL,+ network TEXT,+ enabled INTEGER,+ kill_switch INTEGER,+ stop_loss_pct REAL,+ trigger TEXT,+ data TEXT NOT NULL+ );+ CREATE INDEX IF NOT EXISTS idx_strategies_armed+ ON strategies(network, enabled, kill_switch);++ CREATE TABLE IF NOT EXISTS positions (+ id TEXT PRIMARY KEY,+ strategy_id TEXT,+ agent_id TEXT NOT NULL,+ user_id TEXT,+ wallet TEXT,+ network TEXT NOT NULL,+ mint TEXT NOT NULL,+ symbol TEXT,+ name TEXT,+ status TEXT NOT NULL,+ entry_quote_lamports TEXT,+ base_amount TEXT,+ peak_value_lamports TEXT,+ last_value_lamports TEXT,+ slippage_bps INTEGER,+ take_profit_pct INTEGER,+ stop_loss_pct INTEGER,+ trailing_stop_pct INTEGER,+ max_hold_seconds INTEGER,+ entry_trigger TEXT,+ trigger_ref TEXT,+ error TEXT,+ exit_reason TEXT,+ realized_pnl_lamports TEXT,+ realized_pnl_pct INTEGER,+ buy_sig TEXT,+ sell_sig TEXT,+ opened_at_ms INTEGER,+ created_at_ms INTEGER,+ closed_at_ms INTEGER,+ data TEXT+ );+ CREATE INDEX IF NOT EXISTS idx_positions_agent_net+ ON positions(agent_id, network, status);+ CREATE INDEX IF NOT EXISTS idx_positions_net_status+ ON positions(network, status);+ -- The double-buy guard: only one live position per (agent, mint, network).+ CREATE UNIQUE INDEX IF NOT EXISTS uniq_positions_live_slot+ ON positions(agent_id, mint, network)+ WHERE status NOT IN ('closed', 'failed');++ CREATE TABLE IF NOT EXISTS spend (+ agent_id TEXT NOT NULL,+ network TEXT NOT NULL,+ amount_lamports TEXT NOT NULL,+ category TEXT,+ at INTEGER NOT NULL+ );+ CREATE INDEX IF NOT EXISTS idx_spend_agent_net+ ON spend(agent_id, network, at);+ `);++ const stmtUpsertStrategy = db.prepare(`+ INSERT INTO strategies (id, agent_id, network, enabled, kill_switch, stop_loss_pct, trigger, data)+ VALUES (@id, @agent_id, @network, @enabled, @kill_switch, @stop_loss_pct, @trigger, @data)+ ON CONFLICT(id) DO UPDATE SET+ agent_id = excluded.agent_id,+ network = excluded.network,+ enabled = excluded.enabled,+ kill_switch = excluded.kill_switch,+ stop_loss_pct = excluded.stop_loss_pct,+ trigger = excluded.trigger,+ data = excluded.data+ `);+ const stmtDeleteStrategy = db.prepare('DELETE FROM strategies WHERE id = ?');+ const stmtArmedStrategies = db.prepare(`+ SELECT data FROM strategies+ WHERE enabled = 1+ AND (kill_switch IS NULL OR kill_switch = 0)+ AND network = ?+ AND stop_loss_pct IS NOT NULL+ `);+ const stmtCountOpen = db.prepare(`+ SELECT COUNT(*) AS n FROM positions+ WHERE agent_id = ? AND network = ? AND status IN ('open', 'opening')+ `);+ const stmtDailySpend = db.prepare(`+ SELECT amount_lamports FROM spend+ WHERE agent_id = ? AND network = ? AND at >= ?+ `);+ const stmtGetPosition = db.prepare('SELECT * FROM positions WHERE id = ?');+ const stmtOpenPositions = db.prepare(`+ SELECT * FROM positions+ WHERE network = ? AND status IN ('open', 'closing')+ `);+ const stmtRecordSpend = db.prepare(`+ INSERT INTO spend (agent_id, network, amount_lamports, category, at)+ VALUES (@agent_id, @network, @amount_lamports, @category, @at)+ `);++ function upsertStrategy(s) {+ stmtUpsertStrategy.run(strategyIndexValues(s));+ return s;+ }++ for (const s of opts.strategies || []) upsertStrategy(s);++ return {+ _db: db,+ close() { db.close(); },+ addStrategy(s) { return upsertStrategy(s); },+ removeStrategy(id) { return stmtDeleteStrategy.run(id).changes > 0; },++ async getArmedStrategies(network) {+ return stmtArmedStrategies.all(network).map(rowToStrategy).filter(Boolean);+ },++ async countOpenPositions(agentId, network) {+ return stmtCountOpen.get(agentId, network).n;+ },++ async getDailySpendLamports(agentId, network) {+ const dayStart = startOfUtcDay(Date.now());+ let total = 0n;+ for (const row of stmtDailySpend.all(agentId, network, dayStart)) {+ total += BigInt(row.amount_lamports);+ }+ return total;+ },++ async claimPosition({ strategy, candidate, network }) {+ const row = {+ id: nextId(),+ strategy_id: strategy.id,+ agent_id: strategy.agent_id,+ user_id: strategy.user_id ?? null,+ wallet: 'pending',+ network,+ mint: candidate.mint,+ symbol: candidate.symbol || null,+ name: candidate.name || null,+ status: 'opening',+ entry_quote_lamports: null,+ base_amount: null,+ peak_value_lamports: null,+ last_value_lamports: null,+ slippage_bps: asInt(strategy.slippage_bps ?? 500),+ take_profit_pct: asInt(strategy.take_profit_pct ?? null),+ stop_loss_pct: asInt(strategy.stop_loss_pct),+ trailing_stop_pct: asInt(strategy.trailing_stop_pct ?? null),+ max_hold_seconds: asInt(strategy.max_hold_seconds ?? 1800),+ entry_trigger: candidate.entry_trigger || strategy.trigger || 'new_mint',+ trigger_ref: candidate.trigger_ref || null,+ error: null,+ exit_reason: null,+ realized_pnl_lamports: null,+ realized_pnl_pct: null,+ buy_sig: null,+ sell_sig: null,+ opened_at_ms: null,+ created_at_ms: Date.now(),+ closed_at_ms: null,+ data: null,+ };+ try {+ db.prepare(`+ INSERT INTO positions (+ id, strategy_id, agent_id, user_id, wallet, network, mint, symbol, name, status,+ entry_quote_lamports, base_amount, peak_value_lamports, last_value_lamports,+ slippage_bps, take_profit_pct, stop_loss_pct, trailing_stop_pct, max_hold_seconds,+ entry_trigger, trigger_ref, error, exit_reason, realized_pnl_lamports, realized_pnl_pct,+ buy_sig, sell_sig, opened_at_ms, created_at_ms, closed_at_ms, data+ ) VALUES (+ @id, @strategy_id, @agent_id, @user_id, @wallet, @network, @mint, @symbol, @name, @status,+ @entry_quote_lamports, @base_amount, @peak_value_lamports, @last_value_lamports,+ @slippage_bps, @take_profit_pct, @stop_loss_pct, @trailing_stop_pct, @max_hold_seconds,+ @entry_trigger, @trigger_ref, @error, @exit_reason, @realized_pnl_lamports, @realized_pnl_pct,+ @buy_sig, @sell_sig, @opened_at_ms, @created_at_ms, @closed_at_ms, @data+ )+ `).run(row);+ } catch (err) {+ // Partial-unique violation ⇒ a live slot is already held: skip, no double buy.+ if (err && err.code === 'SQLITE_CONSTRAINT_UNIQUE') return null;+ throw err;+ }+ return rowToPosition(stmtGetPosition.get(row.id));+ },++ async updatePosition(id, patch) {+ const cur = stmtGetPosition.get(id);+ if (!cur) return;++ const sets = [];+ const params = {};+ const extra = cur.data ? JSON.parse(cur.data) : {};+ let extraTouched = false;++ for (const [key, val] of Object.entries(patch)) {+ if (key === 'id') continue; // PK is immutable+ if (POSITION_COLS.has(key)) {+ sets.push(`${key} = @${key}`);+ if (POSITION_LAMPORT_COLS.has(key)) params[key] = asText(val);+ else if (POSITION_INT_COLS.has(key)) params[key] = asInt(val);+ else params[key] = val == null ? null : String(val);+ } else {+ // Unknown patch key → merge into the JSON sidecar (bigints → strings).+ extra[key] = typeof val === 'bigint' ? String(val) : val;+ extraTouched = true;+ }+ }++ if (extraTouched) {+ sets.push('data = @data');+ params.data = JSON.stringify(extra);+ }+ if (!sets.length) return;++ params.id = id;+ db.prepare(`UPDATE positions SET ${sets.join(', ')} WHERE id = @id`).run(params);+ },++ async getOpenPositions(network) {+ return stmtOpenPositions.all(network).map(rowToPosition);+ },++ async recordSpend(e) {+ stmtRecordSpend.run({+ agent_id: e.agentId,+ network: e.network,+ amount_lamports: String(e.amountLamports),+ category: e.category || null,+ at: Date.now(),+ });+ },++ /** Convenience for faces (MCP/API/CLI): list positions for an agent. */+ async listPositions({ agentId, network, status } = {}) {+ const where = [];+ const args = [];+ if (agentId) { where.push('agent_id = ?'); args.push(agentId); }+ if (network) { where.push('network = ?'); args.push(network); }+ if (status) { where.push('status = ?'); args.push(status); }+ const sql = `SELECT * FROM positions${where.length ? ' WHERE ' + where.join(' AND ') : ''}`;+ return db.prepare(sql).all(...args).map(rowToPosition);+ },+ };+}++export default createSqliteStore;diff --git a/packages/agent-sniper/src/adapters/wallet/custodial.js b/packages/agent-sniper/src/adapters/wallet/custodial.jsnew file mode 100644index 000000000..5f9f51e86--- /dev/null+++ b/packages/agent-sniper/src/adapters/wallet/custodial.js@@ -0,0 +1,46 @@+// agent-sniper — custodial Wallet adapter.+//+// For a hosted, multi-tenant deployment where the operator holds (encrypted)+// keys on behalf of users — e.g. three.ws's `agent_identities.encrypted_solana_+// secret`. You supply a single async `resolve(agentId, ctx)` that returns a+// Keypair (decrypting on demand from your own KMS/secret box); this adapter adds+// a short TTL cache so a long-lived process doesn't re-decrypt on every trade.+//+// SECURITY: cache hits keep key material in process memory for up to ttlMs. The+// resolve callback is the right place to write your decrypt audit row — it's+// invoked once per (cold) load, never on a cache hit, which is the correct+// audit semantics (no key left the process on a hit).++const DEFAULT_TTL_MS = 5 * 60_000;++/**+ * @param {object} opts+ * @param {(agentId: string, ctx: { userId?: string, reason?: string }) =>+ * Promise<import('@solana/web3.js').Keypair|null>} opts.resolve+ * @param {number} [opts.ttlMs]+ * @returns {import('../../types.js').Wallet & { clearCache: () => void }}+ */+export function createCustodialWallet(opts) {+ if (typeof opts?.resolve !== 'function') {+ throw new Error('[agent-sniper] createCustodialWallet requires a resolve(agentId, ctx) callback');+ }+ const ttlMs = opts.ttlMs ?? DEFAULT_TTL_MS;+ const cache = new Map(); // agentId → { keypair, at }++ return {+ clearCache() { cache.clear(); },++ async loadKeypair(agentId, ctx = {}) {+ const hit = cache.get(agentId);+ if (hit && Date.now() - hit.at < ttlMs) {+ return { keypair: hit.keypair, address: hit.keypair.publicKey.toBase58() };+ }+ const keypair = await opts.resolve(agentId, ctx);+ if (!keypair) return null;+ cache.set(agentId, { keypair, at: Date.now() });+ return { keypair, address: keypair.publicKey.toBase58() };+ },+ };+}++export default createCustodialWallet;diff --git a/packages/agent-sniper/src/adapters/wallet/self-custody.js b/packages/agent-sniper/src/adapters/wallet/self-custody.jsnew file mode 100644index 000000000..63bd3a2e5--- /dev/null+++ b/packages/agent-sniper/src/adapters/wallet/self-custody.js@@ -0,0 +1,78 @@+// agent-sniper — self-custodial Wallet adapter.+//+// Keys never leave the machine. Each agent maps to a local ed25519 Keypair,+// loaded from (in priority order):+// 1. an in-memory map passed to the constructor (agentId → secret)+// 2. SNIPER_WALLET_<AGENTID> env (base58 or JSON array secret key)+// 3. a keystore directory of `<agentId>.json` files (Solana CLI keypair format)+// 4. a single default keypair (SOLANA_SECRET_KEY / --keypair) for one-agent runs+//+// Accepts base58 strings, JSON byte arrays (`[12,34,...]`), and 0x-hex secrets.++import fs from 'node:fs';+import path from 'node:path';+import { Keypair } from '@solana/web3.js';+import bs58 from 'bs58';++function decodeSecret(raw) {+ if (!raw) return null;+ const s = String(raw).trim();+ try {+ if (s.startsWith('[')) {+ const arr = Uint8Array.from(JSON.parse(s));+ return Keypair.fromSecretKey(arr);+ }+ if (s.startsWith('0x')) {+ const bytes = Uint8Array.from(Buffer.from(s.slice(2), 'hex'));+ return Keypair.fromSecretKey(bytes);+ }+ return Keypair.fromSecretKey(bs58.decode(s));+ } catch (err) {+ throw new Error(`[agent-sniper] could not decode wallet secret: ${err.message}`);+ }+}++function envKeyFor(agentId) {+ // SNIPER_WALLET_<AGENTID> with non-alphanumerics → underscore, uppercased.+ return `SNIPER_WALLET_${String(agentId).replace(/[^a-zA-Z0-9]/g, '_').toUpperCase()}`;+}++/**+ * @param {object} [opts]+ * @param {Record<string, string>} [opts.secrets] agentId → secret (base58/json/hex)+ * @param {string} [opts.keystoreDir] dir of <agentId>.json keypairs+ * @param {string} [opts.defaultSecret] fallback secret for any agentId (single-wallet mode)+ * @returns {import('../../types.js').Wallet}+ */+export function createSelfCustodyWallet(opts = {}) {+ const cache = new Map(); // agentId → Keypair+ const inline = new Map(Object.entries(opts.secrets || {}));+ const keystoreDir = opts.keystoreDir || process.env.SNIPER_KEYSTORE_DIR || null;+ const defaultSecret = opts.defaultSecret || process.env.SOLANA_SECRET_KEY || null;++ function resolve(agentId) {+ if (cache.has(agentId)) return cache.get(agentId);++ let kp = null;+ if (inline.has(agentId)) kp = decodeSecret(inline.get(agentId));+ if (!kp && process.env[envKeyFor(agentId)]) kp = decodeSecret(process.env[envKeyFor(agentId)]);+ if (!kp && keystoreDir) {+ const file = path.join(keystoreDir, `${agentId}.json`);+ if (fs.existsSync(file)) kp = decodeSecret(fs.readFileSync(file, 'utf8'));+ }+ if (!kp && defaultSecret) kp = decodeSecret(defaultSecret);++ if (kp) cache.set(agentId, kp);+ return kp;+ }++ return {+ async loadKeypair(agentId) {+ const keypair = resolve(agentId);+ if (!keypair) return null;+ return { keypair, address: keypair.publicKey.toBase58() };+ },+ };+}++export default createSelfCustodyWallet;diff --git a/packages/agent-sniper/src/agents/manifest.js b/packages/agent-sniper/src/agents/manifest.jsnew file mode 100644index 000000000..210ef45e0--- /dev/null+++ b/packages/agent-sniper/src/agents/manifest.js@@ -0,0 +1,229 @@+// agent-sniper — 3D agent layer.+//+// The "embodiment" half of @three-ws/agent-sniper. The engine (engine.js) runs+// the trade loop; this module turns a Strategy + an avatar choice into a+// renderable 3D-agent config, and normalizes the live screen-push events the+// engine already emits (Hooks.onScreen) into desk-monitor frames a web watch+// view or the in-world desk can paint.+//+// Product vision: every user's sniper is embodied by a humanoid AI agent+// standing at a desk in /play, whose monitor shows live sniping activity. The+// avatars + animation clips referenced here are REAL three.ws assets shipped+// under public/ (so the same URLs resolve in /play, /agent-screen, and the SDK):+//+// • Avatars — public/avatars/*.glb (default.glb, mannequin.glb, …).+// • Animation — public/animations/manifest.json canonical clips ('idle',+// 'walk'). Any humanoid rig can be driven by them: src/glb-canonicalize.js+// maps its bone names to the canonical set and src/animation-retarget.js+// retargets the clip on, so we never need a per-avatar clip — the three.ws+// avatar stack handles retargeting at render time.+//+// Pure ESM, zero runtime deps, zero three.ws backend imports. This is a data /+// config module: it references asset paths as plain strings and shapes events;+// it never loads GLBs, opens an SSE connection, or reads the clock. Frame ids+// are deterministic — pass a `ts` in if you want one, otherwise it stays null.++/** lamports → SOL, matching executor.js's `lamportsToSol`. @param {string|number|bigint} l */+const lamportsToSol = (l) => (l == null ? 0 : Number(BigInt(l)) / 1e9);++/**+ * Selectable 3D-agent avatar presets. Every `glb` is a REAL asset shipped at+ * that absolute path under three.ws/public — e.g. `/avatars/default.glb`+ * resolves to https://three.ws/avatars/default.glb in production and is served+ * locally by Vite in dev. The first entry is the platform default.+ *+ * @type {ReadonlyArray<{ id: string, name: string, glb: string, description: string }>}+ */+export const AGENT_AVATARS = Object.freeze([+ {+ id: 'default',+ name: 'Operator',+ glb: '/avatars/default.glb',+ description: 'The three.ws default rig — neutral humanoid, fits any desk.',+ },+ {+ id: 'mannequin',+ name: 'Mannequin',+ glb: '/avatars/mannequin.glb',+ description: 'Clean studio mannequin. Reads well on the monitor backlight.',+ },+ {+ id: 'michelle',+ name: 'Michelle',+ glb: '/avatars/michelle.glb',+ description: 'Stylized analyst — expressive face for narration moments.',+ },+ {+ id: 'realistic-male',+ name: 'Trader',+ glb: '/avatars/realistic-male.glb',+ description: 'Realistic humanoid trader, head-down at the terminal.',+ },+]);++/** The platform default avatar (first preset). @type {AGENT_AVATARS[number]} */+const DEFAULT_AVATAR = AGENT_AVATARS[0];++/**+ * Canonical animation clips ANY humanoid avatar can be driven by. These names+ * are the REAL entries in public/animations/manifest.json. Retargeting onto an+ * arbitrary rig is handled by the three.ws avatar stack (glb-canonicalize.js →+ * animation-retarget.js) at render time — no per-avatar clip is needed here.+ *+ * idle — the desk figure's resting/breathing loop while it waits for signal.+ * walk — locomotion clip, used if the agent paces between events.+ *+ * @type {{ idle: string, walk: string }}+ */+export const ANIMATION_CLIPS = Object.freeze({+ idle: 'idle',+ walk: 'walk',+});++/**+ * Resolve a preset by id, falling back to the platform default when the id is+ * missing or unknown. Never returns null — the desk always has a body to spawn.+ * @param {string} [avatarId]+ * @returns {AGENT_AVATARS[number]}+ */+function resolveAvatar(avatarId) {+ if (!avatarId) return DEFAULT_AVATAR;+ return AGENT_AVATARS.find((a) => a.id === avatarId) || DEFAULT_AVATAR;+}++/**+ * Bind a sniper Strategy to an avatar and produce a renderable 3D-agent config.+ * Lamport fields are converted to SOL for display; the raw strategy is never+ * mutated. The returned shape is what a desk spawner / web watch view consumes.+ *+ * @param {object} p+ * @param {import('../types.js').Strategy} p.strategy the armed strategy to embody+ * @param {string} [p.avatarId] one of AGENT_AVATARS[].id (falls back to default)+ * @param {string} [p.name] display name override (else strategy.agent_name)+ * @returns {{+ * agentId: string,+ * name: string,+ * avatar: AGENT_AVATARS[number],+ * animations: { idle: string, walk: string },+ * desk: { screen: boolean },+ * strategySummary: {+ * trigger: string,+ * perTradeSol: number,+ * dailyBudgetSol: number,+ * stopLossPct: number|null,+ * takeProfitPct: number|null,+ * },+ * }}+ */+export function agentConfig({ strategy, avatarId, name } = {}) {+ if (!strategy || !strategy.agent_id) {+ throw new Error('[agent-sniper/manifest] agentConfig requires a strategy with an agent_id');+ }+ const avatar = resolveAvatar(avatarId);+ return {+ agentId: strategy.agent_id,+ name: name || strategy.agent_name || 'Sniper',+ avatar,+ animations: ANIMATION_CLIPS,+ desk: { screen: true },+ strategySummary: {+ trigger: strategy.trigger || 'new_mint',+ perTradeSol: lamportsToSol(strategy.per_trade_lamports),+ dailyBudgetSol: lamportsToSol(strategy.daily_budget_lamports),+ stopLossPct: strategy.stop_loss_pct ?? null,+ takeProfitPct: strategy.take_profit_pct ?? null,+ },+ };+}++// Phase classification + accent palette. `kind`/`type`/`phase` on a screen-push+// event is one of the engine's three categories (engine.js screen() helper and+// agent-screen-sniper-wiring.md): 'analysis', 'trade', 'activity'. A 'trade'+// frame is colored by P&L direction when a delta is present, so a win reads+// green and a loss reads red on the monitor; 'analysis' is the scoring blue and+// 'activity' is the neutral status gray.+const ACCENTS = Object.freeze({+ analysis: '#5b8fff', // blue — matches walk-agent-desk.js PAL.accent+ tradeUp: '#3ddc84', // green — matches walk-agent-desk.js PAL.live+ tradeDown: '#ff5b6e',// red+ tradeFlat: '#3ddc84',// green — a trade with no signed delta still reads "live"+ activity: '#8a90a2', // gray — neutral status line+});++/** Map a raw screen-push kind to a normalized phase. */+function normalizePhase(kind) {+ const k = String(kind || 'activity').toLowerCase();+ if (k === 'analysis' || k === 'scored' || k === 'score' || k === 'hold') return 'analysis';+ if (k === 'trade' || k === 'buy' || k === 'sell' || k === 'exit') return 'trade';+ return 'activity';+}++/** Pick the first finite signed number from a list of candidates, else null. */+function firstNumber(...vals) {+ for (const v of vals) {+ if (v == null || v === '') continue;+ const n = Number(v);+ if (Number.isFinite(n)) return n;+ }+ return null;+}++/**+ * Normalize a single screen-push event into a desk-monitor frame the 3D desk+ * (walk-agent-desk.js) or the 2D web watch view can render. Pure and+ * deterministic: no Date.now, no Math.random. Pass `ts` to stamp the frame;+ * omit it and `ts` stays null (the renderer assigns its own arrival time).+ *+ * Accepts the SAME event shape the engine emits and agent-screen-sniper-wiring+ * documents: { text, kind|type|phase, mint?, symbol?, solDelta?, pct? }.+ *+ * @param {{+ * text?: string,+ * activity?: string,+ * kind?: string, type?: string, phase?: string,+ * mint?: string,+ * symbol?: string,+ * solDelta?: number|string,+ * pct?: number|string,+ * }} [event]+ * @param {number|null} [ts] optional frame timestamp (ms). Default null.+ * @returns {{+ * ts: number|null,+ * phase: 'analysis'|'trade'|'activity',+ * line: string,+ * accent: string,+ * ticker?: { symbol: string|null, solDelta: number|null, pct: number|null },+ * }}+ */+export function deskMonitorFrame(event = {}, ts = null) {+ const phase = normalizePhase(event.kind ?? event.type ?? event.phase);+ const line = String(event.text ?? event.activity ?? '').trim();+ const symbol = event.symbol ? String(event.symbol).toUpperCase() : null;+ const solDelta = firstNumber(event.solDelta);+ const pct = firstNumber(event.pct);++ let accent;+ if (phase === 'analysis') {+ accent = ACCENTS.analysis;+ } else if (phase === 'trade') {+ const dir = solDelta != null ? solDelta : pct;+ accent = dir == null ? ACCENTS.tradeFlat : dir < 0 ? ACCENTS.tradeDown : ACCENTS.tradeUp;+ } else {+ accent = ACCENTS.activity;+ }++ /** @type {{ ts: number|null, phase: string, line: string, accent: string, ticker?: object }} */+ const frame = {+ ts: ts ?? null,+ phase,+ line,+ accent,+ };++ // Attach a P&L ticker only when there's something quantitative to show.+ if (symbol || solDelta != null || pct != null) {+ frame.ticker = { symbol, solDelta, pct };+ }++ return frame;+}diff --git a/packages/agent-sniper/src/config.js b/packages/agent-sniper/src/config.jsnew file mode 100644index 000000000..68de18200--- /dev/null+++ b/packages/agent-sniper/src/config.js@@ -0,0 +1,64 @@+// agent-sniper — runtime configuration.+//+// Standalone: no database or platform env is required. Reads SNIPER_* env for+// defaults, then applies an explicit overrides object (which always wins). The+// result is the immutable runtime config the engine reads on every tick.++function num(name, def) {+ const raw = process.env[name];+ if (raw == null || raw === '') return def;+ const n = Number(raw);+ return Number.isFinite(n) ? n : def;+}++function bool(name, def = false) {+ const raw = process.env[name];+ if (raw == null || raw === '') return def;+ return /^(1|true|yes|on)$/i.test(String(raw).trim());+}++/**+ * @param {Partial<ReturnType<typeof loadConfig>>} [overrides]+ */+export function loadConfig(overrides = {}) {+ const network = (overrides.network || process.env.SNIPER_NETWORK || 'mainnet').trim();+ if (network !== 'mainnet' && network !== 'devnet') {+ throw new Error(`[agent-sniper] network must be mainnet|devnet, got "${network}"`);+ }++ const mode = (overrides.mode || process.env.SNIPER_MODE || 'simulate').trim();+ if (mode !== 'live' && mode !== 'simulate') {+ throw new Error(`[agent-sniper] mode must be live|simulate, got "${mode}"`);+ }++ // Live trading on a public RPC will 429 under the new-mint firehose. Refuse to+ // start live without a real endpoint rather than silently dropping trades.+ const rpcUrl = overrides.rpcUrl || process.env.SOLANA_RPC_URL || null;+ if (mode === 'live' && !rpcUrl && !process.env.HELIUS_API_KEY) {+ throw new Error('[agent-sniper] live mode requires rpcUrl / SOLANA_RPC_URL or HELIUS_API_KEY (public RPC will rate-limit)');+ }++ const cfg = {+ network,+ mode,+ rpcUrl,+ globalKill: overrides.globalKill ?? bool('SNIPER_GLOBAL_KILL', false),+ // Position re-quote / exit-evaluation cadence.+ pollMs: Math.max(1_000, overrides.pollMs ?? num('SNIPER_POLL_MS', 5_000)),+ // How often the strategy cache is refreshed from the Store.+ strategyRefreshMs: Math.max(5_000, overrides.strategyRefreshMs ?? num('SNIPER_STRATEGY_REFRESH_MS', 15_000)),+ // Platform-wide buy throttle — a backstop independent of per-agent caps.+ maxGlobalBuysPerMin: Math.max(0, overrides.maxGlobalBuysPerMin ?? num('SNIPER_MAX_GLOBAL_BUYS_PER_MIN', 10)),+ // Max concurrent in-flight snipe attempts (bounds RPC pressure).+ buyConcurrency: Math.max(1, overrides.buyConcurrency ?? num('SNIPER_BUY_CONCURRENCY', 3)),+ buyQueueDepth: Math.max(1, overrides.buyQueueDepth ?? num('SNIPER_BUY_QUEUE_DEPTH', 50)),+ // Confirmation timeout for a broadcast trade.+ confirmTimeoutMs: Math.max(15_000, overrides.confirmTimeoutMs ?? num('SNIPER_CONFIRM_TIMEOUT_MS', 60_000)),+ // Watchdog: if the feed delivers nothing for this long, re-subscribe.+ feedWatchdogMs: Math.max(30_000, overrides.feedWatchdogMs ?? num('SNIPER_FEED_WATCHDOG_MS', 180_000)),+ // Sentiment-flip exit (requires a Hooks/Store that supplies sentiment).+ exitOnBearish: overrides.exitOnBearish ?? bool('SNIPER_EXIT_ON_BEARISH', false),+ exitBearishMinConfidence: Math.max(0, Math.min(1, overrides.exitBearishMinConfidence ?? num('SNIPER_EXIT_BEARISH_MIN_CONFIDENCE', 0.7))),+ };+ return Object.freeze(cfg);+}diff --git a/packages/agent-sniper/src/engine.js b/packages/agent-sniper/src/engine.jsnew file mode 100644index 000000000..2fc2cfb5c--- /dev/null+++ b/packages/agent-sniper/src/engine.js@@ -0,0 +1,130 @@+// agent-sniper — orchestrator.+//+// Wires a Feed → scorer → bounded buy queue, plus a position sweep on an+// interval, all over the injected adapters. createSniper() is the single public+// constructor: pass the adapters you want (or accept the defaults), call+// start(), get back a handle with stop() + introspection.++import { loadConfig } from './config.js';+import { log as defaultLog } from './log.js';+import { scoreMint, scoreIntel } from './scorer.js';+import { makeThrottle, makeQueue } from './guards.js';+import { executeBuy } from './executor.js';+import { runPositionSweep } from './positions.js';++/**+ * @param {object} deps+ * @param {Partial<ReturnType<typeof loadConfig>>} [deps.config]+ * @param {import('./types.js').Store} deps.store+ * @param {import('./types.js').Wallet} deps.wallet+ * @param {import('./types.js').SolanaClient} deps.solana+ * @param {import('./types.js').Executor} deps.executor+ * @param {import('./types.js').Feed} deps.feed+ * @param {import('./types.js').Hooks} [deps.hooks]+ * @param {Record<string, number>|null} [deps.intelWeights]+ * @param {typeof defaultLog} [deps.logger]+ */+export function createSniper(deps) {+ const cfg = loadConfig(deps.config || {});+ const log = deps.logger || defaultLog;+ const hooks = deps.hooks || {};+ const ports = { store: deps.store, wallet: deps.wallet, solana: deps.solana, executor: deps.executor, hooks, log };+ if (!ports.store || !ports.wallet || !ports.solana || !ports.executor || !deps.feed) {+ throw new Error('[agent-sniper] createSniper requires store, wallet, solana, executor, and feed adapters');+ }++ const throttle = makeThrottle(cfg.maxGlobalBuysPerMin);+ let strategies = [];+ let stopFeed = null;+ let sweepTimer = null;+ let refreshTimer = null;+ let draining = false;+ let lastEventAt = Date.now();+ const stats = { events: 0, candidates: 0, buys: 0, sells: 0, errors: 0 };++ const queue = makeQueue(cfg.buyConcurrency, cfg.buyQueueDepth, {+ onError: (err) => { stats.errors++; log.error('buy job crashed', { err: err?.message }); },+ onDrop: () => log.warn('buy queue full — dropping snipe'),+ });++ async function refreshStrategies() {+ try {+ strategies = await ports.store.getArmedStrategies(cfg.network);+ } catch (err) {+ log.error('strategy refresh failed', { err: err?.message });+ }+ }++ function screen(text, kind) { try { hooks.onScreen?.({ text, kind }); } catch { /* best-effort */ } }++ function onEvent({ kind, data }) {+ lastEventAt = Date.now();+ stats.events++;+ if (draining || cfg.globalKill || !data?.mint) return;+ const sym = (data.symbol || data.mint.slice(0, 6)).toUpperCase();++ for (const strat of strategies) {+ const trig = strat.trigger || 'new_mint';+ // Route the event to strategies whose trigger matches its kind.+ if (kind === 'mint' && trig !== 'new_mint') continue;+ if (kind === 'intel' && trig !== 'intel_confirmed') continue;+ if (kind === 'claim' && trig !== 'first_claim') continue;+ if (!['mint', 'intel', 'claim'].includes(kind)) continue;++ const { pass, score, reasons } = trig === 'intel_confirmed'+ ? scoreIntel(data, strat, deps.intelWeights || null)+ : scoreMint(data, strat);+ if (!pass) continue;++ stats.candidates++;+ log.info('candidate', { agent: strat.agent_id, mint: data.mint, symbol: data.symbol, score, reasons });+ screen(`$${sym} scored ${score} — BUYING`, 'trade');+ queue.push(async () => {+ const res = await executeBuy({ cfg, strat, candidate: data, throttle, ports });+ if (res?.status === 'open') stats.buys++;+ });+ }+ }++ async function sweep() {+ await runPositionSweep(cfg, ports);+ }++ return {+ config: cfg,+ stats: () => ({ ...stats, strategies: strategies.length, queued: queue.inFlight, lastEventAt }),+ strategies: () => strategies.slice(),++ async start() {+ log.info('boot', { network: cfg.network, mode: cfg.mode, globalKill: cfg.globalKill, pollMs: cfg.pollMs });+ screen(`Sniper online — ${cfg.network} / ${cfg.mode} mode`, 'activity');+ await refreshStrategies();+ refreshTimer = setInterval(refreshStrategies, cfg.strategyRefreshMs);+ refreshTimer.unref?.();+ sweepTimer = setInterval(() => { sweep().catch((err) => log.error('sweep failed', { err: err?.message })); }, cfg.pollMs);+ sweepTimer.unref?.();+ stopFeed = await deps.feed.start(onEvent);+ return this;+ },++ /** Score + (queue) a single candidate by hand — drives the `manual` trigger / MCP snipe_now. */+ submitCandidate(candidate, { force = false } = {}) {+ if (force) {+ // Bypass the feed scorer: run every armed strategy's buy directly.+ for (const strat of strategies) {+ queue.push(() => executeBuy({ cfg, strat, candidate, throttle, ports }));+ }+ return;+ }+ onEvent({ kind: candidate.entry_trigger === 'intel_confirmed' ? 'intel' : 'mint', data: candidate });+ },++ async stop() {+ draining = true;+ try { stopFeed?.(); } catch { /* feed already closed */ }+ if (sweepTimer) clearInterval(sweepTimer);+ if (refreshTimer) clearInterval(refreshTimer);+ log.info('shutdown', stats);+ },+ };+}diff --git a/packages/agent-sniper/src/executor.js b/packages/agent-sniper/src/executor.jsnew file mode 100644index 000000000..45fe59c37--- /dev/null+++ b/packages/agent-sniper/src/executor.js@@ -0,0 +1,302 @@+// agent-sniper — the only module that signs and broadcasts.+//+// executeBuy / executeSell own every guardrail, the idempotency claim, the trade+// build, the broadcast, and the position writes — all through the injected+// adapters (Store, Wallet, Solana, Executor) and optional Hooks. In `simulate`+// mode the full path runs against REAL on-chain quotes but the broadcast is+// skipped (sig = 'SIMULATED'). No three.ws / Postgres coupling.++import { PublicKey } from '@solana/web3.js';+import BN from 'bn.js';+import {+ checkConcurrency, checkDailyBudgetLamports, checkSolHeadroom, checkPriceImpact,+ snipeConfidence, SOL_FEE_HEADROOM_LAMPORTS,+} from './guards.js';++const WSOL_MINT = 'So11111111111111111111111111111111111111112';++// ── per-agent serialization ──────────────────────────────────────────────────+// A per-agent in-process lock makes the budget + concurrency checks race-free+// within one process. (Horizontal scaling needs an atomic Store reservation — see+// README "Scaling beyond one process".)+const _locks = new Map();+async function withAgentLock(agentId, fn) {+ const prev = _locks.get(agentId) || Promise.resolve();+ let release;+ const next = new Promise((r) => (release = r));+ _locks.set(agentId, prev.then(() => next));+ await prev;+ try {+ return await fn();+ } finally {+ release();+ if (_locks.get(agentId) === next) _locks.delete(agentId);+ }+}++const toBN = (v) => new BN(BigInt(v).toString());+const lamportsToSol = (l) => Number(BigInt(l)) / 1e9;+const symOf = (m) => (m.symbol || m.mint.slice(0, 6)).toUpperCase();++/**+ * @typedef {object} Ports+ * @property {import('./types.js').Store} store+ * @property {import('./types.js').Wallet} wallet+ * @property {import('./types.js').SolanaClient} solana+ * @property {import('./types.js').Executor} executor+ * @property {import('./types.js').Hooks} hooks+ * @property {typeof import('./log.js').log} log+ */++/**+ * Attempt to snipe `candidate` for `strat`. All checks short-circuit before any+ * tx is built. Returns a small status object; never throws.+ *+ * @param {object} p+ * @param {ReturnType<import('./config.js').loadConfig>} p.cfg+ * @param {import('./types.js').Strategy} p.strat+ * @param {import('./types.js').Candidate} p.candidate+ * @param {{ tryConsume: () => boolean }} p.throttle+ * @param {Ports} p.ports+ */+export async function executeBuy({ cfg, strat, candidate, throttle, ports }) {+ const { store, wallet, solana, executor, hooks, log } = ports;+ return withAgentLock(strat.agent_id, async () => {+ const perTrade = BigInt(strat.per_trade_lamports);+ const tag = { agent: strat.agent_id, mint: candidate.mint, symbol: candidate.symbol };+ const screen = (text, kind, extra) => safe(() => hooks.onScreen?.({ text, kind, ...extra }));++ // 1. global throttle (platform-wide backstop)+ if (!throttle.tryConsume()) return skip(log, tag, 'global_throttle');++ // 2. concurrency cap+ const open = await store.countOpenPositions(strat.agent_id, cfg.network);+ const conc = checkConcurrency(open, strat.max_concurrent_positions);+ if (conc) return skip(log, tag, conc.reason);++ // 3. daily budget cap+ const spent = await store.getDailySpendLamports(strat.agent_id, cfg.network);+ const budget = checkDailyBudgetLamports(spent, perTrade, BigInt(strat.daily_budget_lamports));+ if (budget) return skip(log, tag, budget.reason);++ // 4. optional oracle/conviction gate+ if (hooks.oracleGate) {+ const og = await safeAsync(() => hooks.oracleGate({ agentId: strat.agent_id, candidate, network: cfg.network, strategy: strat }));+ if (og && og.pass === false) {+ screen(`$${symOf(candidate)} oracle blocked: ${og.reason}`, 'analysis');+ return skip(log, tag, og.reason || 'oracle_gate');+ }+ }++ // 5. idempotency claim — reserve (agent,mint,network) BEFORE the tx.+ const position = await store.claimPosition({ strategy: strat, candidate, network: cfg.network });+ if (!position) return skip(log, tag, 'already_held');+ const posId = position.id;++ try {+ // 6. agent wallet + funds+ const loaded = await wallet.loadKeypair(strat.agent_id, { userId: strat.user_id, reason: 'sniper_buy' });+ if (!loaded) return await fail(store, log, posId, tag, 'no_wallet');+ const { keypair, address } = loaded;+ await store.updatePosition(posId, { wallet: address });++ const balance = BigInt(await solana.connection.getBalance(keypair.publicKey, 'confirmed'));+ const headroom = checkSolHeadroom(balance, perTrade, SOL_FEE_HEADROOM_LAMPORTS);+ if (headroom) return await fail(store, log, posId, tag, headroom.reason);++ const mintPk = new PublicKey(candidate.mint);+ const slippagePct = (strat.slippage_bps ?? 500) / 100;++ // 7. quote + price-impact circuit breaker+ const quote = await solana.quoteForBuy({ mint: mintPk, quoteLamports: perTrade, slippagePct });+ if (strat.require_sol_quote !== false && quote.quoteMint && quote.quoteMint.toBase58 &&+ quote.quoteMint.toBase58() !== WSOL_MINT && !quote.quoteMint.equals?.(PublicKey.default)) {+ return await fail(store, log, posId, tag, 'quote_not_sol');+ }+ const impact = checkPriceImpact(Number(quote.priceImpactPct), Number(strat.max_price_impact_pct));+ if (impact) return await fail(store, log, posId, tag, impact.reason);++ // 8. rug/honeypot firewall (optional hook). 'block' aborts a block verdict;+ // 'warn' logs + proceeds; 'off' skips. A hook throw degrades to 'warn'.+ const firewallLevel = ['warn', 'off'].includes(strat.firewall_level) ? strat.firewall_level : 'block';+ let firewall = null;+ if (firewallLevel !== 'off' && hooks.assessSafety) {+ const a = await safeAsync(() => hooks.assessSafety({+ network: cfg.network, mint: candidate.mint, side: 'buy',+ payer: keypair.publicKey, quoteLamports: perTrade,+ connection: solana.connection, priceImpactPct: Number(quote.priceImpactPct),+ }));+ if (a) {+ if (firewallLevel === 'block' && a.verdict === 'block') {+ const reason = a.reasons?.[0] || 'firewall_blocked';+ await store.updatePosition(posId, { status: 'failed', error: `firewall_block: ${reason}`.slice(0, 280) });+ log.warn('buy blocked by firewall', { ...tag, score: a.score, reasons: a.reasons });+ screen(`$${symOf(candidate)} blocked by firewall: ${reason}`, 'analysis');+ return { status: 'failed', reason: 'firewall_block' };+ }+ firewall = { verdict: a.verdict, score: a.score };+ }+ }++ // 9. build + (live) broadcast+ const built = await solana.buildBuyInstructions({ mint: mintPk, user: keypair.publicKey, quoteLamports: perTrade, slippagePct });+ const baseAmount = BigInt(built.expectedBaseTokens.toString());+ if (baseAmount <= 0n) return await fail(store, log, posId, tag, 'zero_tokens');++ let sig = 'SIMULATED';+ let exec = { route: 'simulated', tipLamports: 0n, priorityFeeMicroLamports: null, landedMs: null, attempts: 0 };+ screen(`Buying $${symOf(candidate)} — sending tx`, 'trade');+ if (cfg.mode === 'live') {+ const tipMode = ['economy', 'turbo'].includes(strat.mev_tip_mode) ? strat.mev_tip_mode : 'off';+ const onTip = makeTipGuard({ strat, spentLamports: spent, committedLamports: perTrade, store, mint: candidate.mint });+ const result = await executor.submit({+ network: cfg.network, connection: solana.connection, payer: keypair,+ instructions: built.instructions, confirmTimeoutMs: cfg.confirmTimeoutMs, tipMode, onTip,+ });+ sig = result.signature;+ exec = result;+ log.trade('exec', { ...tag, route: result.route, tip: String(result.tipLamports ?? 0n), fee: result.priorityFeeMicroLamports, landed_ms: result.landedMs, attempts: result.attempts, fallback: result.fallbackReason || null });+ }++ const pricePerToken = Number(perTrade) / Number(baseAmount);+ await store.updatePosition(posId, {+ status: 'open', buy_sig: sig,+ entry_quote_lamports: perTrade.toString(),+ base_amount: baseAmount.toString(),+ entry_price_lamports_per_token: pricePerToken,+ entry_price_impact_pct: Number(quote.priceImpactPct),+ peak_value_lamports: Number(perTrade),+ last_value_lamports: Number(perTrade),+ exec_route: exec.route,+ tip_lamports: exec.tipLamports != null ? String(exec.tipLamports) : null,+ priority_fee_microlamports: exec.priorityFeeMicroLamports != null ? String(exec.priorityFeeMicroLamports) : null,+ landed_ms: exec.landedMs ?? null,+ opened_at_ms: Date.now(),+ });+ log.trade('buy', { ...tag, mode: cfg.mode, sig, sol: lamportsToSol(perTrade), base: baseAmount.toString(), impact: Number(quote.priceImpactPct).toFixed(2) });+ screen(`Bought $${symOf(candidate)} at ${lamportsToSol(perTrade).toFixed(4)} SOL — position open`, 'trade');+ safe(() => hooks.onBuy?.({ strategy: strat, candidate, posId, sig, solSpent: lamportsToSol(perTrade), mode: cfg.mode, network: cfg.network }));++ await safeAsync(() => store.recordSpend?.({+ agentId: strat.agent_id, userId: strat.user_id, category: 'snipe', network: cfg.network,+ amountLamports: perTrade, signature: sig !== 'SIMULATED' ? sig : null, mint: candidate.mint,+ status: cfg.mode === 'live' ? 'confirmed' : 'ok',+ }));+ await safeAsync(() => hooks.recordDecision?.(buildDecision({ strat, network: cfg.network, candidate, posId, sig, mode: cfg.mode, priceImpactPct: Number(quote.priceImpactPct), firewall, perTradeLamports: perTrade })));+ return { status: 'open', sig, posId };+ } catch (err) {+ return await fail(store, log, posId, tag, errCode(err), err);+ }+ });+}++/**+ * Close `position` for `reason`. Re-quotes fresh for slippage, builds the sell,+ * broadcasts (live), records realized P&L. A failed sell leaves the position+ * 'open' so the next sweep retries rather than stranding the bag.+ *+ * @param {object} p+ * @param {ReturnType<import('./config.js').loadConfig>} p.cfg+ * @param {import('./types.js').Position} p.position+ * @param {string} p.reason+ * @param {Ports} p.ports+ */+export async function executeSell({ cfg, position, reason, ports }) {+ const { store, wallet, solana, executor, hooks, log } = ports;+ return withAgentLock(position.agent_id, async () => {+ const tag = { agent: position.agent_id, mint: position.mint, symbol: position.symbol, reason };+ const screen = (text, kind, extra) => safe(() => hooks.onScreen?.({ text, kind, ...extra }));+ await store.updatePosition(position.id, { status: 'closing' });+ screen(`Selling $${symOf(position)}: ${reason}`, 'trade');++ try {+ const loaded = await wallet.loadKeypair(position.agent_id, { userId: position.user_id, reason: 'sniper_sell' });+ if (!loaded) {+ await store.updatePosition(position.id, { status: 'open', error: 'no_wallet' });+ return { status: 'retry', reason: 'no_wallet' };+ }+ const { keypair } = loaded;+ const mintPk = new PublicKey(position.mint);+ const baseAmount = BigInt(position.base_amount);+ const slippagePct = (position.slippage_bps ?? 500) / 100;++ const quote = await solana.quoteForSell({ mint: mintPk, baseAmount, slippagePct });+ let expectedOut = BigInt(quote.expectedQuoteOut.toString());+ const built = await solana.buildSellInstructions({ mint: mintPk, user: keypair.publicKey, baseAmount, slippagePct });+ if (built.expectedQuoteOut != null) expectedOut = BigInt(built.expectedQuoteOut.toString());++ let sig = 'SIMULATED';+ if (cfg.mode === 'live') {+ const result = await executor.submit({+ network: cfg.network, connection: solana.connection, payer: keypair,+ instructions: built.instructions, confirmTimeoutMs: cfg.confirmTimeoutMs, tipMode: 'off',+ });+ sig = result.signature;+ }++ const entry = BigInt(position.entry_quote_lamports || '0');+ const pnl = expectedOut - entry;+ const pnlPct = entry > 0n ? (Number(pnl) / Number(entry)) * 100 : 0;+ await store.updatePosition(position.id, {+ status: 'closed', exit_reason: reason, sell_sig: sig,+ exit_quote_lamports: expectedOut.toString(),+ realized_pnl_lamports: pnl.toString(), realized_pnl_pct: pnlPct,+ error: null, closed_at_ms: Date.now(),+ });+ const pnlSol = lamportsToSol(pnl);+ log.trade('sell', { ...tag, mode: cfg.mode, sig, pnl_sol: pnlSol, pnl_pct: pnlPct.toFixed(1) });+ screen(`Sold $${symOf(position)} — ${pnlPct >= 0 ? 'profit' : 'loss'}: ${pnlSol >= 0 ? '+' : ''}${pnlSol.toFixed(4)} SOL`, 'trade',+ { phase: 'exit', mint: position.mint, symbol: position.symbol || null, solDelta: pnlSol, pct: pnlPct });+ safe(() => hooks.onSell?.({ position, pnlSol, pnlPct, exitReason: reason, mode: cfg.mode, sig, network: cfg.network }));+ return { status: 'closed', sig, pnl: pnl.toString() };+ } catch (err) {+ await store.updatePosition(position.id, { status: 'open', error: errCode(err) });+ log.warn('sell failed (will retry)', { ...tag, code: errCode(err), err: err?.message });+ screen(`Error: sell $${symOf(position)} failed (${errCode(err)}) — retrying`, 'activity');+ return { status: 'retry', reason: errCode(err) };+ }+ });+}++// Veto hook the executor calls before appending a Jito tip. A tip is real SOL+// leaving the wallet, so it must obey the same daily budget. Throws to veto.+function makeTipGuard({ strat, spentLamports, committedLamports, store, mint }) {+ return async function onTip(tipLamports, route) {+ const tip = BigInt(tipLamports);+ if (tip <= 0n) return;+ if (strat.kill_switch === true) throw Object.assign(new Error('strategy kill switch is on'), { code: 'spend_guard' });+ const budget = BigInt(strat.daily_budget_lamports);+ if (BigInt(spentLamports) + BigInt(committedLamports) + tip > budget) {+ throw Object.assign(new Error('tip would exceed daily budget'), { code: 'spend_guard' });+ }+ await safeAsync(() => store.recordSpend?.({+ agentId: strat.agent_id, userId: strat.user_id, category: 'mev_tip', network: strat.network || 'mainnet',+ amountLamports: tip, signature: null, mint, status: 'confirmed',+ }));+ void route;+ };+}++function buildDecision({ strat, network, candidate, posId, sig, mode, priceImpactPct, firewall, perTradeLamports }) {+ const perTradeSol = Number(BigInt(perTradeLamports)) / 1e9;+ const confidence = snipeConfidence({ priceImpactPct, maxImpactPct: Number(strat.max_price_impact_pct) || 10, firewallVerdict: firewall?.verdict || null });+ const trigger = candidate.entry_trigger || strat.trigger || 'new_mint';+ return {+ agentId: strat.agent_id, kind: 'snipe', subjectRef: candidate.mint, actionRef: String(posId), confidence, network,+ inputs: { entry_trigger: trigger, price_impact_pct: Number(priceImpactPct.toFixed(4)), per_trade_sol: Number(perTradeSol.toFixed(6)), firewall, position_id: posId, buy_sig: sig !== 'SIMULATED' ? sig : null, mode, symbol: candidate.symbol || null },+ prediction: { direction: 'up', basis: 'snipe entry expects a profitable exit', metric: 'realized_pnl' },+ rationale: `Sniped $${symOf(candidate)} on a ${trigger} trigger with ${priceImpactPct.toFixed(2)}% price impact${firewall ? `; firewall ${firewall.verdict} (score ${firewall.score})` : ''}. Committed ${perTradeSol.toFixed(4)} SOL expecting a profitable exit.`,+ };+}++function skip(log, tag, reason) { log.info('skip', { ...tag, reason }); return { status: 'skip', reason }; }+async function fail(store, log, posId, tag, reason, err) {+ await store.updatePosition(posId, { status: 'failed', error: reason, closed_at_ms: Date.now() });+ log.warn('buy aborted', { ...tag, reason, err: err?.message });+ return { status: 'failed', reason };+}+function errCode(err) { return err?.code || err?.name || 'error'; }+function safe(fn) { try { return fn(); } catch { /* best-effort hook */ } }+async function safeAsync(fn) { try { return await fn(); } catch { return null; } }++export { toBN, lamportsToSol };diff --git a/packages/agent-sniper/src/exit-logic.js b/packages/agent-sniper/src/exit-logic.jsnew file mode 100644index 000000000..42bbbca23--- /dev/null+++ b/packages/agent-sniper/src/exit-logic.js@@ -0,0 +1,61 @@+// agent-sniper — exit decision. Pure, no I/O.+//+// Given a position, its current on-chain value, the high-water mark, the clock,+// and an optional sentiment read, decide whether to close — and why. Evaluated+// in a fixed priority order so the reason is deterministic and explainable:+// stop-loss → trailing-stop → take-profit → timeout → sentiment-flip.+//+// Returns an exit-reason string, or null to hold.++function num(v, def = null) {+ if (v == null || v === '') return def;+ const n = Number(v);+ return Number.isFinite(n) ? n : def;+}++/**+ * @param {import('./types.js').Position} pos+ * @param {number} value current value of the position in lamports+ * @param {number} peak high-water mark in lamports (>= value seen so far)+ * @param {number} nowMs Date.now()+ * @param {{ signal: string, confidence: number|null, minConfidence: number }|null} [sentiment]+ * @returns {string|null}+ */+export function decideExit(pos, value, peak, nowMs, sentiment = null) {+ const entry = num(pos.entry_quote_lamports, 0) || 0;+ if (entry <= 0) return null;++ const pnlPct = ((value - entry) / entry) * 100;++ // ── stop-loss (mandatory) ────────────────────────────────────────────────+ const stop = num(pos.stop_loss_pct);+ if (stop != null && pnlPct <= -Math.abs(stop)) return 'stop_loss';++ // ── trailing-stop: drawdown from the peak ────────────────────────────────+ const trail = num(pos.trailing_stop_pct);+ if (trail != null && peak > 0) {+ const dropFromPeakPct = ((peak - value) / peak) * 100;+ // Only arms once the position has been in profit at least the trail amount,+ // so a coin that never moves up can't trail-stop on entry noise.+ if (peak > entry && dropFromPeakPct >= Math.abs(trail)) return 'trailing_stop';+ }++ // ── take-profit ──────────────────────────────────────────────────────────+ const tp = num(pos.take_profit_pct);+ if (tp != null && pnlPct >= Math.abs(tp)) return 'take_profit';++ // ── timeout ──────────────────────────────────────────────────────────────+ const maxHold = num(pos.max_hold_seconds);+ const openedAt = num(pos.opened_at_ms);+ if (maxHold != null && openedAt != null && nowMs - openedAt >= maxHold * 1000) {+ return 'timeout';+ }++ // ── sentiment flip (opt-in, only meaningful while underwater) ─────────────+ if (sentiment && value < entry && sentiment.signal === 'bearish') {+ const conf = num(sentiment.confidence);+ if (conf != null && conf >= sentiment.minConfidence) return 'signal_flip';+ }++ return null;+}diff --git a/packages/agent-sniper/src/faces/api.js b/packages/agent-sniper/src/faces/api.jsnew file mode 100644index 000000000..c029f1191--- /dev/null+++ b/packages/agent-sniper/src/faces/api.js@@ -0,0 +1,328 @@+// agent-sniper — HTTP API face (sniper-as-a-service).+//+// Exposes the engine over HTTP so other agents/users can pay to arm strategies+// and trigger snipes. Reads are free; the three MUTATING endpoints (arm a+// strategy, fire a snipe, disarm a strategy) are gated behind x402 USDC+// micropayments via @three-ws/x402-server's `paid()` middleware — verify the+// X-PAYMENT header against the facilitator, run the work, settle on-chain, emit+// the receipt. The same verify → dispatch → settle order the platform enforces.+//+// import { createSniperApi, serve } from '@three-ws/agent-sniper/api';+// await serve({ payTo: { solana: '<merchant>' } }, { port: 8787 });+//+// Zero three.ws backend imports — only local package files, express (optional),+// and the published @three-ws/x402-server SDK.++import { pathToFileURL } from 'node:url';+import { randomUUID } from 'node:crypto';+import { paid } from '@three-ws/x402-server';+import { presets, createMemoryStore } from '../index.js';++// 1 SOL = 1e9 lamports. The wire takes human SOL amounts; the engine + store+// speak lamports (string-encoded BigInt, mirroring the Strategy contract).+const LAMPORTS_PER_SOL = 1_000_000_000n;++// Default per-endpoint prices in USDC atomic units (6 decimals): 10000 = $0.01,+// 50000 = $0.05, 5000 = $0.005. Overridable via deps.prices.+const DEFAULT_PRICES = {+ arm: '10000', // POST /strategies → $0.01+ snipe: '50000', // POST /snipe → $0.05+ disarm: '5000', // POST /strategies/:id/disarm → $0.005+};++/**+ * Lazily resolve express (an optional dependency). A deployment that never+ * mounts the HTTP face shouldn't have to install it; one that does gets a clear+ * instruction instead of an opaque module-not-found.+ */+async function loadExpress() {+ try {+ const mod = await import('express');+ return mod.default || mod;+ } catch {+ throw new Error('express is required for the HTTP API face — install it');+ }+}++// Convert a human SOL amount (number|string) into a lamports BigInt string.+// Returns null on anything non-finite/negative so the caller can 400 cleanly.+function solToLamportsString(sol) {+ const n = Number(sol);+ if (!Number.isFinite(n) || n < 0) return null;+ // Carry 9 decimals of precision, then drop the fraction — lamports are integer.+ const lamports = (BigInt(Math.round(n * 1e9)) * LAMPORTS_PER_SOL) / 1_000_000_000n;+ return lamports.toString();+}++/**+ * Build the Express router that mounts every sniper endpoint. Free reads mount+ * directly; the three mutating routes are wrapped in `paid()` when payTo is+ * configured, or a 503 guard when it is not (so the server still boots for+ * local/dev without payment config).+ *+ * @param {object} deps+ * @param {ReturnType<import('../engine.js').createSniper>} [deps.sniper] started/unstarted handle; built from presets.local when omitted.+ * @param {import('../types.js').Store} [deps.store] defaults to sniper-bound memory store.+ * @param {{ solana?: string, base?: string }} [deps.payTo] merchant wallet(s); env fallback X402_PAY_TO_SOLANA / X402_PAY_TO_BASE.+ * @param {Record<string,string>} [deps.prices] per-endpoint USDC atomic prices ({ arm, snipe, disarm }).+ * @param {string} [deps.facilitatorUrl] x402 facilitator base URL for /verify + /settle.+ */+export async function createSniperApiRouter(deps = {}) {+ const express = await loadExpress();++ const sniper = deps.sniper || (await presets.local());+ // Reuse the sniper's own store when the caller didn't pass one. presets.local+ // builds a memory store and hands it to createSniper, but doesn't surface it —+ // so an omitted store means an omitted sniper too, where we fall back to a+ // fresh memory store that shares nothing. Prefer an explicit deps.store.+ const store = deps.store || createMemoryStore();++ const payTo = {+ solana: deps.payTo?.solana || process.env.X402_PAY_TO_SOLANA || null,+ base: deps.payTo?.base || process.env.X402_PAY_TO_BASE || null,+ };+ const lanes = {};+ if (payTo.solana) lanes.solana = payTo.solana;+ if (payTo.base) lanes.base = payTo.base;+ const x402Configured = Object.keys(lanes).length > 0;++ const prices = { ...DEFAULT_PRICES, ...(deps.prices || {}) };+ const facilitator = deps.facilitatorUrl || process.env.X402_FACILITATOR_URL || undefined;+ // PayAI's Solana facilitator rejects an accept without a sponsor fee-payer.+ // Forward it from env when present; without it the Solana lane self-disables+ // to the Base lane (or the 503 guard) rather than erroring at challenge time.+ const feePayer = process.env.X402_FEE_PAYER_SOLANA || undefined;++ const router = express.Router();+ router.use(express.json({ limit: '64kb' }));++ // Permissive CORS so any agent/browser can call the service; preflight is+ // answered here before any route runs.+ router.use((req, res, next) => {+ res.setHeader('Access-Control-Allow-Origin', '*');+ res.setHeader('Access-Control-Allow-Methods', 'GET,POST,OPTIONS');+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type, X-PAYMENT, Authorization');+ res.setHeader('Access-Control-Expose-Headers', 'PAYMENT-REQUIRED, X-PAYMENT-RESPONSE');+ if (req.method === 'OPTIONS') return res.status(204).end();+ return next();+ });++ // Wrap a mutating handler so it requires an x402 payment. When payTo is+ // unset the endpoint still mounts but answers 503 — the server boots without+ // payment config for local/dev rather than charging into a void.+ function gate(priceKey, handler) {+ if (!x402Configured) {+ return (req, res) => {+ res.status(503).json({+ error: 'x402 not configured: set payTo.solana or X402_PAY_TO_SOLANA',+ });+ };+ }+ return paid(+ {+ price: prices[priceKey],+ asset: 'usdc',+ payTo: lanes,+ facilitator,+ feePayer,+ description: 'agent-sniper paid endpoint',+ serviceName: 'agent-sniper',+ },+ // paid()'s node adapter invokes (req, res, payment); our handlers are+ // async and own the response. Boundary errors are caught here and+ // forwarded to the error handler via the captured `next`.+ (req, res, payment) => Promise.resolve(handler(req, res, payment)).catch(req._onError),+ );+ }++ // Capture express's `next` for the paid handlers (paid()'s node adapter calls+ // the handler with (req, res, payment) and no next), so a thrown boundary+ // error still reaches the shared error handler.+ router.use((req, res, next) => {+ req._onError = next;+ next();+ });++ // ── Free reads ──────────────────────────────────────────────────────────────++ // GET /health — liveness + a snapshot of network/mode/stats.+ router.get('/health', (req, res) => {+ res.json({+ ok: true,+ network: sniper.config.network,+ mode: sniper.config.mode,+ stats: sniper.stats(),+ });+ });++ // GET /status — full stats plus the immutable runtime config.+ router.get('/status', (req, res) => {+ res.json({ stats: sniper.stats(), config: sniper.config });+ });++ // GET /strategies — the armed strategy set the engine is evaluating.+ router.get('/strategies', (req, res) => {+ res.json({ strategies: sniper.strategies() });+ });++ // GET /positions?agentId=&status= — list positions from the store.+ router.get('/positions', (req, res, next) => {+ const query = {};+ if (typeof req.query.agentId === 'string') query.agentId = req.query.agentId;+ if (typeof req.query.status === 'string') query.status = req.query.status;+ Promise.resolve(+ typeof store.listPositions === 'function'+ ? store.listPositions(query)+ : [],+ )+ .then((positions) => res.json({ positions }))+ .catch(next);+ });++ // ── Paid mutations ───────────────────────────────────────────────────────────++ // POST /strategies — arm a new strategy. SOL budgets convert to lamports; a+ // stop-loss is mandatory (the engine refuses to arm without one).+ router.post('/strategies', gate('arm', async (req, res) => {+ const body = req.body || {};+ if (body.stop_loss_pct == null) {+ return res.status(400).json({ error: 'stop_loss_pct is required — the engine will not arm a strategy without a stop-loss.' });+ }+ const perTrade = solToLamportsString(body.per_trade_sol);+ const dailyBudget = solToLamportsString(body.daily_budget_sol);+ if (perTrade == null || dailyBudget == null) {+ return res.status(400).json({ error: 'per_trade_sol and daily_budget_sol must be non-negative numbers.' });+ }++ const strategy = {+ ...body,+ id: typeof body.id === 'string' && body.id.trim() ? body.id.trim() : `strat_${randomUUID()}`,+ agent_id: typeof body.agent_id === 'string' && body.agent_id ? body.agent_id : `agent_${randomUUID().slice(0, 8)}`,+ enabled: body.enabled !== false,+ network: body.network === 'devnet' ? 'devnet' : 'mainnet',+ per_trade_lamports: perTrade,+ daily_budget_lamports: dailyBudget,+ stop_loss_pct: Number(body.stop_loss_pct),+ };+ // Drop the human-facing SOL fields — the stored row speaks lamports.+ delete strategy.per_trade_sol;+ delete strategy.daily_budget_sol;++ const stored = await store.addStrategy(strategy);+ return res.status(201).json({ strategy: stored });+ }));++ // POST /snipe — force a snipe on { mint, symbol?, agentId? }. Bypasses the+ // scorer (force:true) so every armed strategy attempts the buy immediately.+ router.post('/snipe', gate('snipe', async (req, res) => {+ const body = req.body || {};+ const mint = typeof body.mint === 'string' ? body.mint.trim() : '';+ if (!mint) {+ return res.status(400).json({ error: 'mint is required.' });+ }+ const candidate = { mint };+ if (typeof body.symbol === 'string' && body.symbol) candidate.symbol = body.symbol;+ if (typeof body.agentId === 'string' && body.agentId) candidate.agent_id = body.agentId;++ sniper.submitCandidate(candidate, { force: true });+ return res.status(202).json({ ok: true, queued: true, mint });+ }));++ // POST /strategies/:id/disarm — flip a strategy off (enabled=false). The+ // engine drops it on the next strategy-cache refresh.+ router.post('/strategies/:id/disarm', gate('disarm', async (req, res) => {+ const id = req.params.id;+ if (typeof store.disableStrategy === 'function') {+ const ok = await store.disableStrategy(id);+ return res.status(ok ? 200 : 404).json(ok ? { ok: true, id, enabled: false } : { error: 'strategy not found' });+ }+ // Memory store: re-add the row with enabled=false (addStrategy upserts by id).+ const current = sniper.strategies().find((s) => s.id === id);+ if (!current && typeof store.removeStrategy !== 'function') {+ return res.status(404).json({ error: 'strategy not found' });+ }+ if (typeof store.addStrategy === 'function' && current) {+ await store.addStrategy({ ...current, enabled: false });+ return res.status(200).json({ ok: true, id, enabled: false });+ }+ return res.status(404).json({ error: 'strategy not found' });+ }));++ return router;+}++/**+ * Build a complete Express app exposing the sniper API. Mounts the router at the+ * root and attaches a JSON error handler.+ *+ * @param {Parameters<typeof createSniperApiRouter>[0]} [deps]+ */+export async function createSniperApi(deps = {}) {+ const express = await loadExpress();+ const app = express();+ app.disable('x-powered-by');++ const router = await createSniperApiRouter(deps);+ app.use(router);++ // 404 for anything unmatched.+ app.use((req, res) => {+ res.status(404).json({ error: 'not found' });+ });++ // Boundary error handler: map known x402/facilitator statuses, default 500.+ // eslint-disable-next-line no-unused-vars -- express identifies error handlers by arity (4 args).+ app.use((err, req, res, next) => {+ const status = Number(err?.status) >= 400 && Number(err?.status) < 600 ? Number(err.status) : 500;+ if (!res.headersSent) {+ res.status(status).json({ error: err?.message || 'internal error' });+ }+ });++ // Stash the resolved handle so serve() can start it without rebuilding.+ app.locals.sniper = deps.sniper;+ return app;+}++/**+ * Build the app, start the sniper if it isn't running, and listen.+ *+ * @param {Parameters<typeof createSniperApiRouter>[0]} [deps]+ * @param {object} [opts]+ * @param {number} [opts.port]+ */+export async function serve(deps = {}, { port = Number(process.env.PORT) || 8787 } = {}) {+ // Resolve the sniper once so the API and the start() call share one handle.+ const sniper = deps.sniper || (await presets.local());+ const app = await createSniperApi({ ...deps, sniper });++ // Start the trade loop if it isn't already running. The handle is idempotent-+ // safe to call once; a double start would double-subscribe the feed, so we+ // track it with a flag on the handle.+ if (!sniper.__started) {+ await sniper.start();+ sniper.__started = true;+ }++ return await new Promise((resolve) => {+ const server = app.listen(port, () => {+ // eslint-disable-next-line no-console -- this is a server entry point.+ console.log(`[agent-sniper] HTTP API listening on :${port} (${sniper.config.network}/${sniper.config.mode})`);+ resolve({ app, server, sniper });+ });+ });+}++// Runnable as an entry point: `node src/faces/api.js`. The pathToFileURL compare+// is the ESM equivalent of `require.main === module` — true only when this file+// is the process entry, not when it's imported.+const isProcessEntryPoint = process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href;+if (isProcessEntryPoint) {+ serve().catch((err) => {+ // eslint-disable-next-line no-console -- entry-point fatal.+ console.error(`[agent-sniper] failed to start HTTP API: ${err?.message || err}`);+ process.exitCode = 1;+ });+}++export default { createSniperApi, createSniperApiRouter, serve };diff --git a/packages/agent-sniper/src/faces/mcp.js b/packages/agent-sniper/src/faces/mcp.jsnew file mode 100644index 000000000..f018bdaf3--- /dev/null+++ b/packages/agent-sniper/src/faces/mcp.js@@ -0,0 +1,400 @@+// @three-ws/agent-sniper — MCP (Model Context Protocol) stdio face.+//+// Exposes the sniper engine as an MCP stdio server so AI agents / Claude can arm+// strategies, snipe pump.fun coins by hand, and inspect open positions — all over+// the same engine handle the CLI and HTTP faces drive. Every tool maps 1:1 onto a+// public engine/store method; no engine internals are reached around.+//+// Run standalone:+// node src/faces/mcp.js+// # network/mode come from SNIPER_NETWORK / SNIPER_MODE when no sniper is injected.+//+// Or wire into Claude Desktop / Cursor by pointing the MCP client at that command.+//+// Testability: `createSniperMcpServer(deps)` builds and returns the fully-registered+// McpServer WITHOUT connecting any transport — safe to construct in a test and call+// server.connect(new InMemoryTransport()) on. The stdio boot in `startStdio()` runs+// only when this file is the process entry point.+//+// x402 note: this base server is intentionally unauthenticated and local. Paid+// gating can be layered by wrapping each tool handler (settle USDC, then delegate) —+// the three.ws *hosted* MCP does exactly that. We do NOT implement payment here; the+// surface stays lightweight so anyone can run it against their own wallet/RPC.++import { createRequire } from 'node:module';+import { pathToFileURL } from 'node:url';+import { realpathSync } from 'node:fs';++import { z } from 'zod';+import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';+import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';++// Advertised MCP version tracks package.json so it can't drift from the npm release.+const { version: PKG_VERSION } = createRequire(import.meta.url)('../../package.json');++const SERVER_INSTRUCTIONS =+ 'agent-sniper over MCP: arm per-agent pump.fun snipe strategies, fire manual buys, and inspect ' ++ 'positions, all driving a real sniper engine. arm_strategy registers a policy (stop_loss_pct is ' ++ 'mandatory; SOL amounts are converted to lamports for you). snipe_now forces a manual buy across ' ++ 'armed agents. list_strategies / list_positions / sniper_status are read-only. close_position and ' ++ 'disarm_strategy change behavior. This server is unauthenticated and meant to run locally against ' ++ 'your own wallet/RPC — never expose it on an open port without a payment/auth wrapper.';++// One SOL = 1e9 lamports. SOL inputs are floats; lamports are integers stored as a+// decimal string so a BigInt round-trips through JSON without precision loss.+const LAMPORTS_PER_SOL = 1_000_000_000n;+const solToLamportsString = (sol) => {+ // Scale via integer math on a fixed-precision string to avoid float drift on the+ // fractional part (e.g. 0.1 SOL must land on exactly 100000000 lamports).+ const [whole, frac = ''] = String(sol).split('.');+ const fracPadded = (frac + '000000000').slice(0, 9);+ const lamports = BigInt(whole || '0') * LAMPORTS_PER_SOL + BigInt(fracPadded || '0');+ return lamports.toString();+};++let _idSeq = 0;+const nextStrategyId = () => `strat_${Date.now().toString(36)}_${(++_idSeq).toString(36)}`;++// MCP result envelope helpers. Every handler returns JSON in both a text content+// block (for clients that only read content) and structuredContent (for clients on+// the typed-result path). Errors flip isError but still carry a readable payload.+const ok = (result) => ({+ content: [{ type: 'text', text: JSON.stringify(result) }],+ structuredContent: result,+});+const fail = (err) => {+ const message = err?.message || String(err);+ const payload = { ok: false, error: message };+ return { content: [{ type: 'text', text: JSON.stringify(payload) }], structuredContent: payload, isError: true };+};++// Write a strategy through whichever method the store exposes. A generic store may+// offer upsertStrategy; the default memory store offers addStrategy (which also+// upserts by id). Either way the stored row is returned to the caller.+function writeStrategy(store, strategy) {+ if (typeof store.upsertStrategy === 'function') return store.upsertStrategy(strategy);+ if (typeof store.addStrategy === 'function') return store.addStrategy(strategy);+ throw new Error('store exposes neither upsertStrategy nor addStrategy — cannot arm a strategy');+}++// Read a single strategy by id from the engine's live strategy cache.+const findStrategy = (sniper, id) => sniper.strategies().find((s) => s.id === id) || null;++/**+ * Build a fully-registered agent-sniper McpServer WITHOUT connecting a transport.+ *+ * @param {object} [deps]+ * @param {object} [deps.sniper] an already-built sniper handle (createSniper / presets.*).+ * When omitted, a default `presets.local` sniper is built from SNIPER_NETWORK /+ * SNIPER_MODE env, and started so tools operate against a live engine.+ * @param {import('../types.js').Store} [deps.store] the store backing `deps.sniper`+ * (so tools can read/write strategies + positions). Required when `deps.sniper` is+ * supplied; auto-derived when this function builds the default sniper.+ * @returns {Promise<McpServer>}+ */+export async function createSniperMcpServer(deps = {}) {+ let { sniper, store } = deps;++ if (!sniper) {+ // No injected handle → stand up the zero-config local wiring. Build the store+ // first so it's shared with the sniper and reachable by the tools.+ const { createMemoryStore } = await import('../adapters/store/memory.js');+ store = store || createMemoryStore({});+ const { createPumpClient } = await import('../adapters/solana/pump-client.js');+ const { createSelfCustodyWallet } = await import('../adapters/wallet/self-custody.js');+ const { createWeb3Executor } = await import('../adapters/solana/executor-web3.js');+ const { createPumpPortalFeed } = await import('../adapters/feed/pumpportal.js');+ const { createSniper } = await import('../engine.js');+ const network = (process.env.SNIPER_NETWORK || 'mainnet').trim();+ const mode = (process.env.SNIPER_MODE || 'simulate').trim();+ const solana = await createPumpClient({ network });+ sniper = createSniper({+ config: { network, mode },+ store,+ wallet: createSelfCustodyWallet({}),+ solana,+ executor: createWeb3Executor(),+ feed: createPumpPortalFeed({ network }),+ });+ await sniper.start();+ }++ if (!store) {+ throw new Error('[agent-sniper/mcp] deps.store is required when deps.sniper is supplied');+ }++ const server = new McpServer(+ { name: 'agent-sniper', version: PKG_VERSION },+ {+ // Our tool surface is fixed per-process — declare tools with no+ // list_changed notifications so strict 2025-06-18 clients don't wait for them.+ capabilities: { tools: { listChanged: false } },+ instructions: SERVER_INSTRUCTIONS,+ },+ );++ // ── arm_strategy ──────────────────────────────────────────────────────────────+ // Registers / updates an armed strategy. Not read-only (it changes future trading+ // behavior) but not destructive (it creates state, deletes nothing). SOL ceilings+ // are converted to lamport strings to match the Strategy contract.+ server.registerTool(+ 'arm_strategy',+ {+ title: 'Arm snipe strategy',+ description:+ 'Register (or update) a pump.fun snipe strategy for an agent. SOL amounts are converted to ' ++ 'lamports for you. stop_loss_pct is mandatory — the engine refuses to arm without it. Returns ' ++ 'the stored strategy row.',+ inputSchema: {+ agentId: z.string().min(1).describe('Owning agent id — one wallet per agent.'),+ strategyId: z.string().min(1).optional().describe('Reuse to update an existing strategy; omit to create one.'),+ per_trade_sol: z.number().positive().describe('SOL committed per snipe.'),+ daily_budget_sol: z.number().positive().describe('SOL/day spend ceiling for this agent.'),+ stop_loss_pct: z.number().describe('REQUIRED. Exit when down this percent from entry.'),+ take_profit_pct: z.number().optional().describe('Exit when up this percent from entry.'),+ trailing_stop_pct: z.number().optional().describe('Exit when down this percent from peak.'),+ max_hold_seconds: z.number().int().positive().optional().describe('Hard time-stop (default 1800).'),+ slippage_bps: z.number().int().nonnegative().optional().describe('Entry slippage tolerance, bps (default 500).'),+ max_price_impact_pct: z.number().optional().describe('Entry circuit breaker (default 10).'),+ trigger: z.enum(['new_mint', 'intel_confirmed', 'first_claim', 'manual']).optional().describe('What fires the buy.'),+ network: z.enum(['mainnet', 'devnet']).optional().describe('Chain (defaults to the sniper network).'),+ mev_tip_mode: z.enum(['off', 'economy', 'turbo']).optional().describe('MEV tip aggressiveness.'),+ firewall_level: z.enum(['block', 'warn', 'off']).optional().describe('Rug/honeypot firewall posture.'),+ min_market_cap_usd: z.number().optional().describe('Skip candidates below this market cap.'),+ max_market_cap_usd: z.number().optional().describe('Skip candidates above this market cap.'),+ require_socials: z.boolean().optional().describe('Require twitter/telegram/website on the candidate.'),+ },+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },+ },+ async (input) => {+ try {+ const id = input.strategyId || nextStrategyId();+ const strategy = {+ id,+ agent_id: input.agentId,+ enabled: true,+ trigger: input.trigger || 'new_mint',+ network: input.network || sniper.config.network,+ per_trade_lamports: solToLamportsString(input.per_trade_sol),+ daily_budget_lamports: solToLamportsString(input.daily_budget_sol),+ stop_loss_pct: input.stop_loss_pct,+ };+ // Only set optional fields when supplied — keep the row clean for stores+ // that round-trip it to a typed column (null vs absent matters in SQL).+ if (input.take_profit_pct != null) strategy.take_profit_pct = input.take_profit_pct;+ if (input.trailing_stop_pct != null) strategy.trailing_stop_pct = input.trailing_stop_pct;+ if (input.max_hold_seconds != null) strategy.max_hold_seconds = input.max_hold_seconds;+ if (input.slippage_bps != null) strategy.slippage_bps = input.slippage_bps;+ if (input.max_price_impact_pct != null) strategy.max_price_impact_pct = input.max_price_impact_pct;+ if (input.mev_tip_mode != null) strategy.mev_tip_mode = input.mev_tip_mode;+ if (input.firewall_level != null) strategy.firewall_level = input.firewall_level;+ if (input.min_market_cap_usd != null) strategy.min_market_cap_usd = input.min_market_cap_usd;+ if (input.max_market_cap_usd != null) strategy.max_market_cap_usd = input.max_market_cap_usd;+ if (input.require_socials != null) strategy.require_socials = input.require_socials;++ const stored = (await writeStrategy(store, strategy)) || strategy;+ return ok({ ok: true, strategy: stored });+ } catch (err) {+ return fail(err);+ }+ },+ );++ // ── disarm_strategy ─────────────────────────────────────────────────────────────+ // Flips a strategy off. Patches enabled=false (re-arm later by id) rather than+ // deleting, so the policy isn't lost. Falls back to removeStrategy if the store+ // can't patch. Marked destructive: it stops future buys for the agent.+ server.registerTool(+ 'disarm_strategy',+ {+ title: 'Disarm snipe strategy',+ description: 'Disable an armed strategy (enabled=false). The agent stops sniping new candidates; open positions still exit on their own rules.',+ inputSchema: { strategyId: z.string().min(1).describe('Strategy id to disarm.') },+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },+ },+ async ({ strategyId }) => {+ try {+ const cur = findStrategy(sniper, strategyId);+ if (cur) {+ await writeStrategy(store, { ...cur, enabled: false });+ } else if (typeof store.removeStrategy === 'function') {+ store.removeStrategy(strategyId);+ } else {+ return fail(new Error(`strategy "${strategyId}" not found`));+ }+ return ok({ ok: true, strategyId, enabled: false });+ } catch (err) {+ return fail(err);+ }+ },+ );++ // ── list_strategies ─────────────────────────────────────────────────────────────+ server.registerTool(+ 'list_strategies',+ {+ title: 'List armed strategies',+ description: 'List every currently armed strategy the sniper is evaluating candidates against.',+ inputSchema: {},+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },+ },+ async () => {+ try {+ const strategies = sniper.strategies();+ return ok({ ok: true, count: strategies.length, strategies });+ } catch (err) {+ return fail(err);+ }+ },+ );++ // ── snipe_now ───────────────────────────────────────────────────────────────────+ // Force a manual buy of a specific mint. force:true bypasses the feed scorer and+ // runs every armed strategy's buy directly. Not read-only — it spends.+ server.registerTool(+ 'snipe_now',+ {+ title: 'Snipe a mint now',+ description: 'Force a manual buy of a pump.fun mint across all armed agents (bypasses the candidate scorer). In simulate mode no funds move.',+ inputSchema: {+ mint: z.string().min(1).describe('The pump.fun token mint to buy.'),+ symbol: z.string().optional().describe('Optional ticker for logs/screen.'),+ agentId: z.string().optional().describe('Reserved for future per-agent targeting; current build snipes all armed agents.'),+ },+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },+ },+ async ({ mint, symbol, agentId }) => {+ try {+ const candidate = { mint, entry_trigger: 'manual' };+ if (symbol) candidate.symbol = symbol;+ sniper.submitCandidate(candidate, { force: true });+ return ok({ ok: true, scheduled: true, mint, agentId: agentId || null });+ } catch (err) {+ return fail(err);+ }+ },+ );++ // ── list_positions ──────────────────────────────────────────────────────────────+ server.registerTool(+ 'list_positions',+ {+ title: 'List positions',+ description: 'List sniper positions, optionally filtered by agentId and/or status (opening|open|closing|closed|failed).',+ inputSchema: {+ agentId: z.string().optional().describe('Filter to one agent.'),+ status: z.enum(['opening', 'open', 'closing', 'closed', 'failed']).optional().describe('Filter by lifecycle status.'),+ },+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },+ },+ async ({ agentId, status }) => {+ try {+ if (typeof store.listPositions !== 'function') {+ throw new Error('store does not expose listPositions — cannot enumerate positions');+ }+ const positions = await store.listPositions({ agentId, network: sniper.config.network, status });+ return ok({ ok: true, count: positions.length, positions });+ } catch (err) {+ return fail(err);+ }+ },+ );++ // ── close_position ──────────────────────────────────────────────────────────────+ // The engine handle deliberately does not expose executeSell, so rather than+ // reaching into the executor we flip the position's kill_switch via the store. The+ // next position sweep (cfg.pollMs) sees kill_switch and exits the position through+ // the normal sell path — same code, no duplicated broadcast logic. Hence the result+ // is { scheduled: true }: the close is queued for the upcoming sweep, not synchronous.+ server.registerTool(+ 'close_position',+ {+ title: 'Close a position',+ description: 'Schedule an exit for an open position. Flips its kill switch; the next position sweep sells it through the normal exit path. Returns once scheduled — the sell lands shortly after.',+ inputSchema: { positionId: z.string().min(1).describe('Position id to close (from list_positions).') },+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },+ },+ async ({ positionId }) => {+ try {+ if (typeof store.listPositions !== 'function' || typeof store.updatePosition !== 'function') {+ throw new Error('store must expose listPositions + updatePosition to close a position');+ }+ const all = await store.listPositions({ network: sniper.config.network });+ const pos = all.find((p) => p.id === positionId);+ if (!pos) return fail(new Error(`position "${positionId}" not found on ${sniper.config.network}`));+ if (pos.status === 'closed' || pos.status === 'failed') {+ return ok({ ok: true, scheduled: false, positionId, status: pos.status, note: 'position already terminal' });+ }+ await store.updatePosition(positionId, { kill_switch: true });+ return ok({ ok: true, scheduled: true, positionId });+ } catch (err) {+ return fail(err);+ }+ },+ );++ // ── sniper_status ───────────────────────────────────────────────────────────────+ server.registerTool(+ 'sniper_status',+ {+ title: 'Sniper status',+ description: 'Engine health snapshot: event/candidate/buy/sell counts, armed-strategy count, queue depth, plus the network and mode.',+ inputSchema: {},+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },+ },+ async () => {+ try {+ const result = {+ ok: true,+ network: sniper.config.network,+ mode: sniper.config.mode,+ stats: sniper.stats(),+ };+ return ok(result);+ } catch (err) {+ return fail(err);+ }+ },+ );++ return server;+}++/**+ * Build the server and connect it over stdio. stdout is reserved for MCP JSON-RPC+ * frames, so all human logging goes to stderr.+ *+ * @param {object} [deps] same shape as createSniperMcpServer.+ * @returns {Promise<McpServer>}+ */+export async function startStdio(deps = {}) {+ const server = await createSniperMcpServer(deps);+ const transport = new StdioServerTransport();+ await server.connect(transport);+ console.error(`[agent-sniper/mcp] ready — sniper tools registered over stdio (v${PKG_VERSION})`);+ return server;+}++// Run the stdio boot ONLY when this file is the process entry point. Importing the+// module (tests, the CLI `mcp` subcommand reusing createSniperMcpServer) must NOT+// connect a transport. argv[1] is compared both directly and via realpath so a launch+// through an npm-bin symlink still resolves to this module.+function isProcessEntryPoint() {+ const argvPath = process.argv[1];+ if (!argvPath) return false;+ if (import.meta.url === pathToFileURL(argvPath).href) return true;+ try {+ return import.meta.url === pathToFileURL(realpathSync(argvPath)).href;+ } catch {+ return false;+ }+}++if (isProcessEntryPoint()) {+ startStdio().catch((err) => {+ console.error(`agent-sniper/mcp: ${err?.message || err}`);+ process.exit(1);+ });+}++export default { createSniperMcpServer, startStdio };diff --git a/packages/agent-sniper/src/guards.js b/packages/agent-sniper/src/guards.jsnew file mode 100644index 000000000..ddaa5aec6--- /dev/null+++ b/packages/agent-sniper/src/guards.js@@ -0,0 +1,97 @@+// agent-sniper — pre-trade guards + flow control. Pure where possible.+//+// Every check short-circuits BEFORE any transaction is built. Each returns a+// `{ reason }` object on a breach (truthy) or null when the trade may proceed —+// so call sites read as `const x = check(...); if (x) return skip(x.reason)`.++// Leave this much SOL in the wallet for fees + rent so a snipe can't drain the+// account to a state where the very next sell can't pay its own fee. ~0.012 SOL.+export const SOL_FEE_HEADROOM_LAMPORTS = 12_000_000n;++/** @returns {{ reason: string }|null} */+export function checkConcurrency(openCount, maxConcurrent) {+ const cap = Number(maxConcurrent) || 1;+ if (openCount >= cap) return { reason: 'max_concurrency' };+ return null;+}++/** @returns {{ reason: string }|null} */+export function checkDailyBudgetLamports(spentLamports, perTradeLamports, budgetLamports) {+ const spent = BigInt(spentLamports || 0n);+ const trade = BigInt(perTradeLamports || 0n);+ const budget = BigInt(budgetLamports || 0n);+ if (budget <= 0n) return { reason: 'no_budget' };+ if (spent + trade > budget) return { reason: 'daily_budget_exceeded' };+ return null;+}++/** @returns {{ reason: string }|null} */+export function checkSolHeadroom(balanceLamports, perTradeLamports, headroom = SOL_FEE_HEADROOM_LAMPORTS) {+ const bal = BigInt(balanceLamports || 0n);+ const trade = BigInt(perTradeLamports || 0n);+ if (bal < trade + BigInt(headroom)) return { reason: 'insufficient_sol' };+ return null;+}++/** @returns {{ reason: string }|null} */+export function checkPriceImpact(impactPct, maxImpactPct) {+ const max = Number(maxImpactPct);+ if (!Number.isFinite(max) || max <= 0) return null; // unset ⇒ no gate+ if (Number(impactPct) > max) return { reason: 'price_impact_too_high' };+ return null;+}++/**+ * Sliding-window throttle: at most `maxPerMin` consumes per rolling 60s. A+ * platform-wide backstop independent of per-agent caps. maxPerMin<=0 disables it.+ */+export function makeThrottle(maxPerMin) {+ const hits = [];+ return {+ tryConsume() {+ if (maxPerMin <= 0) return true;+ const now = Date.now();+ while (hits.length && now - hits[0] > 60_000) hits.shift();+ if (hits.length >= maxPerMin) return false;+ hits.push(now);+ return true;+ },+ };+}++/**+ * Bounded work queue: caps concurrent jobs at `concurrency`, drops (rather than+ * unbounded-buffers) once `maxDepth` are waiting so a launch firehose can't grow+ * memory without bound. A dropped job calls `onDrop`.+ */+export function makeQueue(concurrency, maxDepth, { onError, onDrop } = {}) {+ let active = 0;+ const q = [];+ const pump = () => {+ while (active < concurrency && q.length) {+ const job = q.shift();+ active++;+ Promise.resolve()+ .then(job)+ .catch((err) => onError?.(err))+ .finally(() => { active--; pump(); });+ }+ };+ return {+ push(job) {+ if (q.length >= maxDepth) { onDrop?.(); return false; }+ q.push(job);+ pump();+ return true;+ },+ get inFlight() { return active + q.length; },+ };+}++/** Self-rated entry conviction 0..1 for the optional decision ledger. */+export function snipeConfidence({ priceImpactPct, maxImpactPct, firewallVerdict }) {+ const impactPenalty = Math.min(1, Math.max(0, priceImpactPct) / (maxImpactPct > 0 ? maxImpactPct : 10)) * 0.4;+ const fwBonus = firewallVerdict === 'allow' ? 0.1 : firewallVerdict === 'warn' ? -0.15 : 0;+ const c = 0.6 + fwBonus - impactPenalty;+ return Math.min(0.95, Math.max(0.05, c));+}diff --git a/packages/agent-sniper/src/index.js b/packages/agent-sniper/src/index.jsnew file mode 100644index 000000000..f6cdf516d--- /dev/null+++ b/packages/agent-sniper/src/index.js@@ -0,0 +1,73 @@+// @three-ws/agent-sniper — public library surface.+//+// A lightweight, embeddable pump.fun sniper engine for 3D AI agents. Bring your+// own (or accept the default) wallet / store / RPC / feed adapters; the same+// trade loop runs anywhere. See README.md for the full guide and src/types.js+// for the adapter contracts.+//+// import { createSniper, presets } from '@three-ws/agent-sniper';+// const sniper = await presets.local({ network: 'devnet' });+// await sniper.start();++import { createSniper } from './engine.js';+import { loadConfig } from './config.js';+import { createMemoryStore } from './adapters/store/memory.js';+import { createSelfCustodyWallet } from './adapters/wallet/self-custody.js';+import { createCustodialWallet } from './adapters/wallet/custodial.js';+import { createPumpClient } from './adapters/solana/pump-client.js';+import { createWeb3Executor } from './adapters/solana/executor-web3.js';++// ── core ──────────────────────────────────────────────────────────────────────+export { createSniper } from './engine.js';+export { loadConfig } from './config.js';+export { scoreMint, scoreIntel, learnedScore } from './scorer.js';+export { decideExit } from './exit-logic.js';+export {+ checkConcurrency, checkDailyBudgetLamports, checkSolHeadroom, checkPriceImpact,+ makeThrottle, makeQueue, SOL_FEE_HEADROOM_LAMPORTS,+} from './guards.js';++// ── adapters (defaults; swap any) ──────────────────────────────────────────────+export { createMemoryStore } from './adapters/store/memory.js';+export { createSelfCustodyWallet } from './adapters/wallet/self-custody.js';+export { createCustodialWallet } from './adapters/wallet/custodial.js';+export { createPumpClient } from './adapters/solana/pump-client.js';+export { createWeb3Executor } from './adapters/solana/executor-web3.js';+export { createPumpPortalFeed } from './adapters/feed/pumpportal.js';++// ── 3D agents ──────────────────────────────────────────────────────────────────+export { AGENT_AVATARS, ANIMATION_CLIPS, agentConfig, deskMonitorFrame } from './agents/manifest.js';++/**+ * Ready-made wirings. Each returns an unstarted sniper handle — call `.start()`.+ */+export const presets = {+ /**+ * Fully local, self-custodial sniper. Memory store + self-custody wallet ++ * pump.fun client + web3 executor + PumpPortal feed. The zero-to-running path.+ *+ * @param {object} [o]+ * @param {'mainnet'|'devnet'} [o.network]+ * @param {'simulate'|'live'} [o.mode]+ * @param {string} [o.rpcUrl]+ * @param {import('./types.js').Strategy[]} [o.strategies]+ * @param {Record<string,string>} [o.secrets] agentId → wallet secret+ * @param {import('./types.js').Hooks} [o.hooks]+ */+ async local(o = {}) {+ const { createPumpPortalFeed } = await import('./adapters/feed/pumpportal.js');+ const store = createMemoryStore({ strategies: o.strategies || [] });+ const solana = await createPumpClient({ network: o.network || 'mainnet', rpcUrl: o.rpcUrl });+ return createSniper({+ config: { network: o.network, mode: o.mode, rpcUrl: o.rpcUrl },+ store,+ wallet: createSelfCustodyWallet({ secrets: o.secrets }),+ solana,+ executor: createWeb3Executor(),+ feed: createPumpPortalFeed({ network: o.network || 'mainnet' }),+ hooks: o.hooks,+ });+ },+};++export default { createSniper, loadConfig, presets };diff --git a/packages/agent-sniper/src/positions.js b/packages/agent-sniper/src/positions.jsnew file mode 100644index 000000000..275fb4832--- /dev/null+++ b/packages/agent-sniper/src/positions.js@@ -0,0 +1,71 @@+// agent-sniper — position lifecycle loop.+//+// Every cfg.pollMs: re-quote each open position's current SOL value, update the+// high-water mark, and exit on stop-loss / trailing-stop / take-profit / timeout+// (in that priority order). Pricing is authoritative on-chain (quoteForSell), so+// it needs no per-mint trade feed.++import { PublicKey } from '@solana/web3.js';+import { decideExit } from './exit-logic.js';+import { executeSell } from './executor.js';++async function tickPosition(cfg, pos, ports) {+ const { solana, hooks, log } = ports;+ const screen = (text, kind) => { try { hooks.onScreen?.({ text, kind }); } catch { /* best-effort */ } };++ if (pos.kill_switch) {+ await executeSell({ cfg, position: pos, reason: 'kill_switch', ports });+ return;+ }++ const mintPk = new PublicKey(pos.mint);+ const baseAmount = BigInt(pos.base_amount);+ const slippagePct = (pos.slippage_bps ?? 500) / 100;++ let value;+ try {+ const quote = await solana.quoteForSell({ mint: mintPk, baseAmount, slippagePct });+ value = Number(quote.expectedQuoteOut.toString());+ } catch (err) {+ log.warn('position re-quote failed', { mint: pos.mint, err: err?.message });+ return; // transient — try again next sweep+ }++ const prevPeak = Number(pos.peak_value_lamports || pos.entry_quote_lamports || 0);+ const peak = Math.max(prevPeak, value);+ await ports.store.updatePosition(pos.id, { last_value_lamports: Math.round(value), peak_value_lamports: Math.round(peak) });++ const entry = Number(pos.entry_quote_lamports || 0);+ const pnlPct = entry > 0 ? ((value - entry) / entry) * 100 : 0;+ const sym = (pos.symbol || pos.mint.slice(0, 6)).toUpperCase();+ screen(`$${sym}: ${pnlPct >= 0 ? '+' : ''}${pnlPct.toFixed(1)}% P&L — monitoring`, 'trade');++ let sentiment = null;+ if (cfg.exitOnBearish && value < entry && hooks.readSentiment) {+ try {+ const s = await hooks.readSentiment(pos.mint, cfg.network);+ if (s) sentiment = { ...s, minConfidence: cfg.exitBearishMinConfidence };+ } catch { /* sentiment offline — fall back to stop/trailing/TP */ }+ }++ const reason = decideExit(pos, value, peak, Date.now(), sentiment);+ if (reason) await executeSell({ cfg, position: pos, reason, ports });+}++/** Run one sweep over all open positions. An error on one never aborts the rest. */+export async function runPositionSweep(cfg, ports) {+ let positions;+ try {+ positions = await ports.store.getOpenPositions(cfg.network);+ } catch (err) {+ ports.log.error('open-position query failed', { err: err?.message });+ return;+ }+ for (const pos of positions) {+ try {+ await tickPosition(cfg, pos, ports);+ } catch (err) {+ ports.log.error('position tick failed', { mint: pos.mint, err: err?.message });+ }+ }+}