Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(agent-sniper): add agent-sniper package scaffolding

nirholas99456757a94c
diff --git a/packages/agent-sniper/jsconfig.json b/packages/agent-sniper/jsconfig.json
new file mode 100644
index 000000000..b0258bf42
--- /dev/null
+++ b/packages/agent-sniper/jsconfig.json
@@ -0,0 +1,14 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "ESNext",
+ "moduleResolution": "Bundler",
+ "checkJs": true,
+ "allowJs": true,
+ "noEmit": true,
+ "strict": false,
+ "skipLibCheck": true,
+ "resolveJsonModule": true
+ },
+ "include": ["src/**/*.js", "bin/**/*.js", "test/**/*.js"]
+}
diff --git a/packages/agent-sniper/package.json b/packages/agent-sniper/package.json
new file mode 100644
index 000000000..bf63c5e46
--- /dev/null
+++ b/packages/agent-sniper/package.json
@@ -0,0 +1,76 @@
+{
+ "name": "@three-ws/agent-sniper",
+ "version": "0.1.0",
+ "description": "Lightweight, embeddable pump.fun sniper engine for 3D AI agents — multi-agent, multi-user, with pluggable wallet/store/RPC adapters. Library + CLI + MCP server + x402 paid API.",
+ "type": "module",
+ "license": "MIT",
+ "author": "three.ws",
+ "homepage": "https://three.ws",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/nirholas/agent-sniper.git"
+ },
+ "keywords": [
+ "solana",
+ "pumpfun",
+ "sniper",
+ "trading-bot",
+ "ai-agent",
+ "mcp",
+ "x402",
+ "3d-agent",
+ "memecoin"
+ ],
+ "engines": {
+ "node": ">=20"
+ },
+ "bin": {
+ "agent-sniper": "bin/agent-sniper.js"
+ },
+ "main": "src/index.js",
+ "exports": {
+ ".": "./src/index.js",
+ "./mcp": "./src/faces/mcp.js",
+ "./api": "./src/faces/api.js",
+ "./adapters/store/memory": "./src/adapters/store/memory.js",
+ "./adapters/store/sqlite": "./src/adapters/store/sqlite.js",
+ "./adapters/wallet/self-custody": "./src/adapters/wallet/self-custody.js",
+ "./adapters/wallet/custodial": "./src/adapters/wallet/custodial.js",
+ "./adapters/solana/pump-client": "./src/adapters/solana/pump-client.js",
+ "./adapters/feed/pumpportal": "./src/adapters/feed/pumpportal.js",
+ "./agents": "./src/agents/manifest.js"
+ },
+ "files": [
+ "src",
+ "bin",
+ "assets",
+ "README.md",
+ "LICENSE",
+ ".env.example"
+ ],
+ "scripts": {
+ "start": "node bin/agent-sniper.js run",
+ "mcp": "node bin/agent-sniper.js mcp",
+ "serve": "node bin/agent-sniper.js serve",
+ "test": "vitest run"
+ },
+ "dependencies": {
+ "@modelcontextprotocol/sdk": "^1.29.0",
+ "@pump-fun/pump-sdk": "^1.36.0",
+ "@pump-fun/pump-swap-sdk": "^1.17.0",
+ "@solana/spl-token": "^0.4.14",
+ "@solana/web3.js": "^1.98.4",
+ "@three-ws/x402-server": "^0.1.0",
+ "bn.js": "^5.2.3",
+ "bs58": "^6.0.0",
+ "ws": "^8.21.0",
+ "zod": "^3.23.8"
+ },
+ "optionalDependencies": {
+ "better-sqlite3": "^11.0.0",
+ "express": "^5.2.1"
+ },
+ "devDependencies": {
+ "vitest": "^4.1.7"
+ }
+}
diff --git a/packages/agent-sniper/src/log.js b/packages/agent-sniper/src/log.js
new file mode 100644
index 000000000..20d6fd0c1
--- /dev/null
+++ b/packages/agent-sniper/src/log.js
@@ -0,0 +1,26 @@
+// agent-sniper — minimal structured logger.
+//
+// Zero-dependency. Emits one JSON line per event to stderr so stdout stays
+// clean for MCP stdio transport. A consumer can swap this for their own logger
+// by passing `{ logger }` into createSniper(); every module imports `log` from
+// here only as the default.
+
+function emit(level, msg, fields) {
+ const line = { t: new Date().toISOString(), level, msg, ...(fields || {}) };
+ try {
+ process.stderr.write(`${JSON.stringify(line)}\n`);
+ } catch {
+ // stderr closed (rare) — drop the line rather than crash the trader.
+ }
+}
+
+export const log = {
+ debug: (msg, fields) => { if (process.env.SNIPER_DEBUG) emit('debug', msg, fields); },
+ info: (msg, fields) => emit('info', msg, fields),
+ warn: (msg, fields) => emit('warn', msg, fields),
+ error: (msg, fields) => emit('error', msg, fields),
+ // `trade` is a distinct channel so fills are greppable and never debug-gated.
+ trade: (msg, fields) => emit('trade', msg, fields),
+};
+
+export default log;
diff --git a/packages/agent-sniper/src/scorer.js b/packages/agent-sniper/src/scorer.js
new file mode 100644
index 000000000..e3a88747f
--- /dev/null
+++ b/packages/agent-sniper/src/scorer.js
@@ -0,0 +1,143 @@
+// agent-sniper — entry scoring. Pure, no I/O.
+//
+// Given an enriched candidate (from a Feed) and a Strategy, decide whether to
+// snipe. Returns { pass, score, reasons }. `reasons` always explains the verdict
+// — kept on skipped events too so logs show WHY a mint was passed over, which is
+// what you stare at when tuning a strategy.
+
+function n(v) {
+ if (v == null) return null;
+ const x = Number(v);
+ return Number.isFinite(x) ? x : null;
+}
+
+/**
+ * Optional learned model: `weights` is a flat map of signal-key → coefficient.
+ * Contribution is the dot product of present numeric signals with their weights,
+ * squashed into a small bounded range so it nudges rather than dominates the
+ * deterministic gates. Returns null when no weights are supplied.
+ *
+ * @param {object} signals
+ * @param {Record<string, number>|null} weights
+ * @returns {number|null}
+ */
+export function learnedScore(signals, weights) {
+ if (!weights || typeof weights !== 'object') return null;
+ let acc = 0;
+ let used = 0;
+ for (const [k, w] of Object.entries(weights)) {
+ const v = n(signals?.[k]);
+ if (v == null || !Number.isFinite(w)) continue;
+ acc += v * w;
+ used++;
+ }
+ if (!used) return null;
+ // bound to ±0.5 so the learned term can't swamp the quality baseline.
+ return Number(Math.max(-0.5, Math.min(0.5, acc)).toFixed(4));
+}
+
+/**
+ * Score a fresh launch for a `new_mint` strategy. Fires blind on the create
+ * event, so it leans on hard creator/market filters.
+ *
+ * @param {import('./types.js').Candidate} mint
+ * @param {import('./types.js').Strategy} strat
+ * @returns {{ pass: boolean, score: number, reasons: string[] }}
+ */
+export function scoreMint(mint, strat) {
+ const reasons = [];
+ let score = 0;
+
+ // ── hard filters (any failure → skip) ────────────────────────────────────
+ if (strat.require_sol_quote !== false && mint.is_usdc_pair) {
+ return { pass: false, score: 0, reasons: ['quote_not_sol'] };
+ }
+
+ const mcUsd = n(mint.market_cap_usd);
+ const minMc = n(strat.min_market_cap_usd);
+ const maxMc = n(strat.max_market_cap_usd);
+ if (minMc != null && (mcUsd == null || mcUsd < minMc)) {
+ return { pass: false, score: 0, reasons: ['mc_below_min'] };
+ }
+ if (maxMc != null && mcUsd != null && mcUsd > maxMc) {
+ return { pass: false, score: 0, reasons: ['mc_above_max'] };
+ }
+
+ const launches = n(mint.creator_launches);
+ const graduated = n(mint.creator_graduated);
+ const maxLaunches = n(strat.max_creator_launches);
+ const minGrad = n(strat.min_creator_graduated);
+ if (maxLaunches != null && launches != null && launches > maxLaunches) {
+ return { pass: false, score: 0, reasons: ['creator_too_many_launches'] };
+ }
+ if (minGrad != null && (graduated == null || graduated < minGrad)) {
+ return { pass: false, score: 0, reasons: ['creator_too_few_graduated'] };
+ }
+
+ const hasSocials = !!(mint.twitter || mint.telegram || mint.website);
+ if (strat.require_socials && !hasSocials) {
+ return { pass: false, score: 0, reasons: ['no_socials'] };
+ }
+
+ // ── soft signals (contribute to score; tie-break / future ranking) ───────
+ if (hasSocials) { score += 1; reasons.push('has_socials'); }
+ if (graduated != null && graduated > 0) { score += graduated; reasons.push(`creator_graduated:${graduated}`); }
+ const initBuy = n(mint.initial_buy_sol);
+ if (initBuy != null && initBuy >= 1) { score += 1; reasons.push(`initial_buy:${initBuy.toFixed(2)}sol`); }
+ if (mcUsd != null) reasons.push(`mc_usd:${Math.round(mcUsd)}`);
+
+ return { pass: true, score, reasons };
+}
+
+/**
+ * Score a coin AFTER an intelligence pass has observed it (`intel_confirmed`).
+ * Has the full picture — bundle likelihood, organic score, concentration, dev
+ * behaviour, classification — so it can afford to be picky.
+ *
+ * @param {import('./types.js').Candidate} rec
+ * @param {import('./types.js').Strategy} strat
+ * @param {Record<string, number>|null} [weights]
+ * @returns {{ pass: boolean, score: number, reasons: string[] }}
+ */
+export function scoreIntel(rec, strat, weights = null) {
+ const reasons = [];
+ const s = rec?.signals || {};
+
+ // ── hard gates ───────────────────────────────────────────────────────────
+ const minQ = n(strat.min_quality_score);
+ if (minQ != null && (rec.quality_score == null || rec.quality_score < minQ)) {
+ return { pass: false, score: 0, reasons: [`quality_below_min:${rec.quality_score}`] };
+ }
+ const maxBundle = n(strat.max_bundle_score);
+ if (maxBundle != null && s.bundle_score != null && s.bundle_score > maxBundle) {
+ return { pass: false, score: 0, reasons: [`bundle_above_max:${s.bundle_score}`] };
+ }
+ const maxConc = n(strat.max_concentration_top1);
+ if (maxConc != null && s.concentration_top1 != null && s.concentration_top1 > maxConc) {
+ return { pass: false, score: 0, reasons: [`whale_concentration:${s.concentration_top1}`] };
+ }
+ if (strat.avoid_dev_dump !== false && s.dev_sold) {
+ return { pass: false, score: 0, reasons: ['dev_dumped'] };
+ }
+ const cats = Array.isArray(strat.allowed_categories) ? strat.allowed_categories.filter(Boolean) : [];
+ if (cats.length && rec.category && !cats.includes(rec.category)) {
+ return { pass: false, score: 0, reasons: [`category_excluded:${rec.category}`] };
+ }
+ if (strat.require_socials && !(rec.twitter || rec.telegram || rec.website)) {
+ return { pass: false, score: 0, reasons: ['no_socials'] };
+ }
+
+ // ── score: baseline quality + learned model + organic, minus risk ─────────
+ let score = (rec.quality_score ?? 0) / 100;
+ reasons.push(`quality:${rec.quality_score}`);
+ if (s.organic_score != null) { score += s.organic_score * 0.5; reasons.push(`organic:${s.organic_score}`); }
+ if (s.bundle_score != null) { score -= s.bundle_score * 0.5; if (s.bundle_score >= 0.4) reasons.push(`bundle:${s.bundle_score}`); }
+
+ const learned = learnedScore(s, weights);
+ if (learned != null) { score += learned; reasons.push(`learned:${learned}`); }
+
+ if (rec.category) reasons.push(`cat:${rec.category}`);
+ for (const flag of rec.risk_flags || []) reasons.push(`flag:${flag}`);
+
+ return { pass: true, score: Number(score.toFixed(4)), reasons };
+}
diff --git a/packages/agent-sniper/src/types.js b/packages/agent-sniper/src/types.js
new file mode 100644
index 000000000..6a98c7c98
--- /dev/null
+++ b/packages/agent-sniper/src/types.js
@@ -0,0 +1,234 @@
+// agent-sniper — adapter contracts (JSDoc typedefs, no runtime code).
+//
+// The engine is pure orchestration over four pluggable adapters. Implement these
+// shapes and the same trade loop runs against any wallet custody model, any
+// persistence backend, any RPC, and any launch feed. Default implementations
+// for every one live under src/adapters/.
+//
+// Store — persistence: strategies, positions, spend ledger.
+// Wallet — resolve a signing Keypair for an agentId.
+// Solana — quote/build pump.fun buy & sell instructions + an RPC connection.
+// Executor — sign + broadcast instructions, return landing telemetry.
+// Feed — stream new-mint / trigger events.
+// Hooks — optional cross-cutting callbacks (firewall, notify, screen, ledger).
+
+/**
+ * A strategy is the per-agent policy the engine evaluates every candidate
+ * against. Mirrors the three.ws `agent_sniper_strategies` row so a Postgres
+ * store can map 1:1, but no field here is three.ws-specific.
+ *
+ * @typedef {object} Strategy
+ * @property {string} id stable strategy id
+ * @property {string} agent_id owning agent (1 wallet per agent)
+ * @property {string} [user_id] owner (audit only)
+ * @property {string} [agent_name]
+ * @property {boolean} enabled must be true to arm
+ * @property {boolean} [kill_switch] emergency per-agent halt
+ * @property {'new_mint'|'intel_confirmed'|'first_claim'|'manual'} [trigger]
+ * @property {'mainnet'|'devnet'} [network]
+ * @property {string|number|bigint} daily_budget_lamports SOL/day ceiling
+ * @property {string|number|bigint} per_trade_lamports SOL per snipe
+ * @property {number} [max_concurrent_positions]
+ * @property {number} [slippage_bps] default 500
+ * @property {number} [max_price_impact_pct] entry circuit breaker, default 10
+ * @property {'off'|'economy'|'turbo'} [mev_tip_mode]
+ * @property {'block'|'warn'|'off'} [firewall_level]
+ * @property {number} [min_market_cap_usd]
+ * @property {number} [max_market_cap_usd]
+ * @property {number} [min_creator_graduated]
+ * @property {number} [max_creator_launches]
+ * @property {boolean} [require_socials]
+ * @property {boolean} [require_sol_quote] default true
+ * @property {number} [take_profit_pct]
+ * @property {number} [stop_loss_pct] MANDATORY (engine enforces non-null)
+ * @property {number} [trailing_stop_pct]
+ * @property {number} [max_hold_seconds] default 1800
+ * @property {number} [min_quality_score] intel trigger
+ * @property {number} [max_bundle_score] intel trigger
+ * @property {number} [max_concentration_top1] intel trigger
+ * @property {boolean} [avoid_dev_dump] intel trigger, default true
+ * @property {string[]} [allowed_categories]
+ * @property {string} [telegram_chat_id]
+ */
+
+/**
+ * An enriched candidate event from a Feed. `mint` is the only required field.
+ * @typedef {object} Candidate
+ * @property {string} mint
+ * @property {string} [symbol]
+ * @property {string} [name]
+ * @property {number} [market_cap_usd]
+ * @property {boolean} [is_usdc_pair]
+ * @property {number} [creator_launches]
+ * @property {number} [creator_graduated]
+ * @property {string} [twitter]
+ * @property {string} [telegram]
+ * @property {string} [website]
+ * @property {number} [initial_buy_sol]
+ * @property {string} [entry_trigger]
+ * @property {string} [trigger_ref]
+ * @property {object} [signals] intel-trigger signal bag
+ * @property {number} [quality_score]
+ * @property {string} [category]
+ * @property {string[]} [risk_flags]
+ */
+
+/**
+ * @typedef {object} Position
+ * @property {string} id
+ * @property {string} strategy_id
+ * @property {string} agent_id
+ * @property {string} [user_id]
+ * @property {string} wallet
+ * @property {'mainnet'|'devnet'} network
+ * @property {string} mint
+ * @property {string} [symbol]
+ * @property {'opening'|'open'|'closing'|'closed'|'failed'} status
+ * @property {string|number|bigint} [entry_quote_lamports]
+ * @property {string|number|bigint} [base_amount]
+ * @property {number} [peak_value_lamports]
+ * @property {number} [last_value_lamports]
+ * @property {number} [slippage_bps]
+ * @property {number} [take_profit_pct]
+ * @property {number} [stop_loss_pct]
+ * @property {number} [trailing_stop_pct]
+ * @property {number} [max_hold_seconds]
+ * @property {number} [opened_at_ms]
+ * @property {boolean} [kill_switch]
+ * @property {string} [error]
+ */
+
+/**
+ * Store — persistence boundary. All methods async. A backend that can't satisfy
+ * `claimPosition` atomically (insert-if-absent on agent+mint+network) MUST
+ * serialize per agent some other way, or duplicate buys become possible.
+ *
+ * @typedef {object} Store
+ * @property {(network: string) => Promise<Strategy[]>} getArmedStrategies
+ * Return every enabled, non-kill-switched strategy for the network.
+ * @property {(agentId: string, network: string) => Promise<number>} countOpenPositions
+ * @property {(agentId: string, network: string) => Promise<bigint>} getDailySpendLamports
+ * Sum of today's committed snipe spend (lamports) for the agent.
+ * @property {(p: { strategy: Strategy, candidate: Candidate, network: string }) => Promise<Position|null>} claimPosition
+ * Atomically reserve the (agent_id, mint, network) slot. Return the new
+ * Position row, or null if the slot is already held (→ skip, no double buy).
+ * @property {(id: string, patch: Partial<Position>) => Promise<void>} updatePosition
+ * @property {(network: string) => Promise<Position[]>} getOpenPositions
+ * Positions in status 'open' (and 'opening' older than a grace window).
+ * @property {(e: SpendEvent) => Promise<void>} [recordSpend]
+ * Optional audit/ledger write. Absent ⇒ no-op.
+ */
+
+/**
+ * @typedef {object} SpendEvent
+ * @property {string} agentId
+ * @property {string} [userId]
+ * @property {'snipe'|'mev_tip'} category
+ * @property {string} network
+ * @property {bigint} amountLamports
+ * @property {string|null} [signature]
+ * @property {string} [mint]
+ * @property {'ok'|'confirmed'} status
+ */
+
+/**
+ * Wallet — resolve a signing Keypair for an agent. Self-custody returns a local
+ * keypair; a custodial adapter decrypts on demand. Return null if the agent has
+ * no provisioned wallet (the engine then fails the trade cleanly, never auto-
+ * provisions an unfunded wallet).
+ *
+ * @typedef {object} Wallet
+ * @property {(agentId: string, ctx?: { userId?: string, reason?: string }) =>
+ * Promise<{ keypair: import('@solana/web3.js').Keypair, address: string }|null>} loadKeypair
+ */
+
+/**
+ * Solana — pump.fun trade primitives + a web3 Connection. The default impl
+ * (adapters/solana/pump-client.js) is built on @pump-fun/pump-sdk; swap it to
+ * route quotes/builds through any venue.
+ *
+ * @typedef {object} SolanaClient
+ * @property {import('@solana/web3.js').Connection} connection
+ * @property {(p: BuyQuoteReq) => Promise<TradeQuote>} quoteForBuy
+ * @property {(p: BuyBuildReq) => Promise<BuiltTrade>} buildBuyInstructions
+ * @property {(p: SellReq) => Promise<TradeQuote>} quoteForSell
+ * @property {(p: SellReq & { user: import('@solana/web3.js').PublicKey }) => Promise<BuiltTrade>} buildSellInstructions
+ */
+
+/**
+ * @typedef {object} BuyQuoteReq
+ * @property {import('@solana/web3.js').PublicKey} mint
+ * @property {bigint} quoteLamports
+ * @property {number} slippagePct
+ *
+ * @typedef {BuyQuoteReq & { user: import('@solana/web3.js').PublicKey }} BuyBuildReq
+ *
+ * @typedef {object} SellReq
+ * @property {import('@solana/web3.js').PublicKey} mint
+ * @property {bigint} baseAmount
+ * @property {number} slippagePct
+ *
+ * @typedef {object} TradeQuote
+ * @property {number} priceImpactPct
+ * @property {bigint} [expectedQuoteOut] sell quotes
+ * @property {import('@solana/web3.js').PublicKey} [quoteMint]
+ *
+ * @typedef {object} BuiltTrade
+ * @property {import('@solana/web3.js').TransactionInstruction[]} instructions
+ * @property {bigint} [expectedBaseTokens] buy builds
+ * @property {bigint} [expectedQuoteOut] sell builds
+ */
+
+/**
+ * Executor — the one place that signs and broadcasts. Return landing telemetry.
+ * In simulate mode the engine never calls this (sig = 'SIMULATED').
+ *
+ * @typedef {object} Executor
+ * @property {(p: SubmitReq) => Promise<ExecResult>} submit
+ *
+ * @typedef {object} SubmitReq
+ * @property {string} network
+ * @property {import('@solana/web3.js').Connection} connection
+ * @property {import('@solana/web3.js').Keypair} payer
+ * @property {import('@solana/web3.js').TransactionInstruction[]} instructions
+ * @property {number} confirmTimeoutMs
+ * @property {'off'|'economy'|'turbo'} [tipMode]
+ * @property {(tipLamports: bigint, route: string) => Promise<void>} [onTip]
+ * Spend-guard veto hook: throw to cancel the tip (engine falls back to the
+ * untipped route). Called BEFORE a tip leaves the wallet.
+ *
+ * @typedef {object} ExecResult
+ * @property {string} signature
+ * @property {number} [slot]
+ * @property {string} route 'standard' | 'jito' | 'simulated'
+ * @property {bigint} [tipLamports]
+ * @property {number|null} [priorityFeeMicroLamports]
+ * @property {number} [attempts]
+ * @property {number|null} [landedMs]
+ * @property {string|null} [fallbackReason]
+ */
+
+/**
+ * Feed — push trigger events into the engine. `start` receives a callback and
+ * returns a stop function. Emit `{ kind: 'mint'|'intel'|'claim', data: Candidate }`.
+ *
+ * @typedef {object} Feed
+ * @property {(onEvent: (e: { kind: string, data: Candidate }) => void) => Promise<() => void>} start
+ */
+
+/**
+ * Hooks — optional cross-cutting callbacks. Every one is best-effort: a throw or
+ * rejection is swallowed and never aborts a trade (except `onTip`, which is a
+ * deliberate veto). Omit any you don't need.
+ *
+ * @typedef {object} Hooks
+ * @property {(p: object) => Promise<{ verdict: 'allow'|'warn'|'block', score: number, reasons?: string[] }|null>} [assessSafety]
+ * Rug/honeypot firewall, run after the quote and before broadcast.
+ * @property {(p: { agentId: string, candidate: Candidate, network: string, strategy: Strategy }) => Promise<{ pass: boolean, reason?: string, skipped?: boolean }>} [oracleGate]
+ * @property {(p: object) => void} [onScreen] live-visualization push (3D desk / web view)
+ * @property {(p: object) => void} [onBuy]
+ * @property {(p: object) => void} [onSell]
+ * @property {(p: object) => Promise<void>} [recordDecision] tamper-evident ledger
+ */
+
+export {};