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
Agent Sniper 0.1.6: restore fail-closed quoting on the published tree
nirholasf2ebcda0cfa8
diff --git a/packages/agent-sniper/package.json b/packages/agent-sniper/package.jsonindex bb00ec602..c015ba2d5 100644--- a/packages/agent-sniper/package.json+++ b/packages/agent-sniper/package.json@@ -1,6 +1,6 @@{"name": "@three-ws/agent-sniper",- "version": "0.1.5",+ "version": "0.1.6","mcpName": "io.github.nirholas/agent-sniper","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",diff --git a/packages/agent-sniper/server.json b/packages/agent-sniper/server.jsonindex d10900504..8d41eabd7 100644--- a/packages/agent-sniper/server.json+++ b/packages/agent-sniper/server.json@@ -18,12 +18,12 @@"source": "github","subfolder": "packages/agent-sniper"},- "version": "0.1.5",+ "version": "0.1.6","packages": [{"registryType": "npm","identifier": "@three-ws/agent-sniper",- "version": "0.1.5",+ "version": "0.1.6","runtimeHint": "npx","transport": {"type": "stdio"diff --git a/packages/agent-sniper/src/adapters/solana/pump-client.js b/packages/agent-sniper/src/adapters/solana/pump-client.jsindex cded6fc4d..04a2d89a0 100644--- a/packages/agent-sniper/src/adapters/solana/pump-client.js+++ b/packages/agent-sniper/src/adapters/solana/pump-client.js@@ -8,17 +8,82 @@// 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.+//+// ── Which pump.fun pricing regime this adapter covers ────────────────────────+// PumpTradeClient prices the pump program's BONDING CURVE, pre-graduation coins+// only. Spot price comes from the curve's virtual_quote_reserves /+// virtual_token_reserves. Those quote-side curve fields were renamed upstream+// (virtual_sol_reserves → virtual_quote_reserves, real_sol_reserves →+// real_quote_reserves) when a non-SOL quote asset became possible.+//+// The PumpSwap (pump_amm) POOL account has its own, unrelated field also called+// virtual_quote_reserves. It applies only AFTER graduation, is a signed i128,+// and pool quotes must price against the effective reserve+// (pool_quote_token_account.amount + pool.virtual_quote_reserves) while the base+// side stays the raw pool_base_token_account.amount. This adapter never touches+// a pool; an AMM-routed SolanaClient must handle that itself.+//+// ── Fail closed, never zero ──────────────────────────────────────────────────+// Every number below feeds a spend decision with no human in the loop, so a+// missing field is an error, not a default. `priceImpactPct ?? 0` sails straight+// through the entry circuit breaker as a perfect 0% impact; a `quoteMint`+// guessed as wSOL defeats the require_sol_quote gate; a zero sell quote reads as+// a -100% position and stop-losses a healthy bag. All three now throw.-import { Connection, PublicKey } from '@solana/web3.js';+import { Connection } 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());+// A quote whose price impact did not compute is unusable: the entry breaker+// compares against it, and any non-number silently passes the comparison.+export function requireImpactPct(value, side) {+ // Reject the absent cases before coercing: `Number(null)` is 0, which is the+ // very "healthy quote" reading a failed price computation must never produce.+ const n = value == null || value === '' ? NaN : Number(value);+ if (!Number.isFinite(n)) {+ throw Object.assign(+ new Error(`pump quote for ${side} returned no usable priceImpactPct (${String(value)})`),+ { code: 'quote_unpriced' },+ );+ }+ return n;+}++// The quote asset must be reported, never assumed. Guessing wSOL here would let+// a USDC-paired coin through a SOL-only strategy and denominate its P&L in the+// wrong unit.+export function requireQuoteMint(value, side) {+ if (!value || typeof value.toBase58 !== 'function') {+ throw Object.assign(new Error(`pump quote for ${side} reported no quoteMint`), {+ code: 'quote_mint_missing',+ });+ }+ return value;+}++// A sell quote of zero (or a missing one) means the curve/pool read failed, not+// that the bag is worthless. Returning 0 to the position sweep would read as a+// -100% position and fire an immediate stop-loss on a perfectly healthy coin.+export function requireQuoteOut(value, side) {+ if (value == null) {+ throw Object.assign(new Error(`pump quote for ${side} returned no expectedQuoteOut`), {+ code: 'quote_unpriced',+ });+ }+ const out = BigInt(value.toString());+ if (out <= 0n) {+ throw Object.assign(new Error(`pump quote for ${side} valued the position at zero`), {+ code: 'quote_unpriced',+ });+ }+ return out;+}+/*** @param {object} [opts]* @param {'mainnet'|'devnet'} [opts.network]@@ -39,8 +104,8 @@ export async function createPumpClient(opts = {}) {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),+ priceImpactPct: requireImpactPct(q.priceImpactPct, 'buy'),+ quoteMint: requireQuoteMint(q.quoteMint, 'buy'),};},@@ -54,7 +119,11 @@ export async function createPumpClient(opts = {}) {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()) };+ return {+ priceImpactPct: requireImpactPct(q.priceImpactPct, 'sell'),+ expectedQuoteOut: requireQuoteOut(q.expectedQuoteOut, 'sell'),+ quoteMint: requireQuoteMint(q.quoteMint, 'sell'),+ };},async buildSellInstructions({ mint, user, baseAmount, slippagePct }) {diff --git a/packages/agent-sniper/src/guards.js b/packages/agent-sniper/src/guards.jsindex ddaa5aec6..40d14ddc1 100644--- a/packages/agent-sniper/src/guards.js+++ b/packages/agent-sniper/src/guards.js@@ -37,7 +37,15 @@ export function checkSolHeadroom(balanceLamports, perTradeLamports, headroom = Sexport 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' };+ // Fails CLOSED on an unusable impact figure. `undefined > 10` and `NaN > 10`+ // are both false, so an unpriced quote used to walk straight through this+ // gate: the exact silent-zero failure a mispriced or half-decoded pool+ // produces. `Number(null)` and `Number('')` are 0, so the absent cases must+ // be rejected BEFORE coercion, or "no data" arrives as a perfect 0% impact.+ if (impactPct == null || impactPct === '') return { reason: 'price_impact_unknown' };+ const impact = Number(impactPct);+ if (!Number.isFinite(impact)) return { reason: 'price_impact_unknown' };+ if (impact > max) return { reason: 'price_impact_too_high' };return null;}@@ -90,7 +98,13 @@ export function makeQueue(concurrency, maxDepth, { onError, onDrop } = {}) {/** 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;+ // An unusable impact figure takes the FULL penalty rather than writing a NaN+ // confidence into the decision ledger: "we could not price this" is low+ // conviction, not missing data.+ const impact = priceImpactPct == null || priceImpactPct === '' ? NaN : Number(priceImpactPct);+ const impactPenalty = Number.isFinite(impact)+ ? Math.min(1, Math.max(0, impact) / (maxImpactPct > 0 ? maxImpactPct : 10)) * 0.4+ : 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/positions.js b/packages/agent-sniper/src/positions.jsindex d03199e9c..604211d93 100644--- a/packages/agent-sniper/src/positions.js+++ b/packages/agent-sniper/src/positions.js@@ -22,10 +22,24 @@ async function tickPosition(cfg, pos, ports) {const baseAmount = BigInt(pos.base_amount);const slippagePct = (pos.slippage_bps ?? 500) / 100;+ // Re-quote the bag. This number decides whether the position exits, so an+ // unusable quote must NOT be read as a valuation. The bundled adapter throws+ // on a missing or non-positive quote, but a custom SolanaClient may not, so+ // the sweep re-checks independently: a zero here would compute as -100% P&L+ // and stop-loss a perfectly healthy position on the very next tick. A real+ // collapse still exits, because a real collapse still returns a real number.let value;try {const quote = await solana.quoteForSell({ mint: mintPk, baseAmount, slippagePct });- value = Number(quote.expectedQuoteOut.toString());+ const out = quote?.expectedQuoteOut == null ? null : Number(quote.expectedQuoteOut.toString());+ if (out == null || !Number.isFinite(out) || out <= 0) {+ log.warn('position re-quote returned no usable value, holding', {+ mint: pos.mint,+ expected_quote_out: String(quote?.expectedQuoteOut),+ });+ return; // hold, do not value the bag at zero+ }+ value = out;} catch (err) {log.warn('position re-quote failed', { mint: pos.mint, err: err?.message });return; // transient — try again next sweepdiff --git a/packages/agent-sniper/test/pricing-boundary.test.js b/packages/agent-sniper/test/pricing-boundary.test.jsnew file mode 100644index 000000000..f58aa5674--- /dev/null+++ b/packages/agent-sniper/test/pricing-boundary.test.js@@ -0,0 +1,180 @@+// Pricing-boundary regression tests.+//+// Two upstream pump.fun changes made "the reserves decoded to nothing" a live+// possibility rather than a theoretical one:+//+// · The bonding curve renamed its quote-side fields (virtual_sol_reserves →+// virtual_quote_reserves, real_sol_reserves → real_quote_reserves). A+// decoder still reading the old names gets `undefined`, which coerces to 0+// rather than throwing, so a coin reads as 0% to graduation at a zero price.+// · The PumpSwap Pool gained virtual_quote_reserves, and quotes now price on+// pool_quote_token_account.amount + pool.virtual_quote_reserves. Pricing off+// the raw vault balance is silently wrong, not an error.+//+// Both fail as bad NUMBERS, never as exceptions, and this engine spends real SOL+// on those numbers with no human in the loop. So the boundary where a quote+// enters the engine has to reject an unpriced quote instead of reading it as a+// zero, and the position sweep must not mistake a failed read for a wipeout.++import { describe, it, expect, vi } from 'vitest';+import { PublicKey } from '@solana/web3.js';++import {+ requireImpactPct,+ requireQuoteMint,+ requireQuoteOut,+} from '../src/adapters/solana/pump-client.js';+import { runPositionSweep } from '../src/positions.js';++const WSOL = new PublicKey('So11111111111111111111111111111111111111112');+// $THREE. A real, valid mint is needed because the sweep parses pos.mint into a+// PublicKey before it quotes; nothing here touches the chain.+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';++describe('quote boundary: requireImpactPct', () => {+ it('passes a real figure through, zero included', () => {+ expect(requireImpactPct(3.5, 'buy')).toBe(3.5);+ expect(requireImpactPct(0, 'buy')).toBe(0);+ expect(requireImpactPct('2.25', 'buy')).toBe(2.25);+ });++ it('throws rather than defaulting a missing impact to 0', () => {+ // `priceImpactPct ?? 0` here would hand the entry breaker a perfect score+ // for a quote that never priced.+ for (const bad of [undefined, null, NaN, 'abc', Infinity]) {+ expect(() => requireImpactPct(bad, 'buy')).toThrow(/priceImpactPct/);+ }+ expect(() => requireImpactPct(undefined, 'sell')).toThrow(+ expect.objectContaining({ code: 'quote_unpriced' }),+ );+ });+});++describe('quote boundary: requireQuoteMint', () => {+ it('passes the reported quote mint through', () => {+ expect(requireQuoteMint(WSOL, 'buy')).toBe(WSOL);+ });++ // The curve gained a quote_mint field; assuming wSOL when it is absent would+ // let a non-SOL-paired coin past a SOL-only strategy and denominate its P&L+ // in the wrong asset.+ it('throws rather than assuming wSOL', () => {+ expect(() => requireQuoteMint(undefined, 'buy')).toThrow(+ expect.objectContaining({ code: 'quote_mint_missing' }),+ );+ expect(() => requireQuoteMint({}, 'buy')).toThrow(/quoteMint/);+ });+});++describe('quote boundary: requireQuoteOut', () => {+ it('returns the quoted amount as a bigint', () => {+ expect(requireQuoteOut({ toString: () => '12345' }, 'sell')).toBe(12345n);+ expect(requireQuoteOut(7n, 'sell')).toBe(7n);+ });++ // Empty-reserve decode → a quote of 0. That is a failed read, not a+ // worthless bag, and the difference is a forced sale at the bottom.+ it('throws on a zero or missing valuation instead of reporting it', () => {+ expect(() => requireQuoteOut(0n, 'sell')).toThrow(/zero/);+ expect(() => requireQuoteOut(undefined, 'sell')).toThrow(/expectedQuoteOut/);+ expect(() => requireQuoteOut(null, 'sell')).toThrow(+ expect.objectContaining({ code: 'quote_unpriced' }),+ );+ });+});++// ── position sweep ───────────────────────────────────────────────────────────+// A second line of defence for adapters that are not the bundled one: even if a+// custom SolanaClient does return 0, the sweep must hold rather than exit.++function harness({ quoteForSell }) {+ const position = {+ id: 'pos_1',+ agent_id: 'agent_1',+ mint: THREE_MINT,+ base_amount: '1000000',+ slippage_bps: 500,+ entry_quote_lamports: '100000000',+ peak_value_lamports: '100000000',+ stop_loss_pct: 20,+ opened_at_ms: Date.now(),+ status: 'open',+ };+ const updatePosition = vi.fn(async () => {});+ const warn = vi.fn();+ return {+ position,+ updatePosition,+ warn,+ cfg: { network: 'mainnet', exitOnBearish: false },+ ports: {+ store: {+ getOpenPositions: async () => [position],+ updatePosition,+ },+ wallet: {+ loadKeypair: async () => {+ throw new Error('sweep must not reach the wallet on a bad quote');+ },+ },+ solana: { quoteForSell, connection: {} },+ executor: {+ submit: async () => {+ throw new Error('sweep must not broadcast on a bad quote');+ },+ },+ hooks: {},+ log: { info: () => {}, warn, error: () => {}, trade: () => {} },+ },+ };+}++describe('runPositionSweep', () => {+ it('holds the position when the re-quote values it at zero', async () => {+ const h = harness({+ quoteForSell: async () => ({ priceImpactPct: 0, expectedQuoteOut: 0n }),+ });+ await runPositionSweep(h.cfg, h.ports);+ // No valuation written, no exit attempted: the wallet/executor stubs+ // above would have thrown had the sell path run.+ expect(h.updatePosition).not.toHaveBeenCalled();+ expect(h.warn).toHaveBeenCalledWith(+ 'position re-quote returned no usable value, holding',+ expect.objectContaining({ mint: h.position.mint }),+ );+ });++ it('holds when the re-quote omits expectedQuoteOut entirely', async () => {+ const h = harness({ quoteForSell: async () => ({ priceImpactPct: 1 }) });+ await runPositionSweep(h.cfg, h.ports);+ expect(h.updatePosition).not.toHaveBeenCalled();+ });++ it('records the valuation and holds when a real quote shows a healthy position', async () => {+ const h = harness({+ quoteForSell: async () => ({ priceImpactPct: 1, expectedQuoteOut: 110_000_000n }),+ });+ await runPositionSweep(h.cfg, h.ports);+ expect(h.updatePosition).toHaveBeenCalledWith('pos_1', {+ last_value_lamports: 110_000_000,+ peak_value_lamports: 110_000_000,+ });+ });++ it('still exits on a real quote that shows the position through its stop-loss', async () => {+ // 100_000_000 entry, 20% stop → a genuine 50_000_000 quote must sell. The+ // zero-guard must not become a way for a collapsing coin to be held.+ const h = harness({+ quoteForSell: async () => ({ priceImpactPct: 1, expectedQuoteOut: 50_000_000n }),+ });+ await runPositionSweep(h.cfg, h.ports);+ expect(h.updatePosition).toHaveBeenCalledWith('pos_1', {+ last_value_lamports: 50_000_000,+ peak_value_lamports: 100_000_000,+ });+ // The exit path runs: it marks the position 'closing' before selling, then+ // fails on the deliberately-throwing wallet stub and returns it to 'open'.+ const statuses = h.updatePosition.mock.calls.map(([, patch]) => patch.status).filter(Boolean);+ expect(statuses).toContain('closing');+ });+});diff --git a/packages/agent-sniper/test/publish-metadata.test.js b/packages/agent-sniper/test/publish-metadata.test.jsnew file mode 100644index 000000000..d76bbb51a--- /dev/null+++ b/packages/agent-sniper/test/publish-metadata.test.js@@ -0,0 +1,32 @@+import { describe, it, expect } from 'vitest';+import { readFile } from 'node:fs/promises';++// The MCP registry rejects a server.json whose declared version disagrees with+// the npm package it points at, and npm refuses to republish an existing+// version. Both have bitten this org: npm reached 0.1.2 here while+// package.json still read 0.1.0, because publish-time bumps were never+// committed back. The repo could not publish and misreported what was live.+describe('publish metadata stays internally consistent', () => {+ const load = async (f) =>+ JSON.parse(await readFile(new URL(`../${f}`, import.meta.url), 'utf8'));++ it('server.json version tracks package.json', async () => {+ const [pkg, server] = await Promise.all([load('package.json'), load('server.json')]);+ expect(server.version).toBe(pkg.version);+ });++ it('server.json npm package entry tracks package.json', async () => {+ const [pkg, server] = await Promise.all([load('package.json'), load('server.json')]);+ const entry = server.packages?.find(+ (p) => p.registryType === 'npm' && p.identifier === pkg.name,+ );+ expect(entry, `server.json must list an npm entry for ${pkg.name}`).toBeDefined();+ expect(entry.version).toBe(pkg.version);+ });++ it('mcpName ties the npm package to its registry identity', async () => {+ const [pkg, server] = await Promise.all([load('package.json'), load('server.json')]);+ // A mismatch publishes an orphaned registry entry that resolves to nothing.+ expect(pkg.mcpName).toBe(server.name);+ });+});