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.

fix(strategy-lab): source real mints for backtests and simulated runs, and design the signed-out and quiet-session states

nirholas101df5049caf
diff --git a/api/_lib/pump-trending.js b/api/_lib/pump-trending.js
index 29e6379fb..bf4297ae0 100644
--- a/api/_lib/pump-trending.js
+++ b/api/_lib/pump-trending.js
@@ -98,11 +98,16 @@ async function fetchBirdeye(limit) {
// Fallback: pump.fun's public frontend feed (no API key). Mapped into the exact
// same shape so every consumer keeps working. pump.fun doesn't expose a clean
// per-token USD price here, so price_usd is left null rather than fabricated.
-async function fetchPumpFun(limit) {
+//
+// `sort` picks the feed: 'market_cap' is the trending list, 'created_timestamp'
+// the newest launches. Both come back in the same slim shape, plus the creator
+// wallet and creation time the frontend feed carries for free (null when a row
+// lacks them), which the strategy runtime's token-age metric reads.
+async function fetchPumpFun(limit, sort = 'market_cap') {
const url = new URL('/coins', PUMP_FRONTEND_BASE);
url.searchParams.set('offset', '0');
url.searchParams.set('limit', String(limit));
- url.searchParams.set('sort', 'market_cap');
+ url.searchParams.set('sort', sort);
url.searchParams.set('order', 'DESC');
url.searchParams.set('includeNsfw', 'false');
let upstream;
@@ -123,6 +128,8 @@ async function fetchPumpFun(limit) {
logo: normalizeGatewayURL(c.image_uri || c.image || '') || null,
price_usd: null,
usd_market_cap: typeof c.usd_market_cap === 'number' ? c.usd_market_cap : null,
+ creator: typeof c.creator === 'string' && c.creator.length >= 32 ? c.creator : null,
+ created_at: typeof c.created_timestamp === 'number' ? c.created_timestamp : null,
rank: i + 1,
}))
.filter((t) => typeof t.mint === 'string' && t.mint.length >= 32);
@@ -195,3 +202,79 @@ export async function getTrendingSlim(limit) {
_cache = { value: data, storedAt: now, expiresAt: now + TTL_MS, limit: data.length };
return { data: data.slice(0, limit), stale: false };
}
+
+// ── Newest launches ─────────────────────────────────────────────────────────
+// Same contract as trending, for the "most recently launched" feed the strategy
+// runtime scans (`scan.kind: 'newTokens'`) and the pump.fun MCP's get_new_tokens
+// tool serve. Rungs: pump.fun's public frontend feed sorted by creation time,
+// then the recorder database (pump_coin_intel ingests every launch the WS feed
+// sees, so it is the freshest thing the platform owns when egress is blocked),
+// then the stale cache. New launches churn by the second, so the TTL is short.
+let _newCache = { value: null, storedAt: 0, expiresAt: 0, limit: 0 };
+const NEW_TTL_MS = 10_000;
+const NEW_FETCH_LIMIT = 50;
+
+function serveStaleNew(limit, now) {
+ if (!_newCache.value) return null;
+ if (now - _newCache.storedAt > STALE_MAX_MS) return null;
+ return _newCache.value.slice(0, limit);
+}
+
+async function fetchDbNew(limit) {
+ try {
+ const rows = await sql`
+ SELECT mint, symbol, name, image_uri, creator, created_at, first_seen_at
+ FROM pump_coin_intel
+ WHERE first_seen_at > now() - interval '6 hours'
+ ORDER BY first_seen_at DESC
+ LIMIT ${limit}
+ `;
+ const data = rows
+ .map((r, i) => {
+ const created = r.created_at || r.first_seen_at;
+ return {
+ mint: r.mint || '',
+ symbol: r.symbol || '?',
+ name: r.name || r.symbol || '',
+ logo: normalizeGatewayURL(r.image_uri || '') || null,
+ price_usd: null,
+ usd_market_cap: null,
+ creator: typeof r.creator === 'string' && r.creator.length >= 32 ? r.creator : null,
+ created_at: created ? new Date(created).getTime() : null,
+ rank: i + 1,
+ };
+ })
+ .filter((t) => typeof t.mint === 'string' && t.mint.length >= 32);
+ return data.length ? data : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Get up to `limit` of the most recently launched pump.fun tokens (thin
+ * projection plus creator + created_at), cached 10s with a stale fallback across
+ * a pump.fun→recorder-DB failover.
+ *
+ * @param {number} limit
+ * @returns {Promise<{ data: object[]|null, stale: boolean }>}
+ * `data: null` only when every live source is down AND no usable stale cache
+ * exists.
+ */
+export async function getNewSlim(limit) {
+ const now = Date.now();
+ if (_newCache.value && _newCache.expiresAt > now && _newCache.limit >= limit) {
+ return { data: _newCache.value.slice(0, limit), stale: false };
+ }
+ const fetchN = Math.max(NEW_FETCH_LIMIT, limit);
+ let data = await fetchPumpFun(fetchN, 'created_timestamp');
+ if (!data) data = await fetchDbNew(fetchN);
+ if (!data) {
+ const stale = serveStaleNew(limit, now);
+ if (stale) return { data: stale, stale: true };
+ console.warn('[pump-trending] new-launch sources failed (pump.fun, recorder db) and no stale cache');
+ return { data: null, stale: false };
+ }
+ _newCache = { value: data, storedAt: now, expiresAt: now + NEW_TTL_MS, limit: data.length };
+ return { data: data.slice(0, limit), stale: false };
+}
diff --git a/api/_lib/skill-runtime.js b/api/_lib/skill-runtime.js
index 629acc028..ed84f217a 100644
--- a/api/_lib/skill-runtime.js
+++ b/api/_lib/skill-runtime.js
@@ -52,6 +52,54 @@ async function loadManifest(name) {
}
}
+// ── Server-side fetch for isomorphic skills ────────────────────────────────
+// Skill handlers are shared with the browser, where a relative `/api/...` URL
+// resolves against the page origin. On the server there is no origin, and
+// Node's fetch throws `Failed to parse URL from /api/pump-fun-mcp`: that one
+// line was every scan tick of every strategy run in production (2026-09-01),
+// so no backtest or simulated session ever sourced a mint. Two rungs:
+// 1. POST /api/pump-fun-mcp tools/call dispatches IN-PROCESS to the same tool
+// handlers the HTTP route runs, wrapped in the JSON-RPC envelope the skill
+// unwraps. No loopback hop, and the strategy loop (four tools per mint,
+// every few seconds) stops spending the server's own per-IP MCP limit.
+// 2. Any other relative path resolves against APP_ORIGIN.
+// Absolute URLs and Request objects pass straight through untouched.
+async function serverFetch(input, init) {
+ const url = typeof input === 'string' ? input : input?.url;
+ if (typeof url !== 'string' || !url.startsWith('/')) return globalThis.fetch(input, init);
+ const path = url.split('?')[0];
+ const isPost = String(init?.method || 'GET').toUpperCase() === 'POST';
+ let rpc = null;
+ if (path === '/api/pump-fun-mcp' && isPost) {
+ try { rpc = JSON.parse(typeof init?.body === 'string' ? init.body : '{}'); } catch { rpc = null; }
+ }
+ if (rpc?.method === 'tools/call') {
+ const id = rpc.id ?? null;
+ let envelope;
+ try {
+ const { callPumpFunTool } = await import('../pump-fun-mcp.js');
+ const data = await callPumpFunTool(rpc.params?.name, rpc.params?.arguments ?? {});
+ envelope = {
+ jsonrpc: '2.0',
+ id,
+ result: { content: [{ type: 'text', text: JSON.stringify(data) }], structuredContent: data },
+ };
+ } catch (err) {
+ envelope = {
+ jsonrpc: '2.0',
+ id,
+ error: { code: err?.rpcCode ?? -32603, message: err?.message ?? 'tool error' },
+ };
+ }
+ return new Response(JSON.stringify(envelope), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ });
+ }
+ const { env } = await import('./env.js');
+ return globalThis.fetch(new URL(url, env.APP_ORIGIN).href, init);
+}
+
/**
* Build a context for invoking skills from a serverless endpoint.
*
@@ -59,13 +107,13 @@ async function loadManifest(name) {
* @param {object} [opts.configOverrides] - per-skill config overrides keyed by skill name
* @param {object} [opts.wallet] - solana wallet contract for signing skills
* @param {(event: object) => void} [opts.onEvent] - notified on every memory.note call
- * @param {object} [opts.fetch] - fetch impl (defaults to globalThis.fetch)
+ * @param {object} [opts.fetch] - fetch impl (defaults to serverFetch: in-process for /api/pump-fun-mcp, APP_ORIGIN for other relative paths)
* @param {string} [opts.agentId] - if set, every memory.note is persisted to agent_actions
* @param {string} [opts.signerAddress] - persisted with each agent_actions row when agentId is set
* @param {Record<string, { skill_id: string, author_id: string }>} [opts.skillMeta] - DB-sourced royalty metadata keyed by skill name
*/
export function makeRuntime(opts = {}) {
- const { configOverrides = {}, wallet, onEvent, fetch = globalThis.fetch, agentId, signerAddress, skillMeta = {} } = opts;
+ const { configOverrides = {}, wallet, onEvent, fetch = serverFetch, agentId, signerAddress, skillMeta = {} } = opts;
let _sql;
// Map skill-internal tags to canonical action types so existing
// aggregations (spend-policy, portfolio cost-basis) keep working.
diff --git a/api/pump-fun-mcp.js b/api/pump-fun-mcp.js
index 21d0e638d..f1409d849 100644
--- a/api/pump-fun-mcp.js
+++ b/api/pump-fun-mcp.js
@@ -41,6 +41,7 @@ import { reservePaymentProof } from './_lib/x402/payment-identifier-server.js';
import { getPumpSdk, getConnection, solanaPubkey, getAmmPoolState } from './_lib/pump.js';
import { solPriceUsd } from './_lib/sol-price.js';
import { pumpfunMcp, pumpfunBotEnabled } from './_lib/pumpfun-mcp.js';
+import { getTrendingSlim, getNewSlim } from './_lib/pump-trending.js';
import { TOOLS, resolveToolName, rpcError, rpcEnvelope } from '../src/pump/mcp-tools.js';
import { generateVanityKey } from '../src/pump/vanity-keygen.js';
import bs58 from 'bs58';
@@ -231,16 +232,42 @@ async function handleSnsReverseLookup({ address }) {
// reappear automatically once the env var is set, with no code change. The
// -32004 guard in indexerOrUnavailable() stays as defence for any client that
// calls one anyway (e.g. from a cached tool list). get_token_trades is NOT
-// here: it has a real on-chain fallback and works without the indexer.
+// here: it has a real on-chain fallback and works without the indexer. Neither
+// are get_trending_tokens and get_new_tokens: both fall through to the live
+// pump.fun feed (liveFeedOrIndexer below), so the strategy runtime's scans keep
+// sourcing real mints on a deployment that never configured the indexer.
const INDEXER_TOOLS = new Set([
'search_tokens',
- 'get_trending_tokens',
- 'get_new_tokens',
'get_graduated_tokens',
'get_king_of_the_hill',
'get_creator_profile',
]);
+// Discovery tools with a rung below the indexer. The indexer is preferred when
+// configured (richer rows); when it is absent or fails, the shared pump.fun
+// feed (api/_lib/pump-trending.js: pump.fun frontend → recorder DB → stale
+// cache) answers in the `{ tokens: [...] }` shape every consumer already
+// unwraps (`r.tokens ?? r`, then `t.mint`). Only when every rung is down does
+// the call surface -32004, the same code the indexer path uses.
+function liveFeedOrIndexer(name, feed) {
+ const viaIndexer = indexerOrUnavailable(name);
+ return async (args = {}) => {
+ const limit = Math.min(50, Math.max(1, Math.floor(Number(args.limit) || 10)));
+ if (pumpfunBotEnabled()) {
+ try {
+ return await viaIndexer({ ...args, limit });
+ } catch (err) {
+ console.warn(`[pump-fun-mcp] ${name}: indexer failed, using live pump.fun feed`, err?.message);
+ }
+ }
+ const { data, stale } = await feed(limit);
+ if (!data) {
+ throw rpcError(-32004, `tool "${name}": every live pump.fun source is unavailable right now`);
+ }
+ return { tokens: data, source: 'pump.fun', stale: !!stale };
+ };
+}
+
function indexerOrUnavailable(name) {
return async (args) => {
if (!pumpfunBotEnabled()) {
@@ -1409,8 +1436,8 @@ const HANDLERS = {
kol_leaderboard: handleKolLeaderboard,
search_tokens: indexerOrUnavailable('search_tokens'),
get_token_trades: handleGetTokenTrades,
- get_trending_tokens: indexerOrUnavailable('get_trending_tokens'),
- get_new_tokens: indexerOrUnavailable('get_new_tokens'),
+ get_trending_tokens: liveFeedOrIndexer('get_trending_tokens', getTrendingSlim),
+ get_new_tokens: liveFeedOrIndexer('get_new_tokens', getNewSlim),
get_graduated_tokens: indexerOrUnavailable('get_graduated_tokens'),
get_king_of_the_hill: indexerOrUnavailable('get_king_of_the_hill'),
social_cashtag_sentiment: handleSocialCashtagSentiment,
@@ -1428,6 +1455,28 @@ const HANDLERS = {
pumpfun_bot_status: handlePumpfunBotStatus,
};
+/**
+ * In-process tool call for server-side callers (the skill runtime behind
+ * /api/pump/strategy-*). Same alias resolution and handler table as the HTTP
+ * route, without the loopback hop: a strategy loop polling four tools per mint
+ * every three seconds would otherwise spend the server's own per-IP MCP rate
+ * limit on itself. Gated tools (vanity grind, whale watch, metadata pin) stay
+ * HTTP-only because their bearer / x402 proof lives on the request.
+ *
+ * Resolves with the tool's data; rejects with an Error carrying `rpcCode` so a
+ * caller can wrap it in the JSON-RPC envelope the skills unwrap.
+ */
+export async function callPumpFunTool(requestedName, args = {}) {
+ const name = resolveToolName(requestedName);
+ const handler =
+ typeof name === 'string' && Object.hasOwn(HANDLERS, name) ? HANDLERS[name] : null;
+ if (!handler) throw rpcError(-32601, `unknown tool: ${requestedName}`);
+ if (AUTH_REQUIRED_TOOLS.has(name)) {
+ throw rpcError(-32001, `tool "${name}" needs a bearer or x402 payment: call it over HTTP`);
+ }
+ return handler(args && typeof args === 'object' ? args : {});
+}
+
// ── HTTP entrypoint ────────────────────────────────────────────────────────
// Keep in sync with api/_lib/mcp-dispatch.js PROTOCOL_VERSION. Declared locally
diff --git a/data/changelog.json b/data/changelog.json
index 8003ecfbb..15f21a934 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -25400,6 +25400,16 @@
"fix"
],
"link": "/three"
+ },
+ {
+ "date": "2026-09-01",
+ "title": "Strategy Lab backtests and simulated runs find real launches again",
+ "summary": "In production, every Strategy Lab backtest and simulated session was scanning for candidates and coming back empty: the server-side strategy runtime was asking for pump.fun data with a page-relative address that only a browser can resolve, and the discovery tools behind it needed an indexer the platform never configured. The runtime now calls the pump.fun tools directly in-process, and the new-launch and trending scans read the live pump.fun feed with the platform's own launch recorder as backup, so a scan returns real mints on the first tick. The Lab page also tells a signed-out visitor exactly what signing in unlocks, links straight to it, shows a live \"session running\" state while a run streams, and explains a quiet session (every candidate filtered out, or the feed briefly unreachable) instead of a bare \"complete\".",
+ "tags": [
+ "fix",
+ "improvement"
+ ],
+ "link": "/strategy-lab"
}
]
}
diff --git a/docs/mcp.md b/docs/mcp.md
index 21732cc64..c836fcfc3 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -58,7 +58,7 @@ There are two kinds. **Hosted remote servers** run over Streamable HTTP with not
| 3D Studio (free) | `/api/mcp-studio` | Free text/image→3D and rigged avatars — no auth, no payment |
| Agent wallet | `/api/mcp-agent` | The agent's custodial wallet: balance, find + pay services, and `monetize_endpoint` |
| x402 Bazaar | `/api/mcp-bazaar` | Discover and price paid agent services across the facilitator network |
-| pump.fun | `/api/pump-fun-mcp` | Free pump.fun + Solana token tools; `pumpfun_upload_metadata` needs a key |
+| pump.fun | `/api/pump-fun-mcp` | Free pump.fun + Solana token tools; `get_new_tokens` and `get_trending_tokens` read the live pump.fun feed with no indexer needed; `pumpfun_upload_metadata` needs a key |
| IBM x402 | `/api/ibm-mcp` | Pay-per-use IBM Granite AI |
**Thirty-eight install-and-run servers** on npm under the `@three-ws` scope, each running over stdio with one command:
diff --git a/docs/strategy-objects.md b/docs/strategy-objects.md
index 0a6a5de56..bec5eba11 100644
--- a/docs/strategy-objects.md
+++ b/docs/strategy-objects.md
@@ -3,7 +3,7 @@
A Strategy Object is a trade strategy as a first-class thing you can own: a structured, validated rule set (entry conditions, sizing, take-profit, stop-loss, risk caps) that your agent can equip and run on-chain, ranked on a leaderboard by real live performance and forkable by anyone. The Strategy Lab is the workbench: write a strategy as data, validate it, backtest it against real recorded pump.fun history with the same evaluator its live runs use, and run it live or in simulation, end to end. Both run strategies as additional constraints on top of your agent's server-side spend policy, never a way around it.
Pages: [/strategies](https://three.ws/strategies) (the library and leaderboard), [/strategy-lab](https://three.ws/strategy-lab) (the workbench)
-API: `GET/POST /api/strategies`, `GET /api/strategies/leaderboard`, `GET/PATCH/DELETE /api/strategies/:id`, `POST /api/strategies/:id/{fork,publish}`, `GET/POST/DELETE /api/dca-strategies`, the Lab's `POST /api/pump/strategy-{validate,backtest,run,close-all}`, and the sniper backtester `POST /api/sniper/backtest`
+API: `GET/POST /api/strategies`, `GET /api/strategies/leaderboard`, `GET/PATCH/DELETE /api/strategies/:id`, `POST /api/strategies/:id/{fork,publish}`, `GET/POST/PATCH/DELETE /api/dca-strategies`, the Lab's `POST /api/pump/strategy-{validate,backtest,run,close-all}`, and the sniper backtester `POST /api/sniper/backtest`
## Why it exists
@@ -26,7 +26,7 @@ Every strategy is normalized and validated by `api/_lib/strategy-schema.js` befo
- **exits**: `take_profit_pct`, a mandatory `stop_loss_pct`, optional `trailing_stop_pct`, and `max_hold_minutes`. Validation requires a stop-loss and at least one upside exit.
- **risk**: `max_concurrent_positions` and `cooldown_minutes`.
-The schema enforces hard bounds on every field, so a stored config can never carry a nonsense number into the runtime. Two pure, synchronous functions, `matchesEntry` (does this real launch pass the entry gate) and `shouldExit` (should this open position close now), are the same logic the live equipped-strategy runtime (`api/_lib/agent-strategy-runtime.js`) and the assisted scan preview (`POST /api/trading/scan`) both evaluate, so a stored rule means exactly the same thing everywhere it runs.
+The schema enforces hard bounds on every field, so a stored config can never carry a nonsense number into the runtime. Two pure, synchronous functions, `matchesEntry` (does this real launch pass the entry gate) and `shouldExit` (should this open position close now), are the same logic the live equipped-strategy runtime (`api/_lib/agent-strategy-runtime.js`) and the assisted scan preview (`POST /api/trading/scan`) both evaluate, so a stored rule means exactly the same thing everywhere it runs. The assisted scan is owner-scoped and rate-limited twice (per IP and per owner, because every match it prices costs an upstream call); when the live launch feed cannot be reached it answers `502 feed_unavailable` rather than an empty scan that looks like "nothing matched".
### The library, leaderboard, and forking
@@ -37,7 +37,7 @@ The schema enforces hard bounds on every field, so a stored config can never car
`/strategy-lab` is where you build and prove a declarative pump.fun strategy. The Lab speaks its own tiny strategy DSL (a spec with `scan`, `filters`, `entry`, and `exit` predicate rules), and one compiled evaluator powers validation, backtest, and live runs, so they cannot drift:
- **Validate** (`POST /api/pump/strategy-validate`) checks the spec with the same validator the runner uses, so a broken spec is caught with field-level issues before anything runs. No sign-in needed.
-- **Backtest** (`POST /api/pump/strategy-backtest`, sign-in required) replays the compiled strategy over real recorded on-chain history: for each candidate mint (from the request's `mints`, the spec's `scan.mints`, or a live scan of new or trending launches) it fetches the token's real details, holders, bonding curve, and recent trades, evaluates the entry gate at the first recorded trade, then walks the subsequent real trades to trigger the exit rules. It never synthesizes launches or invents price paths; the response's `data` carries `spent`, `realizedPnlSol`, `roiPct`, `tradeCount`, `winRate`, `maxDrawdownSol`, the per-mint `trades`, and `mintsUsed`.
+- **Backtest** (`POST /api/pump/strategy-backtest`, sign-in required) replays the compiled strategy over real recorded on-chain history: for each candidate mint (from the request's `mints`, the spec's `scan.mints`, or a live scan of new or trending launches served by the pump.fun MCP's `get_new_tokens` and `get_trending_tokens`, which read pump.fun's public feed and the platform's own launch recorder, so no external indexer is needed) it fetches the token's real details, holders, bonding curve, and recent trades, evaluates the entry gate at the first recorded trade, then walks the subsequent real trades to trigger the exit rules. It never synthesizes launches or invents price paths; the response's `data` carries `spent`, `realizedPnlSol`, `roiPct`, `tradeCount`, `winRate`, `maxDrawdownSol`, the per-mint `trades`, and `mintsUsed`.
- **Run** (`POST /api/pump/strategy-run`) executes the strategy for a bounded duration (5 to 600 seconds) and streams events over Server-Sent Events. In **simulate** mode it needs no wallet and spends nothing; in **live** mode it requires auth, an agent you own with a provisioned Solana wallet, and every buy passes a `policyGuard` that calls the same `checkBuyAllowed` spend-policy check the rest of the platform uses.
- **Close all** (`POST /api/pump/strategy-close-all`, sign-in required) exits open strategy positions.
@@ -45,7 +45,7 @@ A second, separate backtester serves sniper-style rule sets: `POST /api/sniper/b
### DCA and subscription builders
-`/api/dca-strategies` runs recurring, scheduled buys (executed by the `run-dca` cron). Each strategy is validated (agent, delegation, token in and out, amount per execution, a daily or weekly period, and slippage capped server-side), and non-GET methods over a cookie session require a CSRF token because these move real funds on a schedule.
+`/api/dca-strategies` runs recurring, scheduled buys (executed by the `run-dca` cron). Each strategy is validated (agent, delegation, token in and out, amount per execution, a daily or weekly period, and slippage capped server-side), and non-GET methods over a cookie session require a CSRF token because these move real funds on a schedule. `PATCH /api/dca-strategies/:id` with `{ "action": "pause" }` or `{ "action": "resume" }` pauses and resumes a schedule: a resume schedules `next_execution_at` a full period out from the resume, so periods missed while paused never fire as a burst of swaps, and it is refused when the signed delegation behind the strategy is no longer active (grant a new one to restart it). A schedule that fails to execute three times in a row (`MAX_CONSECUTIVE_FAILURES`) pauses itself; a relayer that is switched off or rejects our own credentials is a platform outage and is retried without counting toward that limit. Rows carry `paused_at`, `resumed_at`, and `consecutive_failures`, and the per-agent list (`GET ?agent_id=`) returns every strategy whatever its status, so a paused or cancelled one stays visible with its history.
## Walkthrough
diff --git a/examples/skills/pump-fun/SKILL.md b/examples/skills/pump-fun/SKILL.md
index be59a4b58..43a6bfa22 100644
--- a/examples/skills/pump-fun/SKILL.md
+++ b/examples/skills/pump-fun/SKILL.md
@@ -12,9 +12,9 @@ works on any deployment of three.ws without third-party DNS or proxies.
| `getTokenDetails` | Solana RPC + Metaplex metadata | Mint, supply, decimals, name, symbol. Always available. |
| `getTokenHolders` | `connection.getTokenLargestAccounts` | Top holders + concentration. Always available. |
| `searchTokens` | upstream pumpfun-claims-bot | Requires `PUMPFUN_BOT_URL`. |
-| `getTokenTrades` | upstream pumpfun-claims-bot | Requires `PUMPFUN_BOT_URL`. |
-| `getTrendingTokens` | upstream pumpfun-claims-bot | Requires `PUMPFUN_BOT_URL`. |
-| `getNewTokens` | upstream pumpfun-claims-bot | Requires `PUMPFUN_BOT_URL`. |
+| `getTokenTrades` | upstream pumpfun-claims-bot, else on-chain | Real trades decoded from Solana RPC when `PUMPFUN_BOT_URL` is unset. Always available. |
+| `getTrendingTokens` | upstream pumpfun-claims-bot, else live pump.fun feed | Falls through to pump.fun's public feed and the platform's launch recorder when `PUMPFUN_BOT_URL` is unset. Always available. |
+| `getNewTokens` | upstream pumpfun-claims-bot, else live pump.fun feed | Newest launches from pump.fun's public feed, with the platform's launch recorder as backup, when `PUMPFUN_BOT_URL` is unset. Always available. |
| `getGraduatedTokens` | upstream pumpfun-claims-bot | Requires `PUMPFUN_BOT_URL`. |
| `getKingOfTheHill` | upstream pumpfun-claims-bot | Requires `PUMPFUN_BOT_URL`. |
| `getCreatorProfile` | upstream pumpfun-claims-bot | Requires `PUMPFUN_BOT_URL`. |
diff --git a/examples/skills/pump-fun/handlers.js b/examples/skills/pump-fun/handlers.js
index 74d6126ca..b7571b8f1 100644
--- a/examples/skills/pump-fun/handlers.js
+++ b/examples/skills/pump-fun/handlers.js
@@ -19,7 +19,10 @@ function _endpoint() {
return `${globalThis.location.origin}/api/pump-fun-mcp`;
}
// Skill workers run without window — fall back to a same-origin relative
- // fetch which the host shell will resolve.
+ // fetch which the host shell will resolve. On the three.ws server the skill
+ // runtime (api/_lib/skill-runtime.js) hands this handler a fetch that
+ // dispatches the relative path in-process, so the same code serves
+ // backtests and strategy runs without a loopback HTTP hop.
return '/api/pump-fun-mcp';
}
diff --git a/prompts/swarm-100/route-strategy-lab.md b/prompts/swarm-100/route-strategy-lab.md
deleted file mode 100644
index 20df27feb..000000000
--- a/prompts/swarm-100/route-strategy-lab.md
+++ /dev/null
@@ -1,119 +0,0 @@
-# Route audit: /strategy-lab (Strategy Lab)
-
-How to run: paste this file's repo path into a fresh Claude Code chat in this
-repository and say "run this work order". This file is fully self-contained:
-it depends on no other prompt file anywhere. If neighboring files in
-prompts/swarm-100/ are gone, that work is done; if present, ignore them.
-Every claim below rots; step 0 re-measures, and what you measure wins.
-
-## Operating clause (binding)
-
-- Read CLAUDE.md first. Its rules override everything, including this file.
-- Finish 100% in this session. Never end the turn with a question, an option
- list, or an unexecuted plan. A judgment call goes in one line of the final
- report; it never becomes a question that halts work.
-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real
- funds or any irreversible on-chain write, git push or a production deploy,
- committing content that references a crypto project other than $THREE, and
- destroying unrecoverable data.
-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no
- commented-out code. Real APIs and real integrations only.
-- The em-dash and en-dash characters are banned in everything you write.
-- Concurrent agents share this worktree: stage explicit paths only (never a
- bare add-everything), and commit finished work promptly.
-- Before committing, run: npm run check:rules -- --paths <files you touched>.
- It must exit 0.
-
-## Step 0: re-derive the current state
-
-1. This route's declared entry (path, description, added date):
-
- node -e "const p=require('./data/pages.json');for(const s of p.sections)for(const g of s.pages)if(g.path==='/strategy-lab')console.log(JSON.stringify(g,null,2))"
-
-2. Find the serving implementation: grep "/strategy-lab" in vercel.json (the live
- route table server/index.mjs boots from), then list matching files in
- pages/ and src/. STRUCTURE.md maps every surface to its directory if the
- grep is ambiguous.
-3. Production right now:
-
- curl -so /dev/null -w '%{http_code}\n' https://three.ws/strategy-lab
-
-4. Start (or reuse) the local dev server: npm run dev (vite, port 3000).
-
-## Task: audit this one route end to end, then fix everything found
-
-Route: /strategy-lab ("Strategy Lab", section "crypto").
-Declared purpose: Build DCA and subscription strategies that trade on-chain on your behalf.
-
-Drive the page in a real headless browser. Playwright is already a dev
-dependency; keep your probe script in the session scratchpad, never in the
-repo.
-
-1. Load http://localhost:3000/strategy-lab. Record the HTTP status, every console
- error and warning, and every failed network request.
-2. Exercise it like a first-time user: click the primary actions, run the
- primary flow if one exists, follow the page's internal links. Every button
- must do something real; every link must resolve. If the page renders data,
- prove in the network log that it came from a live endpoint, not a baked-in
- fallback array.
-3. States: verify populated, empty, loading, and error states are designed and
- reachable. Block the page's primary fetch in Playwright and confirm an
- actionable error state appears, not a blank void or a raw exception.
-4. Responsive: render at 320, 768, and 1440 px. No horizontal page scroll, no
- overlapping or clipped controls.
-5. Accessibility basics: one h1; interactive elements are real buttons or
- links with visible focus states; images carry alt text; form fields have
- labels.
-6. Head: a specific title tag and meta description that match the declared
- purpose above.
-7. Fix every defect at its root in the page's real source files and re-run the
- probe until clean. Defects in shared modules are in scope when this route
- exercises them.
-
-## Definition of done
-
-- [ ] Local load of /strategy-lab: HTTP 200, zero console errors, zero unhandled
- failed requests (a third-party outage must land in a designed fallback,
- not a broken page).
-- [ ] No dead interactive element on the page: no stub href="#", no button
- without a handler, no link to a missing path.
-- [ ] Empty, loading, error, and populated states verified.
-- [ ] 320 / 768 / 1440 px renders verified clean.
-- [ ] Title and meta description present and specific.
-- [ ] npm test passes; npm run check:rules -- --paths <touched files> exits 0.
-- [ ] Production status from step 0 recorded in the report; if production
- needs a deploy to pick up a fix, the report says so (deploys stay
- owner-gated).
-
-## Never blocked
-
-| Blocker | Resolution (act, do not ask) |
-|---|---|
-| Missing env var or credential | Check .env and .env.local, then the Cloud Run service env, then Secret Manager (the CLAUDE.md self-unblock playbook has the exact commands). If it truly exists nowhere, wire the code fully behind the env var, prove the wiring with a dry run, and name the single missing var in the report. |
-| gcloud not on PATH | Run: export PATH="$HOME/google-cloud-sdk/bin:$PATH" |
-| Dev server port 3000 busy | Another agent may be serving this repo; probe it and reuse if so. Otherwise start your own on a free port: npx vite --port 3101 |
-| Playwright browser missing | npx playwright install chromium |
-| A surface needs a signed-in user | Register a fresh account through the real /register flow against the real API and use it. Never mock the session. |
-| A defect sits in code you did not touch | Fix it if it blocks a Definition of done line (root cause it, never mask it). Otherwise note it in the report and continue. |
-| An unrelated test is red | Same rule. Never pipe npm test through tail; it masks exit codes. |
-
-## Close out (required)
-
-1. Verify every Definition of done line with the actual command output in
- front of you. Never claim a line you did not verify.
-2. Commit with explicit paths and a subject that describes the diff (house
- style: type(scope): what changed and why a reader cares).
-3. Delete this prompt file in that same commit:
-
- git rm prompts/swarm-100/route-strategy-lab.md
-
- The shrinking directory is this campaign's only progress ledger; there is
- no progress log to update.
-4. Final report: what step 0 measured, what changed (file list), evidence per
- Definition of done line, and any one-line judgment calls. No trailing
- questions, no unexecuted plans.
-
-If a line genuinely cannot pass inside this session (an external party must
-respond, or an owner-gated action is the final step), finish everything else,
-leave this file in place, and state exactly which line remains and who owns
-it. Never delete this file on a partial.
diff --git a/public/strategy-lab.html b/public/strategy-lab.html
index 9a67ce032..11698fa87 100644
--- a/public/strategy-lab.html
+++ b/public/strategy-lab.html
@@ -473,7 +473,9 @@
const walletInfo = $('walletInfo'), walletStatus = $('walletStatus');
const issuesEl = $('issues'), summaryBox = $('summaryBox'), charts = $('charts');
+ const LOGIN_HREF = '/login?next=' + encodeURIComponent('/strategy-lab');
let mode = 'simulate';
+ let signedIn = false;
let activeRun = null;
let currentWallet = null; // { address, sol }
let lastBacktest = null; // raw backtest data for export
@@ -493,6 +495,16 @@
function pn(n) { return n > 0 ? 'pos' : n < 0 ? 'neg' : ''; }
function explorerLink(addr, net) { return `https://explorer.solana.com/address/${addr}${net === 'devnet' ? '?cluster=devnet' : ''}`; }
function setStatus(msg, kind = 'info') { status.className = 'status ' + kind; status.textContent = msg; }
+ // fetch() rejects with the bare "Failed to fetch" / "Load failed" when the
+ // network is down or three.ws is unreachable; turn that into an instruction.
+ const NETWORK_MSG = 'three.ws could not be reached. Check your connection and try again.';
+ const BAD_REPLY_MSG = 'three.ws answered with something unexpected. Try again in a moment.';
+ function isNetworkError(e) { return e instanceof TypeError || /failed to fetch|load failed|network/i.test(String(e?.message || e)); }
+ function errMsg(e) {
+ if (isNetworkError(e)) return NETWORK_MSG;
+ if (e instanceof SyntaxError) return BAD_REPLY_MSG; // a non-JSON body from an edge or proxy error page
+ return e?.message || String(e);
+ }
function debounce(fn, ms) { let t; return (...a) => { clearTimeout(t); t = setTimeout(() => fn(...a), ms); }; }
// ── Toasts ──────────────────────────────────────────────────────────────
@@ -658,7 +670,12 @@
method: 'POST', headers: { 'content-type': 'application/json' },
body: JSON.stringify({ strategy: s, network: netSel.value }),
}).then((r) => r.json()).catch(() => null);
- if (!r) return; // network hiccup — leave last state
+ if (!r) {
+ // Network failure: say so instead of leaving a stale "Valid" verdict on
+ // a spec that may have changed since. Issues and summary are kept.
+ setStatus('Validation service unreachable. Check your connection; your spec is kept and re-checks on the next edit.', 'warn');
+ return;
+ }
if (r.error) {
const issues = r.issues || r.report?.issues || [{ level: 'error', field: '', message: r.error_description || r.error }];
const errCount = issues.filter((i) => i.level === 'error').length || 1;
@@ -676,11 +693,39 @@
$('validate').onclick = () => liveValidate();
// ── Agent + wallet bootstrap ────────────────────────────────────────────
+ // /api/auth/me answers 200 with { user: null } when signed out, so the
+ // session is resolved with one clean GET instead of a 401 on /api/agents in
+ // every anonymous visitor's console. Signed-out and agent-less visitors get a
+ // link to the next step rather than an inert "sign in" option.
+ function renderSignedOut(message) {
+ signedIn = false;
+ agentSel.innerHTML = '<option value="">Sign in to load agents</option>';
+ walletInfo.innerHTML = message
+ ? `<span class="muted">${escapeHtml(message)}</span>`
+ : `<a href="${LOGIN_HREF}">Sign in</a><span class="muted"> to pick an agent, backtest on real on-chain history, and run live.</span>`;
+ provisionBtn.disabled = true;
+ renderPortfolio(null);
+ }
async function loadAgents() {
+ const me = await fetch('/api/auth/me', { credentials: 'include', headers: { accept: 'application/json' } })
+ .then((r) => (r.ok ? r.json() : null)).catch(() => null);
+ if (!me) { renderSignedOut('three.ws could not be reached. Check your connection and reload to load your agents.'); return; }
+ if (!me.user) { renderSignedOut(); return; }
+ signedIn = true;
const r = await fetch('/api/agents', { credentials: 'include' }).then((r) => r.json()).catch(() => null);
- if (!r?.agents) { agentSel.innerHTML = '<option value="">— sign in to load agents —</option>'; return; }
+ if (!r?.agents) {
+ agentSel.innerHTML = '<option value="">Agents unavailable</option>';
+ walletInfo.innerHTML = '<span class="muted">Your agents could not be loaded. Reload to try again.</span>';
+ return;
+ }
+ if (!r.agents.length) {
+ agentSel.innerHTML = '<option value="">No agents yet</option>';
+ walletInfo.innerHTML = `<a href="/create">Create an agent</a><span class="muted"> to get a Solana wallet for live runs. Backtests work right away.</span>`;
+ return;
+ }
agentSel.innerHTML = '<option value="">— select agent —</option>' +
r.agents.map((a) => `<option value="${a.id}">${escapeHtml(a.name || a.id)}</option>`).join('');
+ walletInfo.innerHTML = '<span class="muted">Pick an agent to load its wallet.</span>';
const saved = localStorage.getItem('strategy-lab:agentId');
if (saved && r.agents.some((a) => a.id === saved)) { agentSel.value = saved; await onAgentChange(); }
}
@@ -744,13 +789,21 @@
const r = await fetch('/api/pump/strategy-backtest', {
method: 'POST', headers: { 'content-type': 'application/json' },
body: JSON.stringify({ strategy: s, network: netSel.value }),
- }).then((r) => r.json()).catch((e) => ({ error: e.message }));
+ }).then((r) => r.json()).catch((e) => ({ error: 'network_error', error_description: errMsg(e) }));
$('backtest').disabled = false;
if (r.error) {
- setStatus('Backtest failed: ' + (r.error_description || r.error), 'bad');
- pushLog('error', '! ' + (r.error_description || r.error));
+ const msg = r.error_description || r.error;
+ pushLog('error', '! ' + msg);
+ if (r.error === 'unauthorized') {
+ setStatus('Sign in to backtest against real on-chain history.', 'warn');
+ showResultSignIn('Backtests replay your strategy against real holder, curve, and trade history, which takes a signed-in account.');
+ return;
+ }
+ setStatus('Backtest failed: ' + msg, 'bad');
if (r.issues) { spec.classList.add('invalid'); renderIssues(r.issues); }
- showResultError(r.error_description || r.error);
+ showResultError(r.error === 'no_candidates'
+ ? 'The scan returned no mints to replay. Widen the scan limit, switch between new and trending, or list mints explicitly.'
+ : msg);
return;
}
lastBacktest = r.data;
@@ -886,9 +939,25 @@
<div class="skel" style="height:60px"></div><div class="skel" style="height:110px"></div>
<div class="skel" style="height:24px"></div><div class="skel" style="height:24px"></div><div class="skel" style="height:24px"></div></div>`;
}
+ function emptyState(ic, title, bodyHtml) {
+ return `<div class="empty"><div class="ic">${ic}</div><div class="t">${escapeHtml(title)}</div><div class="d">${bodyHtml}</div></div>`;
+ }
function showResultError(msg) {
metrics.style.display = 'none'; charts.innerHTML = '';
- resultPanel.innerHTML = `<div class="empty"><div class="ic">⚠️</div><div class="t">Couldn't complete</div><div class="d">${escapeHtml(msg)}</div></div>`;
+ resultPanel.innerHTML = emptyState('⚠️', "Couldn't complete", escapeHtml(msg));
+ }
+ function showResultSignIn(why) {
+ metrics.style.display = 'none'; charts.innerHTML = '';
+ resultPanel.innerHTML = emptyState('🔐', 'Sign in to continue', `${escapeHtml(why)} <a href="${LOGIN_HREF}">Sign in</a> and you land right back here.`);
+ }
+ function showRunInProgress(runMode, network, durationSec) {
+ metrics.style.display = 'none'; charts.innerHTML = '';
+ resultPanel.innerHTML = emptyState('📡', `${runMode === 'live' ? 'Live' : 'Simulated'} session running`,
+ `Scanning ${network} for up to ${durationSec}s. Every entry, exit, and skip streams into the Activity log below as it happens; the summary lands here when the session ends.`);
+ }
+ function showRunStopped() {
+ metrics.style.display = 'none'; charts.innerHTML = '';
+ resultPanel.innerHTML = emptyState('■', 'Session stopped', 'Open positions persist and appear in the Portfolio panel below. Start another run whenever you like.');
}
// ── Export / copy ───────────────────────────────────────────────────────
@@ -920,6 +989,7 @@
const durationSec = Number($('durSel').value) || 60;
if (mode === 'live') {
+ if (!signedIn) { setStatus('Sign in to run a strategy live.', 'warn'); showResultSignIn('Live runs sign real transactions from your agent\'s wallet, which takes a signed-in account.'); return; }
if (!agentId) { setStatus('Select an agent first.', 'bad'); return; }
if (!currentWallet) { setStatus('Provision a Solana wallet first.', 'bad'); return; }
if (currentWallet.sol < 0.02) { setStatus('Wallet balance below 0.02 SOL — fund it before going live.', 'bad'); return; }
@@ -934,6 +1004,7 @@
clearLog();
pushLog('start', `▶ ${mode === 'live' ? 'LIVE' : 'simulated'} run on ${network} · ${durationSec}s`);
setStatus(`Streaming ${mode}…`, 'info'); liveDot.classList.add('on');
+ showRunInProgress(mode, network, durationSec);
$('run').disabled = true; $('backtest').disabled = true; $('stop').disabled = false;
const ctrl = new AbortController(); activeRun = ctrl;
@@ -945,8 +1016,11 @@
});
if (!resp.ok) {
let body = null; try { body = JSON.parse(await resp.text()); } catch {}
- if (body?.issues) { setStatus(`Run rejected — ${body.error_description || body.error}`, 'bad'); spec.classList.add('invalid'); renderIssues(body.issues); }
- else setStatus('Run failed: HTTP ' + resp.status + (body?.error_description ? ' — ' + body.error_description : ''), 'bad');
+ const msg = body?.error_description || body?.error || ('HTTP ' + resp.status);
+ pushLog('error', '! ' + msg);
+ if (resp.status === 401) { setStatus('Sign in to run a strategy live.', 'warn'); showResultSignIn('Live runs sign real transactions from your agent\'s wallet, which takes a signed-in account.'); }
+ else if (body?.issues) { setStatus('Run rejected: ' + msg, 'bad'); spec.classList.add('invalid'); renderIssues(body.issues); showResultError('Fix the flagged rules in the spec, then run again.'); }
+ else { setStatus('Run failed: ' + msg, 'bad'); showResultError(msg); }
return;
}
const reader = resp.body.getReader(), dec = new TextDecoder();
@@ -961,13 +1035,20 @@
setStatus('Run complete', 'ok');
if (mode === 'live') refreshPortfolio();
} catch (e) {
- if (e.name !== 'AbortError') setStatus('Stream error: ' + e.message, 'bad');
+ if (e.name !== 'AbortError') {
+ const started = logCounts.all > 1; // more than the local "run" line: the stream had opened
+ setStatus((started ? 'Stream error: ' : 'Run failed: ') + errMsg(e), 'bad');
+ pushLog('error', '! ' + (started ? 'stream dropped: ' : '') + errMsg(e));
+ showResultError(started
+ ? 'The session stream dropped before it finished. Open positions persist in the Portfolio panel; start the run again to keep going.'
+ : errMsg(e));
+ }
} finally {
liveDot.classList.remove('on');
$('run').disabled = false; $('backtest').disabled = false; $('stop').disabled = true; activeRun = null;
}
};
- $('stop').onclick = () => { activeRun?.abort(); pushLog('error', '■ stopped'); };
+ $('stop').onclick = () => { if (!activeRun) return; activeRun.abort(); pushLog('error', '■ stopped'); setStatus('Run stopped', 'warn'); showRunStopped(); };
function handleSse(chunk) {
const lines = chunk.split('\n');
@@ -989,14 +1070,34 @@
}
function renderRunSummary(d) {
metrics.style.display = ''; charts.innerHTML = '';
- const enters = (d.log || []).filter((l) => l.action === 'enter').length;
- const exits = (d.log || []).filter((l) => l.action === 'exit').length;
+ const log = d.log || [];
+ const count = (action) => log.filter((l) => l.action === action).length;
+ const enters = count('enter'), exits = count('exit'), skips = count('skip');
+ const scanErrors = log.filter((l) => l.action === 'scan-error');
+ const tradeErrors = log.filter((l) => typeof l.action === 'string' && l.action.endsWith('-error') && l.action !== 'scan-error');
metrics.innerHTML = `
<div class="metric"><div class="v">${fmt(d.spent, 3)}</div><div class="l">SOL deployed</div></div>
<div class="metric"><div class="v">${d.openPositions?.length ?? 0}</div><div class="l">open positions</div></div>
<div class="metric"><div class="v">${enters}</div><div class="l">entries</div></div>
- <div class="metric"><div class="v">${exits}</div><div class="l">exits</div></div>`;
- resultPanel.innerHTML = `<div class="empty"><div class="ic">✅</div><div class="t">Session complete</div><div class="d">Open positions persist across runs and appear in the Portfolio panel below.</div></div>`;
+ <div class="metric"><div class="v">${exits}</div><div class="l">exits</div></div>
+ <div class="metric"><div class="v">${skips}</div><div class="l">skipped</div></div>`;
+ if (!enters && scanErrors.length && !skips) {
+ resultPanel.innerHTML = emptyState('⚠️', 'No candidates reached the filters',
+ `Every scan failed: ${escapeHtml(scanErrors[0].error || 'unknown error')}. The live feed may be catching its breath; run again in a minute.`);
+ return;
+ }
+ if (!enters && skips) {
+ resultPanel.innerHTML = emptyState('🔍', 'Nothing passed the filters',
+ `${skips} candidate${skips === 1 ? '' : 's'} scanned, none met every entry rule. Loosen a threshold, drop a filter from the palette, or raise the scan limit, then run again.`);
+ return;
+ }
+ if (!enters) {
+ resultPanel.innerHTML = emptyState('🌙', 'Quiet session', 'No candidates surfaced during the window. Try a longer duration or switch the scan between new and trending launches.');
+ return;
+ }
+ const errNote = tradeErrors.length ? ` ${tradeErrors.length} trade${tradeErrors.length === 1 ? '' : 's'} hit an error; the Activity log has each one.` : '';
+ resultPanel.innerHTML = emptyState('✅', 'Session complete',
+ `${enters} entr${enters === 1 ? 'y' : 'ies'}, ${exits} exit${exits === 1 ? '' : 's'}, ${fmt(d.spent, 3)} SOL deployed.${errNote} Open positions persist across runs and appear in the Portfolio panel below.`);
}
// ── Portfolio ───────────────────────────────────────────────────────────
@@ -1004,14 +1105,20 @@
const id = agentSel.value, net = netSel.value;
if (!id) { renderPortfolio(null); return; }
$('refreshPortfolio').disabled = true; $('refreshPortfolio').textContent = 'Refreshing…';
- const r = await fetch(`/api/pump/portfolio?agentId=${id}&network=${net}`, { credentials: 'include' }).then((r) => r.json()).catch(() => null);
+ const r = await fetch(`/api/pump/portfolio?agentId=${id}&network=${net}`, { credentials: 'include' }).then((r) => r.json()).catch((e) => ({ error: 'network_error', error_description: errMsg(e) }));
$('refreshPortfolio').disabled = false; $('refreshPortfolio').textContent = 'Refresh';
- portfolioData = r?.data || null;
+ if (!r || r.error) {
+ portfolioData = null;
+ $('portfolio').innerHTML = emptyState('⚠️', 'Portfolio unavailable', `${escapeHtml(r?.error_description || r?.error || NETWORK_MSG)} Hit Refresh to try again.`);
+ return;
+ }
+ portfolioData = r.data || null;
renderPortfolio(portfolioData);
}
$('refreshPortfolio').onclick = refreshPortfolio;
$('closeAll').onclick = async () => {
const id = agentSel.value;
+ if (!signedIn) { setStatus('Sign in to manage positions.', 'warn'); showResultSignIn('Selling positions signs real transactions from your agent\'s wallet, which takes a signed-in account.'); return; }
if (!id) { setStatus('Select an agent first.', 'bad'); return; }
const net = netSel.value, netLabel = net === 'mainnet' ? 'mainnet' : 'devnet';
const ok = await confirmDialog({
@@ -1026,8 +1133,8 @@
const r = await fetch('/api/pump/strategy-close-all', {
method: 'POST', credentials: 'include', headers: { 'content-type': 'application/json' },
body: JSON.stringify({ agentId: id, network: net }),
- }).then((r) => r.json()).catch((e) => ({ error: e.message }));
- if (r.error) { setStatus('Close-all failed: ' + (r.error_description || r.error), 'bad'); return; }
+ }).then((r) => r.json()).catch((e) => ({ error: 'network_error', error_description: errMsg(e) }));
+ if (r.error) { setStatus('Close-all failed: ' + (r.error_description || r.error), 'bad'); pushLog('error', '! close-all: ' + (r.error_description || r.error)); return; }
(r.data?.log || []).forEach((e) => {
if (e.action === 'sold') pushLog('exit', `× sold ${e.mint} → ${e.sig?.slice(0, 12) ?? ''}…`);
else if (e.action === 'sell-error') pushLog('error', `! sell-error ${e.mint}: ${e.error}`);
diff --git a/tests/api/pump-fun-mcp.test.js b/tests/api/pump-fun-mcp.test.js
index 9ea08ff22..30e60c547 100644
--- a/tests/api/pump-fun-mcp.test.js
+++ b/tests/api/pump-fun-mcp.test.js
@@ -82,6 +82,14 @@ vi.mock('../../api/_lib/pumpfun-mcp.js', () => ({
}));
import { pumpfunBotEnabled } from '../../api/_lib/pumpfun-mcp.js';
+// The live pump.fun feed rung under get_trending_tokens / get_new_tokens. Each
+// test sets what the feed answers; `data: null` means every rung is down.
+vi.mock('../../api/_lib/pump-trending.js', () => ({
+ getTrendingSlim: vi.fn(async () => ({ data: null, stale: false })),
+ getNewSlim: vi.fn(async () => ({ data: null, stale: false })),
+}));
+import { getTrendingSlim, getNewSlim } from '../../api/_lib/pump-trending.js';
+
// ── helpers ────────────────────────────────────────────────────────────────
function makeReq(body) {
const stream = body ? Readable.from([Buffer.from(JSON.stringify(body))]) : Readable.from([]);
@@ -134,15 +142,16 @@ beforeEach(() => {
// ── Tests ──────────────────────────────────────────────────────────────────
-// The six discovery tools that require the external indexer (PUMPFUN_BOT_URL).
+// The four discovery tools that require the external indexer (PUMPFUN_BOT_URL).
+// get_trending_tokens and get_new_tokens are NOT here: they fall through to the
+// live pump.fun feed and stay advertised without the indexer.
const INDEXER_TOOL_NAMES = [
'search_tokens',
- 'get_trending_tokens',
- 'get_new_tokens',
'get_graduated_tokens',
'get_king_of_the_hill',
'get_creator_profile',
];
+const LIVE_FEED_TOOL_NAMES = ['get_trending_tokens', 'get_new_tokens'];
describe('initialize', () => {
it('returns server info, protocol version, and indexerEnabled flag', async () => {
@@ -163,17 +172,18 @@ describe('initialize', () => {
});
describe('tools/list', () => {
- it('excludes the six indexer tools (keeps pumpfun_bot_status) when unconfigured', async () => {
+ it('excludes the four indexer-only tools (keeps pumpfun_bot_status and the live-feed tools) when unconfigured', async () => {
pumpfunBotEnabled.mockReturnValue(false);
const { json } = await call({ jsonrpc: '2.0', id: 1, method: 'tools/list' });
expect(Array.isArray(json.result.tools)).toBe(true);
const names = json.result.tools.map((t) => t.name);
- // None of the indexer-backed discovery tools are advertised…
+ // None of the indexer-only discovery tools are advertised…
for (const n of INDEXER_TOOL_NAMES) expect(names).not.toContain(n);
- // …but the always-on metadata tool is.
+ // …but the always-on metadata tool and the live-feed discovery tools are.
expect(names).toContain('pumpfun_bot_status');
- // 25 total declared − 6 indexer tools = 19 advertised.
- expect(json.result.tools).toHaveLength(19);
+ for (const n of LIVE_FEED_TOOL_NAMES) expect(names).toContain(n);
+ // 25 total declared − 4 indexer-only tools = 21 advertised.
+ expect(json.result.tools).toHaveLength(21);
for (const t of json.result.tools) expect(t.inputSchema.type).toBe('object');
});
@@ -251,13 +261,75 @@ describe('tools/call indexer-required tools', () => {
jsonrpc: '2.0',
id: 1,
method: 'tools/call',
- params: { name: 'getTrendingTokens', arguments: { limit: 5 } },
+ params: { name: 'searchTokens', arguments: { query: 'three', limit: 5 } },
});
expect(json.error.code).toBe(-32004);
expect(json.error.message).toMatch(/indexer/i);
});
});
+describe('tools/call live-feed discovery tools', () => {
+ const row = (mint, i) => ({
+ mint,
+ symbol: `S${i}`,
+ name: `Coin ${i}`,
+ logo: null,
+ price_usd: null,
+ usd_market_cap: 1000 * (i + 1),
+ rank: i + 1,
+ });
+
+ it('getTrendingTokens answers from the live pump.fun feed without the indexer', async () => {
+ pumpfunBotEnabled.mockReturnValue(false);
+ getTrendingSlim.mockResolvedValueOnce({
+ data: ['THREEsynthetic1111111111111111111111111111', 'THREEsynthetic2222222222222222222222222222'].map(row),
+ stale: false,
+ });
+ const { json } = await call({
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'tools/call',
+ params: { name: 'getTrendingTokens', arguments: { limit: 5 } },
+ });
+ expect(json.error).toBeUndefined();
+ expect(getTrendingSlim).toHaveBeenCalledWith(5);
+ const data = json.result.structuredContent;
+ expect(data.source).toBe('pump.fun');
+ expect(data.stale).toBe(false);
+ expect(data.tokens.map((t) => t.mint)).toEqual([
+ 'THREEsynthetic1111111111111111111111111111',
+ 'THREEsynthetic2222222222222222222222222222',
+ ]);
+ });
+
+ it('get_new_tokens clamps the limit and flags a stale feed', async () => {
+ pumpfunBotEnabled.mockReturnValue(false);
+ getNewSlim.mockResolvedValueOnce({ data: [row('THREEsynthetic3333333333333333333333333333', 0)], stale: true });
+ const { json } = await call({
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'tools/call',
+ params: { name: 'get_new_tokens', arguments: { limit: 500 } },
+ });
+ expect(getNewSlim).toHaveBeenCalledWith(50);
+ expect(json.result.structuredContent.stale).toBe(true);
+ expect(json.result.structuredContent.tokens).toHaveLength(1);
+ });
+
+ it('returns -32004 only when every live rung is down', async () => {
+ pumpfunBotEnabled.mockReturnValue(false);
+ getNewSlim.mockResolvedValueOnce({ data: null, stale: false });
+ const { json } = await call({
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'tools/call',
+ params: { name: 'getNewTokens', arguments: { limit: 5 } },
+ });
+ expect(json.error.code).toBe(-32004);
+ expect(json.error.message).toMatch(/pump\.fun/i);
+ });
+});
+
describe('tools/call pumpfun_bot_status', () => {
it('reports unconfigured + unhealthy with a message when the bot is unset', async () => {
pumpfunBotEnabled.mockReturnValue(false);
diff --git a/tests/api/strategy-runtime.test.js b/tests/api/strategy-runtime.test.js
index de7a61c87..58b206c66 100644
--- a/tests/api/strategy-runtime.test.js
+++ b/tests/api/strategy-runtime.test.js
@@ -2,9 +2,15 @@
// We don't spin up a real HTTP server — just unit-test the runtime dispatcher
// and exercise the backtest endpoint's stub-invoke path through the handler.
-import { describe, it, expect } from 'vitest';
+import { describe, it, expect, vi } from 'vitest';
import { makeRuntime } from '../../api/_lib/skill-runtime.js';
+// The in-process pump.fun tool dispatcher the server-side runtime routes the
+// pump-fun skill's relative /api/pump-fun-mcp fetch into. Each test decides
+// what a tool answers; the real module would pull the Solana SDK graph.
+const callPumpFunTool = vi.fn();
+vi.mock('../../api/pump-fun-mcp.js', () => ({ callPumpFunTool: (...a) => callPumpFunTool(...a) }));
+
describe('skill runtime', () => {
it('dispatches validateStrategy through the runtime', async () => {
const rt = makeRuntime();
@@ -91,3 +97,42 @@ describe('backtest via runtime + sibling pump-fun stubs', () => {
expect(r.data.realizedPnlSol).toBeGreaterThan(0);
});
});
+
+describe('server-side fetch for the isomorphic pump-fun skill', () => {
+ it('dispatches the relative /api/pump-fun-mcp call in-process instead of failing to parse the URL', async () => {
+ callPumpFunTool.mockResolvedValueOnce({
+ tokens: [{ mint: 'THREEsynthetic1111111111111111111111111111' }],
+ source: 'pump.fun',
+ });
+ const rt = makeRuntime();
+ const r = await rt.invoke('pump-fun.getNewTokens', { limit: 3 });
+ expect(r.ok).toBe(true);
+ expect(callPumpFunTool).toHaveBeenCalledWith('getNewTokens', { limit: 3 });
+ expect(r.data.tokens[0].mint).toBe('THREEsynthetic1111111111111111111111111111');
+ });
+
+ it('surfaces a tool error as a clean { ok: false } result with the rpc message', async () => {
+ callPumpFunTool.mockRejectedValueOnce(
+ Object.assign(new Error('tool "get_new_tokens": every live pump.fun source is unavailable right now'), { rpcCode: -32004 }),
+ );
+ const rt = makeRuntime();
+ const r = await rt.invoke('pump-fun.getNewTokens', { limit: 3 });
+ expect(r.ok).toBe(false);
+ expect(r.error).toMatch(/every live pump\.fun source/);
+ });
+
+ it('leaves an explicit fetch override untouched', async () => {
+ const seen = [];
+ const fetchImpl = async (url, init) => {
+ seen.push({ url, method: init?.method });
+ return new Response(JSON.stringify({ jsonrpc: '2.0', id: 1, result: { content: [{ type: 'text', text: '{"tokens":[]}' }] } }), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ });
+ };
+ const rt = makeRuntime({ fetch: fetchImpl });
+ const r = await rt.invoke('pump-fun.getTrendingTokens', { limit: 2 });
+ expect(r.ok).toBe(true);
+ expect(seen).toEqual([{ url: '/api/pump-fun-mcp', method: 'POST' }]);
+ });
+});