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
Add unit tests for exit logic, guards, scorer, memory store, wallet adapters, and Vitest configuration
qbdz866571b1048d
diff --git a/data/changelog.json b/data/changelog.jsonindex a5d99ae17..73eb1c68b 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,15 @@{"$comment": "Curated changelog entries for three.ws \u2014 the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-06-30",+ "title": "Agent Sniper is now a standalone open-source package",+ "summary": "The engine that lets three.ws agents snipe pump.fun launches is now its own lightweight, embeddable package: @three-ws/agent-sniper. Run it four ways — as a library, a CLI, an MCP server your AI agent can drive, or a paid x402 API that other agents pay in USDC to use. It ships with pluggable wallet, storage, RPC, and launch-feed adapters, so you can run a fully self-custodial sniper from your own keypair or a multi-tenant hosted service from one engine. Every agent gets its own wallet, its own budget and concurrency caps, a mandatory stop-loss, a price-impact circuit breaker, and a simulate-first default — plus the 3D-agent layer that puts a live trading desk on screen. Multiple agents and multiple users can snipe side by side, each embodied by its own 3D AI agent.",+ "tags": [+ "sdk",+ "feature"+ ]+ },{"date": "2026-06-30","title": "Oracle now has full documentation",diff --git a/package.json b/package.jsonindex feaffdb5e..54e242dc7 100644--- a/package.json+++ b/package.json@@ -59,6 +59,7 @@"packages/intel-mcp","packages/marketplace-mcp","packages/x402-mcp",+ "packages/agent-sniper","packages/provenance-mcp","packages/autopilot-mcp","packages/portfolio-mcp",diff --git a/packages/agent-sniper/LICENSE b/packages/agent-sniper/LICENSEnew file mode 100644index 000000000..6f401e890--- /dev/null+++ b/packages/agent-sniper/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) three.ws++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/packages/agent-sniper/README.md b/packages/agent-sniper/README.mdnew file mode 100644index 000000000..c96a54964--- /dev/null+++ b/packages/agent-sniper/README.md@@ -0,0 +1,376 @@+# @three-ws/agent-sniper++A lightweight, embeddable pump.fun sniper engine for 3D AI agents. One trade+loop — feed a stream of new launches, score each against a per-agent strategy,+run the pre-trade guards, buy, then sweep open positions on an interval and exit+on stop-loss / take-profit / trailing-stop / timeout / sentiment-flip. It is+multi-agent and multi-user by construction (one wallet per `agentId`), and every+external dependency — wallet custody, persistence, RPC/venue, launch feed — is a+pluggable adapter, so the same engine runs locally with in-memory state or+hosted across thousands of tenants. The package ships with four faces over that+one engine: a **library**, a **CLI**, an **MCP server**, and an **x402 paid HTTP+API**.++---++## Why — the adapter architecture++The engine is pure orchestration. It owns the decision pipeline; it owns nothing+about *where* the money, the data, or the chain live. Five adapter interfaces+(`src/types.js`) are the seams, and a default implementation ships for each:++```+ ┌──────────────────────────── engine ────────────────────────────┐+ Feed ──{mint|intel|claim}─▶ score ──▶ guards ──▶ executeBuy ──▶ claimPosition │+ (PumpPortal) (scorer) (concurrency, (quote + (atomic slot) │+ budget, SOL build + sign │+ headroom, + broadcast) │+ price impact) │+ position sweep (every pollMs) │+ ──▶ decideExit ──▶ executeSell │+ └────────────────────────────────────────────────────────────────────┘+ adapters: Feed Solana Wallet Executor Store+ (launch (quote/build (resolve a (sign + (strategies,+ stream) pump.fun ix) Keypair per broadcast) positions,+ agentId) spend ledger)+```++Swap any one without touching the loop: a custodial KMS wallet instead of local+keys, a Postgres store instead of memory, a different launch feed, a different+venue. Implement the shape, pass it to `createSniper()`, done.++| Adapter | Responsibility |+|------------|----------------|+| `Feed` | Push `{ kind: 'mint'\|'intel'\|'claim', data: Candidate }` events into the engine. |+| `Solana` | Quote + build pump.fun buy/sell instructions; expose a web3 `Connection`. |+| `Wallet` | Resolve a signing `Keypair` for an `agentId` (or `null` if unprovisioned). |+| `Executor` | The one place that signs and broadcasts; returns landing telemetry. |+| `Store` | Persist strategies, positions, and the daily spend ledger; atomic `claimPosition`. |++Optional `Hooks` (firewall `assessSafety`, `oracleGate`, `onScreen`, `onBuy`,+`onSell`, `recordDecision`) are best-effort cross-cutting callbacks — a throw is+swallowed and never aborts a trade, except `onTip`, which is a deliberate veto.++---++## Install++```bash+npm i @three-ws/agent-sniper+```++Optional peers, installed only if you use the face that needs them:++```bash+npm i better-sqlite3 # durable Store (src/adapters/store/sqlite.js)+npm i express # the x402 HTTP API face+```++Requires Node >= 20.++---++## Quickstart (library)++The `presets.local` wiring is the zero-to-running path: in-memory store ++self-custody wallet + pump.fun client + web3 executor + PumpPortal feed. Run it+in **simulate** mode on **devnet** first — the engine scores, guards, and logs+every decision but never broadcasts.++A strategy **must** carry a `stop_loss_pct` — the engine refuses to arm a+strategy without one. SOL amounts on a strategy are expressed in **lamports**+(1 SOL = 1,000,000,000 lamports), as a string, number, or bigint.++```js+import { createSniper, createMemoryStore, presets } from '@three-ws/agent-sniper';++// 1 SOL = 1e9 lamports.+const SOL = 1_000_000_000n;++const strategy = {+ id: 'strat_scout_1',+ agent_id: 'scout', // one wallet per agentId+ enabled: true,+ trigger: 'new_mint', // fire on the create event+ network: 'devnet',+ per_trade_lamports: (SOL / 100n).toString(), // 0.01 SOL per snipe+ daily_budget_lamports: (SOL / 2n).toString(), // 0.5 SOL/day ceiling+ max_concurrent_positions: 3,+ slippage_bps: 500, // 5%+ max_price_impact_pct: 10, // entry circuit breaker+ stop_loss_pct: 30, // REQUIRED — exit when down 30%+ take_profit_pct: 80, // exit when up 80%+ trailing_stop_pct: 20, // exit when down 20% from peak (after profit)+ max_hold_seconds: 1800, // hard time-stop+ require_socials: true, // skip launches with no twitter/telegram/website+ max_creator_launches: 10, // skip serial launchers+};++const sniper = await presets.local({+ network: 'devnet',+ mode: 'simulate', // no funds move+ strategies: [strategy],+ // secrets: { scout: '<base58 | [byte,array] | 0x-hex secret>' }, // for live mode+});++await sniper.start();++console.log(sniper.stats()); // { events, candidates, buys, sells, errors, strategies, queued, lastEventAt }+console.log(sniper.strategies()); // the live armed-strategy cache++// Fire a manual buy by hand (drives the same path as MCP snipe_now):+sniper.submitCandidate(+ { mint: 'THREEsynthetic1111111111111111111111111111111', entry_trigger: 'manual' },+ { force: true },+);++// later…+await sniper.stop();+```++`createSniper(deps)` is the lower-level constructor when you want to bring your+own adapters — pass `{ config, store, wallet, solana, executor, feed, hooks }`.+`presets.local` is just one wiring of it.++---++## CLI usage++The package installs an `agent-sniper` binary. Default mode is **simulate** — it+will not move funds until you pass `--mode live` (or set `SNIPER_MODE=live`),+which trades **real funds**.++```bash+# Run the engine. Mode defaults to simulate; live trades real funds.+npx agent-sniper run --network devnet --strategy ./strategy.json++# Serve the engine over MCP (stdio) for Claude / Cursor / any MCP client.+agent-sniper mcp++# Serve the x402-gated HTTP API.+agent-sniper serve++# Help.+agent-sniper help+```++> **Safety.** `run`/`serve`/`mcp` all start in simulate mode unless you opt into+> live explicitly. In live mode every armed strategy can spend up to its+> `daily_budget_lamports` per UTC day. Read **Safety & guardrails** below before+> you flip the switch.++`--strategy ./strategy.json` loads a strategy (or array of strategies) as JSON.+A minimal file mirrors the object in the Quickstart — note `stop_loss_pct` is+required.++---++## MCP server++`agent-sniper mcp` exposes the engine as an MCP stdio server. Every tool maps+1:1 onto a public engine/store method — no internals are reached around. The+server is unauthenticated and meant to run locally against your own wallet/RPC.++| Tool | Kind | Purpose |+|------|------|---------|+| `arm_strategy` | write | Register/update a strategy. SOL → lamports for you; `stop_loss_pct` mandatory. |+| `disarm_strategy` | write | Disable a strategy (`enabled=false`); open positions still exit on their rules. |+| `list_strategies` | read | List the armed strategy set the engine is evaluating. |+| `snipe_now` | write | Force a manual buy of a mint across all armed agents (bypasses the scorer). |+| `list_positions` | read | List positions, filter by `agentId` and/or `status`. |+| `close_position` | write | Schedule an exit — flips the position's kill switch; the next sweep sells it. |+| `sniper_status` | read | Engine health: event/candidate/buy/sell counts, armed count, queue depth, network/mode. |++Wire it into an MCP client (Claude Desktop, Cursor, etc.):++```json+{+ "mcpServers": {+ "agent-sniper": {+ "command": "npx",+ "args": ["-y", "@three-ws/agent-sniper", "mcp"],+ "env": {+ "SNIPER_NETWORK": "devnet",+ "SNIPER_MODE": "simulate"+ }+ }+ }+}+```++`createSniperMcpServer(deps)` builds the fully-registered server **without**+connecting a transport, so you can construct it in a test and drive it over an+in-memory transport.++---++## x402 paid HTTP API++`agent-sniper serve` (or `import { serve } from '@three-ws/agent-sniper/api'`)+mounts the engine over HTTP. Reads are free; the three mutating endpoints are+gated behind x402 USDC micropayments via `@three-ws/x402-server` — the+middleware verifies the `X-PAYMENT` header against the facilitator, runs the+work, settles on-chain, and emits the receipt.++| Method | Endpoint | Price | Notes |+|--------|----------|-------|-------|+| GET | `/health` | free | Liveness + network/mode/stats. |+| GET | `/status` | free | Full stats + immutable runtime config. |+| GET | `/strategies` | free | The armed strategy set. |+| GET | `/positions?agentId=&status=` | free | Positions from the store. |+| POST | `/strategies` | **$0.01 USDC** | Arm a strategy (SOL → lamports; stop-loss required). |+| POST | `/snipe` | **$0.05 USDC** | Force a snipe on `{ mint, symbol?, agentId? }`. |+| POST | `/strategies/:id/disarm` | **$0.005 USDC** | Disable a strategy. |++Prices are the defaults (USDC atomic units, 6 decimals); override via+`deps.prices = { arm, snipe, disarm }`.++Gating turns on when a merchant wallet is configured — `deps.payTo.solana` or the+`X402_PAY_TO_SOLANA` env (a Base lane is available via `X402_PAY_TO_BASE`). When+no `payTo` is set, the mutating routes still mount but answer `503`, so the+server boots cleanly for local/dev without payment config.++```js+import { serve } from '@three-ws/agent-sniper/api';++await serve(+ { payTo: { solana: process.env.X402_PAY_TO_SOLANA } },+ { port: 8787 },+);+```++---++## Multi-agent / multi-user++The engine is multi-tenant by design. The unit of isolation is the `agentId`:++- **One wallet per agent.** The `Wallet` adapter resolves a signing `Keypair`+ per `agentId`. Self-custody reads it (in order) from a `secrets` map,+ `SNIPER_WALLET_<AGENTID>` env, a keystore directory of `<agentId>.json` files,+ or a single default `SOLANA_SECRET_KEY`. If an agent has no provisioned+ wallet, `loadKeypair` returns `null` and the engine fails the trade cleanly —+ it never auto-provisions an unfunded wallet.+- **Custodial for hosted deployments.** `createCustodialWallet({ resolve })`+ takes a single async `resolve(agentId, ctx)` that decrypts a key from your own+ KMS/secret box on demand, with a short TTL cache so a long-lived process+ doesn't re-decrypt every trade. The cache is keyed per agent; `clearCache()`+ forces a re-resolve.+- **Per-agent caps.** Each strategy carries its own `daily_budget_lamports` and+ `max_concurrent_positions`. The guards enforce them per agent, independent of+ the platform-wide buy throttle.+- **Mandatory stop-loss.** `getArmedStrategies` filters out any strategy missing+ `stop_loss_pct`, so an agent can never run uncapped downside.+- **Idempotent claims prevent double-buys.** Before a buy, the engine calls+ `Store.claimPosition` to atomically reserve the `(agent_id, mint, network)`+ slot. A second event for the same slot returns `null` and is skipped.++---++## 3D agents++`@three-ws/agent-sniper/agents` is the presentation layer that lets a 3D AI+agent *embody* the sniper: avatar definitions, the canonical animation clip+library, and a desk-monitor visualization driven by the engine's `onScreen`+hook. Wire the hook to push live activity (`Sniper online…`, `$SYM scored N —+BUYING`) onto the agent's monitor so the trading loop is something you can watch,+not just a log stream. The `onScreen` payload shape is `{ text, kind }` with+`kind` in `activity | trade`.++---++## Adapter reference++Implement any of these (`src/types.js` has the full JSDoc contracts) and pass it+to `createSniper`. Defaults live under `src/adapters/`.++| Interface | Default implementation | Write your own when… |+|-----------|------------------------|----------------------|+| `Store` | `createMemoryStore` · `createSqliteStore` (`./adapters/store/sqlite`) | you need durable or shared multi-process state (e.g. Postgres). |+| `Wallet` | `createSelfCustodyWallet` · `createCustodialWallet` | keys live in a KMS/HSM or a hosted secret store. |+| `Solana` | `createPumpClient` (`./adapters/solana/pump-client`) | you route quotes/builds through a different venue. |+| `Executor` | `createWeb3Executor` (`./adapters/solana/executor-web3`) | you broadcast through a custom relay/bundler. |+| `Feed` | `createPumpPortalFeed` (`./adapters/feed/pumpportal`) | you ingest launches from a different source. |++The `Store` contract is the load-bearing one: `getArmedStrategies`,+`countOpenPositions`, `getDailySpendLamports`, `claimPosition` (atomic),+`updatePosition`, `getOpenPositions`, and optional `recordSpend`. See the+in-memory reference at `src/adapters/store/memory.js`.++---++## Configuration++All `SNIPER_*` env vars (read by `loadConfig`, `src/config.js`). Explicit+overrides passed to `createSniper`/`loadConfig` always win. See `.env.example`.++| Variable | Default | Meaning |+|----------|---------|---------|+| `SNIPER_NETWORK` | `mainnet` | `mainnet` \| `devnet`. |+| `SNIPER_MODE` | `simulate` | `simulate` \| `live`. Simulate never broadcasts. |+| `SOLANA_RPC_URL` | — | RPC endpoint. Live mode requires this (or `HELIUS_API_KEY`). |+| `SNIPER_GLOBAL_KILL` | `false` | Emergency switch — halts all buys when true. |+| `SNIPER_POLL_MS` | `5000` | Position re-quote / exit cadence (floor 1000). |+| `SNIPER_STRATEGY_REFRESH_MS` | `15000` | Strategy-cache refresh interval (floor 5000). |+| `SNIPER_MAX_GLOBAL_BUYS_PER_MIN` | `10` | Platform-wide buy throttle; 0 disables. |+| `SNIPER_BUY_CONCURRENCY` | `3` | Max concurrent in-flight snipes (floor 1). |+| `SNIPER_BUY_QUEUE_DEPTH` | `50` | Queued-snipe cap before drops (floor 1). |+| `SNIPER_CONFIRM_TIMEOUT_MS` | `60000` | Confirmation timeout per trade (floor 15000). |+| `SNIPER_FEED_WATCHDOG_MS` | `180000` | Re-subscribe if the feed goes quiet (floor 30000). |+| `SNIPER_EXIT_ON_BEARISH` | `false` | Enable the sentiment-flip exit. |+| `SNIPER_EXIT_BEARISH_MIN_CONFIDENCE` | `0.7` | Min bearish confidence (0..1) to act. |++---++## Safety & guardrails++- **Simulate by default.** Every face starts in simulate mode. You opt into live+ trading explicitly.+- **Mandatory stop-loss.** A strategy without `stop_loss_pct` is never armed.+- **Daily budget + concurrency caps.** Per-agent `daily_budget_lamports` and+ `max_concurrent_positions` are enforced before any transaction is built+ (`checkDailyBudgetLamports`, `checkConcurrency`).+- **SOL fee headroom.** `checkSolHeadroom` keeps ~0.012 SOL in the wallet so a+ snipe can't drain the account below the cost of the very next sell's fee.+- **Price-impact circuit breaker.** `max_price_impact_pct` (default 10) skips a+ buy whose quote impact is too high (`checkPriceImpact`; unset ⇒ no gate).+- **Live-RPC refusal.** Live mode refuses to start on a public RPC — it requires+ a real endpoint so trades aren't silently dropped to rate limits.+- **Optional firewall hook.** The `assessSafety` hook runs after the quote and+ before broadcast; a `block` verdict cancels the trade.+- **Global kill switch.** `SNIPER_GLOBAL_KILL=true` (or `config.globalKill`)+ halts every buy across every agent immediately.++---++## Scaling beyond one process++`claimPosition` in the memory and sqlite stores is atomic **within one+process** — the memory store relies on JS being single-threaded; the sqlite+store on a single-writer transaction. Combined with the engine's bounded in-+process buy queue, that prevents double-buying the same `(agent_id, mint,+network)` slot inside a single sniper instance.++Run **two sniper processes against the same agent** and that guarantee no longer+holds: nothing serializes the claim across processes. To scale horizontally,+back the `Store` with a database whose `claimPosition` is a genuinely atomic+insert-if-absent (e.g. a unique constraint on `(agent_id, mint, network)` with+`INSERT … ON CONFLICT DO NOTHING RETURNING`), so the reservation is decided by+the database, not by any one process. The `Store` contract documents exactly+this requirement.++---++## Testing++Pure-logic and in-memory-adapter suites run with no network/RPC:++```bash+npm test # vitest run+```++---++## License++MIT — see [LICENSE](./LICENSE). Copyright © three.ws.diff --git a/packages/agent-sniper/test/exit-logic.test.js b/packages/agent-sniper/test/exit-logic.test.jsnew file mode 100644index 000000000..b7d5baf56--- /dev/null+++ b/packages/agent-sniper/test/exit-logic.test.js@@ -0,0 +1,104 @@+// Unit tests for the pure exit decision (src/exit-logic.js). No I/O.+import { describe, it, expect } from 'vitest';+import { decideExit } from '../src/exit-logic.js';++const NOW = 1_700_000_000_000;++// Helper: a position entered at `entry` lamports with the given exit rules.+function pos(entry, rules = {}) {+ return { entry_quote_lamports: entry, opened_at_ms: NOW, ...rules };+}++describe('decideExit — guards', () => {+ it('holds (null) when entry is non-positive', () => {+ expect(decideExit(pos(0, { stop_loss_pct: 10 }), 1, 1, NOW)).toBe(null);+ });++ it('holds when no rule is breached', () => {+ const p = pos(1_000, { stop_loss_pct: 50, take_profit_pct: 50 });+ expect(decideExit(p, 1_010, 1_010, NOW)).toBe(null);+ });+});++describe('decideExit — stop_loss (highest priority)', () => {+ it('fires when down at least the stop-loss percent', () => {+ const p = pos(1_000, { stop_loss_pct: 20 });+ expect(decideExit(p, 800, 1_000, NOW)).toBe('stop_loss');+ });++ it('takes priority over take_profit and timeout when all breached', () => {+ // value below entry → stop_loss must win even with tp/timeout also set.+ const p = pos(1_000, { stop_loss_pct: 20, take_profit_pct: 10, max_hold_seconds: 1 });+ expect(decideExit(p, 700, 1_500, NOW + 10_000)).toBe('stop_loss');+ });+});++describe('decideExit — trailing_stop', () => {+ it('arms only after the peak exceeds entry', () => {+ // peak never beat entry → trailing stop does not arm even on a large drop.+ const p = pos(1_000, { trailing_stop_pct: 10 });+ expect(decideExit(p, 850, 950, NOW)).toBe(null);+ });++ it('fires when in profit and the drawdown from peak exceeds the trail', () => {+ // peak 1500 (> entry 1000), value 1300 → 13.3% drop from peak >= 10%.+ const p = pos(1_000, { trailing_stop_pct: 10 });+ expect(decideExit(p, 1_300, 1_500, NOW)).toBe('trailing_stop');+ });++ it('outranks take_profit when both apply', () => {+ const p = pos(1_000, { trailing_stop_pct: 10, take_profit_pct: 20 });+ // value 1300 is up 30% (tp) but also 13% off the 1500 peak (trail) → trail wins.+ expect(decideExit(p, 1_300, 1_500, NOW)).toBe('trailing_stop');+ });+});++describe('decideExit — take_profit', () => {+ it('fires when up at least the take-profit percent', () => {+ const p = pos(1_000, { take_profit_pct: 25 });+ expect(decideExit(p, 1_300, 1_300, NOW)).toBe('take_profit');+ });++ it('outranks timeout when both apply', () => {+ const p = pos(1_000, { take_profit_pct: 25, max_hold_seconds: 1 });+ expect(decideExit(p, 1_300, 1_300, NOW + 10_000)).toBe('take_profit');+ });+});++describe('decideExit — timeout', () => {+ it('fires once max_hold_seconds has elapsed', () => {+ const p = pos(1_000, { max_hold_seconds: 30 });+ expect(decideExit(p, 1_010, 1_010, NOW + 31_000)).toBe('timeout');+ });++ it('holds before the hold window elapses', () => {+ const p = pos(1_000, { max_hold_seconds: 30 });+ expect(decideExit(p, 1_010, 1_010, NOW + 5_000)).toBe(null);+ });+});++describe('decideExit — signal_flip (sentiment)', () => {+ const bearish = { signal: 'bearish', confidence: 0.9, minConfidence: 0.7 };++ it('fires when underwater, bearish, and confident enough', () => {+ const p = pos(1_000, { stop_loss_pct: 90 });+ // value 950 < entry, no other rule breached, bearish above min confidence.+ expect(decideExit(p, 950, 1_000, NOW, bearish)).toBe('signal_flip');+ });++ it('holds while in profit even on a bearish flip', () => {+ const p = pos(1_000, {});+ expect(decideExit(p, 1_100, 1_100, NOW, bearish)).toBe(null);+ });++ it('holds when confidence is below the minimum', () => {+ const p = pos(1_000, { stop_loss_pct: 90 });+ const weak = { signal: 'bearish', confidence: 0.5, minConfidence: 0.7 };+ expect(decideExit(p, 950, 1_000, NOW, weak)).toBe(null);+ });++ it('is lowest priority — stop_loss still wins', () => {+ const p = pos(1_000, { stop_loss_pct: 5 });+ expect(decideExit(p, 800, 1_000, NOW, bearish)).toBe('stop_loss');+ });+});diff --git a/packages/agent-sniper/test/guards.test.js b/packages/agent-sniper/test/guards.test.jsnew file mode 100644index 000000000..6fc37f407--- /dev/null+++ b/packages/agent-sniper/test/guards.test.js@@ -0,0 +1,165 @@+// Unit tests for the pre-trade guards + flow control (src/guards.js). Pure.+import { describe, it, expect, vi } from 'vitest';+import {+ checkConcurrency,+ checkDailyBudgetLamports,+ checkSolHeadroom,+ checkPriceImpact,+ makeThrottle,+ makeQueue,+ SOL_FEE_HEADROOM_LAMPORTS,+} from '../src/guards.js';++describe('checkConcurrency', () => {+ it('passes (null) below the cap', () => {+ expect(checkConcurrency(2, 3)).toBe(null);+ });++ it('breaches at the cap', () => {+ expect(checkConcurrency(3, 3)).toEqual({ reason: 'max_concurrency' });+ });++ it('defaults the cap to 1 when unset', () => {+ expect(checkConcurrency(0, undefined)).toBe(null);+ expect(checkConcurrency(1, undefined)).toEqual({ reason: 'max_concurrency' });+ });+});++describe('checkDailyBudgetLamports', () => {+ it('breaches when no budget is set', () => {+ expect(checkDailyBudgetLamports(0n, 100n, 0n)).toEqual({ reason: 'no_budget' });+ });++ it('passes when spent + trade is within budget', () => {+ expect(checkDailyBudgetLamports(100n, 100n, 1_000n)).toBe(null);+ });++ it('breaches when spent + trade exceeds budget', () => {+ expect(checkDailyBudgetLamports(950n, 100n, 1_000n)).toEqual({ reason: 'daily_budget_exceeded' });+ });++ it('does bigint math beyond Number.MAX_SAFE_INTEGER', () => {+ const spent = 9_007_199_254_740_993n; // > 2^53+ const trade = 1n;+ const budget = spent + trade;+ expect(checkDailyBudgetLamports(spent, trade, budget)).toBe(null);+ expect(checkDailyBudgetLamports(spent, 2n, budget)).toEqual({ reason: 'daily_budget_exceeded' });+ });++ it('coerces non-bigint numeric inputs', () => {+ expect(checkDailyBudgetLamports(0, 500, 1_000)).toBe(null);+ });+});++describe('checkSolHeadroom', () => {+ it('passes when balance covers trade plus the default fee headroom', () => {+ const trade = 1_000_000n;+ const bal = trade + SOL_FEE_HEADROOM_LAMPORTS;+ expect(checkSolHeadroom(bal, trade)).toBe(null);+ });++ it('breaches when balance falls one lamport short of headroom', () => {+ const trade = 1_000_000n;+ const bal = trade + SOL_FEE_HEADROOM_LAMPORTS - 1n;+ expect(checkSolHeadroom(bal, trade)).toEqual({ reason: 'insufficient_sol' });+ });++ it('accepts a custom headroom', () => {+ expect(checkSolHeadroom(150n, 100n, 50n)).toBe(null);+ expect(checkSolHeadroom(149n, 100n, 50n)).toEqual({ reason: 'insufficient_sol' });+ });+});++describe('checkPriceImpact', () => {+ it('does not gate when the max is unset / non-positive', () => {+ expect(checkPriceImpact(99, undefined)).toBe(null);+ expect(checkPriceImpact(99, 0)).toBe(null);+ expect(checkPriceImpact(99, NaN)).toBe(null);+ });++ it('passes when impact is at or below the max', () => {+ expect(checkPriceImpact(10, 10)).toBe(null);+ expect(checkPriceImpact(5, 10)).toBe(null);+ });++ it('breaches when impact exceeds the max', () => {+ expect(checkPriceImpact(11, 10)).toEqual({ reason: 'price_impact_too_high' });+ });+});++describe('makeThrottle', () => {+ it('allows everything when the rate is disabled (<= 0)', () => {+ const t = makeThrottle(0);+ for (let i = 0; i < 100; i++) expect(t.tryConsume()).toBe(true);+ });++ it('caps consumes within the sliding 60s window', () => {+ const t = makeThrottle(2);+ expect(t.tryConsume()).toBe(true);+ expect(t.tryConsume()).toBe(true);+ expect(t.tryConsume()).toBe(false);+ });++ it('frees slots once the window slides past old hits', () => {+ vi.useFakeTimers();+ try {+ vi.setSystemTime(0);+ const t = makeThrottle(1);+ expect(t.tryConsume()).toBe(true);+ expect(t.tryConsume()).toBe(false);+ vi.setSystemTime(61_000); // > 60s later → old hit expires+ expect(t.tryConsume()).toBe(true);+ } finally {+ vi.useRealTimers();+ }+ });+});++describe('makeQueue', () => {+ it('reports in-flight as active + queued', async () => {+ const q = makeQueue(1, 10, {});+ let release;+ const gate = new Promise((r) => { release = r; });+ q.push(() => gate); // becomes active immediately+ q.push(() => Promise.resolve()); // waits+ expect(q.inFlight).toBe(2);+ release();+ await gate;+ });++ it('caps concurrency and runs queued jobs as slots free', async () => {+ let active = 0;+ let maxActive = 0;+ const q = makeQueue(2, 10, {});+ const run = () => new Promise((resolve) => {+ active++;+ maxActive = Math.max(maxActive, active);+ setTimeout(() => { active--; resolve(); }, 5);+ });+ for (let i = 0; i < 6; i++) q.push(run);+ await new Promise((r) => setTimeout(r, 60));+ expect(maxActive).toBeLessThanOrEqual(2);+ expect(q.inFlight).toBe(0);+ });++ it('drops a job and calls onDrop once maxDepth waiters are queued', () => {+ const onDrop = vi.fn();+ // concurrency 1, depth 1: first job runs (active), one may wait, the next is dropped.+ const q = makeQueue(1, 1, { onDrop });+ q.push(() => new Promise(() => {})); // active forever+ const accepted = q.push(() => new Promise(() => {})); // queued (depth 1)+ const rejected = q.push(() => new Promise(() => {})); // dropped+ expect(accepted).toBe(true);+ expect(rejected).toBe(false);+ expect(onDrop).toHaveBeenCalledTimes(1);+ });++ it('routes a thrown job error to onError', async () => {+ const onError = vi.fn();+ const q = makeQueue(1, 5, { onError });+ q.push(() => Promise.reject(new Error('boom')));+ await new Promise((r) => setTimeout(r, 10));+ expect(onError).toHaveBeenCalledTimes(1);+ expect(onError.mock.calls[0][0].message).toBe('boom');+ });+});diff --git a/packages/agent-sniper/test/scorer.test.js b/packages/agent-sniper/test/scorer.test.jsnew file mode 100644index 000000000..49193f210--- /dev/null+++ b/packages/agent-sniper/test/scorer.test.js@@ -0,0 +1,187 @@+// Unit tests for the pure entry scorer (src/scorer.js). No I/O, no network.+import { describe, it, expect } from 'vitest';+import { scoreMint, scoreIntel, learnedScore } from '../src/scorer.js';++// A clearly-synthetic mint placeholder — never a real coin address.+const MINT = 'THREEsynthetic1111111111111111111111111111111';++describe('scoreMint — hard filters', () => {+ it('requires a SOL quote by default (rejects a USDC pair)', () => {+ const res = scoreMint({ mint: MINT, is_usdc_pair: true }, {});+ expect(res.pass).toBe(false);+ expect(res.reasons).toContain('quote_not_sol');+ });++ it('allows a USDC pair when require_sol_quote is explicitly false', () => {+ const res = scoreMint({ mint: MINT, is_usdc_pair: true }, { require_sol_quote: false });+ expect(res.pass).toBe(true);+ });++ it('rejects a market cap below the configured minimum', () => {+ const res = scoreMint({ mint: MINT, market_cap_usd: 5_000 }, { min_market_cap_usd: 10_000 });+ expect(res.pass).toBe(false);+ expect(res.reasons).toContain('mc_below_min');+ });++ it('rejects when min market cap is set but the candidate has no market cap', () => {+ const res = scoreMint({ mint: MINT }, { min_market_cap_usd: 10_000 });+ expect(res.pass).toBe(false);+ expect(res.reasons).toContain('mc_below_min');+ });++ it('rejects a market cap above the configured maximum', () => {+ const res = scoreMint({ mint: MINT, market_cap_usd: 5_000_000 }, { max_market_cap_usd: 1_000_000 });+ expect(res.pass).toBe(false);+ expect(res.reasons).toContain('mc_above_max');+ });++ it('rejects a creator with too many prior launches', () => {+ const res = scoreMint({ mint: MINT, creator_launches: 50 }, { max_creator_launches: 5 });+ expect(res.pass).toBe(false);+ expect(res.reasons).toContain('creator_too_many_launches');+ });++ it('rejects a creator with too few graduated coins', () => {+ const res = scoreMint({ mint: MINT, creator_graduated: 0 }, { min_creator_graduated: 1 });+ expect(res.pass).toBe(false);+ expect(res.reasons).toContain('creator_too_few_graduated');+ });++ it('rejects when socials are required but absent', () => {+ const res = scoreMint({ mint: MINT }, { require_socials: true });+ expect(res.pass).toBe(false);+ expect(res.reasons).toContain('no_socials');+ });++ it('passes when socials are required and present (twitter)', () => {+ const res = scoreMint({ mint: MINT, twitter: 'https://x.com/example' }, { require_socials: true });+ expect(res.pass).toBe(true);+ expect(res.reasons).toContain('has_socials');+ });+});++describe('scoreMint — soft scoring', () => {+ it('credits socials, graduated count, and a healthy initial buy', () => {+ const res = scoreMint(+ { mint: MINT, twitter: 'x', creator_graduated: 3, initial_buy_sol: 2, market_cap_usd: 42_000 },+ {},+ );+ expect(res.pass).toBe(true);+ // 1 (socials) + 3 (graduated) + 1 (initial_buy >= 1) = 5+ expect(res.score).toBe(5);+ expect(res.reasons).toContain('has_socials');+ expect(res.reasons).toContain('creator_graduated:3');+ expect(res.reasons.some((r) => r.startsWith('initial_buy:'))).toBe(true);+ expect(res.reasons).toContain('mc_usd:42000');+ });++ it('does not credit an initial buy below 1 SOL', () => {+ const res = scoreMint({ mint: MINT, initial_buy_sol: 0.5 }, {});+ expect(res.pass).toBe(true);+ expect(res.score).toBe(0);+ expect(res.reasons.some((r) => r.startsWith('initial_buy:'))).toBe(false);+ });++ it('passes a bare candidate with zero score', () => {+ const res = scoreMint({ mint: MINT }, {});+ expect(res.pass).toBe(true);+ expect(res.score).toBe(0);+ });+});++describe('learnedScore', () => {+ it('returns null without weights', () => {+ expect(learnedScore({ a: 1 }, null)).toBe(null);+ });++ it('returns null when no weighted signal is present', () => {+ expect(learnedScore({ b: 1 }, { a: 0.2 })).toBe(null);+ });++ it('computes a bounded dot product of present signals', () => {+ // 0.5*0.2 + 1*0.1 = 0.2+ expect(learnedScore({ a: 0.5, b: 1 }, { a: 0.2, b: 0.1 })).toBe(0.2);+ });++ it('clamps the contribution to +/-0.5', () => {+ expect(learnedScore({ a: 10 }, { a: 10 })).toBe(0.5);+ expect(learnedScore({ a: 10 }, { a: -10 })).toBe(-0.5);+ });+});++describe('scoreIntel — gates', () => {+ const base = { mint: MINT, quality_score: 80, signals: {} };++ it('rejects quality below the minimum', () => {+ const res = scoreIntel({ ...base, quality_score: 40 }, { min_quality_score: 70 });+ expect(res.pass).toBe(false);+ expect(res.reasons[0]).toContain('quality_below_min');+ });++ it('rejects a bundle score above the maximum', () => {+ const res = scoreIntel({ ...base, signals: { bundle_score: 0.8 } }, { max_bundle_score: 0.5 });+ expect(res.pass).toBe(false);+ expect(res.reasons[0]).toContain('bundle_above_max');+ });++ it('rejects top-1 holder concentration above the maximum', () => {+ const res = scoreIntel({ ...base, signals: { concentration_top1: 0.6 } }, { max_concentration_top1: 0.3 });+ expect(res.pass).toBe(false);+ expect(res.reasons[0]).toContain('whale_concentration');+ });++ it('rejects a dev dump by default', () => {+ const res = scoreIntel({ ...base, signals: { dev_sold: true } }, {});+ expect(res.pass).toBe(false);+ expect(res.reasons).toContain('dev_dumped');+ });++ it('allows a dev dump when avoid_dev_dump is explicitly false', () => {+ const res = scoreIntel({ ...base, signals: { dev_sold: true } }, { avoid_dev_dump: false });+ expect(res.pass).toBe(true);+ });++ it('rejects a category outside the allowlist', () => {+ const res = scoreIntel({ ...base, category: 'meme' }, { allowed_categories: ['ai', 'defi'] });+ expect(res.pass).toBe(false);+ expect(res.reasons[0]).toContain('category_excluded');+ });++ it('allows a category inside the allowlist', () => {+ const res = scoreIntel({ ...base, category: 'ai' }, { allowed_categories: ['ai', 'defi'] });+ expect(res.pass).toBe(true);+ expect(res.reasons).toContain('cat:ai');+ });++ it('rejects when socials are required but absent', () => {+ const res = scoreIntel({ ...base }, { require_socials: true });+ expect(res.pass).toBe(false);+ expect(res.reasons).toContain('no_socials');+ });+});++describe('scoreIntel — scoring', () => {+ it('combines quality baseline, organic boost, and bundle penalty', () => {+ const res = scoreIntel(+ { mint: MINT, quality_score: 80, signals: { organic_score: 0.6, bundle_score: 0.2 } },+ {},+ );+ expect(res.pass).toBe(true);+ // 80/100 + 0.6*0.5 - 0.2*0.5 = 0.8 + 0.3 - 0.1 = 1.0+ expect(res.score).toBe(1);+ expect(res.reasons).toContain('quality:80');+ expect(res.reasons).toContain('organic:0.6');+ });++ it('adds the learned-model dot product when weights are supplied', () => {+ const noWeights = scoreIntel({ mint: MINT, quality_score: 50, signals: { foo: 1 } }, {});+ const withWeights = scoreIntel({ mint: MINT, quality_score: 50, signals: { foo: 1 } }, {}, { foo: 0.4 });+ expect(withWeights.score).toBeCloseTo(noWeights.score + 0.4, 4);+ expect(withWeights.reasons).toContain('learned:0.4');+ });++ it('surfaces risk flags in reasons', () => {+ const res = scoreIntel({ mint: MINT, quality_score: 70, signals: {}, risk_flags: ['fresh_wallet'] }, {});+ expect(res.reasons).toContain('flag:fresh_wallet');+ });+});diff --git a/packages/agent-sniper/test/store-memory.test.js b/packages/agent-sniper/test/store-memory.test.jsnew file mode 100644index 000000000..3d6e88594--- /dev/null+++ b/packages/agent-sniper/test/store-memory.test.js@@ -0,0 +1,151 @@+// Unit tests for the in-memory Store adapter (src/adapters/store/memory.js).+// No network: pure in-process state.+import { describe, it, expect } from 'vitest';+import { createMemoryStore } from '../src/adapters/store/memory.js';++const MINT = 'THREEsynthetic1111111111111111111111111111111';+const MINT_B = 'THREEsynthetic2222222222222222222222222222222';++function strategy(over = {}) {+ return {+ id: 'strat_1',+ agent_id: 'agent_1',+ enabled: true,+ network: 'devnet',+ stop_loss_pct: 20,+ per_trade_lamports: '1000000',+ daily_budget_lamports: '5000000',+ ...over,+ };+}++describe('createMemoryStore — strategies', () => {+ it('seeds strategies from the constructor', () => {+ const store = createMemoryStore({ strategies: [strategy()] });+ expect(store._positions instanceof Map).toBe(true);+ });++ it('addStrategy then getArmedStrategies returns enabled, stop-loss strategies for the network', async () => {+ const store = createMemoryStore();+ store.addStrategy(strategy());+ const armed = await store.getArmedStrategies('devnet');+ expect(armed).toHaveLength(1);+ expect(armed[0].id).toBe('strat_1');+ });++ it('excludes disabled, kill-switched, missing-stop-loss, and wrong-network strategies', async () => {+ const store = createMemoryStore();+ store.addStrategy(strategy({ id: 'a', enabled: false }));+ store.addStrategy(strategy({ id: 'b', kill_switch: true }));+ store.addStrategy(strategy({ id: 'c', stop_loss_pct: null }));+ store.addStrategy(strategy({ id: 'd', network: 'mainnet' }));+ store.addStrategy(strategy({ id: 'e' })); // the only armed one+ const armed = await store.getArmedStrategies('devnet');+ expect(armed.map((s) => s.id)).toEqual(['e']);+ });+});++describe('createMemoryStore — claimPosition (atomic slot)', () => {+ it('returns a new position row on first claim', async () => {+ const store = createMemoryStore();+ const pos = await store.claimPosition({ strategy: strategy(), candidate: { mint: MINT }, network: 'devnet' });+ expect(pos).not.toBe(null);+ expect(pos.agent_id).toBe('agent_1');+ expect(pos.mint).toBe(MINT);+ expect(pos.status).toBe('opening');+ expect(pos.stop_loss_pct).toBe(20);+ });++ it('returns null on a duplicate claim of the same slot (no double buy)', async () => {+ const store = createMemoryStore();+ const first = await store.claimPosition({ strategy: strategy(), candidate: { mint: MINT }, network: 'devnet' });+ const second = await store.claimPosition({ strategy: strategy(), candidate: { mint: MINT }, network: 'devnet' });+ expect(first).not.toBe(null);+ expect(second).toBe(null);+ });++ it('allows re-claiming the slot once the prior position is terminal', async () => {+ const store = createMemoryStore();+ const first = await store.claimPosition({ strategy: strategy(), candidate: { mint: MINT }, network: 'devnet' });+ await store.updatePosition(first.id, { status: 'closed' });+ const again = await store.claimPosition({ strategy: strategy(), candidate: { mint: MINT }, network: 'devnet' });+ expect(again).not.toBe(null);+ });++ it('keeps slots distinct per mint', async () => {+ const store = createMemoryStore();+ const a = await store.claimPosition({ strategy: strategy(), candidate: { mint: MINT }, network: 'devnet' });+ const b = await store.claimPosition({ strategy: strategy(), candidate: { mint: MINT_B }, network: 'devnet' });+ expect(a).not.toBe(null);+ expect(b).not.toBe(null);+ });+});++describe('createMemoryStore — positions', () => {+ it('updatePosition merges a patch', async () => {+ const store = createMemoryStore();+ const pos = await store.claimPosition({ strategy: strategy(), candidate: { mint: MINT }, network: 'devnet' });+ await store.updatePosition(pos.id, { status: 'open', last_value_lamports: 1234 });+ const open = await store.getOpenPositions('devnet');+ expect(open).toHaveLength(1);+ expect(open[0].last_value_lamports).toBe(1234);+ });++ it('updatePosition on an unknown id is a no-op', async () => {+ const store = createMemoryStore();+ await expect(store.updatePosition('nope', { status: 'open' })).resolves.toBeUndefined();+ });++ it('getOpenPositions returns open and closing, not opening/closed/failed', async () => {+ const store = createMemoryStore();+ const opening = await store.claimPosition({ strategy: strategy(), candidate: { mint: MINT }, network: 'devnet' });+ const willOpen = await store.claimPosition({ strategy: strategy({ agent_id: 'agent_2' }), candidate: { mint: MINT_B }, network: 'devnet' });+ await store.updatePosition(willOpen.id, { status: 'open' });+ const open = await store.getOpenPositions('devnet');+ expect(open.map((p) => p.id)).toEqual([willOpen.id]);+ expect(open.map((p) => p.id)).not.toContain(opening.id); // still 'opening'+ });++ it('countOpenPositions counts opening + open for an agent', async () => {+ const store = createMemoryStore();+ await store.claimPosition({ strategy: strategy(), candidate: { mint: MINT }, network: 'devnet' });+ const p2 = await store.claimPosition({ strategy: strategy(), candidate: { mint: MINT_B }, network: 'devnet' });+ await store.updatePosition(p2.id, { status: 'open' });+ expect(await store.countOpenPositions('agent_1', 'devnet')).toBe(2);+ expect(await store.countOpenPositions('agent_1', 'mainnet')).toBe(0);+ });+});++describe('createMemoryStore — spend ledger', () => {+ it('getDailySpendLamports sums today only and isolates by agent', async () => {+ const store = createMemoryStore();+ await store.recordSpend({ agentId: 'agent_1', network: 'devnet', amountLamports: 1_000n, category: 'snipe' });+ await store.recordSpend({ agentId: 'agent_1', network: 'devnet', amountLamports: 500n, category: 'snipe' });+ await store.recordSpend({ agentId: 'agent_2', network: 'devnet', amountLamports: 9_000n, category: 'snipe' });+ const total = await store.getDailySpendLamports('agent_1', 'devnet');+ expect(total).toBe(1_500n);+ });++ it('excludes spend recorded before the current UTC day', async () => {+ const store = createMemoryStore();+ // Reach into the spend array (exposed as _spend) to inject a stale entry.+ store._spend.push({ agentId: 'agent_1', network: 'devnet', amountLamports: 7_000n, at: 0, category: 'snipe' });+ await store.recordSpend({ agentId: 'agent_1', network: 'devnet', amountLamports: 1_000n, category: 'snipe' });+ const total = await store.getDailySpendLamports('agent_1', 'devnet');+ expect(total).toBe(1_000n);+ });+});++describe('createMemoryStore — listPositions', () => {+ it('filters by agentId, network, and status', async () => {+ const store = createMemoryStore();+ const a = await store.claimPosition({ strategy: strategy(), candidate: { mint: MINT }, network: 'devnet' });+ const b = await store.claimPosition({ strategy: strategy({ agent_id: 'agent_2' }), candidate: { mint: MINT_B }, network: 'devnet' });+ await store.updatePosition(b.id, { status: 'open' });++ expect((await store.listPositions({})).length).toBe(2);+ expect((await store.listPositions({ agentId: 'agent_1' })).map((p) => p.id)).toEqual([a.id]);+ expect((await store.listPositions({ status: 'open' })).map((p) => p.id)).toEqual([b.id]);+ expect((await store.listPositions({ network: 'mainnet' })).length).toBe(0);+ });+});diff --git a/packages/agent-sniper/test/wallet.test.js b/packages/agent-sniper/test/wallet.test.jsnew file mode 100644index 000000000..4097f22a8--- /dev/null+++ b/packages/agent-sniper/test/wallet.test.js@@ -0,0 +1,94 @@+// Unit tests for the wallet adapters (self-custody + custodial). No network.+import { describe, it, expect, vi } from 'vitest';+import { Keypair } from '@solana/web3.js';+import bs58Mod from 'bs58';+import { createSelfCustodyWallet } from '../src/adapters/wallet/self-custody.js';+import { createCustodialWallet } from '../src/adapters/wallet/custodial.js';++const bs58 = bs58Mod.default || bs58Mod;++describe('createSelfCustodyWallet', () => {+ it('decodes a base58 secret', async () => {+ const kp = Keypair.generate();+ const wallet = createSelfCustodyWallet({ secrets: { agent_1: bs58.encode(kp.secretKey) } });+ const loaded = await wallet.loadKeypair('agent_1');+ expect(loaded).not.toBe(null);+ expect(loaded.address).toBe(kp.publicKey.toBase58());+ });++ it('decodes a JSON-array secret', async () => {+ const kp = Keypair.generate();+ const json = JSON.stringify(Array.from(kp.secretKey));+ const wallet = createSelfCustodyWallet({ secrets: { agent_1: json } });+ const loaded = await wallet.loadKeypair('agent_1');+ expect(loaded).not.toBe(null);+ expect(loaded.address).toBe(kp.publicKey.toBase58());+ });++ it('returns null when no secret is provisioned for the agent', async () => {+ const wallet = createSelfCustodyWallet({ secrets: {} });+ expect(await wallet.loadKeypair('unknown_agent')).toBe(null);+ });++ it('caches the resolved keypair (same instance across loads)', async () => {+ const kp = Keypair.generate();+ const wallet = createSelfCustodyWallet({ secrets: { agent_1: bs58.encode(kp.secretKey) } });+ const a = await wallet.loadKeypair('agent_1');+ const b = await wallet.loadKeypair('agent_1');+ expect(a.keypair).toBe(b.keypair);+ });+});++describe('createCustodialWallet', () => {+ it('throws without a resolve callback', () => {+ expect(() => createCustodialWallet({})).toThrow(/resolve/);+ });++ it('resolves a keypair through the callback', async () => {+ const kp = Keypair.generate();+ const wallet = createCustodialWallet({ resolve: async () => kp });+ const loaded = await wallet.loadKeypair('agent_1');+ expect(loaded.address).toBe(kp.publicKey.toBase58());+ });++ it('caches within the TTL — resolve is called once', async () => {+ const kp = Keypair.generate();+ const resolve = vi.fn(async () => kp);+ const wallet = createCustodialWallet({ resolve, ttlMs: 60_000 });+ await wallet.loadKeypair('agent_1');+ await wallet.loadKeypair('agent_1');+ await wallet.loadKeypair('agent_1');+ expect(resolve).toHaveBeenCalledTimes(1);+ });++ it('re-resolves after the TTL expires', async () => {+ vi.useFakeTimers();+ try {+ vi.setSystemTime(0);+ const kp = Keypair.generate();+ const resolve = vi.fn(async () => kp);+ const wallet = createCustodialWallet({ resolve, ttlMs: 1_000 });+ await wallet.loadKeypair('agent_1');+ vi.setSystemTime(2_000); // past the TTL+ await wallet.loadKeypair('agent_1');+ expect(resolve).toHaveBeenCalledTimes(2);+ } finally {+ vi.useRealTimers();+ }+ });++ it('returns null when the resolver has no wallet for the agent', async () => {+ const wallet = createCustodialWallet({ resolve: async () => null });+ expect(await wallet.loadKeypair('agent_1')).toBe(null);+ });++ it('clearCache forces a re-resolve', async () => {+ const kp = Keypair.generate();+ const resolve = vi.fn(async () => kp);+ const wallet = createCustodialWallet({ resolve, ttlMs: 60_000 });+ await wallet.loadKeypair('agent_1');+ wallet.clearCache();+ await wallet.loadKeypair('agent_1');+ expect(resolve).toHaveBeenCalledTimes(2);+ });+});diff --git a/packages/agent-sniper/vitest.config.js b/packages/agent-sniper/vitest.config.jsnew file mode 100644index 000000000..188d9f95a--- /dev/null+++ b/packages/agent-sniper/vitest.config.js@@ -0,0 +1,12 @@+import { defineConfig } from 'vitest/config';++// Self-contained config for @three-ws/agent-sniper so its suite runs in+// isolation from the monorepo root config (which scopes its own include globs+// and Vite plugins to platform code). These tests are pure-logic + in-memory+// adapters — no network, no RPC, no Vite transform needs.+export default defineConfig({+ test: {+ include: ['test/**/*.test.js'],+ environment: 'node',+ },+});