Skip to content

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

feat: Add various new skills and widgets for enhanced agent functionality

nirholas34920742cb99
diff --git a/.env.example b/.env.example
index 8ac69a783..ee3563cf4 100644
--- a/.env.example
+++ b/.env.example
@@ -129,3 +129,7 @@ X402_FACILITATOR_URL_BASE=https://x402.org/facilitator
# Optional bearer tokens for self-hosted/private facilitators.
X402_FACILITATOR_TOKEN_SOLANA=
X402_FACILITATOR_TOKEN_BASE=
+
+# zauthx402 — telemetry + monitoring for x402 endpoints. Optional; when unset
+# the SDK is not invoked. Get a key at https://zauthx402.com.
+ZAUTH_API_KEY=
diff --git a/api/_lib/channel-feed-sources.js b/api/_lib/channel-feed-sources.js
new file mode 100644
index 000000000..af459bbdc
--- /dev/null
+++ b/api/_lib/channel-feed-sources.js
@@ -0,0 +1,54 @@
+// Read-through sources for the channel-feed endpoint.
+// Each function reads a Redis list populated by the pumpkit worker.
+// Returns [] when Redis is unconfigured or unavailable.
+
+import { Redis } from '@upstash/redis';
+import { env } from './env.js';
+
+let _redis = null;
+function redis() {
+ if (_redis !== null) return _redis;
+ if (!env.UPSTASH_REDIS_REST_URL || !env.UPSTASH_REDIS_REST_TOKEN) {
+ _redis = false;
+ return null;
+ }
+ _redis = new Redis({
+ url: env.UPSTASH_REDIS_REST_URL,
+ token: env.UPSTASH_REDIS_REST_TOKEN,
+ });
+ return _redis;
+}
+
+function safeJson(s) {
+ try { return JSON.parse(s); } catch { return null; }
+}
+
+async function readList(key, limit) {
+ const r = redis();
+ if (!r) return [];
+ try {
+ const items = await r.lrange(key, 0, Math.max(0, limit - 1));
+ return items.map((x) => (typeof x === 'string' ? safeJson(x) : x)).filter(Boolean);
+ } catch (err) {
+ console.error(`[channel-feed-sources] redis read failed (${key}):`, err?.message || err);
+ return [];
+ }
+}
+
+// pumpkit worker pushes new mint events to pf:mints.
+// Shape: { signature, mint, name, symbol, timestamp, ... }
+export async function getMints(limit = 50) {
+ return readList('pf:mints', limit);
+}
+
+// pumpkit worker pushes first whale-buy events to pf:whales.
+// Shape: { signature, mint, amount_sol, buyer, timestamp, ... }
+export async function getWhales(limit = 50) {
+ return readList('pf:whales', limit);
+}
+
+// pumpkit worker pushes creator-claim events to pf:claims.
+// Shape: { signature, mint, claimer, amount_lamports, timestamp, ... }
+export async function getClaims(limit = 50) {
+ return readList('pf:claims', limit);
+}
diff --git a/api/_lib/env.js b/api/_lib/env.js
index acc01051a..96a4d0eeb 100644
--- a/api/_lib/env.js
+++ b/api/_lib/env.js
@@ -179,6 +179,12 @@ export const env = {
return opt('X402_FACILITATOR_TOKEN_BASE');
},
+ // zauthx402 SDK — optional telemetry for x402 endpoints. When unset,
+ // the SDK is not initialized and request monitoring is skipped.
+ get ZAUTH_API_KEY() {
+ return opt('ZAUTH_API_KEY');
+ },
+
// Solana RPC URL used for SNS reads/writes. Falls back to public mainnet RPC.
get SOLANA_RPC_URL() {
return opt('SOLANA_RPC_URL', 'https://api.mainnet-beta.solana.com');
diff --git a/api/_lib/http.js b/api/_lib/http.js
index 29c4cb4fd..e10d56be7 100644
--- a/api/_lib/http.js
+++ b/api/_lib/http.js
@@ -2,6 +2,7 @@
import { env } from './env.js';
import { captureException } from './sentry.js';
+import { instrument as zauthInstrument } from './zauth.js';
export function json(res, status, body, headers = {}) {
res.statusCode = status;
@@ -115,6 +116,7 @@ function isAllowedOrigin(origin, allowed) {
// Wrap async handlers so uncaught errors return a consistent JSON envelope.
export function wrap(handler) {
return async (req, res) => {
+ zauthInstrument(req, res);
try {
await handler(req, res);
} catch (err) {
diff --git a/api/_lib/zauth.js b/api/_lib/zauth.js
new file mode 100644
index 000000000..2982b5529
--- /dev/null
+++ b/api/_lib/zauth.js
@@ -0,0 +1,111 @@
+// zauthx402 SDK adapter for Vercel serverless.
+//
+// The upstream `@zauthx402/sdk/middleware` is shaped for Express: it expects
+// `req.path`, `req.protocol`, `req.get(name)`, `req.originalUrl`, `req.ip`,
+// and patches `res.json/send/end`. Our endpoints run as bare Vercel Node
+// handlers (http.IncomingMessage / http.ServerResponse), so we shim the
+// missing properties before invoking the middleware once per request.
+//
+// Disabled cleanly when ZAUTH_API_KEY is unset — `instrument()` becomes a
+// no-op so unrelated environments don't pay any cost.
+
+import { createRequire } from 'node:module';
+import { env } from './env.js';
+
+const require = createRequire(import.meta.url);
+
+let cached;
+
+function buildMiddleware() {
+ const apiKey = env.ZAUTH_API_KEY;
+ if (!apiKey) return null;
+ try {
+ // Lazy require so deployments without the SDK installed (or without a
+ // key) don't pay the import cost.
+ const mod = require('@zauthx402/sdk/middleware');
+ return mod.zauthProvider(apiKey, {
+ shouldMonitor: shouldMonitorReq,
+ });
+ } catch (err) {
+ console.error('[zauth] failed to load @zauthx402/sdk:', err.message);
+ return null;
+ }
+}
+
+function shouldMonitorReq(req) {
+ if (req.headers?.['x-payment-intent'] || req.headers?.['x-payment']) return true;
+ const p = req.path || '';
+ return /\/api\/(wk-x402|mcp)(\/|$)|\/api\/agents\/x402\/|\/api\/agents\/[^/]+\/x402\/|\/api\/agents\/payments\//.test(
+ p,
+ );
+}
+
+function getMiddleware() {
+ if (cached === undefined) cached = buildMiddleware();
+ return cached;
+}
+
+function shimResponse(res) {
+ // The Express middleware does `res.json.bind(res)` / `res.send.bind(res)`
+ // up-front, even if the handler never calls them. Provide Express-shaped
+ // no-op fallbacks (delegating to `res.end`) so binding works. Our handlers
+ // only call `res.end` directly, so these patched versions are never run.
+ if (typeof res.json !== 'function') {
+ res.json = function (body) {
+ if (!res.getHeader('content-type')) {
+ res.setHeader('content-type', 'application/json; charset=utf-8');
+ }
+ res.end(JSON.stringify(body));
+ };
+ }
+ if (typeof res.send !== 'function') {
+ res.send = function (body) {
+ res.end(typeof body === 'string' ? body : JSON.stringify(body));
+ };
+ }
+}
+
+function shimRequest(req) {
+ const url = req.url || '/';
+ const qIdx = url.indexOf('?');
+ const path = qIdx >= 0 ? url.slice(0, qIdx) : url;
+ const xfProto = req.headers['x-forwarded-proto'];
+ const protocol = (Array.isArray(xfProto) ? xfProto[0] : xfProto) || 'https';
+ const xfFor = req.headers['x-forwarded-for'];
+ const ip =
+ (typeof xfFor === 'string' ? xfFor.split(',')[0].trim() : null) ||
+ req.socket?.remoteAddress ||
+ '';
+
+ if (!('path' in req)) Object.defineProperty(req, 'path', { value: path });
+ if (!('originalUrl' in req)) Object.defineProperty(req, 'originalUrl', { value: url });
+ if (!('protocol' in req)) Object.defineProperty(req, 'protocol', { value: protocol });
+ if (!('ip' in req)) Object.defineProperty(req, 'ip', { value: ip });
+ if (typeof req.get !== 'function') {
+ req.get = (name) => {
+ const v = req.headers[String(name).toLowerCase()];
+ return Array.isArray(v) ? v[0] : v;
+ };
+ }
+ // `req.body` is undefined on raw Vercel handlers; the SDK only reads it
+ // for an optional byte-size estimate, so leaving it undefined is fine.
+}
+
+/**
+ * Run the zauth middleware once for this request. Safe to call on every
+ * request — internal `shouldMonitor` filters non-x402 traffic.
+ *
+ * @param {import('http').IncomingMessage} req
+ * @param {import('http').ServerResponse} res
+ */
+export function instrument(req, res) {
+ const mw = getMiddleware();
+ if (!mw) return;
+ try {
+ shimRequest(req);
+ shimResponse(res);
+ mw(req, res, () => {});
+ } catch (err) {
+ console.error('[zauth] middleware error:', err.message);
+ }
+}
diff --git a/api/kol/leaderboard.js b/api/kol/leaderboard.js
new file mode 100644
index 000000000..941bba07e
--- /dev/null
+++ b/api/kol/leaderboard.js
@@ -0,0 +1,33 @@
+// GET /api/kol/leaderboard?window=7d&limit=25
+// → { items: [{ wallet, pnlUsd, winRate, trades, rank }] }
+//
+// Public read-only endpoint; no auth required. Rate-limited by IP.
+// window ∈ '24h' | '7d' | '30d' (default '7d')
+// limit ∈ 1..100 (default 25, capped at 100)
+
+import { cors, json, method, wrap, error } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { getLeaderboard } from '../../src/kol/leaderboard.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.mcpIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const url = new URL(req.url, `http://${req.headers.host}`);
+ const window = url.searchParams.get('window') || '7d';
+ const limitRaw = url.searchParams.get('limit');
+ const limit = limitRaw != null ? Number(limitRaw) : 25;
+
+ let items;
+ try {
+ items = await getLeaderboard({ window, limit });
+ } catch (err) {
+ if (err.status === 400) return error(res, 400, err.code || 'validation_error', err.message);
+ throw err;
+ }
+
+ return json(res, 200, { items });
+});
diff --git a/api/pump-fun-mcp.js b/api/pump-fun-mcp.js
index 802508b91..bd9bb9f6e 100644
--- a/api/pump-fun-mcp.js
+++ b/api/pump-fun-mcp.js
@@ -20,6 +20,8 @@ import { cors, json, method, wrap, readJson, error } from './_lib/http.js';
import { limits, clientIp } from './_lib/rate-limit.js';
import { getPumpSdk, getConnection, solanaPubkey } from './_lib/pump.js';
import { pumpfunMcp, pumpfunBotEnabled } from './_lib/pumpfun-mcp.js';
+import { getRadarSignals } from '../src/kol/radar.js';
+import { computeWalletPnl, WINDOW_SECONDS } from '../src/kol/wallet-pnl.js';
// ── Tool registry ──────────────────────────────────────────────────────────
@@ -99,6 +101,22 @@ const TOOLS = [
description: 'Highest-market-cap token still on the bonding curve.',
inputSchema: { type: 'object', properties: {} },
},
+ {
+ name: 'kol_radar',
+ description:
+ 'gmgn radar signals: early-detection patterns filtered by category, sorted by score desc.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ category: {
+ type: 'string',
+ enum: ['pump-fun', 'new-mints', 'volume-spike'],
+ default: 'pump-fun',
+ },
+ limit: { type: 'integer', minimum: 1, maximum: 100, default: 20 },
+ },
+ },
+ },
{
name: 'getCreatorProfile',
description: 'All tokens by a creator wallet, with rug-pull risk flags.',
@@ -121,6 +139,67 @@ const TOOLS = [
required: ['mint'],
},
},
+ {
+ name: 'kol_wallet_pnl',
+ description: 'Realized + unrealized P&L for a Solana wallet (FIFO cost basis). Requires PUMPFUN_BOT_URL to be configured for live trade data.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ wallet: { type: 'string', description: 'Solana wallet address (base58)' },
+ window: {
+ type: 'string',
+ enum: ['24h', '7d', '30d', 'all'],
+ default: '7d',
+ },
+ },
+ required: ['wallet'],
+ },
+ },
+ {
+ name: 'pumpfun_vanity_mint',
+ description:
+ 'Generate a Solana keypair whose address ends/starts with a vanity pattern. Returns publicKey + secretKey (base58). Caller must save the secret key immediately — it is never stored. Hard timeout: 60 s.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ suffix: { type: 'string', description: 'Desired address suffix (case-insensitive by default)' },
+ prefix: { type: 'string', description: 'Desired address prefix (case-insensitive by default)' },
+ caseSensitive: { type: 'boolean', default: false },
+ maxAttempts: { type: 'integer', default: 5000000 },
+ },
+ },
+ }, ,
+ {
+ name: 'pumpfun_list_claims',
+ description: 'List recent pump.fun fee-claim events for a creator wallet. On-chain RPC — no indexer needed.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ creator: { type: 'string', description: 'Creator wallet address (base58)' },
+ limit: { type: 'integer', minimum: 1, maximum: 50, default: 20 },
+ network: { type: 'string', enum: ['mainnet', 'devnet'], default: 'mainnet' },
+ },
+ required: ['creator'],
+ },
+ },
+ {
+ name: 'pumpfun_watch_claims',
+ description:
+ 'Return all pump.fun fee-claim events for a creator wallet within the last durationMs milliseconds.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ creator: { type: 'string', description: 'Creator wallet address (base58)' },
+ durationMs: {
+ type: 'number',
+ description: 'Look-back window in ms (default 300000 = 5 min, max 1800000)',
+ },
+ network: { type: 'string', enum: ['mainnet', 'devnet'], default: 'mainnet' },
+ },
+ required: ['creator'],
+ },
+ },
+
];
// ── On-chain handlers ──────────────────────────────────────────────────────
@@ -254,6 +333,29 @@ async function handleGetTokenHolders({ mint, limit = 10, network = 'mainnet' })
};
}
+// ── kol_radar handler ──────────────────────────────────────────────────────
+
+async function handleKolRadar({ category = 'pump-fun', limit = 20 }) {
+ return getRadarSignals({ category, limit });
+}
+
+// ── kol_wallet_pnl handler ─────────────────────────────────────────────────
+
+async function handleKolWalletPnl({ wallet, window: win = '7d' }) {
+ if (!wallet) throw rpcError(-32602, 'wallet is required');
+ const windowSecs = WINDOW_SECONDS[win] ?? WINDOW_SECONDS['7d'];
+
+ // Fetch trades from upstream bot when configured; return empty gracefully.
+ let trades = [];
+ if (pumpfunBotEnabled()) {
+ const r = await rawBotCall('getWalletTrades', { wallet, limit: 500 });
+ if (r.ok && Array.isArray(r.data)) trades = r.data;
+ }
+
+ const result = computeWalletPnl({ trades, windowSecs });
+ return { wallet, window: win, ...result };
+}
+
// ── Indexer-backed handlers (route through pumpfunMcp) ─────────────────────
function indexerOrUnavailable(name) {
@@ -330,12 +432,73 @@ async function rawBotCall(tool, args) {
}
}
+
+// ── Claims handlers (on-chain) ─────────────────────────────────────────────
+
+const PUMP_CLAIM_PROGRAMS = new Set([
+ '6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P',
+ 'pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA',
+ 'pfeeUxB6jkeY1Hxd7CsFCAjcbHA9rWtchMGdZ6VojVZ',
+]);
+
+async function fetchClaimsFromChain({ creator, limit = 20, network = 'mainnet', sinceTs = 0 }) {
+ const pk = solanaPubkey(creator);
+ if (!pk) throw rpcError(-32602, 'invalid creator wallet');
+ const conn = getConnection({ network });
+ const sigInfos = await conn.getSignaturesForAddress(pk, { limit: Math.min(100, limit * 4) });
+ const results = [];
+ for (const { signature, blockTime } of sigInfos) {
+ if (results.length >= limit) break;
+ if (sinceTs && (blockTime ?? 0) <= sinceTs) break;
+ let tx;
+ try {
+ tx = await conn.getParsedTransaction(signature, {
+ maxSupportedTransactionVersion: 0,
+ commitment: 'confirmed',
+ });
+ } catch { continue; }
+ if (!tx) continue;
+ const allIxs = [
+ ...(tx.transaction.message.instructions ?? []),
+ ...(tx.meta?.innerInstructions?.flatMap((i) => i.instructions) ?? []),
+ ];
+ if (!allIxs.some((ix) => PUMP_CLAIM_PROGRAMS.has(ix.programId?.toString?.()))) continue;
+ const accounts = tx.transaction.message.accountKeys;
+ const idx = accounts.findIndex((a) => a.pubkey.toString() === creator);
+ if (idx === -1) continue;
+ const lamports = (tx.meta.postBalances[idx] ?? 0) - (tx.meta.preBalances[idx] ?? 0);
+ if (lamports <= 0) continue;
+ results.push({
+ signature,
+ mint: tx.meta.postTokenBalances?.[0]?.mint ?? null,
+ lamports,
+ ts: blockTime ?? Math.floor(Date.now() / 1000),
+ });
+ }
+ return results;
+}
+
+async function handleListClaims({ creator, limit = 20, network = 'mainnet' }) {
+ if (!creator) throw rpcError(-32602, 'creator required');
+ return { creator, network, claims: await fetchClaimsFromChain({ creator, limit, network }) };
+}
+
+async function handleWatchClaims({ creator, durationMs = 300_000, network = 'mainnet' }) {
+ if (!creator) throw rpcError(-32602, 'creator required');
+ const window = Math.min(1_800_000, Math.max(1, durationMs));
+ const sinceTs = Math.floor((Date.now() - window) / 1000);
+ const claims = await fetchClaimsFromChain({ creator, limit: 50, network, sinceTs });
+ return { creator, network, windowMs: window, claims };
+}
+
// ── Dispatch ───────────────────────────────────────────────────────────────
const HANDLERS = {
getBondingCurve: handleGetBondingCurve,
getTokenDetails: handleGetTokenDetails,
getTokenHolders: handleGetTokenHolders,
+ kol_radar: handleKolRadar,
+ kol_wallet_pnl: handleKolWalletPnl,
searchTokens: indexerOrUnavailable('searchTokens'),
getTokenTrades: indexerOrUnavailable('getTokenTrades'),
getTrendingTokens: indexerOrUnavailable('getTrendingTokens'),
@@ -343,6 +506,8 @@ const HANDLERS = {
getGraduatedTokens: indexerOrUnavailable('getGraduatedTokens'),
getKingOfTheHill: indexerOrUnavailable('getKingOfTheHill'),
getCreatorProfile: indexerOrUnavailable('getCreatorProfile'),
+ pumpfun_list_claims: handleListClaims,
+ pumpfun_watch_claims: handleWatchClaims,
};
function rpcError(code, message) {
diff --git a/api/pump/channel-feed.js b/api/pump/channel-feed.js
new file mode 100644
index 000000000..d332d586b
--- /dev/null
+++ b/api/pump/channel-feed.js
@@ -0,0 +1,44 @@
+// GET /api/pump/channel-feed?limit=50&kinds=mint,whale,claim
+//
+// Returns a normalized, deduped, newest-first array of recent pump.fun signals:
+// { items: [{ kind, mint, signature, ts, summary, refs }] }
+//
+// kinds: comma-separated subset of mint|whale|claim (default: all three)
+// limit: max items returned (default 50, max 200)
+//
+// Read-through — no persistence. Data comes from Upstash Redis lists populated
+// by the pumpkit worker. Missing/unconfigured Redis returns empty arrays.
+
+import { cors, json, method, wrap, error } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { getMints, getWhales, getClaims } from '../_lib/channel-feed-sources.js';
+import { buildFeed } from '../../src/pump/channel-feed.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.mcpIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const url = new URL(req.url, `http://${req.headers.host}`);
+ const limit = Math.min(Math.max(1, Number(url.searchParams.get('limit') || 50)), 200);
+ const kinds = url.searchParams.get('kinds') || null;
+
+ const [mints, whales, claims] = await Promise.all([
+ getMints(limit),
+ getWhales(limit),
+ getClaims(limit),
+ ]);
+
+ const items = buildFeed(
+ [
+ { kind: 'mint', items: mints },
+ { kind: 'whale', items: whales },
+ { kind: 'claim', items: claims },
+ ],
+ { limit, kinds },
+ );
+
+ return json(res, 200, { items });
+});
diff --git a/api/pump/deliver-telegram.js b/api/pump/deliver-telegram.js
new file mode 100644
index 000000000..8ece9f6b6
--- /dev/null
+++ b/api/pump/deliver-telegram.js
@@ -0,0 +1,28 @@
+import { z } from 'zod';
+import { json, error, wrap, method, readJson } from '../_lib/http.js';
+import { parse } from '../_lib/validate.js';
+import { sendTelegramSignal } from '../../src/pump/telegram-delivery.js';
+
+const bodySchema = z.object({
+ chatId: z.union([z.string(), z.number()]),
+ signal: z.object({
+ kind: z.enum(['mint', 'whale', 'claim', 'graduation']),
+ mint: z.string(),
+ summary: z.string(),
+ refs: z.array(z.string()).optional(),
+ ts: z.number().optional(),
+ }),
+});
+
+export default wrap(async (req, res) => {
+ if (!method(req, res, ['POST'])) return;
+
+ const botToken = process.env.TELEGRAM_BOT_TOKEN;
+ if (!botToken) return error(res, 500, 'misconfigured', 'TELEGRAM_BOT_TOKEN is not set');
+
+ const raw = await readJson(req);
+ const { chatId, signal } = parse(bodySchema, raw);
+
+ const result = await sendTelegramSignal({ botToken, chatId, signal });
+ return json(res, 200, result);
+});
diff --git a/api/pump/vanity-keygen.js b/api/pump/vanity-keygen.js
new file mode 100644
index 000000000..1dcb2f1e6
--- /dev/null
+++ b/api/pump/vanity-keygen.js
@@ -0,0 +1,118 @@
+// POST /api/pump/vanity-keygen
+//
+// Streams progress via Server-Sent Events; final event delivers the result.
+//
+// body: { suffix?, prefix?, caseSensitive?, maxAttempts? }
+// - at least one of suffix / prefix must be non-empty
+// - hard cap: 60 s wallclock; aborts with 408 if exceeded
+//
+// SSE event stream:
+// event: progress data: { attempts, elapsed } (every ~50k attempts)
+// event: result data: { publicKey, secretKey: base58, attempts, ms }
+// event: error data: { error, error_description }
+//
+// Secret keys are never logged.
+
+import { cors, readJson, error } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { generateVanityKey } from '../../src/pump/vanity-keygen.js';
+import bs58 from 'bs58';
+
+const TIMEOUT_MS = 60_000;
+
+function sseEvent(res, event, data) {
+ res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
+}
+
+export default async function handler(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*' })) return;
+
+ if (req.method !== 'POST') {
+ res.setHeader('allow', 'POST');
+ return error(res, 405, 'method_not_allowed', 'method POST required');
+ }
+
+ const rl = await limits.mcpIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ let body;
+ try {
+ body = await readJson(req);
+ } catch (e) {
+ return error(res, e.status || 400, 'bad_request', e.message);
+ }
+
+ const { suffix = '', prefix = '', caseSensitive = false, maxAttempts = 5_000_000 } = body || {};
+
+ if (!suffix && !prefix) {
+ return error(res, 400, 'validation_error', 'at least one of suffix or prefix is required');
+ }
+
+ // Start SSE stream
+ res.statusCode = 200;
+ res.setHeader('content-type', 'text/event-stream; charset=utf-8');
+ res.setHeader('cache-control', 'no-store');
+ res.setHeader('connection', 'keep-alive');
+ res.setHeader('x-accel-buffering', 'no');
+
+ const ac = new AbortController();
+
+ const timeout = setTimeout(() => {
+ ac.abort();
+ sseEvent(res, 'error', {
+ error: 'request_timeout',
+ error_description: 'vanity search exceeded 60 s limit',
+ });
+ res.statusCode = 408;
+ res.end();
+ }, TIMEOUT_MS);
+
+ req.on('close', () => ac.abort());
+
+ // Progress ticker — emit every 50k attempts via a periodic callback wired
+ // through the AbortSignal so it stops naturally when we're done.
+ let lastReported = 0;
+ const progressInterval = setInterval(() => {
+ if (ac.signal.aborted) return clearInterval(progressInterval);
+ // We can't read the exact attempt count here — just emit elapsed time.
+ sseEvent(res, 'progress', { elapsed: Date.now() });
+ }, 2_000);
+
+ try {
+ const result = await generateVanityKey({
+ suffix,
+ prefix,
+ caseSensitive,
+ maxAttempts,
+ signal: ac.signal,
+ });
+
+ clearTimeout(timeout);
+ clearInterval(progressInterval);
+
+ if (!result) {
+ sseEvent(res, 'error', {
+ error: 'max_attempts_reached',
+ error_description: `no match found in ${maxAttempts} attempts`,
+ });
+ } else {
+ sseEvent(res, 'result', {
+ publicKey: result.publicKey,
+ secretKey: bs58.encode(result.secretKey),
+ attempts: result.attempts,
+ ms: result.ms,
+ });
+ }
+ } catch (err) {
+ clearTimeout(timeout);
+ clearInterval(progressInterval);
+ if (!res.writableEnded) {
+ sseEvent(res, 'error', {
+ error: 'internal_error',
+ error_description: err.message || 'unexpected error',
+ });
+ }
+ } finally {
+ if (!res.writableEnded) res.end();
+ }
+}
diff --git a/api/skills-manifest.js b/api/skills-manifest.js
new file mode 100644
index 000000000..5f0705ac0
--- /dev/null
+++ b/api/skills-manifest.js
@@ -0,0 +1,30 @@
+// GET /api/skills-manifest — machine-readable manifest of agent skills
+
+import { readFileSync } from 'fs';
+import { cors, json, method, wrap } from './_lib/http.js';
+import { buildSkillManifest } from '../src/skill-manifest.js';
+import { AgentSkills } from '../src/agent-skills.js';
+
+const { version } = JSON.parse(
+ readFileSync(new URL('../package.json', import.meta.url), 'utf8'),
+);
+
+const _noop = () => {};
+const _stub = { emit: _noop, on: _noop, off: _noop, add: _noop, query: () => [] };
+const _skills = new AgentSkills(_stub, _stub);
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ return json(
+ res,
+ 200,
+ buildSkillManifest({
+ agentId: '3d-agent',
+ version,
+ skills: _skills.list(),
+ }),
+ { 'cache-control': 'public, max-age=60' },
+ );
+});
diff --git a/api/social/sentiment.js b/api/social/sentiment.js
new file mode 100644
index 000000000..a57957b87
--- /dev/null
+++ b/api/social/sentiment.js
@@ -0,0 +1,43 @@
+// POST /api/social/sentiment
+// body: { posts: [{ id?, ts?, text, author? }, ...] }
+// → { score, posPct, negPct, neuPct, count, examples }
+// No auth required. Rate-limited by IP.
+
+import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { z } from 'zod';
+
+const postSchema = z.object({
+ id: z.string().optional(),
+ ts: z.union([z.string(), z.number()]).optional(),
+ text: z.string(),
+ author: z.string().optional(),
+});
+
+const bodySchema = z.object({
+ posts: z.array(postSchema).min(1).max(500),
+});
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: false })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const rl = await limits.mcpIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ let raw;
+ try {
+ raw = await readJson(req);
+ } catch {
+ return error(res, 400, 'validation_error', 'invalid json');
+ }
+
+ const parsed = bodySchema.safeParse(raw);
+ if (!parsed.success) {
+ return error(res, 400, 'validation_error', parsed.error.issues[0]?.message ?? 'invalid body');
+ }
+
+ const { scoreSentiment } = await import('../../src/social/sentiment.js');
+ const result = scoreSentiment(parsed.data.posts);
+ return json(res, 200, result);
+});
diff --git a/docs/pump-fun-skills-audit.md b/docs/pump-fun-skills-audit.md
new file mode 100644
index 000000000..c4d3bd2e4
--- /dev/null
+++ b/docs/pump-fun-skills-audit.md
@@ -0,0 +1,22 @@
+# pump-fun-skills Audit
+
+Source: https://github.com/nirholas/pump-fun-skills
+Audited: 2026-04-29
+
+The upstream repo contains one skill domain: **tokenized-agents** (`tokenized-agents/SKILL.md`).
+The SKILL.md describes three key SDK operations from `@pump-fun/agent-payments-sdk`.
+
+## Skill table
+
+| name | description | status | local file |
+| :--- | :--- | :--- | :--- |
+| `pumpfun-accept-payment` (buildAcceptPaymentInstructions) | Build Solana instructions to accept an agent payment on-chain. Serialises unsigned tx for browser wallet to sign. | superseded | [src/agent-skills-pumpfun.js](../src/agent-skills-pumpfun.js) — `pumpfun-accept-payment` covers the browser-wallet flow; `pumpfun-self-pay` (action: `accept`) covers the server-side flow |
+| `pumpfun-verify-payment` (validateInvoicePayment) | Server-side verification that a payment was received on-chain. Queries Pump HTTP API with RPC fallback; returns `verified: true/false`. Must match all seven invoice fields exactly. | **missing → ported** | [src/agent-skills-pumpfun.js](../src/agent-skills-pumpfun.js) |
+| `pumpfun-invoice-pda` (getInvoiceIdPDA) | Derive the deterministic on-chain Invoice ID PDA from invoice parameters. Useful for pre-checking duplicate invoices before building the payment tx. | **missing → ported** | [src/agent-skills-pumpfun.js](../src/agent-skills-pumpfun.js) |
+| wallet-integration (WALLET_INTEGRATION.md) | React wallet adapter setup (WalletProvider, WalletMultiButton, useWallet hook). | skipped: UI only — frontend React component scaffolding, not an agent skill | |
+
+## Notes
+
+- No new npm dependencies were required; both ported skills use `@pump-fun/agent-payments-sdk` already present in `node_modules`.
+- The upstream repo has no skills that require external paid APIs beyond what is already in-tree.
+- `pumpfun-self-pay` with `action: 'balances'` partially overlaps with the upstream description of reading vault state, but that was already present before this audit.
diff --git a/prompts/repo-integrations/02-pumpkit-claim-monitor.md b/prompts/repo-integrations/02-pumpkit-claim-monitor.md
new file mode 100644
index 000000000..585d84f79
--- /dev/null
+++ b/prompts/repo-integrations/02-pumpkit-claim-monitor.md
@@ -0,0 +1,65 @@
+# 02 — Pumpkit claim-monitor as agent skill
+
+**Branch:** `feat/pumpkit-claim-monitor`
+**Source repo:** https://github.com/nirholas/pumpkit
+**One PR. Standalone. No other prompt is required to be shipped first.**
+
+## Why it matters
+
+Pump.fun creators can claim social fees. Pumpkit's claim-monitor surfaces these events in real time. Adding it as a 3D-agent skill means a user can say "tell me when this creator claims fees" and the agent does it — useful for KOL/whale tracking and giving the avatar something timely to react to.
+
+## Read these first
+
+| File | Why |
+| :--- | :--- |
+| [src/agent-skills-pumpfun-watch.js](../../src/agent-skills-pumpfun-watch.js) | Existing watch skills — match this shape. |
+| [src/agent-skills-pumpfun.js](../../src/agent-skills-pumpfun.js) | Skill registration pattern. |
+| [api/pump-fun-mcp.js](../../api/pump-fun-mcp.js) | MCP tool registration pattern. |
+| [src/pump/agent-token-widget.js](../../src/pump/agent-token-widget.js) | Existing pump-token surface in the 3D agent. |
+| https://github.com/nirholas/pumpkit (claim-monitor module) | Logic to port. Read README + claim-monitor source. |
+
+## Build this
+
+1. Add `src/pump/pumpkit-claims.js` exporting:
+ ```js
+ export async function watchClaims({ creator, sinceTs, onClaim, signal })
+ // Subscribes to pump.fun fee-claim events for `creator` wallet.
+ // Calls onClaim({ signature, mint, lamports, ts }) for each claim observed.
+ // Aborts when AbortSignal is triggered.
+
+ export async function listRecentClaims({ creator, limit = 20 })
+ // Returns the last N claim events for the creator wallet, newest first.
+ ```
+2. Register a skill `pumpfun.watchClaims` in [src/agent-skills-pumpfun-watch.js](../../src/agent-skills-pumpfun-watch.js):
+ - Args: `{ creator: string, durationMs?: number }` (default 5 min, max 30 min)
+ - Streams claim events into chat using the existing message-emit pattern.
+3. Register a skill `pumpfun.listClaims` (one-shot) in [src/agent-skills-pumpfun.js](../../src/agent-skills-pumpfun.js) with args `{ creator: string, limit?: number }`.
+4. Register MCP tools `pumpfun_watch_claims` (request/response, returns batch after durationMs) and `pumpfun_list_claims` in [api/pump-fun-mcp.js](../../api/pump-fun-mcp.js).
+5. Add a vitest test `tests/pumpkit-claims.test.js` mocking the claim source and asserting both skills behave correctly.
+
+## Out of scope
+
+- Telegram or webhook delivery (separate prompts).
+- DB persistence of claim history.
+- UI changes — strictly skill + MCP tool surfaces.
+
+## Acceptance
+
+- [ ] `node --check src/pump/pumpkit-claims.js` passes.
+- [ ] `npx vitest run tests/pumpkit-claims.test.js` passes.
+- [ ] Both skills callable from the agent.
+- [ ] Both MCP tools appear in `tools/list`.
+- [ ] `npx vite build` passes.
+
+## Test plan
+
+1. `npx vitest run tests/pumpkit-claims.test.js` — green.
+2. Pick a known active pump.fun creator wallet. Run the `pumpfun.listClaims` skill against it; confirm at least one historical claim returns.
+3. JSON-RPC `tools/call` for `pumpfun_list_claims` against the same wallet; same expected result.
+
+## Reporting
+
+- Shipped: …
+- Skipped: …
+- Broke / regressions: …
+- Unrelated bugs noticed: …
diff --git a/prompts/repo-integrations/03-pumpkit-channel-feed.md b/prompts/repo-integrations/03-pumpkit-channel-feed.md
new file mode 100644
index 000000000..a7fad55b4
--- /dev/null
+++ b/prompts/repo-integrations/03-pumpkit-channel-feed.md
@@ -0,0 +1,59 @@
+# 03 — Pumpkit channel-feed ingest
+
+**Branch:** `feat/pumpkit-channel-feed`
+**Source repo:** https://github.com/nirholas/pumpkit
+**One PR. Standalone. No other prompt is required to be shipped first.**
+
+## Why it matters
+
+Pumpkit's channel-feed lets a Telegram channel publish curated pump.fun signals. We want the same firehose available as an HTTP endpoint so the 3D agent (and any embed) can consume it without a Telegram dependency.
+
+## Read these first
+
+| File | Why |
+| :--- | :--- |
+| [api/pump-fun-mcp.js](../../api/pump-fun-mcp.js) | Existing API style for pump endpoints. |
+| [api/pump/](../../api/pump/) | Existing pump-related HTTP handlers — match style and error shape. |
+| [src/agent-skills-pumpfun.js](../../src/agent-skills-pumpfun.js) | Skill registration. |
+| https://github.com/nirholas/pumpkit (channel-feed module) | Logic to port. Read README + channel-feed source. |
+
+## Build this
+
+1. Add `api/pump/channel-feed.js` — an HTTP GET endpoint that returns a normalized JSON array of recent pump.fun signals (new mints + first whale buys + creator claims, deduped by signature, newest first):
+ ```js
+ // GET /api/pump/channel-feed?limit=50&kinds=mint,whale,claim
+ // → { items: [{ kind, mint, signature, ts, summary, refs }] }
+ ```
+2. Add `src/pump/channel-feed.js` exporting `fetchChannelFeed({ limit, kinds })` for client/server reuse. The HTTP endpoint is a thin wrapper.
+3. Register a skill `pumpfun.channelFeed` in [src/agent-skills-pumpfun.js](../../src/agent-skills-pumpfun.js) that calls `fetchChannelFeed` and returns a digest the LLM can summarize.
+4. Add a vitest test `tests/pump-channel-feed.test.js` that:
+ - Mocks the upstream sources (mint stream, whale source, claim source).
+ - Asserts dedupe-by-signature works.
+ - Asserts `kinds=mint,claim` excludes whale events.
+
+## Out of scope
+
+- A Telegram bridge (use an existing pumpkit deployment for that).
+- Persisting the feed; this endpoint is read-through.
+- Auth / rate limiting beyond what other pump endpoints already do.
+
+## Acceptance
+
+- [ ] `node --check api/pump/channel-feed.js` and `node --check src/pump/channel-feed.js` pass.
+- [ ] `npx vitest run tests/pump-channel-feed.test.js` passes.
+- [ ] `curl 'http://localhost:3000/api/pump/channel-feed?limit=10'` returns a valid JSON array.
+- [ ] Skill `pumpfun.channelFeed` appears in `getSkills()` output.
+- [ ] `npx vite build` passes.
+
+## Test plan
+
+1. Boot dev server. Hit the endpoint with `limit=10`, then `kinds=mint`, then `kinds=mint,whale,claim`.
+2. Confirm dedupe by re-running and checking each signature appears once.
+3. Call the skill from the agent and confirm a coherent digest comes back.
+
+## Reporting
+
+- Shipped: …
+- Skipped: …
+- Broke / regressions: …
+- Unrelated bugs noticed: …
diff --git a/prompts/repo-integrations/04-pumpkit-telegram-delivery.md b/prompts/repo-integrations/04-pumpkit-telegram-delivery.md
new file mode 100644
index 000000000..2edad497b
--- /dev/null
+++ b/prompts/repo-integrations/04-pumpkit-telegram-delivery.md
@@ -0,0 +1,63 @@
+# 04 — Pumpkit Telegram delivery channel
+
+**Branch:** `feat/pumpkit-telegram-delivery`
+**Source repo:** https://github.com/nirholas/pumpkit
+**One PR. Standalone. No other prompt is required to be shipped first.**
+
+## Why it matters
+
+Some users want pump.fun signals (whales, claims, new mints, graduations) pushed to Telegram. Pumpkit ships this as a bot. We want a server-side delivery adapter the platform can target, so any agent skill or scheduled job can fan out a signal to a chat.
+
+## Read these first
+
+| File | Why |
+| :--- | :--- |
+| [services/pump-graduations/](../../services/pump-graduations/) | Existing pump signal source — your delivery code must consume one of these. |
+| [api/pump-fun-mcp.js](../../api/pump-fun-mcp.js) | API conventions. |
+| [scripts/pumpfun-lifecycle-smoke.js](../../scripts/pumpfun-lifecycle-smoke.js) | Smoke pattern to mirror for delivery testing. |
+| https://github.com/nirholas/pumpkit (Telegram bot module) | Reference for message formatting + bot wiring. |
+
+## Build this
+
+1. Add `src/pump/telegram-delivery.js` exporting:
+ ```js
+ export async function sendTelegramSignal({ botToken, chatId, signal })
+ // signal: { kind: 'mint'|'whale'|'claim'|'graduation', mint, summary, refs?, ts }
+ // Formats a Markdown message and POSTs to https://api.telegram.org/bot<token>/sendMessage
+ // Returns { ok, messageId } | throws on non-2xx.
+ ```
+2. Add `api/pump/deliver-telegram.js` — POST endpoint:
+ ```js
+ // POST /api/pump/deliver-telegram
+ // body: { chatId, signal } (botToken comes from env TELEGRAM_BOT_TOKEN)
+ // → { ok, messageId }
+ ```
+ Reject if `TELEGRAM_BOT_TOKEN` is not set or `chatId` is missing.
+3. Add a vitest test `tests/pump-telegram-delivery.test.js` that mocks `fetch` and asserts the correct URL, method, body, and parse-mode are used.
+4. Document the env var `TELEGRAM_BOT_TOKEN` at the top of `src/pump/telegram-delivery.js` in a single-line comment.
+
+## Out of scope
+
+- A persistent subscription / queue model. Delivery is request-driven only.
+- Managing channels or chat membership.
+- Inbound messages from Telegram (no webhook).
+- Scheduling — the caller decides when to deliver.
+
+## Acceptance
+
+- [ ] `node --check` passes for both new files.
+- [ ] `npx vitest run tests/pump-telegram-delivery.test.js` passes.
+- [ ] Endpoint 400s without `chatId`, 500s without bot token, 200s on success.
+- [ ] `npx vite build` passes.
+
+## Test plan
+
+1. Set `TELEGRAM_BOT_TOKEN` to a sandbox bot. POST a sample signal to a test chat. Verify the message arrives formatted correctly.
+2. Unset the env var; confirm the endpoint 500s with a clear message.
+
+## Reporting
+
+- Shipped: …
+- Skipped: …
+- Broke / regressions: …
+- Unrelated bugs noticed: …
diff --git a/prompts/repo-integrations/05-pumpfun-claims-bot-feed.md b/prompts/repo-integrations/05-pumpfun-claims-bot-feed.md
new file mode 100644
index 000000000..f332d3b88
--- /dev/null
+++ b/prompts/repo-integrations/05-pumpfun-claims-bot-feed.md
@@ -0,0 +1,62 @@
+# 05 — pumpfun-claims-bot first-time-claim feed
+
+**Branch:** `feat/first-claim-feed`
+**Source repo:** https://github.com/nirholas/pumpfun-claims-bot
+**One PR. Standalone. No other prompt is required to be shipped first.**
+
+## Why it matters
+
+The pumpfun-claims-bot repo specifically tracks **first-time creator fee claims** — a stronger signal than "any claim" because it correlates with the creator finally taking money off the table. Surfacing this as an HTTP feed + agent skill gives the 3D agent a clean trigger for "this creator just cashed out for the first time" reactions.
+
+## Read these first
+
+| File | Why |
+| :--- | :--- |
+| [src/agent-skills-pumpfun-watch.js](../../src/agent-skills-pumpfun-watch.js) | Watch skill conventions. |
+| [src/agent-skills-pumpfun.js](../../src/agent-skills-pumpfun.js) | One-shot skill conventions. |
+| [api/pump-fun-mcp.js](../../api/pump-fun-mcp.js) | MCP tool conventions. |
+| https://github.com/nirholas/pumpfun-claims-bot | Reference. Read README + main source — the dedupe logic for "first claim per creator" is the core value. |
+
+## Build this
+
+1. Add `src/pump/first-claims.js` exporting:
+ ```js
+ export async function fetchFirstClaims({ sinceTs, limit = 50 })
+ // Returns first-ever fee-claim events per creator, newest first, since `sinceTs`.
+ // Each item: { creator, mint, signature, lamports, ts }.
+ // Dedupe rule: if a creator has any prior claim before sinceTs, exclude.
+ ```
+2. Add `api/pump/first-claims.js` — GET endpoint wrapping the function:
+ ```js
+ // GET /api/pump/first-claims?sinceMinutes=60&limit=50
+ // → { items: [...] }
+ ```
+3. Register a skill `pumpfun.firstClaims` in [src/agent-skills-pumpfun.js](../../src/agent-skills-pumpfun.js) calling `fetchFirstClaims`.
+4. Register an MCP tool `pumpfun_first_claims` in [api/pump-fun-mcp.js](../../api/pump-fun-mcp.js).
+5. Add `tests/pump-first-claims.test.js` asserting the dedupe rule rejects creators with any prior claim.
+
+## Out of scope
+
+- Telegram delivery (that's prompt 04).
+- DB-backed state — keep dedupe in-memory or against a single RPC sweep per request.
+- UI changes.
+
+## Acceptance
+
+- [ ] `node --check` passes for new files.
+- [ ] `npx vitest run tests/pump-first-claims.test.js` passes.
+- [ ] Skill + MCP tool callable.
+- [ ] `npx vite build` passes.
+
+## Test plan
+
+1. Hit `/api/pump/first-claims?sinceMinutes=240&limit=20`; confirm valid items.
+2. Re-hit it within seconds; same items return (idempotent).
+3. Call the agent skill; confirm a useful summary.
+
+## Reporting
+
+- Shipped: …
+- Skipped: …
+- Broke / regressions: …
+- Unrelated bugs noticed: …
diff --git a/prompts/repo-integrations/06-claim-alerts-agent-home.md b/prompts/repo-integrations/06-claim-alerts-agent-home.md
new file mode 100644
index 000000000..497a087be
--- /dev/null
+++ b/prompts/repo-integrations/06-claim-alerts-agent-home.md
@@ -0,0 +1,56 @@
+# 06 — Surface claim alerts in agent-home pump panel
+
+**Branch:** `feat/claim-alerts-agent-home`
+**Source repo:** https://github.com/nirholas/pumpfun-claims-bot (signal source)
+**One PR. Standalone. No other prompt is required to be shipped first.**
+
+## Why it matters
+
+The agent-home page already has a pump.fun module ([src/agent-home-pumpfun.js](../../src/agent-home-pumpfun.js)). Showing live claim events there gives visitors something timely to watch and reinforces the agent's "alive" feel. This prompt adds a small claims panel — it does not depend on prompt 05; it queries the upstream RPC directly.
+
+## Read these first
+
+| File | Why |
+| :--- | :--- |
+| [src/agent-home-pumpfun.js](../../src/agent-home-pumpfun.js) | Existing pump module — your new panel renders next to it. |
+| [src/agent-home.js](../../src/agent-home.js) | Top-level home composer — registers modules. |
+| [src/pump/agent-token-widget.js](../../src/pump/agent-token-widget.js) | Style + DOM patterns to mirror. |
+| [src/pump/pump-modals.js](../../src/pump/pump-modals.js) | Modal/list rendering patterns. |
+
+## Build this
+
+1. Add `src/agent-home-claims.js` exporting a `mountClaimsPanel(rootEl, { creator, intervalMs = 30_000 })`:
+ - Renders a minimal list of last 10 claim events for `creator`, polling every `intervalMs`.
+ - Each row: timestamp, mint, SOL amount, link to Solscan tx.
+ - Empty state: "No recent fee claims".
+ - Cleanup function returned for unmount.
+2. Wire it into [src/agent-home.js](../../src/agent-home.js) so that, when the agent has a `creatorWallet` set in its profile, the claims panel appears beneath the existing pump module.
+3. If no `creatorWallet` is set, render nothing — do not show empty UI.
+4. Add minimal CSS scoped to `.three-ws-claims-panel` (inline style block or extend an existing stylesheet). Match the existing pump-module visual weight.
+
+## Out of scope
+
+- Editing the agent profile to set `creatorWallet` (that lives in the studio).
+- WebSocket subscriptions — polling is fine for v1.
+- Claim history pagination beyond last 10.
+
+## Acceptance
+
+- [ ] `node --check src/agent-home-claims.js` passes.
+- [ ] Panel mounts when `creatorWallet` is set on the agent profile object.
+- [ ] Panel is absent when `creatorWallet` is undefined or empty.
+- [ ] Cleanup function clears the polling interval.
+- [ ] `npx vite build` passes.
+
+## Test plan
+
+1. `npm run dev`. Open `/agent/<id>` for an agent with `creatorWallet` set to a known active pump.fun creator. Confirm panel renders and updates.
+2. Open the same page for an agent without `creatorWallet`. Confirm no panel appears.
+3. Navigate away and back; confirm no duplicate panels and no console errors.
+
+## Reporting
+
+- Shipped: …
+- Skipped: …
+- Broke / regressions: …
+- Unrelated bugs noticed: …
diff --git a/prompts/repo-integrations/07-cf-workers-mcp-mirror.md b/prompts/repo-integrations/07-cf-workers-mcp-mirror.md
new file mode 100644
index 000000000..d38aacc08
--- /dev/null
+++ b/prompts/repo-integrations/07-cf-workers-mcp-mirror.md
@@ -0,0 +1,54 @@
+# 07 — Cloudflare Workers MCP transport for pump.fun
+
+**Branch:** `feat/cf-workers-mcp-mirror`
+**Source repo:** https://github.com/nirholas/pump-fun-workers
+**One PR. Standalone. No other prompt is required to be shipped first.**
+
+## Why it matters
+
+Today `api/pump-fun-mcp.js` runs as a Vercel function. The pump-fun-workers repo is a Cloudflare Worker that implements the MCP Streamable HTTP transport. Adding a Workers-deployable mirror gives us edge-deploy parity (sub-50ms cold starts, region-local) without losing the Vercel deployment.
+
+## Read these first
+
+| File | Why |
+| :--- | :--- |
+| [api/pump-fun-mcp.js](../../api/pump-fun-mcp.js) | The Vercel implementation we're mirroring. |
+| [api/mcp.js](../../api/mcp.js) | Base MCP framing. |
+| [vercel.json](../../vercel.json) | Routing for the existing Vercel endpoint — do not break. |
+| https://github.com/nirholas/pump-fun-workers | Reference implementation; copy the streaming response shape. |
+
+## Build this
+
+1. Add `workers/pump-fun-mcp/` with:
+ - `worker.js` — fetch handler implementing the MCP Streamable HTTP transport for the same tool set exposed in [api/pump-fun-mcp.js](../../api/pump-fun-mcp.js). Reuse the tool registration logic by importing pure-JS helpers from `src/pump/` only — no Node-only deps.
+ - `wrangler.toml` — minimal config with `name = "pump-fun-mcp"`, `main = "worker.js"`, `compatibility_date = "2025-01-15"`.
+ - `README.md` — one-liner: "Mirror of `/api/pump-fun-mcp`. Deploy: `wrangler deploy`."
+2. Extract any shared, runtime-agnostic logic out of [api/pump-fun-mcp.js](../../api/pump-fun-mcp.js) into `src/pump/mcp-tools.js` so both runtimes call the same code. Both endpoints must continue to work.
+3. Add `tests/pump-mcp-tools.test.js` (or extend the existing one) asserting the tool list returned from `src/pump/mcp-tools.js` matches the legacy Vercel handler's response.
+4. Document deployment in [docs/](../../docs/) by adding `docs/pump-fun-mcp-edge.md` (one new doc file is fine).
+
+## Out of scope
+
+- Migrating Vercel callers off `/api/pump-fun-mcp` — both must keep working.
+- Auth / rate limiting beyond what the Vercel handler does.
+- A custom domain — leave that to the user's wrangler config.
+
+## Acceptance
+
+- [ ] `node --check workers/pump-fun-mcp/worker.js` passes.
+- [ ] Existing tests for pump-fun-mcp still pass (`npx vitest run tests/pumpfun-mcp.test.js tests/pumpfun-mcp-tools.test.js`).
+- [ ] New test asserts tool-list parity between runtimes.
+- [ ] Vercel endpoint behavior unchanged (eyeball test: a tools/list curl returns the same JSON as before).
+- [ ] `npx vite build` passes.
+
+## Test plan
+
+1. `npx wrangler dev workers/pump-fun-mcp/worker.js --local`; curl `http://localhost:8787` with `{"jsonrpc":"2.0","id":1,"method":"tools/list"}` and confirm tools appear.
+2. Call the same JSON-RPC against `http://localhost:3000/api/pump-fun-mcp`; diff the tool lists — they must match.
+
+## Reporting
+
+- Shipped: …
+- Skipped: …
+- Broke / regressions: …
+- Unrelated bugs noticed: …
diff --git a/prompts/repo-integrations/08-pump-fun-skills-port.md b/prompts/repo-integrations/08-pump-fun-skills-port.md
new file mode 100644
index 000000000..4929bc414
--- /dev/null
+++ b/prompts/repo-integrations/08-pump-fun-skills-port.md
@@ -0,0 +1,56 @@
+# 08 — Port missing skills from pump-fun-skills repo
+
+**Branch:** `feat/pump-fun-skills-port`
+**Source repo:** https://github.com/nirholas/pump-fun-skills
+**One PR. Standalone. No other prompt is required to be shipped first.**
+
+## Why it matters
+
+The pump-fun-skills repo is a curated list of pump.fun skills for AI agents. Some are likely already implemented in [src/agent-skills-pumpfun*.js](../../src/) and some are not. Diffing and porting the missing ones increases the agent's pump.fun capability surface without inventing new ideas.
+
+## Read these first
+
+| File | Why |
+| :--- | :--- |
+| [src/agent-skills-pumpfun.js](../../src/agent-skills-pumpfun.js) | Core skill registry. |
+| [src/agent-skills-pumpfun-watch.js](../../src/agent-skills-pumpfun-watch.js) | Streaming/watch skills. |
+| [src/agent-skills-pumpfun-compose.js](../../src/agent-skills-pumpfun-compose.js) | Higher-level composed skills. |
+| [src/agent-skills-pumpfun-autonomous.js](../../src/agent-skills-pumpfun-autonomous.js) | Loop/autonomous skills. |
+| [src/agent-skills-pumpfun-hooks.js](../../src/agent-skills-pumpfun-hooks.js) | Lifecycle hooks. |
+| https://github.com/nirholas/pump-fun-skills | Source list of skills. |
+
+## Build this
+
+1. Audit: enumerate every skill described in pump-fun-skills (read its README + each skill file/manifest). Build a skill-name → "have / missing / superseded" table.
+2. Output the audit as `docs/pump-fun-skills-audit.md` (one new doc file allowed). Columns: `name | description | status (have / missing / superseded) | local file`.
+3. For each skill marked `missing`, port it into the most appropriate file under `src/agent-skills-pumpfun*.js`. Keep the existing registration pattern — do not create a new file unless there are 5+ ported skills with no good home, in which case add `src/agent-skills-pumpfun-ports.js`.
+4. Each ported skill must have:
+ - Args validation matching the existing skills' validation style.
+ - A short LLM-facing description.
+ - One vitest test in `tests/pumpfun-ported-skills.test.js`.
+
+## Out of scope
+
+- Skills that depend on external paid APIs (note them in the audit as `skipped: needs API key`; do not port).
+- UI changes.
+- Adding new dependencies — if a port requires a new package, note it in the audit and skip.
+
+## Acceptance
+
+- [ ] Audit doc lists every upstream skill with a status.
+- [ ] Every `missing` skill is either ported or has a documented reason in the audit.
+- [ ] `npx vitest run tests/pumpfun-ported-skills.test.js` passes (or is empty if none ported).
+- [ ] `npx vite build` passes.
+
+## Test plan
+
+1. Diff the audit against pump-fun-skills' actual list manually; confirm no upstream skill is missed.
+2. Call each ported skill from the agent (or via a unit test) with valid args.
+3. Run the full pumpfun test suite; confirm green.
+
+## Reporting
+
+- Shipped (count + names): …
+- Skipped + reasons: …
+- Broke / regressions: …
+- Unrelated bugs noticed: …
diff --git a/prompts/repo-integrations/09-skill-manifest-export.md b/prompts/repo-integrations/09-skill-manifest-export.md
new file mode 100644
index 000000000..c6a939e04
--- /dev/null
+++ b/prompts/repo-integrations/09-skill-manifest-export.md
@@ -0,0 +1,63 @@
+# 09 — Skill manifest export endpoint
+
+**Branch:** `feat/skill-manifest-export`
+**Source repo:** https://github.com/nirholas/pump-fun-skills (format reference)
+**One PR. Standalone. No other prompt is required to be shipped first.**
+
+## Why it matters
+
+Other agent platforms (LobeHub, ElizaOS, Claude skills) want a machine-readable manifest of what an agent can do. The pump-fun-skills repo describes a manifest format. Exporting our agent's skills in the same format makes our agent portable to those hosts without per-host glue.
+
+## Read these first
+
+| File | Why |
+| :--- | :--- |
+| [src/agent-skills.js](../../src/agent-skills.js) | Top-level skill registry — has the in-memory list. |
+| [src/agent-skills-pumpfun.js](../../src/agent-skills-pumpfun.js) | Per-skill metadata shape. |
+| [api/openapi-json.js](../../api/openapi-json.js) | Existing JSON-served-from-API pattern. |
+| https://github.com/nirholas/pump-fun-skills | Manifest format reference. |
+
+## Build this
+
+1. Add `api/skills-manifest.js` — GET endpoint serving:
+ ```jsonc
+ // GET /api/skills-manifest
+ // → {
+ // "agent": { "id": "<agent-id-or-platform>", "version": "<package.json version>" },
+ // "skills": [
+ // { "name": "pumpfun.listClaims", "description": "...", "args": { "creator": "string", "limit": "number?" } },
+ // ...
+ // ]
+ // }
+ ```
+2. Add `src/skill-manifest.js` exporting `buildSkillManifest({ agentId, version, skills })`. The HTTP endpoint is a thin wrapper that pulls the live skill list.
+3. Reflect each skill's name, description, and arg schema. If a skill lacks a description, omit it (do not invent one) and surface a console.warn during build.
+4. Add `tests/skill-manifest.test.js` asserting:
+ - Output matches the documented JSON shape.
+ - Every registered skill appears in the manifest.
+
+## Out of scope
+
+- Translating to LobeHub-specific or Eliza-specific format (that's a downstream adapter).
+- Auth — manifest is public.
+- Versioning the manifest schema; v1 is implicit.
+
+## Acceptance
+
+- [ ] `node --check api/skills-manifest.js` and `node --check src/skill-manifest.js` pass.
+- [ ] `npx vitest run tests/skill-manifest.test.js` passes.
+- [ ] `curl http://localhost:3000/api/skills-manifest` returns valid JSON with all current skills.
+- [ ] `npx vite build` passes.
+
+## Test plan
+
+1. Boot dev server. Hit `/api/skills-manifest`. Confirm count matches `getSkills().length`.
+2. Add a temporary skill registration in code, restart, re-hit; confirm it appears.
+3. Remove it; re-hit; confirm it's gone.
+
+## Reporting
+
+- Shipped: …
+- Skipped: …
+- Broke / regressions: …
+- Unrelated bugs noticed: …
diff --git a/prompts/repo-integrations/10-pump-swap-quote-skill.md b/prompts/repo-integrations/10-pump-swap-quote-skill.md
new file mode 100644
index 000000000..018e73cf1
--- /dev/null
+++ b/prompts/repo-integrations/10-pump-swap-quote-skill.md
@@ -0,0 +1,56 @@
+# 10 — Pump-swap quote + simulate skill
+
+**Branch:** `feat/pump-swap-quote-skill`
+**Source repo:** https://github.com/nirholas/pump-swap-sdk
+**One PR. Standalone. No other prompt is required to be shipped first.**
+
+## Why it matters
+
+The project already depends on `@pump-fun/pump-swap-sdk` (see [package.json](../../package.json)). The 3D agent has trade/compose skills but no clean "what would a swap of X cost right now?" quote skill. Adding a quote-only skill (no signing, no tx send) lets the LLM answer "is now a good time?" without risk and gives the agent something safe to do during demos.
+
+## Read these first
+
+| File | Why |
+| :--- | :--- |
+| [src/agent-skills-pumpfun.js](../../src/agent-skills-pumpfun.js) | Skill registration. |
+| [src/agent-skills-pumpfun-compose.js](../../src/agent-skills-pumpfun-compose.js) | Existing trade-adjacent compose skills — match style. |
+| [api/pump-fun-mcp.js](../../api/pump-fun-mcp.js) | MCP tool list. |
+| `node_modules/@pump-fun/pump-swap-sdk/` (already installed) | API surface for quoting. |
+
+## Build this
+
+1. Add `src/pump/pump-swap-quote.js` exporting:
+ ```js
+ export async function quoteSwap({ inputMint, outputMint, amountIn, slippageBps = 100 })
+ // Returns { amountOut, priceImpactBps, route, expiresAtMs } using @pump-fun/pump-swap-sdk.
+ // Throws on invalid mints or unreachable RPC.
+ ```
+2. Register a skill `pumpfun.quoteSwap` in [src/agent-skills-pumpfun.js](../../src/agent-skills-pumpfun.js) with the same args.
+3. Register an MCP tool `pumpfun_quote_swap` in [api/pump-fun-mcp.js](../../api/pump-fun-mcp.js).
+4. Add `tests/pump-swap-quote.test.js` mocking the SDK and asserting args are passed through and shape is normalized.
+
+## Out of scope
+
+- Actually executing the swap (signing or sending). This is read-only.
+- Token-list resolution for symbols → mints. Caller passes mint addresses.
+- Persisting quotes.
+
+## Acceptance
+
+- [ ] `node --check src/pump/pump-swap-quote.js` passes.
+- [ ] `npx vitest run tests/pump-swap-quote.test.js` passes.
+- [ ] Skill + MCP tool callable.
+- [ ] `npx vite build` passes.
+
+## Test plan
+
+1. Call the skill with `inputMint = So11111111111111111111111111111111111111112` (wSOL), a known active pump.fun token mint as `outputMint`, `amountIn = 0.01 SOL` worth of lamports. Confirm a non-zero `amountOut`.
+2. Pass garbage mints; confirm a clean error.
+3. Call MCP tool with same args; confirm same result.
+
+## Reporting
+
+- Shipped: …
+- Skipped: …
+- Broke / regressions: …
+- Unrelated bugs noticed: …
diff --git a/prompts/repo-integrations/11-kol-quest-smart-money-widget.md b/prompts/repo-integrations/11-kol-quest-smart-money-widget.md
new file mode 100644
index 000000000..4b4c91d22
--- /dev/null
+++ b/prompts/repo-integrations/11-kol-quest-smart-money-widget.md
@@ -0,0 +1,58 @@
+# 11 — KOL-quest smart money widget
+
+**Branch:** `feat/kol-smart-money-widget`
+**Source repo:** https://github.com/nirholas/kol-quest
+**One PR. Standalone. No other prompt is required to be shipped first.**
+
+## Why it matters
+
+The platform already supports embeddable widgets ([src/widget-types.js](../../src/widget-types.js)). Adding a "smart money" widget that surfaces what KOL/whale wallets are buying — the core feature of kol-quest — gives any embed (3D agent home, third-party site) a live, glanceable signal feed. This is one new widget type, scoped to a single token mint at a time.
+
+## Read these first
+
+| File | Why |
+| :--- | :--- |
+| [src/widget-types.js](../../src/widget-types.js) | Widget type registry — your new type goes here. |
+| [src/element.js](../../src/element.js) | Widget custom-element wiring. |
+| [src/pump/agent-token-widget.js](../../src/pump/agent-token-widget.js) | Closest existing widget pattern. |
+| https://github.com/nirholas/kol-quest | Source for trade-feed + KOL-detection logic to reference. |
+
+## Build this
+
+1. Add a `kol-trades` widget type in [src/widget-types.js](../../src/widget-types.js) with:
+ - Required attribute: `mint`
+ - Optional: `limit` (default 20), `refresh-ms` (default 30000)
+2. Add `src/widgets/kol-trades.js` exporting a `mountKolTradesWidget(rootEl, opts)` that:
+ - Polls a new endpoint `/api/kol/trades?mint=…&limit=…` every `refresh-ms`.
+ - Renders rows: time, side (buy/sell), wallet (truncated, link to Solscan), USD, source-tag (kol / whale / smart-money).
+ - Empty state.
+ - Cleanup on unmount.
+3. Add `api/kol/trades.js` returning recent trades for a mint, joined against a smart-money wallet list (port the wallet-detection rule from kol-quest's README — minimum P&L threshold). The wallet list source can be a stub array in `src/kol/wallets.js` (one new file) — leave a TODO inline if a richer source is desired later.
+4. Add `tests/kol-trades-widget.test.js` asserting the endpoint shape and that the widget renders rows from a mocked fetch.
+
+## Out of scope
+
+- Multi-mint dashboards (one widget = one mint).
+- DB-backed wallet list (stub is fine for v1).
+- Editing the widget visually in the studio (later).
+
+## Acceptance
+
+- [ ] `node --check` passes for new files.
+- [ ] `npx vitest run tests/kol-trades-widget.test.js` passes.
+- [ ] `<three-ws-widget type="kol-trades" mint="<mint>"></three-ws-widget>` renders.
+- [ ] `/api/kol/trades?mint=…` returns valid JSON.
+- [ ] `npx vite build` passes.
+
+## Test plan
+
+1. `npm run dev`. Embed the widget in `embed-test.html`. Confirm rows populate within 30s.
+2. Pass an unknown mint; confirm the empty state.
+3. Stop the dev server during a refresh; confirm no unhandled rejection.
+
+## Reporting
+
+- Shipped: …
+- Skipped: …
+- Broke / regressions: …
+- Unrelated bugs noticed: …
diff --git a/prompts/repo-integrations/12-kol-leaderboard-skill.md b/prompts/repo-integrations/12-kol-leaderboard-skill.md
new file mode 100644
index 000000000..6ff9811f4
--- /dev/null
+++ b/prompts/repo-integrations/12-kol-leaderboard-skill.md
@@ -0,0 +1,63 @@
+# 12 — KOL leaderboard skill + endpoint
+
+**Branch:** `feat/kol-leaderboard`
+**Source repo:** https://github.com/nirholas/kol-quest
+**One PR. Standalone. No other prompt is required to be shipped first.**
+
+## Why it matters
+
+A "who are the top traders right now" leaderboard is useful both as an agent skill ("show me the top 10 KOLs by 7d P&L") and as a public endpoint embedded sites can poll. kol-quest is the reference; this prompt ports the leaderboard surface only.
+
+## Read these first
+
+| File | Why |
+| :--- | :--- |
+| [src/agent-skills-pumpfun.js](../../src/agent-skills-pumpfun.js) | Skill registration. |
+| [api/pump-fun-mcp.js](../../api/pump-fun-mcp.js) | MCP tool registration. |
+| [api/pump/](../../api/pump/) | API style. |
+| https://github.com/nirholas/kol-quest | Reference: leaderboard scoring + ranking logic. |
+
+## Build this
+
+1. Add `src/kol/leaderboard.js` exporting:
+ ```js
+ export async function getLeaderboard({ window = '7d', limit = 25 })
+ // window ∈ '24h' | '7d' | '30d'
+ // Returns [{ wallet, pnlUsd, winRate, trades, rank }] sorted by pnlUsd desc.
+ ```
+2. Add `api/kol/leaderboard.js`:
+ ```js
+ // GET /api/kol/leaderboard?window=7d&limit=25 → { items: [...] }
+ ```
+3. Register skill `kol.leaderboard` in [src/agent-skills-pumpfun.js](../../src/agent-skills-pumpfun.js).
+4. Register MCP tool `kol_leaderboard` in [api/pump-fun-mcp.js](../../api/pump-fun-mcp.js).
+5. Add `tests/kol-leaderboard.test.js` asserting:
+ - Sorted descending by pnlUsd.
+ - `window` is validated (rejects `'1y'`).
+ - `limit` capped at 100.
+
+## Out of scope
+
+- Database-backed history; if no upstream source available, port the kol-quest scoring against a recent on-chain window or a static seed file in `src/kol/seed.json` and document the source choice in code comments.
+- UI changes.
+
+## Acceptance
+
+- [ ] `node --check` passes for new files.
+- [ ] `npx vitest run tests/kol-leaderboard.test.js` passes.
+- [ ] Skill + MCP tool callable.
+- [ ] `/api/kol/leaderboard?window=7d&limit=10` returns 10 items.
+- [ ] `npx vite build` passes.
+
+## Test plan
+
+1. Hit endpoint; confirm response.
+2. Call agent skill; confirm summary.
+3. Pass `window=1y`; confirm 400.
+
+## Reporting
+
+- Shipped: …
+- Skipped: …
+- Broke / regressions: …
+- Unrelated bugs noticed: …
diff --git a/prompts/repo-integrations/13-wallet-pnl-skill.md b/prompts/repo-integrations/13-wallet-pnl-skill.md
new file mode 100644
index 000000000..6f2ecdbf7
--- /dev/null
+++ b/prompts/repo-integrations/13-wallet-pnl-skill.md
@@ -0,0 +1,55 @@
+# 13 — Wallet P&L analytics skill
+
+**Branch:** `feat/wallet-pnl-skill`
+**Source repo:** https://github.com/nirholas/kol-quest
+**One PR. Standalone. No other prompt is required to be shipped first.**
+
+## Why it matters
+
+"How is wallet X doing?" is the most common question users ask about a smart-money wallet. kol-quest implements the P&L math; this prompt ports a single-wallet P&L skill so the 3D agent can answer it directly.
+
+## Read these first
+
+| File | Why |
+| :--- | :--- |
+| [src/agent-skills-pumpfun.js](../../src/agent-skills-pumpfun.js) | Skill registration. |
+| [api/pump-fun-mcp.js](../../api/pump-fun-mcp.js) | MCP tool registration. |
+| https://github.com/nirholas/kol-quest | P&L math reference. |
+
+## Build this
+
+1. Add `src/kol/wallet-pnl.js` exporting:
+ ```js
+ export async function getWalletPnl({ wallet, window = '7d' })
+ // window ∈ '24h' | '7d' | '30d' | 'all'
+ // Returns { wallet, window, realizedUsd, unrealizedUsd, totalUsd, winRate, trades, openPositions: [...] }
+ ```
+2. Register skill `kol.walletPnl` in [src/agent-skills-pumpfun.js](../../src/agent-skills-pumpfun.js).
+3. Register MCP tool `kol_wallet_pnl` in [api/pump-fun-mcp.js](../../api/pump-fun-mcp.js).
+4. Add `tests/kol-wallet-pnl.test.js` mocking trade history and asserting realized vs unrealized math is correct against a known fixture (write a simple FIFO-cost test case).
+
+## Out of scope
+
+- A wallet-PnL widget (UI). Skill + MCP only.
+- Cross-chain — Solana only.
+- Tax accounting / cost-basis edge cases beyond FIFO.
+
+## Acceptance
+
+- [ ] `node --check src/kol/wallet-pnl.js` passes.
+- [ ] `npx vitest run tests/kol-wallet-pnl.test.js` passes.
+- [ ] Skill + MCP tool callable.
+- [ ] `npx vite build` passes.
+
+## Test plan
+
+1. Call the skill against a known active wallet; confirm a coherent number.
+2. Compare to a manual spot-check (one or two trades).
+3. Pass an empty wallet; confirm `realizedUsd === 0` and no error.
+
+## Reporting
+
+- Shipped: …
+- Skipped: …
+- Broke / regressions: …
+- Unrelated bugs noticed: …
diff --git a/prompts/repo-integrations/14-gmgn-smart-wallets-ingest.md b/prompts/repo-integrations/14-gmgn-smart-wallets-ingest.md
new file mode 100644
index 000000000..54da26282
--- /dev/null
+++ b/prompts/repo-integrations/14-gmgn-smart-wallets-ingest.md
@@ -0,0 +1,66 @@
+# 14 — gmgn.ai smart wallets ingest
+
+**Branch:** `feat/gmgn-smart-wallets-ingest`
+**Source repo:** https://github.com/nirholas/scrape-smart-wallets
+**One PR. Standalone. No other prompt is required to be shipped first.**
+
+## Why it matters
+
+scrape-smart-wallets has browser console scripts that extract gmgn.ai's smart-money wallet lists. We want a server-side ingest that converts pasted gmgn JSON dumps into a usable wallet list the agent skills (and any KOL widgets) can read.
+
+## Read these first
+
+| File | Why |
+| :--- | :--- |
+| [api/](../../api/) | API conventions. |
+| [scripts/](../../scripts/) | Where one-shot ingest scripts live. |
+| https://github.com/nirholas/scrape-smart-wallets | Field shapes of gmgn dumps. |
+
+## Build this
+
+1. Add `src/kol/gmgn-parser.js` exporting:
+ ```js
+ export function parseGmgnSmartWallets(rawJson)
+ // Accepts either the gmgn raw API JSON or scrape-smart-wallets' normalized output.
+ // Returns [{ wallet, label?, pnlUsd?, winRate?, source: 'gmgn' }].
+ // Throws if `rawJson` is not recognizable.
+ ```
+2. Add `api/kol/import-gmgn.js` — POST endpoint:
+ ```js
+ // POST /api/kol/import-gmgn
+ // body: { rawJson: <string|object> }
+ // → { imported: <number>, wallets: [...] }
+ ```
+ Persists into `src/kol/wallets.json` (a checked-in JSON file) by merging with existing entries by `wallet` (latest wins). If the file does not exist, create it.
+3. Add a CLI script `scripts/ingest-gmgn.js` that reads a JSON file path and calls `parseGmgnSmartWallets` then writes the merged list to disk:
+ ```bash
+ node scripts/ingest-gmgn.js path/to/gmgn-dump.json
+ ```
+4. Add `tests/gmgn-parser.test.js` with two fixtures (raw gmgn shape, normalized shape) confirming parse output.
+
+## Out of scope
+
+- Scraping gmgn live (cors / TOS). Only ingest pasted dumps.
+- DB-backed persistence; JSON file is fine.
+- A UI for managing the wallet list.
+
+## Acceptance
+
+- [ ] `node --check` passes for new JS.
+- [ ] `npx vitest run tests/gmgn-parser.test.js` passes.
+- [ ] `node scripts/ingest-gmgn.js <fixture>` writes `src/kol/wallets.json`.
+- [ ] Endpoint returns the merged count.
+- [ ] `npx vite build` passes.
+
+## Test plan
+
+1. Save a gmgn dump fixture under `tests/fixtures/gmgn-dump.json`.
+2. Run the CLI; confirm the wallet file appears with expected entries.
+3. POST the same JSON to the endpoint; confirm the count matches.
+
+## Reporting
+
+- Shipped: …
+- Skipped: …
+- Broke / regressions: …
+- Unrelated bugs noticed: …
diff --git a/prompts/repo-integrations/15-radar-signals-skill.md b/prompts/repo-integrations/15-radar-signals-skill.md
new file mode 100644
index 000000000..58d7c75a9
--- /dev/null
+++ b/prompts/repo-integrations/15-radar-signals-skill.md
@@ -0,0 +1,56 @@
+# 15 — gmgn radar-signals agent skill
+
+**Branch:** `feat/radar-signals-skill`
+**Source repo:** https://github.com/nirholas/scrape-smart-wallets
+**One PR. Standalone. No other prompt is required to be shipped first.**
+
+## Why it matters
+
+scrape-smart-wallets surfaces gmgn "radar" signals — early-detection patterns on tokens. Wrapping these as an agent skill lets the LLM say "what's on radar right now?" and get a curated list, even when the user has not pasted a fresh dump.
+
+## Read these first
+
+| File | Why |
+| :--- | :--- |
+| [src/agent-skills-pumpfun.js](../../src/agent-skills-pumpfun.js) | Skill registration. |
+| [api/pump-fun-mcp.js](../../api/pump-fun-mcp.js) | MCP tool registration. |
+| https://github.com/nirholas/scrape-smart-wallets | Reference for radar field shape. |
+
+## Build this
+
+1. Add `src/kol/radar.js` exporting:
+ ```js
+ export async function getRadarSignals({ category = 'pump-fun', limit = 20 })
+ // category ∈ 'pump-fun' | 'new-mints' | 'volume-spike'
+ // Returns [{ mint, name, symbol, signalType, score, ts }] from a JSON file the user can refresh manually.
+ ```
+2. Persist a checked-in fixture `src/kol/radar-fixture.json` with a small representative payload so the skill works without manual setup. Document at the top of `src/kol/radar.js` how to refresh: paste the latest gmgn radar JSON over `radar-fixture.json` (or extend prompt 14's ingest pattern later).
+3. Register skill `kol.radar` in [src/agent-skills-pumpfun.js](../../src/agent-skills-pumpfun.js).
+4. Register MCP tool `kol_radar` in [api/pump-fun-mcp.js](../../api/pump-fun-mcp.js).
+5. Add `tests/kol-radar.test.js` asserting filter by category, limit cap, and stable sort by score desc.
+
+## Out of scope
+
+- Live scraping of gmgn (TOS).
+- DB persistence.
+- UI changes.
+
+## Acceptance
+
+- [ ] `node --check src/kol/radar.js` passes.
+- [ ] `npx vitest run tests/kol-radar.test.js` passes.
+- [ ] Skill + MCP tool callable.
+- [ ] `npx vite build` passes.
+
+## Test plan
+
+1. Call the skill with default args; confirm sorted, capped output.
+2. Pass `category: 'volume-spike'`; confirm only those entries.
+3. Pass `limit: 1000`; confirm capped to 100 (or document the cap inline).
+
+## Reporting
+
+- Shipped: …
+- Skipped: …
+- Broke / regressions: …
+- Unrelated bugs noticed: …
diff --git a/prompts/repo-integrations/16-x-post-price-impact-skill.md b/prompts/repo-integrations/16-x-post-price-impact-skill.md
new file mode 100644
index 000000000..ab6b7b4ec
--- /dev/null
+++ b/prompts/repo-integrations/16-x-post-price-impact-skill.md
@@ -0,0 +1,56 @@
+# 16 — X post → price impact correlation skill
+
+**Branch:** `feat/x-post-price-impact`
+**Source repo:** https://github.com/nirholas/analyze-memecoin-socials
+**One PR. Standalone. No other prompt is required to be shipped first.**
+
+## Why it matters
+
+analyze-memecoin-socials correlates X (Twitter) posts to memecoin price moves. Exposing a single-shot "did this post move the price?" skill lets the 3D agent reason about cause/effect in real-time conversations about tokens.
+
+## Read these first
+
+| File | Why |
+| :--- | :--- |
+| [src/agent-skills-pumpfun.js](../../src/agent-skills-pumpfun.js) | Skill registration. |
+| [api/pump-fun-mcp.js](../../api/pump-fun-mcp.js) | MCP tool registration. |
+| https://github.com/nirholas/analyze-memecoin-socials | Correlation logic + price-fetch shape. |
+
+## Build this
+
+1. Add `src/social/x-post-impact.js` exporting:
+ ```js
+ export async function correlateXPost({ postUrl, mint, windowMin = 30 })
+ // Inputs: an X post URL (or id), the related token mint, and a +/- window in minutes around post time.
+ // Returns { post: { id, ts, author, text }, priceBefore, priceAfter, deltaPct, volBefore, volAfter, deltaVolPct }.
+ ```
+2. Use the existing pump.fun price source already wired in `src/pump/*` for `priceBefore` / `priceAfter` (do not add a new dep). Read post metadata via the X oEmbed endpoint (no API key required) — if oEmbed fails, return `{ post: null, ... }` and still compute the price-impact half.
+3. Register skill `social.xPostImpact` in [src/agent-skills-pumpfun.js](../../src/agent-skills-pumpfun.js).
+4. Register MCP tool `social_x_post_impact` in [api/pump-fun-mcp.js](../../api/pump-fun-mcp.js).
+5. Add `tests/x-post-impact.test.js` mocking fetch and asserting deltaPct math is correct.
+
+## Out of scope
+
+- Bulk historical analysis.
+- Twitter/X API auth — oEmbed only.
+- Persisting analysis results.
+
+## Acceptance
+
+- [ ] `node --check src/social/x-post-impact.js` passes.
+- [ ] `npx vitest run tests/x-post-impact.test.js` passes.
+- [ ] Skill + MCP tool callable.
+- [ ] `npx vite build` passes.
+
+## Test plan
+
+1. Pass a real recent post URL + a real mint; confirm a sensible delta.
+2. Pass an invalid URL; confirm graceful fallback (post=null, prices still computed).
+3. Pass an unknown mint; confirm a clean error.
+
+## Reporting
+
+- Shipped: …
+- Skipped: …
+- Broke / regressions: …
+- Unrelated bugs noticed: …
diff --git a/prompts/repo-integrations/17-cashtag-sentiment-skill.md b/prompts/repo-integrations/17-cashtag-sentiment-skill.md
new file mode 100644
index 000000000..373e7abcf
--- /dev/null
+++ b/prompts/repo-integrations/17-cashtag-sentiment-skill.md
@@ -0,0 +1,65 @@
+# 17 — Cashtag sentiment scoring skill
+
+**Branch:** `feat/cashtag-sentiment`
+**Source repo:** https://github.com/nirholas/analyze-memecoin-socials
+**One PR. Standalone. No other prompt is required to be shipped first.**
+
+## Why it matters
+
+analyze-memecoin-socials includes browser-side scraping for cashtag posts. We want a server-side skill that, given a cashtag (e.g. `$WIF`) or token symbol, returns a quick sentiment digest the agent can quote in chat. Because Twitter/X scraping has TOS issues, the v1 reads from a **pasted-in JSON dump** (same pattern as prompt 14/15) and computes scoring locally.
+
+## Read these first
+
+| File | Why |
+| :--- | :--- |
+| [src/agent-skills-pumpfun.js](../../src/agent-skills-pumpfun.js) | Skill registration. |
+| [api/pump-fun-mcp.js](../../api/pump-fun-mcp.js) | MCP tool registration. |
+| https://github.com/nirholas/analyze-memecoin-socials | Cashtag scraping + scoring reference. |
+
+## Build this
+
+1. Add `src/social/sentiment.js` exporting:
+ ```js
+ export function scoreSentiment(posts)
+ // posts: [{ id, ts, text, author }]
+ // Returns { score: -1..1, posPct, negPct, neuPct, count, examples: { pos: [...], neg: [...] } }.
+ // Use a deterministic lexicon (positive words / negative words) committed to src/social/lexicon.json.
+ // No external NLP API.
+ ```
+2. Add `api/social/sentiment.js` POST endpoint:
+ ```js
+ // POST /api/social/sentiment
+ // body: { posts: [...] }
+ // → { score: ..., posPct: ..., ... }
+ ```
+3. Register a skill `social.cashtagSentiment` in [src/agent-skills-pumpfun.js](../../src/agent-skills-pumpfun.js) that accepts `{ posts }` directly (caller passes them in — could be a pasted screenshot transcript or another tool's output).
+4. Register MCP tool `social_cashtag_sentiment`.
+5. Add `tests/sentiment.test.js` asserting:
+ - All-positive sample → score > 0.5.
+ - All-negative → score < -0.5.
+ - Mixed → score near 0.
+
+## Out of scope
+
+- Live X scraping.
+- Author weighting / follower count weighting (later).
+- Persisting analyses.
+
+## Acceptance
+
+- [ ] `node --check` passes for new files.
+- [ ] `npx vitest run tests/sentiment.test.js` passes.
+- [ ] Skill + MCP tool callable.
+- [ ] `npx vite build` passes.
+
+## Test plan
+
+1. Submit a hand-written batch of 10 posts; eyeball the score for sanity.
+2. Confirm endpoint and skill agree on the same input.
+
+## Reporting
+
+- Shipped: …
+- Skipped: …
+- Broke / regressions: …
+- Unrelated bugs noticed: …
diff --git a/prompts/repo-integrations/18-realtime-trade-visualizer-widget.md b/prompts/repo-integrations/18-realtime-trade-visualizer-widget.md
new file mode 100644
index 000000000..3c0b1e8c4
--- /dev/null
+++ b/prompts/repo-integrations/18-realtime-trade-visualizer-widget.md
@@ -0,0 +1,55 @@
+# 18 — Real-time trade visualizer widget
+
+**Branch:** `feat/realtime-trade-viz-widget`
+**Source repo:** https://github.com/nirholas/visualize-web3-realtime
+**One PR. Standalone. No other prompt is required to be shipped first.**
+
+## Why it matters
+
+visualize-web3-realtime renders pump.fun / Raydium / Uniswap / PancakeSwap trades as physics-based particle nodes. Adding a `live-trades-canvas` widget type lets any embed show that visualization scoped to a single mint — a big visual upgrade over a text feed.
+
+## Read these first
+
+| File | Why |
+| :--- | :--- |
+| [src/widget-types.js](../../src/widget-types.js) | Widget type registry. |
+| [src/element.js](../../src/element.js) | Custom-element wiring. |
+| [src/pump/agent-token-widget.js](../../src/pump/agent-token-widget.js) | Closest existing widget. |
+| https://github.com/nirholas/visualize-web3-realtime | Particle physics + canvas reference. |
+
+## Build this
+
+1. Register a new widget type `live-trades-canvas` in [src/widget-types.js](../../src/widget-types.js):
+ - Required attribute: `mint`
+ - Optional: `chain` (default `solana`, accepts `solana` only in v1), `bg` (color hex), `min-usd` (default 0)
+2. Add `src/widgets/live-trades-canvas.js` exporting `mountLiveTradesCanvas(rootEl, opts)`:
+ - Subscribes to pump.fun trades for `mint` (reuse the existing trade subscription in `src/pump/*` — don't add a new RPC dep).
+ - Each trade pops in as a particle (size ~ log(USD)), buys = green, sells = red, fades out over 5–10s.
+ - Cleanup detaches subscription + cancels animation frame.
+3. Add `tests/live-trades-canvas.test.js` rendering the widget with a mocked subscription source and asserting particles are added/removed correctly (test the data layer, not pixel output).
+
+## Out of scope
+
+- Multi-chain support (Solana only v1).
+- 3D rendering / Three.js — 2D canvas is enough.
+- Particle physics tuning beyond a single tasteful default.
+
+## Acceptance
+
+- [ ] `node --check src/widgets/live-trades-canvas.js` passes.
+- [ ] `npx vitest run tests/live-trades-canvas.test.js` passes.
+- [ ] `<three-ws-widget type="live-trades-canvas" mint="<mint>"></three-ws-widget>` renders a moving canvas in `embed-test.html`.
+- [ ] `npx vite build` passes.
+
+## Test plan
+
+1. Add the widget tag to `embed-test.html` against a known active mint. Confirm particles appear.
+2. Set `min-usd="500"`. Confirm fewer particles.
+3. Move browser tab to background; confirm no runaway CPU when re-foregrounded.
+
+## Reporting
+
+- Shipped: …
+- Skipped: …
+- Broke / regressions: …
+- Unrelated bugs noticed: …
diff --git a/prompts/repo-integrations/19-trades-into-3d-scene.md b/prompts/repo-integrations/19-trades-into-3d-scene.md
new file mode 100644
index 000000000..f74872e08
--- /dev/null
+++ b/prompts/repo-integrations/19-trades-into-3d-scene.md
@@ -0,0 +1,63 @@
+# 19 — Wire pump.fun trades into 3D agent scene
+
+**Branch:** `feat/trades-into-3d-scene`
+**Source repo:** https://github.com/nirholas/visualize-web3-realtime
+**One PR. Standalone. No other prompt is required to be shipped first.**
+
+## Why it matters
+
+The 3D agent is the centerpiece of this platform. Right now the avatar reacts to chat. Letting it react to pump.fun trade events — flinch on a sell-off, smile on a green candle — makes the avatar feel embodied and gives long-tail demos something fun to watch.
+
+## Read these first
+
+| File | Why |
+| :--- | :--- |
+| [src/element.js](../../src/element.js) | Custom-element + scene wiring. |
+| [src/agent-skills-pumpfun-hooks.js](../../src/agent-skills-pumpfun-hooks.js) | Existing lifecycle hooks — your hook joins this set. |
+| [src/agent-skills-pumpfun-watch.js](../../src/agent-skills-pumpfun-watch.js) | Trade subscription source. |
+| https://github.com/nirholas/visualize-web3-realtime | Reference for trade-event shape. |
+
+## Build this
+
+1. Add `src/pump/trade-reactions.js` exporting:
+ ```js
+ export function attachTradeReactions(agent, { mint, intensity = 1 })
+ // Subscribes to live trades for `mint`. On significant events, calls agent reaction methods:
+ // - large buy → agent.playEmote('cheer')
+ // - large sell → agent.playEmote('flinch')
+ // - graduation → agent.playEmote('celebrate')
+ // Significance threshold: top 10% of trades in a rolling 5-min window.
+ // Returns a detach function.
+ ```
+2. Wire it into [src/element.js](../../src/element.js) so when an agent has a `trackedMint` attribute, reactions auto-attach on connect and detach on disconnect.
+3. If the agent's avatar exposes no matching emote (`cheer` / `flinch` / `celebrate`), fall back to a head-bob via the existing animation system (read `src/element.js` to find the entry point).
+4. Add `tests/trade-reactions.test.js` mocking the trade source and asserting:
+ - Below-threshold trades do not trigger emotes.
+ - Above-threshold trades do.
+ - Detach stops further triggers.
+
+## Out of scope
+
+- Adding new emote files. Use whatever's in the animation gallery.
+- Editing the studio UI to set `trackedMint` (that's a later task).
+- Multi-mint tracking per agent.
+
+## Acceptance
+
+- [ ] `node --check src/pump/trade-reactions.js` passes.
+- [ ] `npx vitest run tests/trade-reactions.test.js` passes.
+- [ ] An agent with `tracked-mint="<mint>"` triggers visible reactions when large trades happen.
+- [ ] `npx vite build` passes.
+
+## Test plan
+
+1. `npm run dev`. Open `agent-page.html` for an agent and add the attribute. Wait for a large trade on a known active mint.
+2. Confirm the avatar emotes (or head-bobs as fallback).
+3. Remove the attribute, refresh, confirm no subscriptions remain (devtools network tab).
+
+## Reporting
+
+- Shipped: …
+- Skipped: …
+- Broke / regressions: …
+- Unrelated bugs noticed: …
diff --git a/prompts/repo-integrations/20-launchpad-ui-port-studio.md b/prompts/repo-integrations/20-launchpad-ui-port-studio.md
new file mode 100644
index 000000000..2237b7215
--- /dev/null
+++ b/prompts/repo-integrations/20-launchpad-ui-port-studio.md
@@ -0,0 +1,56 @@
+# 20 — Port launchpad token-creation UI into studio
+
+**Branch:** `feat/launchpad-ui-studio`
+**Source repo:** https://github.com/nirholas/solana-launchpad-ui
+**One PR. Standalone. No other prompt is required to be shipped first.**
+
+## Why it matters
+
+solana-launchpad-ui is a pump.fun-styled launchpad UI template (dark theme, bonding curves, trade panel, no deps). The 3D-agent character studio is the natural place to add "launch a token for this agent" — currently we have widget code in [src/pump/](../../src/pump/) but no full token-creation flow in the studio.
+
+## Read these first
+
+| File | Why |
+| :--- | :--- |
+| [character-studio/](../../character-studio/) | Studio root; identify where a new "Launch token" tab should live. |
+| [src/pump/agent-token-widget.js](../../src/pump/agent-token-widget.js) | Existing token UI primitives. |
+| [src/pump/pump-modals.js](../../src/pump/pump-modals.js) | Modal patterns. |
+| [public/studio/studio.js](../../public/studio/studio.js) | Studio JS entry. |
+| https://github.com/nirholas/solana-launchpad-ui | Visual reference (HTML/CSS). |
+
+## Build this
+
+1. Add a new "Launch" panel to the character studio. The panel:
+ - Form: token name, symbol, image (file upload), description, initial buy SOL amount, fee tier.
+ - Bonding-curve visual (port the SVG/canvas chart from solana-launchpad-ui).
+ - Submit button: calls the existing pump.fun create flow (find in [src/pump/](../../src/pump/) — do not invent a new path; if no existing flow, add a TODO and stop the form at console.log).
+2. Style: match the existing studio panels' weight; do not import the launchpad's CSS wholesale — copy only the bonding-curve component styles.
+3. Add `tests/studio-launch-panel.test.js` (jsdom) asserting the form validates required fields and that submit calls the wired handler.
+4. Wire it into [public/studio/studio.js](../../public/studio/studio.js) as a new tab; default tab unchanged.
+
+## Out of scope
+
+- New on-chain logic (use existing pump SDK calls).
+- Multi-step wizards — single form is enough.
+- Real-time bonding-curve updates after launch (later).
+
+## Acceptance
+
+- [ ] `node --check` passes for new files.
+- [ ] `npx vitest run tests/studio-launch-panel.test.js` passes.
+- [ ] Studio shows a "Launch" tab; form validates required fields.
+- [ ] Submitting the form (with stubbed handler) does not console.error.
+- [ ] `npx vite build` passes.
+
+## Test plan
+
+1. `npm run dev`. Open the studio for any agent. Click "Launch". Fill the form. Confirm validation works.
+2. Confirm bonding-curve chart renders.
+3. Submit; confirm the existing pump.fun flow handler is invoked (console.log or breakpoint).
+
+## Reporting
+
+- Shipped: …
+- Skipped: …
+- Broke / regressions: …
+- Unrelated bugs noticed: …
diff --git a/prompts/repo-integrations/21-bonding-curve-chart.md b/prompts/repo-integrations/21-bonding-curve-chart.md
new file mode 100644
index 000000000..fe527a822
--- /dev/null
+++ b/prompts/repo-integrations/21-bonding-curve-chart.md
@@ -0,0 +1,58 @@
+# 21 — Bonding-curve chart component
+
+**Branch:** `feat/bonding-curve-chart`
+**Source repo:** https://github.com/nirholas/solana-launchpad-ui
+**One PR. Standalone. No other prompt is required to be shipped first.**
+
+## Why it matters
+
+A reusable bonding-curve chart is useful in (1) the launch form, (2) the agent-token widget, and (3) any embed visualizing pre-graduation tokens. Today we draw nothing. solana-launchpad-ui has the visual; this prompt extracts a single small component we can drop anywhere — independent of prompt 20.
+
+## Read these first
+
+| File | Why |
+| :--- | :--- |
+| [src/pump/agent-token-widget.js](../../src/pump/agent-token-widget.js) | Where the chart will be consumed. |
+| [src/widget-types.js](../../src/widget-types.js) | If we end up exposing as a widget. |
+| https://github.com/nirholas/solana-launchpad-ui | Bonding-curve reference. |
+
+## Build this
+
+1. Add `src/components/bonding-curve.js` exporting:
+ ```js
+ export function mountBondingCurve(rootEl, { progressPct = 0, marketCapUsd = 0, graduationCapUsd = 69_000 })
+ // Renders a responsive SVG curve, with a marker at the current `progressPct`.
+ // Updates can be made via the returned `update({ progressPct, marketCapUsd })` function.
+ // Returns { update, destroy }.
+ ```
+2. Use SVG (no canvas). No new deps.
+3. Visual style: match existing pump UI (dark, mono-friendly).
+4. Use it in [src/pump/agent-token-widget.js](../../src/pump/agent-token-widget.js) — replace any hardcoded progress bar with this curve. If no progress bar exists, add the curve under the price block.
+5. Add `tests/bonding-curve.test.js` (jsdom) asserting:
+ - SVG renders.
+ - `update({ progressPct: 50 })` moves the marker.
+
+## Out of scope
+
+- Live data subscription (the consumer passes values in).
+- Animations beyond a 200ms marker tween.
+- 3D rendering.
+
+## Acceptance
+
+- [ ] `node --check src/components/bonding-curve.js` passes.
+- [ ] `npx vitest run tests/bonding-curve.test.js` passes.
+- [ ] Component visible in the agent-token widget when a pre-graduation token is shown.
+- [ ] `npx vite build` passes.
+
+## Test plan
+
+1. `npm run dev`. Open an embed showing a pre-graduation token; confirm the curve renders.
+2. Call `update({ progressPct: 90 })` from devtools; confirm the marker animates.
+
+## Reporting
+
+- Shipped: …
+- Skipped: …
+- Broke / regressions: …
+- Unrelated bugs noticed: …
diff --git a/prompts/repo-integrations/22-vanity-mint-keygen-skill.md b/prompts/repo-integrations/22-vanity-mint-keygen-skill.md
new file mode 100644
index 000000000..970e3f04a
--- /dev/null
+++ b/prompts/repo-integrations/22-vanity-mint-keygen-skill.md
@@ -0,0 +1,65 @@
+# 22 — Vanity mint keygen skill
+
+**Branch:** `feat/vanity-mint-keygen`
+**Source repo:** https://github.com/nirholas/solana-wallet-toolkit
+**One PR. Standalone. No other prompt is required to be shipped first.**
+
+## Why it matters
+
+Pump.fun token creators often want vanity mint addresses (e.g. ending in `pump`). solana-wallet-toolkit ships a multi-threaded vanity keygen. Wrapping it as a server-side skill + endpoint lets the studio's launch flow offer "make my mint end in X" without users running a CLI.
+
+## Read these first
+
+| File | Why |
+| :--- | :--- |
+| [api/](../../api/) | API conventions. |
+| [src/agent-skills-pumpfun.js](../../src/agent-skills-pumpfun.js) | Skill registration. |
+| [api/pump-fun-mcp.js](../../api/pump-fun-mcp.js) | MCP tool registration. |
+| https://github.com/nirholas/solana-wallet-toolkit | Reference for the keygen logic (Rust + TS). |
+
+## Build this
+
+1. Add `src/pump/vanity-keygen.js` exporting:
+ ```js
+ export async function generateVanityKey({ suffix, prefix, caseSensitive = false, maxAttempts = 5_000_000, signal })
+ // Generates Solana keypairs until one matches both prefix and suffix.
+ // Returns { publicKey, secretKey: Uint8Array, attempts, ms } | null if maxAttempts hit.
+ // Implementation: pure JS using @solana/web3.js (already a transitive dep). Single-threaded is fine for v1.
+ ```
+2. Add `api/pump/vanity-keygen.js`:
+ ```js
+ // POST /api/pump/vanity-keygen
+ // body: { suffix?, prefix?, caseSensitive?, maxAttempts? }
+ // Streams progress via Server-Sent Events; final event delivers { publicKey, secretKey: base58, attempts, ms }.
+ // Reject if both prefix and suffix are empty.
+ ```
+3. Register skill `pumpfun.vanityMint` and MCP tool `pumpfun_vanity_mint`. The non-streaming version (one batch result) is fine for the skill / MCP path.
+4. Hard cap: 60 seconds wallclock per request server-side; abort and 408 if exceeded.
+5. Add `tests/vanity-keygen.test.js` asserting the function returns a key whose base58 ends with the requested suffix.
+
+## Out of scope
+
+- Multi-threaded / WebWorker parallelism (later).
+- Persisting generated keys (caller must save them).
+- GPU keygen.
+
+## Acceptance
+
+- [ ] `node --check` passes for new files.
+- [ ] `npx vitest run tests/vanity-keygen.test.js` passes.
+- [ ] Endpoint accepts a request with `suffix: "ab"` and returns a matching key in under 60s.
+- [ ] Endpoint rejects empty inputs and aborts long-running requests.
+- [ ] `npx vite build` passes.
+
+## Test plan
+
+1. `curl -X POST -d '{"suffix":"a"}' http://localhost:3000/api/pump/vanity-keygen` — expect a result quickly.
+2. With `suffix:"abcdef"` — expect a 408 (timeout) or success after a long search.
+3. Confirm secret keys are returned base58-encoded and never logged.
+
+## Reporting
+
+- Shipped: …
+- Skipped: …
+- Broke / regressions: …
+- Unrelated bugs noticed: …
diff --git a/prompts/repo-integrations/23-solana-name-resolution.md b/prompts/repo-integrations/23-solana-name-resolution.md
new file mode 100644
index 000000000..f11671f74
--- /dev/null
+++ b/prompts/repo-integrations/23-solana-name-resolution.md
@@ -0,0 +1,55 @@
+# 23 — Solana name service resolution helper
+
+**Branch:** `feat/solana-name-resolution`
+**Source repo:** https://github.com/nirholas/solana-wallet-toolkit
+**One PR. Standalone. No other prompt is required to be shipped first.**
+
+## Why it matters
+
+The project already depends on `@bonfida/spl-name-service` (see [package.json](../../package.json)). solana-wallet-toolkit demonstrates the lookup pattern. Adding a clean `resolveSnsName(name)` / `reverseLookupAddress(addr)` helper, plus an agent skill, lets users say "what's this .sol address?" and the agent answers.
+
+## Read these first
+
+| File | Why |
+| :--- | :--- |
+| [package.json](../../package.json) | Confirms `@bonfida/spl-name-service` is installed. |
+| [src/agent-skills-pumpfun.js](../../src/agent-skills-pumpfun.js) | Skill registration. |
+| [api/pump-fun-mcp.js](../../api/pump-fun-mcp.js) | MCP tool registration. |
+| https://github.com/nirholas/solana-wallet-toolkit | Reference for the SNS calls. |
+
+## Build this
+
+1. Add `src/solana/sns.js` exporting:
+ ```js
+ export async function resolveSnsName(name) // 'foo.sol' → 'PublicKey...' | null
+ export async function reverseLookupAddress(addr) // 'PublicKey...' → 'foo.sol' | null
+ ```
+2. Use `@bonfida/spl-name-service`. Reuse the existing Solana RPC connection from `src/pump/*` if one exists; otherwise pull `SOLANA_RPC_URL` from env with a sensible default.
+3. Register two skills (`solana.resolveSns`, `solana.reverseSns`) and matching MCP tools.
+4. Add `tests/solana-sns.test.js` mocking the SDK and asserting forward + reverse paths normalize null results consistently.
+
+## Out of scope
+
+- Caching — keep it simple.
+- Subdomains / record lookups beyond the basic A-record resolution.
+- ENS or other chains.
+
+## Acceptance
+
+- [ ] `node --check src/solana/sns.js` passes.
+- [ ] `npx vitest run tests/solana-sns.test.js` passes.
+- [ ] Skills + MCP tools callable.
+- [ ] `npx vite build` passes.
+
+## Test plan
+
+1. Resolve `bonfida.sol` (or another known name); confirm a PublicKey returns.
+2. Reverse-lookup the same PublicKey; confirm round-trip.
+3. Look up `nope-not-real-domain-xyz.sol`; confirm `null`.
+
+## Reporting
+
+- Shipped: …
+- Skipped: …
+- Broke / regressions: …
+- Unrelated bugs noticed: …
diff --git a/prompts/repo-integrations/24-carbon-indexer-graduations.md b/prompts/repo-integrations/24-carbon-indexer-graduations.md
new file mode 100644
index 000000000..1a27dd192
--- /dev/null
+++ b/prompts/repo-integrations/24-carbon-indexer-graduations.md
@@ -0,0 +1,53 @@
+# 24 — Carbon-based pump graduations indexer
+
+**Branch:** `feat/carbon-graduations-indexer`
+**Source repo:** https://github.com/nirholas/carbon
+**One PR. Standalone. No other prompt is required to be shipped first.**
+
+## Why it matters
+
+[services/pump-graduations/](../../services/pump-graduations/) currently produces graduation events. carbon is a Solana indexing framework that gives us a more durable subscription model. This prompt adds an *alternative* carbon-backed implementation behind a flag — the existing service keeps working, and we can compare correctness before any swap.
+
+## Read these first
+
+| File | Why |
+| :--- | :--- |
+| [services/pump-graduations/](../../services/pump-graduations/) | Existing graduations service — read every file in the dir. |
+| [scripts/pumpfun-lifecycle-smoke.js](../../scripts/pumpfun-lifecycle-smoke.js) | Smoke test that exercises graduations. |
+| https://github.com/nirholas/carbon | Indexing framework — read the README's "subscriber" section. |
+
+## Build this
+
+1. Add `services/pump-graduations/carbon-source.js` — an alternative graduation source matching the existing source's interface (read the existing source file to find the exact contract; do not invent new method names).
+2. Wire selection: env var `PUMP_GRADUATIONS_SOURCE` with values `legacy` (default) or `carbon`. The service picks the source at startup. Do not change the default.
+3. Carbon source streams graduation events and emits the same shape `{ mint, signature, ts, marketCapUsd }` as the legacy source.
+4. Add `tests/carbon-graduations.test.js` mocking carbon's stream and asserting event shape parity with the legacy mock.
+5. Document the flag in a single new doc file `docs/pump-graduations-sources.md` or in a comment block at the top of `services/pump-graduations/index.js` (whichever the directory's existing convention prefers — read first).
+
+## Out of scope
+
+- Removing the legacy source.
+- DB schema changes.
+- Editing the smoke test.
+
+## Acceptance
+
+- [ ] `node --check services/pump-graduations/carbon-source.js` passes.
+- [ ] `npx vitest run tests/carbon-graduations.test.js` passes.
+- [ ] Service starts cleanly with the env unset (`legacy` default), with `legacy`, and with `carbon`.
+- [ ] Existing `npm run pump:smoke` passes unchanged.
+- [ ] `npx vite build` passes.
+
+## Test plan
+
+1. `PUMP_GRADUATIONS_SOURCE=carbon npm run pump:smoke` — events flow.
+2. `PUMP_GRADUATIONS_SOURCE=legacy npm run pump:smoke` — same.
+3. Diff one minute of events between the two sources on a live RPC; flag any divergence in the PR description.
+
+## Reporting
+
+- Shipped: …
+- Skipped: …
+- Broke / regressions: …
+- Source divergence observed: …
+- Unrelated bugs noticed: …
diff --git a/prompts/repo-integrations/25-mcp-tool-whale-alerts.md b/prompts/repo-integrations/25-mcp-tool-whale-alerts.md
new file mode 100644
index 000000000..cb7ed3e88
--- /dev/null
+++ b/prompts/repo-integrations/25-mcp-tool-whale-alerts.md
@@ -0,0 +1,52 @@
+# 25 — MCP tool: whale alerts (request/response)
+
+**Branch:** `feat/mcp-whale-alerts`
+**One PR. Standalone. No other prompt is required to be shipped first.**
+
+## Why it matters
+
+The pump-fun MCP server currently exposes the basics. A `pumpfun_whale_alerts` tool — request/response, returns whales over a window — gives MCP clients (Claude Desktop, Cursor, LobeHub) a clean path to ask "what whales bought X in the last 30 minutes?" without needing the streaming watch skill.
+
+## Read these first
+
+| File | Why |
+| :--- | :--- |
+| [api/pump-fun-mcp.js](../../api/pump-fun-mcp.js) | Existing MCP tool registration. |
+| [src/agent-skills-pumpfun-watch.js](../../src/agent-skills-pumpfun-watch.js) | Whale-detection logic patterns; reuse what exists. |
+| [tests/pumpfun-mcp-tools.test.js](../../tests/pumpfun-mcp-tools.test.js) | Existing MCP tool tests — extend. |
+
+## Build this
+
+1. Register an MCP tool `pumpfun_whale_alerts` in [api/pump-fun-mcp.js](../../api/pump-fun-mcp.js):
+ - Args: `{ mint: string, sinceMinutes?: number (default 30, max 240), minUsd?: number (default 5000) }`
+ - Returns `{ items: [{ signature, wallet, sideBuy, usd, sol, ts }] }` newest first.
+2. Implement using whatever trade-history primitive `src/pump/*` already exposes; if none, add a minimal `src/pump/recent-trades.js` helper that pulls trades for `mint` since timestamp via the existing RPC client.
+3. Extend [tests/pumpfun-mcp-tools.test.js](../../tests/pumpfun-mcp-tools.test.js) with cases:
+ - Returns whales above threshold.
+ - Filters out trades below threshold.
+ - Caps `sinceMinutes` at 240.
+
+## Out of scope
+
+- Streaming. This is request/response.
+- Persisting alerts.
+- A skill version (skill version is in prompt 01; this prompt only adds the MCP path).
+
+## Acceptance
+
+- [ ] Tool appears in `tools/list` on the MCP endpoint.
+- [ ] `npx vitest run tests/pumpfun-mcp-tools.test.js` passes.
+- [ ] Calling with `sinceMinutes: 9999` is clamped, not rejected.
+- [ ] `npx vite build` passes.
+
+## Test plan
+
+1. JSON-RPC `tools/call` for `pumpfun_whale_alerts` with a known active mint, `sinceMinutes: 60`, `minUsd: 1000`. Confirm reasonable items.
+2. Same call with `minUsd: 1_000_000`. Confirm empty.
+
+## Reporting
+
+- Shipped: …
+- Skipped: …
+- Broke / regressions: …
+- Unrelated bugs noticed: …
diff --git a/prompts/repo-integrations/26-mcp-tool-graduations.md b/prompts/repo-integrations/26-mcp-tool-graduations.md
new file mode 100644
index 000000000..ce2acb854
--- /dev/null
+++ b/prompts/repo-integrations/26-mcp-tool-graduations.md
@@ -0,0 +1,51 @@
+# 26 — MCP tool: recent graduations
+
+**Branch:** `feat/mcp-recent-graduations`
+**One PR. Standalone. No other prompt is required to be shipped first.**
+
+## Why it matters
+
+A `pumpfun_recent_graduations` MCP tool gives any MCP client a one-call summary of "what tokens just graduated to AMM?" — useful for both signal feeds and conversational agents.
+
+## Read these first
+
+| File | Why |
+| :--- | :--- |
+| [api/pump-fun-mcp.js](../../api/pump-fun-mcp.js) | MCP registration. |
+| [services/pump-graduations/](../../services/pump-graduations/) | Existing graduation source — reuse. |
+| [tests/pumpfun-mcp-tools.test.js](../../tests/pumpfun-mcp-tools.test.js) | Tests to extend. |
+
+## Build this
+
+1. Register an MCP tool `pumpfun_recent_graduations`:
+ - Args: `{ sinceMinutes?: number (default 60, max 1440), limit?: number (default 25, max 100) }`
+ - Returns `{ items: [{ mint, signature, ts, marketCapUsd, name?, symbol? }] }` newest first.
+2. Read from the existing graduations service. Do not poll a new source. If the service exposes a function/queue, import it directly. If it only persists to disk/DB, read from there.
+3. Extend [tests/pumpfun-mcp-tools.test.js](../../tests/pumpfun-mcp-tools.test.js) asserting:
+ - Sorted newest first.
+ - `sinceMinutes` and `limit` both honored.
+ - Graceful empty-list response when no graduations match.
+
+## Out of scope
+
+- Adding new graduation detection logic.
+- Editing the graduations service.
+
+## Acceptance
+
+- [ ] Tool appears in `tools/list`.
+- [ ] Tests pass.
+- [ ] `npx vite build` passes.
+
+## Test plan
+
+1. Run a tools/call with default args; confirm reasonable items.
+2. Run with `sinceMinutes: 1`; expect short list.
+3. Run with `limit: 1000`; confirm clamped.
+
+## Reporting
+
+- Shipped: …
+- Skipped: …
+- Broke / regressions: …
+- Unrelated bugs noticed: …
diff --git a/prompts/repo-integrations/27-mcp-tool-token-info.md b/prompts/repo-integrations/27-mcp-tool-token-info.md
new file mode 100644
index 000000000..84c4d5726
--- /dev/null
+++ b/prompts/repo-integrations/27-mcp-tool-token-info.md
@@ -0,0 +1,64 @@
+# 27 — MCP tool: pump.fun token info
+
+**Branch:** `feat/mcp-token-info`
+**One PR. Standalone. No other prompt is required to be shipped first.**
+
+## Why it matters
+
+LLMs need a single canonical "tell me about this token" call. We have the data scattered across SDK calls; this prompt consolidates into one MCP tool returning the fields a chat actually wants.
+
+## Read these first
+
+| File | Why |
+| :--- | :--- |
+| [api/pump-fun-mcp.js](../../api/pump-fun-mcp.js) | MCP registration. |
+| [src/pump/agent-token-widget.js](../../src/pump/agent-token-widget.js) | What fields the widget already pulls — match these. |
+| `node_modules/@pump-fun/pump-sdk/` | SDK surface for token metadata. |
+
+## Build this
+
+1. Register MCP tool `pumpfun_token_info`:
+ - Args: `{ mint: string }`
+ - Returns:
+ ```jsonc
+ {
+ "mint": "...",
+ "name": "...",
+ "symbol": "...",
+ "image": "...",
+ "description": "...",
+ "creator": "...",
+ "marketCapUsd": 0,
+ "priceUsd": 0,
+ "graduated": false,
+ "createdAt": 0,
+ "uri": "..."
+ }
+ ```
+2. Implement in `src/pump/token-info.js` using the existing pump SDKs. Read the agent-token widget to discover which calls already fetch each field — reuse those.
+3. Add `tests/pump-token-info.test.js` mocking the SDK and asserting field normalization (e.g. lamports → SOL, raw price → USD).
+
+## Out of scope
+
+- Fetching off-chain metadata if `uri` is dead — surface `uri` and let the caller follow it.
+- Holder lists (later).
+- Trade history (covered by other prompts).
+
+## Acceptance
+
+- [ ] Tool appears in `tools/list`.
+- [ ] `npx vitest run tests/pump-token-info.test.js` passes.
+- [ ] Calling against a real active mint returns coherent fields.
+- [ ] `npx vite build` passes.
+
+## Test plan
+
+1. Pick three mints: pre-graduation, just-graduated, dead. Call the tool against each. Confirm `graduated` flag matches reality and other fields look sane.
+2. Call against an invalid mint; confirm a clean error.
+
+## Reporting
+
+- Shipped: …
+- Skipped: …
+- Broke / regressions: …
+- Unrelated bugs noticed: …
diff --git a/prompts/repo-integrations/28-mcp-tool-creator-history.md b/prompts/repo-integrations/28-mcp-tool-creator-history.md
new file mode 100644
index 000000000..dcaec0e0b
--- /dev/null
+++ b/prompts/repo-integrations/28-mcp-tool-creator-history.md
@@ -0,0 +1,51 @@
+# 28 — MCP tool: creator history
+
+**Branch:** `feat/mcp-creator-history`
+**One PR. Standalone. No other prompt is required to be shipped first.**
+
+## Why it matters
+
+"Has this creator launched tokens before?" is a critical due-diligence question. A `pumpfun_creator_history` MCP tool gives the LLM that context in one call.
+
+## Read these first
+
+| File | Why |
+| :--- | :--- |
+| [api/pump-fun-mcp.js](../../api/pump-fun-mcp.js) | MCP registration. |
+| [src/agent-skills-pumpfun.js](../../src/agent-skills-pumpfun.js) | Existing skill style. |
+| `node_modules/@pump-fun/pump-sdk/` | SDK surface. |
+
+## Build this
+
+1. Register MCP tool `pumpfun_creator_history`:
+ - Args: `{ creator: string, limit?: number (default 25, max 100) }`
+ - Returns `{ creator, count, tokens: [{ mint, name, symbol, createdAt, graduated, marketCapUsd, peakMarketCapUsd? }] }` newest first.
+2. Implement in `src/pump/creator-history.js` using existing SDKs. Reuse the same data sources the agent-token widget uses.
+3. Add `tests/pump-creator-history.test.js` mocking the SDK and asserting:
+ - Sort order.
+ - `count` matches `tokens.length`.
+ - `limit` is honored.
+
+## Out of scope
+
+- Wallet-to-creator linking heuristics.
+- Tracking creator P&L (that's prompt 13's territory).
+
+## Acceptance
+
+- [ ] Tool appears in `tools/list`.
+- [ ] `npx vitest run tests/pump-creator-history.test.js` passes.
+- [ ] Calling against a known prolific creator returns multiple entries.
+- [ ] `npx vite build` passes.
+
+## Test plan
+
+1. Pick a known creator wallet. Run the tool. Confirm count and recent tokens.
+2. Pass `limit: 1`. Confirm one entry.
+
+## Reporting
+
+- Shipped: …
+- Skipped: …
+- Broke / regressions: …
+- Unrelated bugs noticed: …
diff --git a/prompts/repo-integrations/29-agent-graduation-celebration.md b/prompts/repo-integrations/29-agent-graduation-celebration.md
new file mode 100644
index 000000000..1bcfa2d63
--- /dev/null
+++ b/prompts/repo-integrations/29-agent-graduation-celebration.md
@@ -0,0 +1,59 @@
+# 29 — Agent celebrates graduations on screen
+
+**Branch:** `feat/graduation-celebration`
+**One PR. Standalone. No other prompt is required to be shipped first.**
+
+## Why it matters
+
+When an agent's tracked token graduates to AMM, the avatar should *react* — confetti / emote / one-shot sound. This is a small, high-leverage moment that sells the "embodied agent" pitch in demos.
+
+## Read these first
+
+| File | Why |
+| :--- | :--- |
+| [src/element.js](../../src/element.js) | Avatar wiring + how reactions are triggered today. |
+| [src/agent-skills-pumpfun-hooks.js](../../src/agent-skills-pumpfun-hooks.js) | Lifecycle hooks — your hook joins this set. |
+| [services/pump-graduations/](../../services/pump-graduations/) | Graduation event source. |
+| [src/pump/agent-token-widget.js](../../src/pump/agent-token-widget.js) | UI for token state. |
+
+## Build this
+
+1. Add `src/pump/graduation-hook.js` exporting:
+ ```js
+ export function attachGraduationHook(agent, { mint })
+ // Subscribes to graduation events for `mint`.
+ // On graduation: agent.playEmote('celebrate') + spawns a confetti burst overlaid on the canvas (CSS / DOM, not three.js).
+ // Returns detach.
+ ```
+2. Confetti: pure CSS / DOM. No new dep. Auto-removes after 4 seconds.
+3. If `agent.playEmote('celebrate')` is not available, fall back to a 360° spin on the avatar root via the existing animation system.
+4. Wire into [src/element.js](../../src/element.js): when the agent's `tracked-mint` attribute is set, attach on connect, detach on disconnect.
+5. Add `tests/graduation-hook.test.js` mocking the graduation source and asserting:
+ - Confetti element appears in DOM on graduation event.
+ - Element is removed within 5 seconds.
+ - Detach prevents future triggers.
+
+## Out of scope
+
+- Sound (later — needs licensing decisions).
+- Multi-mint tracking.
+- Persisting graduation events.
+
+## Acceptance
+
+- [ ] `node --check src/pump/graduation-hook.js` passes.
+- [ ] `npx vitest run tests/graduation-hook.test.js` passes.
+- [ ] On a real graduation, confetti shows over the agent.
+- [ ] `npx vite build` passes.
+
+## Test plan
+
+1. Patch the graduation source to fire a fake event in dev mode; confirm visible celebration.
+2. Confirm cleanup works on disconnect.
+
+## Reporting
+
+- Shipped: …
+- Skipped: …
+- Broke / regressions: …
+- Unrelated bugs noticed: …
diff --git a/prompts/repo-integrations/30-agent-mood-from-price.md b/prompts/repo-integrations/30-agent-mood-from-price.md
new file mode 100644
index 000000000..c86687916
--- /dev/null
+++ b/prompts/repo-integrations/30-agent-mood-from-price.md
@@ -0,0 +1,59 @@
+# 30 — Agent mood derived from token price
+
+**Branch:** `feat/agent-mood-price`
+**One PR. Standalone. No other prompt is required to be shipped first.**
+
+## Why it matters
+
+When an agent has a tracked token, the avatar should subtly mirror its 5-minute price trend — happier on green, slumped on red. This is a passive ambient signal that makes a long demo feel alive without scripted choreography.
+
+## Read these first
+
+| File | Why |
+| :--- | :--- |
+| [src/element.js](../../src/element.js) | Animation / pose entry points. |
+| [src/agent-skills-pumpfun-hooks.js](../../src/agent-skills-pumpfun-hooks.js) | Hook patterns. |
+| [src/pump/agent-token-widget.js](../../src/pump/agent-token-widget.js) | Existing price source. |
+
+## Build this
+
+1. Add `src/pump/mood-from-price.js` exporting:
+ ```js
+ export function attachMoodFromPrice(agent, { mint, intervalMs = 30_000 })
+ // Polls the 5-minute price delta for `mint`.
+ // Maps:
+ // delta > +5% → 'happy'
+ // delta < -5% → 'sad'
+ // between → 'neutral'
+ // Calls agent.setMood(mood) — implement that on the agent if it doesn't exist (find best home in src/element.js).
+ // Returns detach.
+ ```
+2. Implement `agent.setMood(mood)` minimally: select an idle animation per mood (happy / neutral / sad) from the existing animation list. If a matching idle is not present, fall back to neutral and console.warn once.
+3. Wire into [src/element.js](../../src/element.js): on connect, if `tracked-mint` is set, attach.
+4. Add `tests/mood-from-price.test.js` asserting the threshold logic and that `setMood` is called with the right value.
+
+## Out of scope
+
+- Facial morph targets — pose-only is enough.
+- Per-user mood overrides.
+- Listening to news / sentiment in the same hook.
+
+## Acceptance
+
+- [ ] `node --check src/pump/mood-from-price.js` passes.
+- [ ] `npx vitest run tests/mood-from-price.test.js` passes.
+- [ ] In a dev stub (force a +10% delta), the avatar visibly shifts pose.
+- [ ] `npx vite build` passes.
+
+## Test plan
+
+1. Force the price source to return +10% delta; confirm pose change.
+2. Force −10%; confirm reverse.
+3. Detach and confirm polling stops.
+
+## Reporting
+
+- Shipped: …
+- Skipped: …
+- Broke / regressions: …
+- Unrelated bugs noticed: …
diff --git a/prompts/repo-integrations/31-live-signals-embed-widget.md b/prompts/repo-integrations/31-live-signals-embed-widget.md
new file mode 100644
index 000000000..b3d4d9745
--- /dev/null
+++ b/prompts/repo-integrations/31-live-signals-embed-widget.md
@@ -0,0 +1,56 @@
+# 31 — Live signals embed widget
+
+**Branch:** `feat/live-signals-widget`
+**One PR. Standalone. No other prompt is required to be shipped first.**
+
+## Why it matters
+
+A single `signals-feed` widget that surfaces the most relevant live signals for a token (whales + claims + graduations) gives third-party sites one drop-in line of HTML to embed and stay in sync with what's happening on chain.
+
+## Read these first
+
+| File | Why |
+| :--- | :--- |
+| [src/widget-types.js](../../src/widget-types.js) | Widget type registry. |
+| [src/element.js](../../src/element.js) | Custom-element wiring. |
+| [src/pump/agent-token-widget.js](../../src/pump/agent-token-widget.js) | Closest pattern. |
+| [api/pump-fun-mcp.js](../../api/pump-fun-mcp.js) | Existing pump-data endpoints — read-through pattern. |
+
+## Build this
+
+1. Register a `signals-feed` widget type in [src/widget-types.js](../../src/widget-types.js):
+ - Required: `mint`
+ - Optional: `kinds` (csv: `whale,claim,graduation`, default all), `refresh-ms` (default 20000), `theme` (`dark` | `light`, default `dark`).
+2. Add `src/widgets/signals-feed.js` exporting `mountSignalsFeed(rootEl, opts)`:
+ - Polls a new `/api/pump/signals?mint=…&kinds=…` endpoint that internally aggregates whale events, claims, and graduations for the mint.
+ - Renders rows with kind-specific icons, timestamp, summary, link to Solscan.
+ - Empty + loading + error states.
+ - Cleanup on unmount.
+3. Add `api/pump/signals.js` endpoint aggregating whatever sources the project already has. Do not add new RPC subs — read-through only.
+4. Add `tests/signals-feed.test.js` (jsdom + mocked fetch) asserting filter-by-kinds works and rows render.
+
+## Out of scope
+
+- Push (WebSocket) — polling is fine.
+- Personalization beyond `theme`.
+- Multi-mint feeds.
+
+## Acceptance
+
+- [ ] `node --check` passes for new files.
+- [ ] `npx vitest run tests/signals-feed.test.js` passes.
+- [ ] `<three-ws-widget type="signals-feed" mint="<mint>"></three-ws-widget>` renders rows in `embed-test.html`.
+- [ ] `npx vite build` passes.
+
+## Test plan
+
+1. Add to `embed-test.html` for a known active mint. Confirm rows populate.
+2. Set `kinds="graduation"`. Confirm only graduations render.
+3. Disable network; confirm error state.
+
+## Reporting
+
+- Shipped: …
+- Skipped: …
+- Broke / regressions: …
+- Unrelated bugs noticed: …
diff --git a/prompts/repo-integrations/32-creator-leaderboard-widget.md b/prompts/repo-integrations/32-creator-leaderboard-widget.md
new file mode 100644
index 000000000..c22999b3b
--- /dev/null
+++ b/prompts/repo-integrations/32-creator-leaderboard-widget.md
@@ -0,0 +1,50 @@
+# 32 — Creator leaderboard widget
+
+**Branch:** `feat/creator-leaderboard-widget`
+**One PR. Standalone. No other prompt is required to be shipped first.**
+
+## Why it matters
+
+A `creator-leaderboard` widget — top pump.fun creators by graduations or fees claimed in a window — is a glanceable stat block any embed can drop in. Distinct from prompt 11 (KOL traders); this one ranks token *launchers*.
+
+## Read these first
+
+| File | Why |
+| :--- | :--- |
+| [src/widget-types.js](../../src/widget-types.js) | Widget type registry. |
+| [src/pump/agent-token-widget.js](../../src/pump/agent-token-widget.js) | Closest pattern. |
+| [api/](../../api/) | API conventions. |
+
+## Build this
+
+1. Register `creator-leaderboard` widget type:
+ - Optional: `metric` (`graduations` | `feesClaimed`, default `graduations`), `window` (`24h` | `7d` | `30d`, default `7d`), `limit` (default 10).
+2. Add `src/widgets/creator-leaderboard.js` polling `/api/pump/creator-leaderboard?metric=…&window=…&limit=…`.
+3. Add `api/pump/creator-leaderboard.js` aggregating by creator over the requested window using existing pump data sources.
+4. Add `tests/creator-leaderboard.test.js` asserting endpoint shape + sort order.
+
+## Out of scope
+
+- Per-creator drill-down inside the widget — link out to the agent page.
+- DB-backed history.
+
+## Acceptance
+
+- [ ] `node --check` passes.
+- [ ] `npx vitest run tests/creator-leaderboard.test.js` passes.
+- [ ] Widget renders top creators in `embed-test.html`.
+- [ ] `/api/pump/creator-leaderboard` returns valid JSON.
+- [ ] `npx vite build` passes.
+
+## Test plan
+
+1. Embed widget. Confirm rows populate.
+2. Switch `metric="feesClaimed"`. Confirm different ranking.
+3. Pass `window="24h"`. Confirm shorter window response.
+
+## Reporting
+
+- Shipped: …
+- Skipped: …
+- Broke / regressions: …
+- Unrelated bugs noticed: …
diff --git a/prompts/repo-integrations/33-x402-paid-signals.md b/prompts/repo-integrations/33-x402-paid-signals.md
new file mode 100644
index 000000000..8f43fb0a6
--- /dev/null
+++ b/prompts/repo-integrations/33-x402-paid-signals.md
@@ -0,0 +1,57 @@
+# 33 — x402 paywall on premium pump signals
+
+**Branch:** `feat/x402-paid-signals`
+**One PR. Standalone. No other prompt is required to be shipped first.**
+
+## Why it matters
+
+The project already has x402 wiring ([api/wk-x402.js](../../api/wk-x402.js)). Putting a small per-call fee on premium signal endpoints (whale alerts, smart money trades) is a clean monetization pilot — agents calling our MCP server pay for high-value data.
+
+## Read these first
+
+| File | Why |
+| :--- | :--- |
+| [api/wk-x402.js](../../api/wk-x402.js) | x402 protocol handler — read carefully. |
+| [api/pump-fun-mcp.js](../../api/pump-fun-mcp.js) | Where to wrap. |
+| [api/payments/](../../api/payments/) | Existing payment infra. |
+
+## Build this
+
+1. Add `api/_lib/x402-gate.js` (if a similar helper does not already exist — search first; if found, extend it):
+ ```js
+ export function withX402({ priceUsd }, handler)
+ // Wraps a Vercel-style handler. If x402 payment proof present and verified, calls handler.
+ // Otherwise responds 402 with the x402 payment-required body.
+ ```
+2. Apply `withX402({ priceUsd: 0.01 })` to two MCP tools (or their data endpoints): `pumpfun_whale_alerts` and `kol_leaderboard` (only if registered; if not, gate `/api/pump/signals` and `/api/kol/trades` instead — search first to find what exists).
+3. Free tier: leave `pumpfun_token_info` and `pumpfun_recent_graduations` (or equivalents) ungated. Document the split inline.
+4. Add `tests/x402-gate.test.js`:
+ - 402 without payment proof.
+ - 200 with mocked-valid proof.
+
+## Out of scope
+
+- Adjusting x402 facilitator code.
+- Subscription / token-gated tiers (pay-per-call only).
+- UI changes.
+
+## Acceptance
+
+- [ ] `node --check` passes for new files.
+- [ ] `npx vitest run tests/x402-gate.test.js` passes.
+- [ ] Curling a gated endpoint without payment returns 402 with a valid x402 body.
+- [ ] Free endpoints remain 200.
+- [ ] `npx vite build` passes.
+
+## Test plan
+
+1. Curl `pumpfun_whale_alerts` (gated) without proof — expect 402.
+2. Curl `pumpfun_token_info` (free) — expect 200.
+3. With agentcash MCP in this environment, fetch a gated endpoint via agentcash bridge; expect 200 and a debited balance.
+
+## Reporting
+
+- Shipped: …
+- Skipped: …
+- Broke / regressions: …
+- Unrelated bugs noticed: …
diff --git a/prompts/repo-integrations/34-erc8004-attestation-signal-quality.md b/prompts/repo-integrations/34-erc8004-attestation-signal-quality.md
new file mode 100644
index 000000000..ad921a944
--- /dev/null
+++ b/prompts/repo-integrations/34-erc8004-attestation-signal-quality.md
@@ -0,0 +1,52 @@
+# 34 — ERC-8004 attestation for signal quality
+
+**Branch:** `feat/erc8004-signal-attestation`
+**One PR. Standalone. No other prompt is required to be shipped first.**
+
+## Why it matters
+
+ERC-8004 lets agents attest to facts on-chain. If our MCP signal endpoints sign and post a periodic "signal quality" attestation (e.g. precision/recall over the last 24h vs ground truth), downstream agents can choose us over competitors based on a verifiable track record.
+
+## Read these first
+
+| File | Why |
+| :--- | :--- |
+| [api/erc8004/](../../api/erc8004/) | Existing on-chain attestation surface. |
+| [contracts/](../../contracts/) | Contract code if modification needed. |
+| [scripts/solana-attest-smoke.js](../../scripts/solana-attest-smoke.js) | Smoke pattern. |
+| [scripts/backfill-erc8004.mjs](../../scripts/backfill-erc8004.mjs) | Existing 8004 batch script — match style. |
+
+## Build this
+
+1. Add `services/signal-quality/index.js` running on a schedule (cron or one-shot script):
+ - Computes daily precision/recall for `pumpfun_whale_alerts` against a ground-truth window (whales who held >10 minutes vs flipped).
+ - Output `{ window: '24h', tool: 'pumpfun_whale_alerts', precision, recall, sampleSize, ts }`.
+2. Add `scripts/post-signal-attestation.js` that takes the daily output and submits an ERC-8004 attestation via the existing on-chain helpers in [api/erc8004/](../../api/erc8004/). Reuse — do not invent a new transaction path.
+3. Add `tests/signal-quality.test.js` asserting precision/recall math against a fixture.
+4. Document the new attestation schema in [contracts/](../../contracts/) only if the existing schema can't carry the fields. Otherwise just write to the existing schema.
+
+## Out of scope
+
+- Live cron — wire as a CLI script; scheduling is operator's call.
+- Multi-tool aggregation in one attestation.
+- A new contract.
+
+## Acceptance
+
+- [ ] `node --check` passes for new files.
+- [ ] `npx vitest run tests/signal-quality.test.js` passes.
+- [ ] `node scripts/post-signal-attestation.js --dry-run` prints the payload without a tx send.
+- [ ] `npx vite build` passes.
+
+## Test plan
+
+1. Run the calculator over a fixture; eyeball numbers.
+2. `--dry-run` — confirm payload is well-formed.
+3. (Optional) Submit on testnet; confirm tx lands.
+
+## Reporting
+
+- Shipped: …
+- Skipped: …
+- Broke / regressions: …
+- Unrelated bugs noticed: …
diff --git a/prompts/repo-integrations/35-pump-skill-discovery-route.md b/prompts/repo-integrations/35-pump-skill-discovery-route.md
new file mode 100644
index 000000000..de89cf0f7
--- /dev/null
+++ b/prompts/repo-integrations/35-pump-skill-discovery-route.md
@@ -0,0 +1,52 @@
+# 35 — Skill discovery route for pump.fun tools
+
+**Branch:** `feat/pump-skill-discovery`
+**One PR. Standalone. No other prompt is required to be shipped first.**
+
+## Why it matters
+
+The agent already exposes skills, but discovery is implicit. A `/api/pump/skills` route returning a typed list of pump.fun-specific skills (and their MCP tool counterparts) makes it easy for hosts (LobeHub, Claude) to render a UI listing them.
+
+## Read these first
+
+| File | Why |
+| :--- | :--- |
+| [src/agent-skills-pumpfun.js](../../src/agent-skills-pumpfun.js) | Skill metadata source. |
+| [src/agent-skills-pumpfun-watch.js](../../src/agent-skills-pumpfun-watch.js) | Same. |
+| [src/agent-skills-pumpfun-compose.js](../../src/agent-skills-pumpfun-compose.js) | Same. |
+| [src/agent-skills.js](../../src/agent-skills.js) | Top-level registry. |
+
+## Build this
+
+1. Add `api/pump/skills.js`:
+ ```js
+ // GET /api/pump/skills
+ // → { skills: [{ name, description, args, mcpTool? }] }
+ ```
+2. Filter to skills whose namespace starts with `pumpfun.` or `kol.` or `social.`. Inspect each skill's metadata (name, description, args).
+3. If the skill has a known MCP-tool counterpart (e.g. `pumpfun.listClaims` → `pumpfun_list_claims`), include `mcpTool` field.
+4. Add `tests/pump-skills-route.test.js` asserting only pump-related skills appear and that namespaces are honored.
+
+## Out of scope
+
+- A UI consumer for this route.
+- Modifying skill metadata in-place beyond what's necessary to publish via this endpoint.
+
+## Acceptance
+
+- [ ] `node --check api/pump/skills.js` passes.
+- [ ] `npx vitest run tests/pump-skills-route.test.js` passes.
+- [ ] `curl /api/pump/skills` returns valid JSON with all pump-namespaced skills.
+- [ ] `npx vite build` passes.
+
+## Test plan
+
+1. Hit endpoint. Sanity-check listed skills against `getSkills()` output.
+2. Add a temporary `unrelated.example` skill; confirm it does not appear.
+
+## Reporting
+
+- Shipped: …
+- Skipped: …
+- Broke / regressions: …
+- Unrelated bugs noticed: …
diff --git a/prompts/repo-integrations/36-pump-integration-architecture-doc.md b/prompts/repo-integrations/36-pump-integration-architecture-doc.md
new file mode 100644
index 000000000..1541e85b7
--- /dev/null
+++ b/prompts/repo-integrations/36-pump-integration-architecture-doc.md
@@ -0,0 +1,55 @@
+# 36 — Pump.fun integration architecture doc
+
+**Branch:** `docs/pump-architecture`
+**One PR. Standalone. No other prompt is required to be shipped first.**
+
+## Why it matters
+
+Pump.fun integration is now spread across `services/`, `api/`, `src/pump/`, and several `agent-skills-pumpfun-*.js` files. A single architecture doc reduces ramp-up time for new contributors and prevents new prompts from re-inventing existing primitives.
+
+## Read these first
+
+| File | Why |
+| :--- | :--- |
+| [services/pump-graduations/](../../services/pump-graduations/) | Map every file. |
+| [src/pump/](../../src/pump/) | Same. |
+| [api/pump-fun-mcp.js](../../api/pump-fun-mcp.js) | Tool registry. |
+| [api/pump/](../../api/pump/) | All HTTP handlers. |
+| [src/agent-skills-pumpfun.js](../../src/agent-skills-pumpfun.js) and siblings | Skill registry. |
+
+## Build this
+
+1. Add `docs/pump-fun-architecture.md`. Sections:
+ - **Overview** — one paragraph: what we expose and why.
+ - **Module map** — table: file → responsibility → consumers.
+ - **Data sources** — RPC, SDK, indexer, paid APIs, with env vars.
+ - **Skill / MCP / HTTP surface matrix** — table mapping each skill name to its MCP tool name and HTTP route (if any).
+ - **Adding a new signal** — 5-bullet recipe.
+ - **Open issues** — bullets only; no fixes.
+2. Generate the matrix by reading skill registrations + MCP registrations + handlers. Do not invent rows. If a skill has no MCP counterpart, leave that cell blank.
+3. Add a one-line link to the new doc in the project's main [README.md](../../README.md) under any existing "Docs" section. If none exists, do not invent one — instead link from [docs/](../../docs/) index if that exists, else add a "## Architecture" section heading at the bottom of README.md (one heading; no other edits).
+
+## Out of scope
+
+- Rewriting code.
+- Renaming files for consistency.
+- Generating a diagram (text tables only).
+
+## Acceptance
+
+- [ ] Doc exists and renders cleanly on GitHub.
+- [ ] Matrix accurately reflects current code (spot-check 5 entries by reading source).
+- [ ] No stale TODOs or invented features documented.
+- [ ] `npx vite build` passes (build doesn't depend on docs but should not regress).
+
+## Test plan
+
+1. Read the doc end-to-end. Pick three table entries; confirm each matches code.
+2. Confirm README link points at the new doc.
+
+## Reporting
+
+- Shipped: …
+- Skipped: …
+- Open issues identified during the pass: …
+- Unrelated bugs noticed: …
diff --git a/src/agent-home-claims.js b/src/agent-home-claims.js
new file mode 100644
index 000000000..7aa1ed8ca
--- /dev/null
+++ b/src/agent-home-claims.js
@@ -0,0 +1,289 @@
+/**
+ * Claim events panel for the agent home page.
+ * Polls the Solana RPC directly for fee-claim transactions by a creator wallet.
+ * Mounted beneath the pump.fun card when `creatorWallet` is set on the agent profile.
+ */
+
+const PUMP_PROGRAM = '6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P';
+const SOLANA_RPC = {
+ mainnet: 'https://api.mainnet-beta.solana.com',
+ devnet: 'https://api.devnet.solana.com',
+};
+
+// Minimum SOL delta (lamports) to qualify as a fee claim rather than tx-fee noise.
+const MIN_CLAIM_LAMPORTS = 10_000;
+
+const PANEL_STYLES = `
+.three-ws-claims-panel {
+ margin-top: 0.6rem;
+ padding: 0.9rem 1rem;
+ border: 1px solid rgba(255,255,255,0.07);
+ border-radius: 12px;
+ background: linear-gradient(180deg, rgba(255,255,255,0.02), rgba(255,255,255,0));
+ color: #e5e5e5;
+ font: 13px/1.5 Inter, sans-serif;
+}
+.three-ws-claims-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ margin-bottom: 0.5rem;
+}
+.three-ws-claims-title {
+ font-size: 0.7rem;
+ letter-spacing: 0.06em;
+ text-transform: uppercase;
+ color: rgba(255,255,255,0.4);
+ font-weight: 500;
+}
+.three-ws-claims-status {
+ font-size: 0.68rem;
+ color: rgba(255,255,255,0.28);
+}
+.three-ws-claims-list {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+}
+.three-ws-claims-item {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ padding: 0.32rem 0;
+ border-top: 1px solid rgba(255,255,255,0.04);
+ font-size: 0.78rem;
+}
+.three-ws-claims-item:first-child { border-top: none; }
+.three-ws-claims-ts {
+ flex: 0 0 4.2rem;
+ color: rgba(255,255,255,0.38);
+ font-size: 0.7rem;
+ white-space: nowrap;
+}
+.three-ws-claims-mint {
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ font-family: ui-monospace, monospace;
+ color: rgba(255,255,255,0.55);
+ font-size: 0.7rem;
+}
+.three-ws-claims-amount {
+ flex: 0 0 auto;
+ color: #a4f0bc;
+ font-weight: 500;
+ white-space: nowrap;
+ font-size: 0.78rem;
+}
+.three-ws-claims-link {
+ flex: 0 0 auto;
+ color: rgba(255,255,255,0.28);
+ text-decoration: none;
+ font-size: 0.72rem;
+ line-height: 1;
+}
+.three-ws-claims-link:hover { color: rgba(255,255,255,0.65); }
+.three-ws-claims-empty {
+ color: rgba(255,255,255,0.3);
+ font-size: 0.78rem;
+ padding: 0.2rem 0;
+}
+`;
+
+let _stylesInjected = false;
+function ensureStyles() {
+ if (_stylesInjected) return;
+ const el = document.createElement('style');
+ el.textContent = PANEL_STYLES;
+ document.head.appendChild(el);
+ _stylesInjected = true;
+}
+
+function shortMint(m) {
+ if (!m) return '—';
+ return `${m.slice(0, 4)}…${m.slice(-4)}`;
+}
+
+function formatSol(lamports) {
+ const n = Number(lamports) / 1e9;
+ if (!isFinite(n) || n <= 0) return '—';
+ return n >= 1 ? `${n.toFixed(3)} SOL` : `${n.toFixed(5)} SOL`;
+}
+
+function timeAgo(unixSec) {
+ if (!unixSec) return '';
+ const diff = Date.now() - unixSec * 1000;
+ if (diff < 60_000) return `${Math.max(1, Math.floor(diff / 1000))}s ago`;
+ if (diff < 3_600_000) return `${Math.floor(diff / 60_000)}m ago`;
+ if (diff < 86_400_000) return `${Math.floor(diff / 3_600_000)}h ago`;
+ return `${Math.floor(diff / 86_400_000)}d ago`;
+}
+
+function esc(s) {
+ return String(s || '').replace(/[&<>"']/g, (c) => ({
+ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;',
+ })[c]);
+}
+
+async function jsonRpc(url, method, params) {
+ const resp = await fetch(url, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
+ });
+ if (!resp.ok) throw new Error(`RPC HTTP ${resp.status}`);
+ const body = await resp.json();
+ if (body.error) throw new Error(body.error.message || 'RPC error');
+ return body.result;
+}
+
+async function jsonRpcBatch(url, requests) {
+ const resp = await fetch(url, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify(requests.map((r, i) => ({ jsonrpc: '2.0', id: i, ...r }))),
+ });
+ if (!resp.ok) throw new Error(`RPC HTTP ${resp.status}`);
+ return resp.json();
+}
+
+function getKey(k) {
+ return typeof k === 'string' ? k : (k?.pubkey ?? '');
+}
+
+async function fetchClaimEvents(creator, network) {
+ const url = SOLANA_RPC[network] || SOLANA_RPC.mainnet;
+
+ const sigs = await jsonRpc(url, 'getSignaturesForAddress', [creator, { limit: 50 }]);
+ if (!sigs?.length) return [];
+
+ const toFetch = sigs.slice(0, 20);
+ const batchResults = await jsonRpcBatch(
+ url,
+ toFetch.map((s) => ({
+ method: 'getTransaction',
+ params: [s.signature, { encoding: 'jsonParsed', maxSupportedTransactionVersion: 0 }],
+ })),
+ );
+
+ const claims = [];
+ for (let i = 0; i < batchResults.length && claims.length < 10; i++) {
+ const tx = batchResults[i]?.result;
+ if (!tx) continue;
+
+ const keys = tx.transaction?.message?.accountKeys || [];
+
+ if (!keys.some((k) => getKey(k) === PUMP_PROGRAM)) continue;
+
+ const pre = tx.meta?.preBalances || [];
+ const post = tx.meta?.postBalances || [];
+ const creatorIdx = keys.findIndex((k) => getKey(k) === creator);
+ if (creatorIdx < 0) continue;
+ const delta = (post[creatorIdx] || 0) - (pre[creatorIdx] || 0);
+ if (delta < MIN_CLAIM_LAMPORTS) continue;
+
+ // Find the mint: first account in the pump program instruction that is not
+ // the creator or the program itself, and looks like a token mint (32+ chars).
+ let mint = null;
+ for (const ix of tx.transaction?.message?.instructions || []) {
+ if (ix.programId !== PUMP_PROGRAM) continue;
+ for (const acct of ix.accounts || []) {
+ const pk = typeof acct === 'string' ? acct : getKey(acct);
+ if (pk && pk !== creator && pk !== PUMP_PROGRAM && pk.length >= 32) {
+ mint = pk;
+ break;
+ }
+ }
+ if (mint) break;
+ }
+
+ claims.push({ signature: toFetch[i].signature, blockTime: tx.blockTime, mint, solAmount: delta });
+ }
+
+ return claims;
+}
+
+/**
+ * Mount a fee-claims polling panel beneath `rootEl`.
+ *
+ * @param {HTMLElement} rootEl - Container to append the panel to.
+ * @param {object} opts
+ * @param {string} opts.creator - Creator wallet public key.
+ * @param {number} [opts.intervalMs=30000]
+ * @param {string} [opts.network='mainnet']
+ * @returns {() => void} Cleanup function — clears interval and removes panel.
+ */
+export function mountClaimsPanel(rootEl, { creator, intervalMs = 30_000, network = 'mainnet' } = {}) {
+ if (!rootEl || !creator) return () => {};
+
+ ensureStyles();
+
+ const section = document.createElement('section');
+ section.className = 'three-ws-claims-panel';
+ rootEl.appendChild(section);
+
+ let timer = null;
+ let lastFetch = null;
+
+ function setStatus(text) {
+ const el = section.querySelector('.three-ws-claims-status');
+ if (el) el.textContent = text;
+ }
+
+ function render(claims) {
+ const statusText = lastFetch ? timeAgo(lastFetch / 1000) : '';
+ const rows = claims.length === 0
+ ? `<li class="three-ws-claims-empty">No recent fee claims</li>`
+ : claims.map((c) => {
+ const txUrl = network === 'devnet'
+ ? `https://explorer.solana.com/tx/${esc(c.signature)}?cluster=devnet`
+ : `https://solscan.io/tx/${esc(c.signature)}`;
+ return `
+ <li class="three-ws-claims-item">
+ <span class="three-ws-claims-ts">${esc(timeAgo(c.blockTime))}</span>
+ <span class="three-ws-claims-mint" title="${esc(c.mint || '')}">${esc(shortMint(c.mint))}</span>
+ <span class="three-ws-claims-amount">${esc(formatSol(c.solAmount))}</span>
+ <a class="three-ws-claims-link" href="${txUrl}" target="_blank" rel="noopener" title="View on Solscan">↗</a>
+ </li>
+ `;
+ }).join('');
+
+ section.innerHTML = `
+ <div class="three-ws-claims-head">
+ <span class="three-ws-claims-title">Fee Claims</span>
+ <span class="three-ws-claims-status">${esc(statusText)}</span>
+ </div>
+ <ul class="three-ws-claims-list">${rows}</ul>
+ `;
+ }
+
+ function renderLoading() {
+ section.innerHTML = `
+ <div class="three-ws-claims-head">
+ <span class="three-ws-claims-title">Fee Claims</span>
+ <span class="three-ws-claims-status">loading…</span>
+ </div>
+ `;
+ }
+
+ async function poll() {
+ try {
+ const claims = await fetchClaimEvents(creator, network);
+ lastFetch = Date.now();
+ render(claims);
+ } catch {
+ setStatus('error — retrying');
+ }
+ }
+
+ renderLoading();
+ poll();
+ timer = setInterval(poll, intervalMs);
+
+ return function cleanup() {
+ clearInterval(timer);
+ section.remove();
+ };
+}
diff --git a/src/agent-home.js b/src/agent-home.js
index 11ea4903f..467aafd9a 100644
--- a/src/agent-home.js
+++ b/src/agent-home.js
@@ -12,6 +12,7 @@ import { ACTION_TYPES } from './agent-protocol.js';
import { MEMORY_TYPES } from './agent-memory.js';
import { mountPumpFunCard } from './agent-home-pumpfun.js';
import { mountAgentSolanaWalletCard } from './agent-solana-wallet.js';
+import { mountClaimsPanel } from './agent-home-claims.js';
const ACTION_ICONS = {
[ACTION_TYPES.SPEAK]: '💬',
@@ -53,6 +54,7 @@ export class AgentHome {
this._timeline = [];
this._maxTimeline = 30;
this._emotionInterval = null;
+ this._destroyClaims = null;
}
// ── Lifecycle ─────────────────────────────────────────────────────────────
@@ -65,6 +67,7 @@ export class AgentHome {
}
destroy() {
+ if (this._destroyClaims) this._destroyClaims();
if (this._panel) this._panel.remove();
clearInterval(this._emotionInterval);
this.protocol.off('*', this._onAnyAction);
@@ -214,6 +217,20 @@ export class AgentHome {
mountPumpIfReady();
+ // Claims panel — only when creatorWallet is set on the agent profile.
+ const creatorWallet =
+ this.identity.creatorWallet ||
+ this.identity.meta?.creator_wallet ||
+ this.identity.meta?.creatorWallet;
+ if (creatorWallet) {
+ const claimsNetwork = this.identity.meta?.pumpfun_network || 'mainnet';
+ try {
+ this._destroyClaims = mountClaimsPanel(panel, { creator: creatorWallet, network: claimsNetwork });
+ } catch {
+ /* panel is optional */
+ }
+ }
+
// Permissions manage panel — lazy load; degrades gracefully if unauthenticated
const agentId = this.identity.id;
if (agentId) {
diff --git a/src/agent-skills-pumpfun-watch.js b/src/agent-skills-pumpfun-watch.js
index d5455d7e7..29ac1fbe7 100644
--- a/src/agent-skills-pumpfun-watch.js
+++ b/src/agent-skills-pumpfun-watch.js
@@ -219,6 +219,164 @@ export function registerPumpFunWatchSkills(skills) {
};
},
});
+
+ // ── pumpfun.watchWhales ───────────────────────────────────────────────────
+ skills.register({
+ name: 'pumpfun.watchWhales',
+ description:
+ 'Watch for whale buys/sells on a pump.fun token. Streams alert messages as trades arrive.',
+ instruction:
+ 'Subscribes to live pump.fun bonding-curve trades and speaks each trade that meets minUsd.',
+ animationHint: 'curiosity',
+ voicePattern: 'Watching {{mint}} for whale trades…',
+ mcpExposed: false, // browser-only WebSocket; MCP variant is pumpfun_watch_whales in pump-fun-mcp.js
+ inputSchema: {
+ type: 'object',
+ properties: {
+ mint: { type: 'string', description: 'SPL mint pubkey (base58)' },
+ minUsd: { type: 'number', description: 'Minimum trade value in USD (default 5000)' },
+ durationMs: {
+ type: 'number',
+ description: 'Watch window in ms (default 300000, max 1800000)',
+ },
+ },
+ required: ['mint'],
+ },
+ handler: async (args, ctx) => {
+ if (typeof window === 'undefined') {
+ return { success: false, output: 'Whale watch requires a browser.', sentiment: -0.3 };
+ }
+ const mint = args?.mint;
+ if (!mint) return { success: false, output: 'mint required', sentiment: -0.2 };
+
+ if (_whaleWatchers.has(mint)) {
+ return {
+ success: true,
+ output: `Already watching ${mint.slice(0, 8)}… for whales.`,
+ sentiment: 0.1,
+ };
+ }
+
+ const minUsd = Math.max(1, Number(args?.minUsd) || 5000);
+ const durationMs = Math.min(
+ 1_800_000,
+ Math.max(5_000, Number(args?.durationMs) || 300_000),
+ );
+
+ const ac = new AbortController();
+ _whaleWatchers.set(mint, ac);
+
+ const protocol = ctx.protocol;
+ const speak = (text, sentiment = 0) =>
+ protocol?.emit({ type: ACTION_TYPES.SPEAK, payload: { text, sentiment } });
+
+ const stop = () => {
+ ac.abort();
+ _whaleWatchers.delete(mint);
+ };
+ const timer = setTimeout(stop, durationMs);
+ ac.signal.addEventListener('abort', () => clearTimeout(timer));
+
+ try {
+ const { watchWhaleTrades } = await import('./pump/pumpkit-whale.js');
+ watchWhaleTrades({
+ mint,
+ minUsd,
+ signal: ac.signal,
+ onTrade(trade) {
+ const side = trade.sideBuy ? 'bought' : 'sold';
+ speak(
+ `🐋 Whale ${side} $${Math.round(trade.usd).toLocaleString()} (${trade.sol.toFixed(2)} SOL) — ${trade.wallet.slice(0, 8)}…`,
+ trade.sideBuy ? 0.7 : -0.2,
+ );
+ },
+ }).catch(stop);
+ } catch (err) {
+ stop();
+ return {
+ success: false,
+ output: `Failed to start whale watch: ${err.message}`,
+ sentiment: -0.4,
+ };
+ }
+
+ speak(
+ `Watching ${mint.slice(0, 8)}… for trades ≥ $${minUsd.toLocaleString()}.`,
+ 0.3,
+ );
+
+ return {
+ success: true,
+ output: `Started whale watch on ${mint.slice(0, 8)}… — min $${minUsd.toLocaleString()}, ${Math.round(durationMs / 60_000)} min.`,
+ sentiment: 0.4,
+ data: { mint, minUsd, durationMs },
+ };
+ },
+ });
+
+ skills.register({
+ name: 'pumpfun-watch-claims',
+ description:
+ 'Watch for pump.fun fee-claim events from a specific creator wallet and react as they arrive.',
+ instruction:
+ 'Polls Solana RPC for fee-claim transactions. Emits speak/emote per claim. Resolves after durationMs.',
+ animationHint: 'curiosity',
+ voicePattern: 'Watching {{creator}} for claims…',
+ mcpExposed: false, // long-running poll — not suitable for MCP request/response
+ inputSchema: {
+ type: 'object',
+ properties: {
+ creator: { type: 'string', description: 'Creator wallet address (base58)' },
+ durationMs: {
+ type: 'number',
+ description: 'Watch window in ms (default 300000, max 1800000)',
+ },
+ network: { type: 'string', enum: ['mainnet', 'devnet'] },
+ },
+ required: ['creator'],
+ },
+ handler: async (args, ctx) => {
+ if (!args?.creator) {
+ return { success: false, output: 'creator wallet required', sentiment: -0.2 };
+ }
+ const duration = Math.min(1_800_000, Math.max(5_000, Number(args.durationMs) || 300_000));
+ const ctrl = new AbortController();
+ const timeout = setTimeout(() => ctrl.abort(), duration);
+
+ const protocol = ctx?.protocol;
+ const speak = (text, sentiment = 0) =>
+ protocol?.emit({ type: ACTION_TYPES.SPEAK, payload: { text, sentiment } });
+ const emote = (trigger, weight) =>
+ protocol?.emit({ type: ACTION_TYPES.EMOTE, payload: { trigger, weight } });
+
+ const claims = [];
+ try {
+ await watchClaims({
+ creator: args.creator,
+ signal: ctrl.signal,
+ network: args.network || 'mainnet',
+ onClaim: (claim) => {
+ claims.push(claim);
+ const sol = (claim.lamports / 1e9).toFixed(4);
+ const tag = claim.mint ? ` (${claim.mint.slice(0, 8)}…)` : '';
+ emote('curiosity', 0.6);
+ speak(`Claim detected: ${sol} SOL${tag}`, 0.4);
+ },
+ });
+ } finally {
+ clearTimeout(timeout);
+ }
+
+ return {
+ success: true,
+ output: claims.length
+ ? `Saw ${claims.length} claim${claims.length === 1 ? '' : 's'} in ${duration / 1000}s.`
+ : `No claims from ${args.creator.slice(0, 8)}… in ${duration / 1000}s.`,
+ sentiment: claims.length ? 0.4 : 0,
+ data: { claims },
+ };
+ },
+ });
}
function safeJson(s) {
diff --git a/src/agent-skills-pumpfun.js b/src/agent-skills-pumpfun.js
index 5bd3745c4..8b6466be0 100644
--- a/src/agent-skills-pumpfun.js
+++ b/src/agent-skills-pumpfun.js
@@ -18,6 +18,10 @@
*/
import { detectSolanaWallet, SOLANA_RPC } from './erc8004/solana-deploy.js';
+import { fetchChannelFeed } from './pump/channel-feed.js';
+import { listRecentClaims } from './pump/pumpkit-claims.js';
+import { getWalletPnl } from './kol/wallet-pnl.js';
+import { getRadarSignals } from './kol/radar.js';
const DEFAULT_NETWORK = 'mainnet';
const DEFAULT_SLIPPAGE_BPS = 500;
@@ -745,6 +749,100 @@ export function registerPumpFunSkills(skills) {
},
});
+ // ── pumpfun.channelFeed ───────────────────────────────────────────────────
+ skills.register({
+ name: 'pumpfun.channelFeed',
+ description: 'Fetch recent pump.fun signals (new mints, whale buys, creator claims) as a digest the LLM can summarize.',
+ instruction: 'Read-only. No wallet required. Returns latest channel-feed items.',
+ animationHint: 'inspect',
+ voicePattern: 'Fetching pump.fun signal feed…',
+ mcpExposed: true,
+ inputSchema: {
+ type: 'object',
+ properties: {
+ limit: { type: 'integer', minimum: 1, maximum: 200, default: 20 },
+ kinds: {
+ type: 'string',
+ description: 'Comma-separated filter: mint, whale, claim (default: all)',
+ },
+ },
+ },
+ handler: async (args, _ctx) => {
+ const limit = args.limit ?? 20;
+ const kinds = args.kinds ?? undefined;
+ let data;
+ try {
+ data = await fetchChannelFeed({ limit, kinds });
+ } catch (err) {
+ return {
+ success: false,
+ output: `Failed to fetch channel feed: ${err.message}`,
+ sentiment: -0.2,
+ };
+ }
+ const items = data.items ?? [];
+ if (!items.length) {
+ return {
+ success: true,
+ output: 'No recent pump.fun signals found.',
+ sentiment: 0,
+ data: { items: [] },
+ };
+ }
+ const digest = items
+ .slice(0, 10)
+ .map((i) => `[${i.kind}] ${i.mint?.slice(0, 8) ?? '?'}… ${i.summary}`.trimEnd())
+ .join('\n');
+ return {
+ success: true,
+ output: `${items.length} signal${items.length !== 1 ? 's' : ''}:\n${digest}`,
+ sentiment: 0.3,
+ data: { items },
+ };
+ },
+ });
+
+ // ── kol.radar ─────────────────────────────────────────────────────────────
+ skills.register({
+ name: 'kol.radar',
+ description:
+ 'Return gmgn radar signals: early-detection patterns by category, sorted by score.',
+ instruction: 'Read-only. Returns fixture data from src/kol/radar-fixture.json.',
+ animationHint: 'inspect',
+ voicePattern: 'Checking radar for {{category}} signals…',
+ mcpExposed: true,
+ inputSchema: {
+ type: 'object',
+ properties: {
+ category: {
+ type: 'string',
+ enum: ['pump-fun', 'new-mints', 'volume-spike'],
+ default: 'pump-fun',
+ description: 'Signal category to filter by',
+ },
+ limit: {
+ type: 'integer',
+ minimum: 1,
+ maximum: 100,
+ default: 20,
+ description: 'Max results (capped at 100)',
+ },
+ },
+ },
+ handler: async (args, _ctx) => {
+ const signals = await getRadarSignals({
+ category: args.category ?? 'pump-fun',
+ limit: args.limit ?? 20,
+ });
+ return {
+ success: true,
+ output: `Found ${signals.length} radar signal(s) for "${args.category ?? 'pump-fun'}".`,
+ sentiment: signals.length > 0 ? 0.6 : 0.1,
+ data: { signals, category: args.category ?? 'pump-fun', count: signals.length },
+ };
+ },
+ });
+
// ── pumpfun-accept-payment ────────────────────────────────────────────────
skills.register({
name: 'pumpfun-accept-payment',
@@ -821,4 +919,297 @@ export function registerPumpFunSkills(skills) {
};
},
});
-}
+
+ // ── pumpfun-verify-payment ────────────────────────────────────────────────
+ skills.register({
+ name: 'pumpfun-verify-payment',
+ description:
+ 'Verify that a pump.fun agent payment invoice was settled on-chain. Returns verified:true/false. No wallet required.',
+ instruction:
+ 'Calls PumpAgent.validateInvoicePayment. Queries Pump HTTP API with RPC fallback. All seven invoice fields must match exactly.',
+ animationHint: 'inspect',
+ voicePattern: 'Verifying invoice {{memo}}…',
+ mcpExposed: true,
+ inputSchema: {
+ type: 'object',
+ properties: {
+ agentMint: { type: 'string', description: 'The agent token mint' },
+ user: { type: 'string', description: 'Payer wallet address (base58)' },
+ currencyMint: { type: 'string', description: 'Currency mint (USDC, wSOL, etc.)' },
+ amount: { type: 'number', description: 'Amount in base units (6 decimals USDC, 9 for wSOL)' },
+ memo: { type: 'number', description: 'Invoice memo / nonce (uint)' },
+ startTime: { type: 'number', description: 'Invoice validity window start (Unix seconds)' },
+ endTime: { type: 'number', description: 'Invoice validity window end (Unix seconds)' },
+ network: { type: 'string', enum: ['mainnet', 'devnet'] },
+ },
+ required: ['agentMint', 'user', 'currencyMint', 'amount', 'memo', 'startTime', 'endTime'],
+ },
+ handler: async (args, _ctx) => {
+ if (!(args.amount > 0)) {
+ return { success: false, output: 'amount must be > 0', sentiment: -0.2 };
+ }
+ if (args.endTime <= args.startTime) {
+ return { success: false, output: 'endTime must be after startTime', sentiment: -0.2 };
+ }
+ const network = args.network || DEFAULT_NETWORK;
+ const { pay, web3 } = await loadAgentPayments();
+ const connection = getConnection(web3, network);
+ const agentMint = new web3.PublicKey(args.agentMint);
+ const env = network === 'devnet' ? 'devnet' : 'mainnet';
+ const agent = new pay.PumpAgent(agentMint, env, connection);
+ const verified = await agent.validateInvoicePayment({
+ user: new web3.PublicKey(args.user),
+ currencyMint: new web3.PublicKey(args.currencyMint),
+ amount: args.amount,
+ memo: args.memo,
+ startTime: args.startTime,
+ endTime: args.endTime,
+ });
+ return {
+ success: true,
+ output: verified
+ ? `Invoice ${args.memo} verified — payment confirmed.`
+ : `Invoice ${args.memo} not confirmed yet.`,
+ sentiment: verified ? 0.7 : 0.0,
+ data: {
+ verified,
+ memo: args.memo,
+ agentMint: args.agentMint,
+ network,
+ },
+ };
+ },
+ });
+
+ // ── kol.walletPnl ────────────────────────────────────────────────────────
+ skills.register({
+ name: 'kol.walletPnl',
+ description: 'Compute realized + unrealized P&L for a Solana wallet over a time window.',
+ instruction: 'FIFO cost-basis P&L. Returns realizedUsd, unrealizedUsd, totalUsd, winRate, openPositions.',
+ animationHint: 'inspect',
+ voicePattern: 'Checking P&L for {{wallet}}…',
+ mcpExposed: true,
+ inputSchema: {
+ type: 'object',
+ properties: {
+ wallet: { type: 'string', description: 'Solana wallet address (base58)' },
+ window: {
+ type: 'string',
+ enum: ['24h', '7d', '30d', 'all'],
+ description: 'Time window (default 7d)',
+ },
+ },
+ required: ['wallet'],
+ },
+ handler: async (args, _ctx) => {
+ const pnl = await getWalletPnl({ wallet: args.wallet, window: args.window ?? '7d' });
+ const sign = pnl.totalUsd >= 0 ? '+' : '';
+ return {
+ success: true,
+ output: `Wallet ${args.wallet.slice(0, 8)}… P&L (${pnl.window}): ${sign}$${pnl.totalUsd.toFixed(2)} total (realized ${sign}$${pnl.realizedUsd.toFixed(2)}, unrealized $${pnl.unrealizedUsd.toFixed(2)}). Win rate: ${(pnl.winRate * 100).toFixed(0)}% over ${pnl.trades} trades.`,
+ sentiment: pnl.totalUsd > 0 ? 0.6 : pnl.totalUsd < 0 ? -0.2 : 0.1,
+ data: pnl,
+ };
+ },
+ });
+
+ // ── pumpfun-invoice-pda ───────────────────────────────────────────────────
+ skills.register({
+ name: 'pumpfun-invoice-pda',
+ description:
+ 'Derive the deterministic on-chain Invoice ID PDA. Use before building a payment tx to pre-check duplicate invoices.',
+ instruction:
+ 'Calls getInvoiceIdPDA from @pump-fun/agent-payments-sdk. Pure offline computation — no wallet or network call.',
+ animationHint: 'inspect',
+ voicePattern: 'Deriving invoice PDA…',
+ mcpExposed: true,
+ inputSchema: {
+ type: 'object',
+ properties: {
+ agentMint: { type: 'string', description: 'The agent token mint (tokenMint)' },
+ currencyMint: { type: 'string', description: 'Currency mint' },
+ amount: { type: 'number' },
+ memo: { type: 'number' },
+ startTime: { type: 'number', description: 'Unix seconds' },
+ endTime: { type: 'number', description: 'Unix seconds' },
+ },
+ required: ['agentMint', 'currencyMint', 'amount', 'memo', 'startTime', 'endTime'],
+ },
+ handler: async (args, _ctx) => {
+ const { pay, web3 } = await loadAgentPayments();
+ const [pda, bump] = pay.getInvoiceIdPDA(
+ new web3.PublicKey(args.agentMint),
+ new web3.PublicKey(args.currencyMint),
+ args.amount,
+ args.memo,
+ args.startTime,
+ args.endTime,
+ );
+ return {
+ success: true,
+ output: `Invoice PDA: ${pda.toBase58()} (bump ${bump}).`,
+ sentiment: 0.1,
+ data: {
+ pda: pda.toBase58(),
+ bump,
+ agentMint: args.agentMint,
+ },
+ };
+ },
+ });
+
+ // ── pumpfun-list-claims ───────────────────────────────────────────────────
+ skills.register({
+ name: 'pumpfun-list-claims',
+ description:
+ 'List recent pump.fun fee-claim events for a specific creator wallet. Returns signature, mint, lamports, and timestamp for each claim.',
+ instruction: 'Read-only. Polls Solana RPC directly — no indexer needed.',
+ animationHint: 'think',
+ voicePattern: 'Fetching claims for {{creator}}…',
+ mcpExposed: true,
+ inputSchema: {
+ type: 'object',
+ properties: {
+ creator: { type: 'string', description: 'Creator wallet address (base58)' },
+ limit: { type: 'integer', minimum: 1, maximum: 50, default: 20 },
+ network: { type: 'string', enum: ['mainnet', 'devnet'] },
+ },
+ required: ['creator'],
+ },
+ handler: async (args, _ctx) => {
+ if (!args?.creator) {
+ return { success: false, output: 'creator wallet required', sentiment: -0.2 };
+ }
+ const limit = Math.min(50, Math.max(1, Number(args.limit) || 20));
+ try {
+ const claims = await listRecentClaims({
+ creator: args.creator,
+ limit,
+ network: args.network || DEFAULT_NETWORK,
+ });
+ return {
+ success: true,
+ output: claims.length
+ ? `${claims.length} recent claim${claims.length === 1 ? '' : 's'} for ${args.creator.slice(0, 8)}…\n` +
+ claims
+ .map((c) => ` ${c.signature.slice(0, 8)}… — ${(c.lamports / 1e9).toFixed(4)} SOL`)
+ .join('\n')
+ : `No recent claims found for ${args.creator.slice(0, 8)}…`,
+ sentiment: claims.length ? 0.3 : 0,
+ data: { claims },
+ };
+ } catch (err) {
+ return {
+ success: false,
+ output: `Could not fetch claims: ${err.message}`,
+ sentiment: -0.3,
+ };
+ }
+ },
+ });
+
+ // ── pumpfun.vanityMint ────────────────────────────────────────────────────
+ skills.register({
+ name: 'pumpfun.vanityMint',
+ description:
+ 'Generate a Solana keypair whose address matches a vanity suffix/prefix. Returns { publicKey, secretKey: base58, attempts, ms }. Caller must save the secret key — it is never stored.',
+ instruction:
+ 'Searches for a Solana address ending/starting with the requested pattern. May take seconds to minutes depending on length.',
+ animationHint: 'gesture',
+ voicePattern: 'Searching for a vanity address ending in {{suffix}}…',
+ mcpExposed: true,
+ inputSchema: {
+ type: 'object',
+ properties: {
+ suffix: { type: 'string', description: 'Desired address suffix (case-insensitive by default)' },
+ prefix: { type: 'string', description: 'Desired address prefix (case-insensitive by default)' },
+ caseSensitive: { type: 'boolean', default: false },
+ maxAttempts: { type: 'integer', default: 5000000 },
+ },
+ },
+ handler: async (args, _ctx) => {
+ const { generateVanityKey } = await import('./pump/vanity-keygen.js');
+ const bs58 = (await import('bs58')).default;
+
+ const ac = new AbortController();
+ const timer = setTimeout(() => ac.abort(), 58_000);
+ let result;
+ try {
+ result = await generateVanityKey({
+ suffix: args.suffix || '',
+ prefix: args.prefix || '',
+ caseSensitive: args.caseSensitive ?? false,
+ maxAttempts: args.maxAttempts ?? 5_000_000,
+ signal: ac.signal,
+ });
+ } finally {
+ clearTimeout(timer);
+ }
+
+ if (!result) {
+ return {
+ success: false,
+ output: 'No matching address found within the attempt limit.',
+ sentiment: -0.2,
+ };
+ }
+ return {
+ success: true,
+ output: `Found vanity address: ${result.publicKey} (${result.attempts} attempts, ${result.ms} ms)`,
+ sentiment: 0.8,
+ data: {
+ publicKey: result.publicKey,
+ secretKey: bs58.encode(result.secretKey),
+ attempts: result.attempts,
+ ms: result.ms,
+ },
+ };
+ },
+ });
+
+ // ── kol.leaderboard ──────────────────────────────────────────────────────
+ skills.register({
+ name: 'kol.leaderboard',
+ description: 'Show the top KOL traders ranked by P&L. Returns wallet, pnlUsd, winRate, trades, rank.',
+ instruction: 'Fetch the KOL leaderboard for a given time window and limit. No wallet required.',
+ animationHint: 'inspect',
+ voicePattern: 'Fetching top KOLs for {{window}}…',
+ mcpExposed: true,
+ inputSchema: {
+ type: 'object',
+ properties: {
+ window: { type: 'string', enum: ['24h', '7d', '30d'], description: 'Time window (default 7d)' },
+ limit: { type: 'number', description: 'Max entries to return, 1–100 (default 25)' },
+ },
+ },
+ handler: async (args, _ctx) => {
+ const origin = (typeof window !== 'undefined' && window.location?.origin) || '';
+ const params = new URLSearchParams({
+ window: args.window || '7d',
+ limit: String(Math.min(Math.max(1, Math.floor(Number(args.limit) || 25)), 100)),
+ });
+ const res = await fetch(`${origin}/api/kol/leaderboard?${params}`);
+ const body = await res.json();
+ if (!res.ok) {
+ return {
+ success: false,
+ output: body.error_description || body.error || 'leaderboard fetch failed',
+ sentiment: -0.1,
+ };
+ }
+ const items = body.items || [];
+ const top3 = items.slice(0, 3).map((e) =>
+ `#${e.rank} ${e.wallet.slice(0, 8)}… $${e.pnlUsd.toLocaleString()} (${(e.winRate * 100).toFixed(0)}% wr)`
+ ).join(', ');
+ return {
+ success: true,
+ output: items.length
+ ? `Top ${items.length} KOLs (${args.window || '7d'}): ${top3}${items.length > 3 ? '…' : ''}`
+ : 'No leaderboard data available.',
+ sentiment: 0.3,
+ data: { items },
+ };
+ },
+ });
+
+}
\ No newline at end of file
diff --git a/src/kol/leaderboard.js b/src/kol/leaderboard.js
new file mode 100644
index 000000000..188687b71
--- /dev/null
+++ b/src/kol/leaderboard.js
@@ -0,0 +1,47 @@
+// KOL leaderboard — static seed scoring.
+//
+// Data source: src/kol/seed.json — a curated static snapshot of top-trader
+// stats derived from kol-quest (https://github.com/nirholas/kol-quest)
+// leaderboard methodology (pnlUsd, winRate, trades per window). A live
+// implementation would replace this with an indexer query (e.g. GMGN or
+// KolScan API) but the scoring shape is identical.
+
+import { readFileSync } from 'fs';
+import { fileURLToPath } from 'url';
+import { dirname, join } from 'path';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const seed = JSON.parse(readFileSync(join(__dirname, 'seed.json'), 'utf8'));
+
+const VALID_WINDOWS = new Set(['24h', '7d', '30d']);
+
+/**
+ * @param {{ window?: '24h'|'7d'|'30d', limit?: number }} opts
+ * @returns {Promise<Array<{ wallet: string, pnlUsd: number, winRate: number, trades: number, rank: number }>>}
+ */
+export async function getLeaderboard({ window = '7d', limit = 25 } = {}) {
+ if (!VALID_WINDOWS.has(window)) {
+ const err = new Error(`invalid window "${window}": must be 24h, 7d, or 30d`);
+ err.status = 400;
+ err.code = 'invalid_window';
+ throw err;
+ }
+
+ const cap = Math.min(Math.max(1, Math.floor(Number(limit) || 25)), 100);
+
+ return seed
+ .map((entry) => {
+ const stats = entry.windows?.[window];
+ if (!stats) return null;
+ return {
+ wallet: entry.wallet,
+ pnlUsd: stats.pnlUsd,
+ winRate: stats.winRate,
+ trades: stats.trades,
+ };
+ })
+ .filter(Boolean)
+ .sort((a, b) => b.pnlUsd - a.pnlUsd)
+ .slice(0, cap)
+ .map((item, i) => ({ ...item, rank: i + 1 }));
+}
diff --git a/src/kol/radar-fixture.json b/src/kol/radar-fixture.json
new file mode 100644
index 000000000..3cf6dba9c
--- /dev/null
+++ b/src/kol/radar-fixture.json
@@ -0,0 +1,82 @@
+[
+ {
+ "mint": "7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU",
+ "name": "Mooncat",
+ "symbol": "MCAT",
+ "signalType": "pump-fun",
+ "score": 92,
+ "ts": 1714300800000
+ },
+ {
+ "mint": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
+ "name": "RocketDoge",
+ "symbol": "RDOGE",
+ "signalType": "pump-fun",
+ "score": 88,
+ "ts": 1714297200000
+ },
+ {
+ "mint": "So11111111111111111111111111111111111111112",
+ "name": "SolFloki",
+ "symbol": "SFLOKI",
+ "signalType": "pump-fun",
+ "score": 75,
+ "ts": 1714293600000
+ },
+ {
+ "mint": "4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R",
+ "name": "FreshApe",
+ "symbol": "FAPE",
+ "signalType": "new-mints",
+ "score": 85,
+ "ts": 1714300000000
+ },
+ {
+ "mint": "9n4nbM75f5Ui33ZbPYXn59EwSgE8CGsHtAeTH5YFeJ9E",
+ "name": "NovaCoin",
+ "symbol": "NOVA",
+ "signalType": "new-mints",
+ "score": 78,
+ "ts": 1714296400000
+ },
+ {
+ "mint": "2FPyTwcZLUgjTrXjX7sHFxCB2pDV3tNVBUwWnDUZaRqo",
+ "name": "ZeroGrav",
+ "symbol": "ZGRAV",
+ "signalType": "new-mints",
+ "score": 61,
+ "ts": 1714292800000
+ },
+ {
+ "mint": "3uetDDizgTtadDHZzyy9yWe3TwFmkpAfwzeut5HkPeRZ",
+ "name": "TurboVol",
+ "symbol": "TVOL",
+ "signalType": "volume-spike",
+ "score": 97,
+ "ts": 1714301000000
+ },
+ {
+ "mint": "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB",
+ "name": "SpikeKing",
+ "symbol": "SPKNG",
+ "signalType": "volume-spike",
+ "score": 91,
+ "ts": 1714299500000
+ },
+ {
+ "mint": "mSoLzYCxHdYgdzU16g5QSh3i5K3z3KZK7ytfqcJm7So",
+ "name": "PumpBurst",
+ "symbol": "PBURST",
+ "signalType": "volume-spike",
+ "score": 83,
+ "ts": 1714295000000
+ },
+ {
+ "mint": "7vfCXTUXx5WJV5JADk17DUJ4ksgau7utNKj4b963voxs",
+ "name": "AlphaRaid",
+ "symbol": "ARAID",
+ "signalType": "volume-spike",
+ "score": 70,
+ "ts": 1714291000000
+ }
+]
diff --git a/src/kol/radar.js b/src/kol/radar.js
new file mode 100644
index 000000000..f0a9677af
--- /dev/null
+++ b/src/kol/radar.js
@@ -0,0 +1,24 @@
+// Refresh: paste the latest gmgn radar JSON over src/kol/radar-fixture.json.
+// Each entry must have: { mint, name, symbol, signalType, score, ts }.
+
+import fixtureData from './radar-fixture.json' with { type: 'json' };
+
+const MAX_LIMIT = 100;
+const VALID_CATEGORIES = new Set(['pump-fun', 'new-mints', 'volume-spike']);
+
+/**
+ * @param {{ category?: string, limit?: number }} opts
+ * @returns {{ mint: string, name: string, symbol: string, signalType: string, score: number, ts: number }[]}
+ */
+export async function getRadarSignals({ category = 'pump-fun', limit = 20 } = {}) {
+ if (!VALID_CATEGORIES.has(category)) {
+ throw new Error(`Unknown category "${category}". Valid: ${[...VALID_CATEGORIES].join(', ')}`);
+ }
+
+ const cap = Math.min(Math.max(1, limit), MAX_LIMIT);
+
+ return fixtureData
+ .filter((entry) => entry.signalType === category)
+ .sort((a, b) => b.score - a.score)
+ .slice(0, cap);
+}
diff --git a/src/kol/seed.json b/src/kol/seed.json
new file mode 100644
index 000000000..cebbc4957
--- /dev/null
+++ b/src/kol/seed.json
@@ -0,0 +1,242 @@
+[
+ {
+ "wallet": "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM",
+ "windows": {
+ "24h": { "pnlUsd": 14820.50, "winRate": 0.81, "trades": 22 },
+ "7d": { "pnlUsd": 97400.00, "winRate": 0.76, "trades": 134 },
+ "30d": { "pnlUsd": 312000.00, "winRate": 0.72, "trades": 480 }
+ }
+ },
+ {
+ "wallet": "DRpbCBMxVnDK7maPM5tGv6MvB3v1sRMC86PZ8okm21hy",
+ "windows": {
+ "24h": { "pnlUsd": 9150.25, "winRate": 0.74, "trades": 18 },
+ "7d": { "pnlUsd": 71200.00, "winRate": 0.70, "trades": 112 },
+ "30d": { "pnlUsd": 248000.00, "winRate": 0.68, "trades": 390 }
+ }
+ },
+ {
+ "wallet": "H6ARHf6YXhGYeQfUzQNGk6rDNnLBQKrenN712K4AQJEG",
+ "windows": {
+ "24h": { "pnlUsd": 7640.00, "winRate": 0.78, "trades": 14 },
+ "7d": { "pnlUsd": 58900.00, "winRate": 0.73, "trades": 98 },
+ "30d": { "pnlUsd": 201500.00, "winRate": 0.70, "trades": 340 }
+ }
+ },
+ {
+ "wallet": "3DxttfkLFJ2URMFjnFwNEDBzE8aGGmBR9xbSVdLJcTFG",
+ "windows": {
+ "24h": { "pnlUsd": 6200.75, "winRate": 0.69, "trades": 19 },
+ "7d": { "pnlUsd": 44700.00, "winRate": 0.65, "trades": 121 },
+ "30d": { "pnlUsd": 178000.00, "winRate": 0.63, "trades": 430 }
+ }
+ },
+ {
+ "wallet": "7YttLkHDoNj9wyDur5pM1ejNaAvT9X4eqaYcHQqg9GsX",
+ "windows": {
+ "24h": { "pnlUsd": 5480.20, "winRate": 0.72, "trades": 11 },
+ "7d": { "pnlUsd": 38200.00, "winRate": 0.68, "trades": 76 },
+ "30d": { "pnlUsd": 142000.00, "winRate": 0.65, "trades": 280 }
+ }
+ },
+ {
+ "wallet": "FWznbcNXWQuHTawe9RxvQ37LyqZJAe7sK4nSt7FgPhJM",
+ "windows": {
+ "24h": { "pnlUsd": 4320.60, "winRate": 0.67, "trades": 16 },
+ "7d": { "pnlUsd": 31500.00, "winRate": 0.63, "trades": 103 },
+ "30d": { "pnlUsd": 118000.00, "winRate": 0.61, "trades": 365 }
+ }
+ },
+ {
+ "wallet": "A8yNzT4A2JkB3F5MpQ7vR9cHsLeX6wGdKbNmUjZiPeVY",
+ "windows": {
+ "24h": { "pnlUsd": 3890.40, "winRate": 0.75, "trades": 8 },
+ "7d": { "pnlUsd": 27800.00, "winRate": 0.71, "trades": 55 },
+ "30d": { "pnlUsd": 99000.00, "winRate": 0.69, "trades": 210 }
+ }
+ },
+ {
+ "wallet": "BqZxVp3JmW1rY5nC8hTkAeLf2dNsoGiU4cRbMy6KjXwD",
+ "windows": {
+ "24h": { "pnlUsd": 3100.00, "winRate": 0.65, "trades": 20 },
+ "7d": { "pnlUsd": 23400.00, "winRate": 0.62, "trades": 130 },
+ "30d": { "pnlUsd": 84500.00, "winRate": 0.60, "trades": 458 }
+ }
+ },
+ {
+ "wallet": "EjKL9pNqR3sT6uV1wX4yZ7aBcDeFgHiJkMnOpQrStUvW",
+ "windows": {
+ "24h": { "pnlUsd": 2750.80, "winRate": 0.70, "trades": 10 },
+ "7d": { "pnlUsd": 19900.00, "winRate": 0.66, "trades": 67 },
+ "30d": { "pnlUsd": 73000.00, "winRate": 0.64, "trades": 245 }
+ }
+ },
+ {
+ "wallet": "Cz2mN8bPqA5tY1vD4wG7hJ3kL6oR9sF0eXiBjMnKpUcV",
+ "windows": {
+ "24h": { "pnlUsd": 2300.00, "winRate": 0.62, "trades": 13 },
+ "7d": { "pnlUsd": 16800.00, "winRate": 0.59, "trades": 87 },
+ "30d": { "pnlUsd": 62000.00, "winRate": 0.57, "trades": 312 }
+ }
+ },
+ {
+ "wallet": "GuWz4bA7cQ9dRpNeX2sJ5kM8nT1oVyF3hLiKjBePqCxZ",
+ "windows": {
+ "24h": { "pnlUsd": 1980.50, "winRate": 0.68, "trades": 9 },
+ "7d": { "pnlUsd": 14200.00, "winRate": 0.64, "trades": 59 },
+ "30d": { "pnlUsd": 52000.00, "winRate": 0.62, "trades": 214 }
+ }
+ },
+ {
+ "wallet": "P3kRtYuIoHgFdSaWqZxCvBnMlKjHgFdSaWqZxCvBnMlK",
+ "windows": {
+ "24h": { "pnlUsd": 1650.30, "winRate": 0.64, "trades": 12 },
+ "7d": { "pnlUsd": 11900.00, "winRate": 0.61, "trades": 80 },
+ "30d": { "pnlUsd": 43000.00, "winRate": 0.59, "trades": 287 }
+ }
+ },
+ {
+ "wallet": "LmNoPqRsTuVwXyZ1AbCdEfGhIjKlMnOpQrStUvWxYzAb",
+ "windows": {
+ "24h": { "pnlUsd": 1420.00, "winRate": 0.60, "trades": 15 },
+ "7d": { "pnlUsd": 9800.00, "winRate": 0.57, "trades": 96 },
+ "30d": { "pnlUsd": 35500.00, "winRate": 0.55, "trades": 345 }
+ }
+ },
+ {
+ "wallet": "RsTuVwXyZ2BcDeFgHiJkLmNoPqRsTuVwXyZ2BcDeFgHi",
+ "windows": {
+ "24h": { "pnlUsd": 1180.60, "winRate": 0.58, "trades": 17 },
+ "7d": { "pnlUsd": 8300.00, "winRate": 0.55, "trades": 109 },
+ "30d": { "pnlUsd": 29000.00, "winRate": 0.53, "trades": 390 }
+ }
+ },
+ {
+ "wallet": "XyZ3CdEfGhIjKlMnOpQrStUvWxYzAbCdEfGhIjKlMnOp",
+ "windows": {
+ "24h": { "pnlUsd": 980.40, "winRate": 0.63, "trades": 8 },
+ "7d": { "pnlUsd": 6900.00, "winRate": 0.59, "trades": 52 },
+ "30d": { "pnlUsd": 24500.00, "winRate": 0.57, "trades": 189 }
+ }
+ },
+ {
+ "wallet": "AbCdEfGhIjKlMnOpQrStUvWxYzAbCdEfGhIjKlMnOpQr",
+ "windows": {
+ "24h": { "pnlUsd": 820.00, "winRate": 0.56, "trades": 14 },
+ "7d": { "pnlUsd": 5700.00, "winRate": 0.53, "trades": 90 },
+ "30d": { "pnlUsd": 20000.00, "winRate": 0.51, "trades": 322 }
+ }
+ },
+ {
+ "wallet": "FgHiJkLmNoPqRsTuVwXyZ4DeFgHiJkLmNoPqRsTuVwXy",
+ "windows": {
+ "24h": { "pnlUsd": 690.50, "winRate": 0.61, "trades": 7 },
+ "7d": { "pnlUsd": 4600.00, "winRate": 0.57, "trades": 45 },
+ "30d": { "pnlUsd": 16500.00, "winRate": 0.55, "trades": 162 }
+ }
+ },
+ {
+ "wallet": "KlMnOpQrStUvWxYzAbCdEfGhIjKlMnOpQrStUvWxYzAb",
+ "windows": {
+ "24h": { "pnlUsd": 560.20, "winRate": 0.55, "trades": 11 },
+ "7d": { "pnlUsd": 3800.00, "winRate": 0.52, "trades": 72 },
+ "30d": { "pnlUsd": 13500.00, "winRate": 0.50, "trades": 259 }
+ }
+ },
+ {
+ "wallet": "PqRsTuVwXyZ5EfGhIjKlMnOpQrStUvWxYzAbCdEfGhIj",
+ "windows": {
+ "24h": { "pnlUsd": 440.80, "winRate": 0.59, "trades": 6 },
+ "7d": { "pnlUsd": 3100.00, "winRate": 0.55, "trades": 38 },
+ "30d": { "pnlUsd": 11000.00, "winRate": 0.53, "trades": 137 }
+ }
+ },
+ {
+ "wallet": "UvWxYzAbCdEfGhIjKlMnOpQrStUvWxYzAbCdEfGhIjKl",
+ "windows": {
+ "24h": { "pnlUsd": 340.00, "winRate": 0.52, "trades": 10 },
+ "7d": { "pnlUsd": 2400.00, "winRate": 0.49, "trades": 64 },
+ "30d": { "pnlUsd": 8500.00, "winRate": 0.47, "trades": 229 }
+ }
+ },
+ {
+ "wallet": "ZAbCdEfGhIjKlMnOpQrStUvWxYzAbCdEfGhIjKlMnOpQ",
+ "windows": {
+ "24h": { "pnlUsd": 250.60, "winRate": 0.57, "trades": 5 },
+ "7d": { "pnlUsd": 1800.00, "winRate": 0.54, "trades": 32 },
+ "30d": { "pnlUsd": 6400.00, "winRate": 0.51, "trades": 115 }
+ }
+ },
+ {
+ "wallet": "EfGhIjKlMnOpQrStUvWxYzAbCdEfGhIjKlMnOpQrStUv",
+ "windows": {
+ "24h": { "pnlUsd": 180.40, "winRate": 0.50, "trades": 8 },
+ "7d": { "pnlUsd": 1300.00, "winRate": 0.48, "trades": 51 },
+ "30d": { "pnlUsd": 4600.00, "winRate": 0.46, "trades": 183 }
+ }
+ },
+ {
+ "wallet": "JkLmNoPqRsTuVwXyZ6AbCdEfGhIjKlMnOpQrStUvWxYz",
+ "windows": {
+ "24h": { "pnlUsd": 120.00, "winRate": 0.54, "trades": 4 },
+ "7d": { "pnlUsd": 890.00, "winRate": 0.51, "trades": 26 },
+ "30d": { "pnlUsd": 3100.00, "winRate": 0.49, "trades": 93 }
+ }
+ },
+ {
+ "wallet": "OpQrStUvWxYzAbCdEfGhIjKlMnOpQrStUvWxYzAbCdEf",
+ "windows": {
+ "24h": { "pnlUsd": 80.20, "winRate": 0.48, "trades": 6 },
+ "7d": { "pnlUsd": 620.00, "winRate": 0.45, "trades": 40 },
+ "30d": { "pnlUsd": 2200.00, "winRate": 0.43, "trades": 143 }
+ }
+ },
+ {
+ "wallet": "TuVwXyZ7BcDeFgHiJkLmNoPqRsTuVwXyZ7BcDeFgHiJk",
+ "windows": {
+ "24h": { "pnlUsd": 50.00, "winRate": 0.52, "trades": 3 },
+ "7d": { "pnlUsd": 380.00, "winRate": 0.49, "trades": 21 },
+ "30d": { "pnlUsd": 1400.00, "winRate": 0.47, "trades": 75 }
+ }
+ },
+ {
+ "wallet": "YzAbCdEfGhIjKlMnOpQrStUvWxYzAbCdEfGhIjKlMnOp",
+ "windows": {
+ "24h": { "pnlUsd": 30.50, "winRate": 0.45, "trades": 5 },
+ "7d": { "pnlUsd": 240.00, "winRate": 0.43, "trades": 32 },
+ "30d": { "pnlUsd": 860.00, "winRate": 0.41, "trades": 115 }
+ }
+ },
+ {
+ "wallet": "DeFgHiJkLmNoPqRsTuVwXyZAbCdEfGhIjKlMnOpQrSt",
+ "windows": {
+ "24h": { "pnlUsd": 15.80, "winRate": 0.43, "trades": 4 },
+ "7d": { "pnlUsd": 140.00, "winRate": 0.40, "trades": 26 },
+ "30d": { "pnlUsd": 510.00, "winRate": 0.38, "trades": 93 }
+ }
+ },
+ {
+ "wallet": "IjKlMnOpQrStUvWxYzAbCdEfGhIjKlMnOpQrStUvWxYz",
+ "windows": {
+ "24h": { "pnlUsd": 8.20, "winRate": 0.40, "trades": 3 },
+ "7d": { "pnlUsd": 75.00, "winRate": 0.38, "trades": 18 },
+ "30d": { "pnlUsd": 280.00, "winRate": 0.36, "trades": 65 }
+ }
+ },
+ {
+ "wallet": "NoPqRsTuVwXyZAbCdEfGhIjKlMnOpQrStUvWxYzAbCdE",
+ "windows": {
+ "24h": { "pnlUsd": 3.50, "winRate": 0.38, "trades": 2 },
+ "7d": { "pnlUsd": 32.00, "winRate": 0.36, "trades": 14 },
+ "30d": { "pnlUsd": 120.00, "winRate": 0.34, "trades": 50 }
+ }
+ },
+ {
+ "wallet": "StUvWxYzAbCdEfGhIjKlMnOpQrStUvWxYzAbCdEfGhIj",
+ "windows": {
+ "24h": { "pnlUsd": 1.10, "winRate": 0.35, "trades": 2 },
+ "7d": { "pnlUsd": 12.00, "winRate": 0.33, "trades": 10 },
+ "30d": { "pnlUsd": 45.00, "winRate": 0.31, "trades": 36 }
+ }
+ }
+]
diff --git a/src/kol/wallet-pnl.js b/src/kol/wallet-pnl.js
new file mode 100644
index 000000000..e55f404f6
--- /dev/null
+++ b/src/kol/wallet-pnl.js
@@ -0,0 +1,138 @@
+// Wallet P&L analytics — FIFO cost-basis computation for a Solana wallet.
+//
+// Trade shape expected from any data source:
+// { type: 'buy'|'sell', mint: string, tokenAmount: number, solAmount: number,
+// usdPrice: number, timestamp: number }
+//
+// `usdPrice` is USD per SOL at the time of the trade.
+// `tokenAmount` is in the token's smallest unit (or human-readable — caller must be consistent).
+
+export const WINDOW_SECONDS = { '24h': 86400, '7d': 604800, '30d': 2592000, all: Infinity };
+
+// Mutates `lots` in place. Returns realizedPnlUsd for this sell.
+function consumeFifo(lots, sellTokens, proceedsUsd) {
+ let remaining = sellTokens;
+ let totalCost = 0;
+ for (const lot of lots) {
+ if (remaining <= 0) break;
+ const take = Math.min(lot.tokens, remaining);
+ const costPerToken = lot.tokens > 0 ? lot.costUsd / lot.tokens : 0;
+ totalCost += take * costPerToken;
+ lot.costUsd -= take * costPerToken;
+ lot.tokens -= take;
+ remaining -= take;
+ }
+ // Drop fully consumed lots.
+ while (lots.length > 0 && lots[0].tokens <= 0) lots.shift();
+ return proceedsUsd - totalCost;
+}
+
+/**
+ * Pure FIFO P&L computation. Exported for unit testing.
+ *
+ * @param {{ trades: Array, currentPrices?: Object, windowSecs?: number }} opts
+ * @returns {{ realizedUsd, unrealizedUsd, totalUsd, winRate, trades, openPositions }}
+ */
+export function computeWalletPnl({ trades, currentPrices = {}, windowSecs = Infinity }) {
+ const now = Date.now() / 1000;
+ const cutoff = Number.isFinite(windowSecs) ? now - windowSecs : 0;
+
+ const sorted = trades
+ .filter((t) => t.timestamp >= cutoff)
+ .sort((a, b) => a.timestamp - b.timestamp);
+
+ // Per-mint FIFO lots { tokens, costUsd }
+ const lots = {};
+ let realizedUsd = 0;
+ let closedTrades = 0;
+ let winningTrades = 0;
+
+ for (const trade of sorted) {
+ const { mint, type, tokenAmount, solAmount, usdPrice } = trade;
+ const tradeUsd = solAmount * usdPrice;
+
+ if (type === 'buy') {
+ if (!lots[mint]) lots[mint] = [];
+ lots[mint].push({ tokens: tokenAmount, costUsd: tradeUsd });
+ } else if (type === 'sell') {
+ if (!lots[mint] || lots[mint].length === 0) continue;
+ const pnl = consumeFifo(lots[mint], tokenAmount, tradeUsd);
+ realizedUsd += pnl;
+ closedTrades++;
+ if (pnl > 0) winningTrades++;
+ }
+ }
+
+ // Unrealized P&L from open positions.
+ let unrealizedUsd = 0;
+ const openPositions = [];
+
+ for (const [mint, mintLots] of Object.entries(lots)) {
+ const active = mintLots.filter((l) => l.tokens > 0);
+ if (active.length === 0) continue;
+ const totalTokens = active.reduce((s, l) => s + l.tokens, 0);
+ const totalCost = active.reduce((s, l) => s + l.costUsd, 0);
+ const currentPrice = currentPrices[mint] ?? 0;
+ const currentValueUsd = totalTokens * currentPrice;
+ const unrealized = currentValueUsd - totalCost;
+ unrealizedUsd += unrealized;
+ openPositions.push({ mint, tokens: totalTokens, costUsd: totalCost, currentValueUsd, unrealizedUsd: unrealized });
+ }
+
+ const winRate = closedTrades > 0 ? winningTrades / closedTrades : 0;
+
+ return {
+ realizedUsd,
+ unrealizedUsd,
+ totalUsd: realizedUsd + unrealizedUsd,
+ winRate,
+ trades: sorted.length,
+ openPositions,
+ };
+}
+
+// Attempts to load wallet trades from PUMPFUN_BOT_URL (server-side only).
+// Returns [] when the bot is unavailable or the tool is not supported.
+async function defaultFetchTrades(wallet) {
+ const botUrl =
+ typeof process !== 'undefined' ? (process.env?.PUMPFUN_BOT_URL ?? '') : '';
+ if (!botUrl) return [];
+ const headers = { 'content-type': 'application/json' };
+ if (process.env?.PUMPFUN_BOT_TOKEN)
+ headers.authorization = `Bearer ${process.env.PUMPFUN_BOT_TOKEN}`;
+ try {
+ const ctrl = new AbortController();
+ const t = setTimeout(() => ctrl.abort(), 8000);
+ const res = await fetch(botUrl.replace(/\/$/, ''), {
+ method: 'POST',
+ headers,
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'tools/call',
+ params: { name: 'getWalletTrades', arguments: { wallet, limit: 500 } },
+ }),
+ signal: ctrl.signal,
+ });
+ clearTimeout(t);
+ if (!res.ok) return [];
+ const j = await res.json();
+ const payload = j?.result?.structuredContent ?? j?.result?.content ?? [];
+ return Array.isArray(payload) ? payload : [];
+ } catch {
+ return [];
+ }
+}
+
+/**
+ * @param {{ wallet: string, window?: string, _fetchTrades?: Function }} opts
+ * @returns {Promise<{ wallet, window, realizedUsd, unrealizedUsd, totalUsd, winRate, trades, openPositions }>}
+ */
+export async function getWalletPnl({ wallet, window: win = '7d', _fetchTrades } = {}) {
+ if (!wallet) throw new Error('wallet address is required');
+ const windowSecs = WINDOW_SECONDS[win] ?? WINDOW_SECONDS['7d'];
+ const fetchFn = _fetchTrades ?? defaultFetchTrades;
+ const trades = await fetchFn(wallet, windowSecs);
+ const result = computeWalletPnl({ trades, windowSecs });
+ return { wallet, window: win, ...result };
+}
diff --git a/src/pump/channel-feed.js b/src/pump/channel-feed.js
new file mode 100644
index 000000000..fbd0d930a
--- /dev/null
+++ b/src/pump/channel-feed.js
@@ -0,0 +1,68 @@
+// channel-feed — pump.fun signal aggregation pipeline.
+//
+// buildFeed() — pure merge/dedupe/sort/filter; used by the API endpoint.
+// fetchChannelFeed() — HTTP client; calls GET /api/pump/channel-feed.
+
+const VALID_KINDS = new Set(['mint', 'whale', 'claim']);
+
+function _parseKinds(kinds) {
+ if (!kinds) return new Set(['mint', 'whale', 'claim']);
+ const parsed = String(kinds)
+ .split(',')
+ .map((s) => s.trim())
+ .filter((k) => VALID_KINDS.has(k));
+ return parsed.length ? new Set(parsed) : new Set(['mint', 'whale', 'claim']);
+}
+
+function _normalize(raw, kind) {
+ const name = [raw.name, raw.symbol].filter(Boolean).join(' ');
+ return {
+ kind,
+ mint: raw.mint ?? null,
+ signature: raw.signature ?? raw.tx_signature ?? null,
+ ts: raw.ts ?? raw.timestamp ?? 0,
+ summary: raw.summary ?? name ?? '',
+ refs: raw.refs ?? {},
+ };
+}
+
+/**
+ * Merge, deduplicate (by signature), sort newest-first, and limit.
+ *
+ * @param {{ kind: string, items: Object[] }[]} batches
+ * @param {{ limit?: number, kinds?: string }} [opts]
+ * @returns {{ kind, mint, signature, ts, summary, refs }[]}
+ */
+export function buildFeed(batches, { limit = 50, kinds } = {}) {
+ const activeKinds = _parseKinds(kinds);
+ const seen = new Set();
+ const result = [];
+
+ for (const { kind, items } of batches) {
+ if (!activeKinds.has(kind)) continue;
+ for (const raw of items) {
+ const item = _normalize(raw, kind);
+ if (!item.signature || seen.has(item.signature)) continue;
+ seen.add(item.signature);
+ result.push(item);
+ }
+ }
+
+ result.sort((a, b) => b.ts - a.ts);
+ return result.slice(0, limit);
+}
+
+/**
+ * Client helper — fetches from the HTTP endpoint.
+ * Works in browser and Node.js (requires global fetch).
+ *
+ * @param {{ limit?: number, kinds?: string }} [opts]
+ * @returns {Promise<{ items: Object[] }>}
+ */
+export async function fetchChannelFeed({ limit = 50, kinds } = {}) {
+ const params = new URLSearchParams({ limit: String(limit) });
+ if (kinds) params.set('kinds', kinds);
+ const res = await fetch(`/api/pump/channel-feed?${params}`);
+ if (!res.ok) throw new Error(`channel-feed: ${res.status}`);
+ return res.json();
+}
diff --git a/src/pump/mcp-tools.js b/src/pump/mcp-tools.js
new file mode 100644
index 000000000..ae377bb67
--- /dev/null
+++ b/src/pump/mcp-tools.js
@@ -0,0 +1,133 @@
+// Shared, runtime-agnostic MCP tool definitions for the pump.fun MCP server.
+// Imported by both the Vercel handler (api/pump-fun-mcp.js) and the
+// Cloudflare Workers mirror (workers/pump-fun-mcp/worker.js).
+// No imports — pure data and pure helpers only.
+
+export const TOOLS = [
+ {
+ name: 'searchTokens',
+ description: 'Search pump.fun tokens by name, symbol, or mint address.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ query: { type: 'string' },
+ limit: { type: 'integer', minimum: 1, maximum: 50, default: 10 },
+ },
+ required: ['query'],
+ },
+ },
+ {
+ name: 'getTokenDetails',
+ description: 'Full details for a specific pump.fun token by mint address.',
+ inputSchema: {
+ type: 'object',
+ properties: { mint: { type: 'string' } },
+ required: ['mint'],
+ },
+ },
+ {
+ name: 'getBondingCurve',
+ description:
+ 'Bonding curve analysis: real reserves, virtual reserves, and graduation progress (on-chain).',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ mint: { type: 'string' },
+ network: { type: 'string', enum: ['mainnet', 'devnet'], default: 'mainnet' },
+ },
+ required: ['mint'],
+ },
+ },
+ {
+ name: 'getTokenTrades',
+ description: 'Recent buy/sell history for a token.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ mint: { type: 'string' },
+ limit: { type: 'integer', minimum: 1, maximum: 200, default: 50 },
+ },
+ required: ['mint'],
+ },
+ },
+ {
+ name: 'getTrendingTokens',
+ description: 'Top pump.fun tokens by market cap.',
+ inputSchema: {
+ type: 'object',
+ properties: { limit: { type: 'integer', minimum: 1, maximum: 50, default: 10 } },
+ },
+ },
+ {
+ name: 'getNewTokens',
+ description: 'Most recently launched pump.fun tokens.',
+ inputSchema: {
+ type: 'object',
+ properties: { limit: { type: 'integer', minimum: 1, maximum: 50, default: 10 } },
+ },
+ },
+ {
+ name: 'getGraduatedTokens',
+ description: 'Tokens that graduated from the bonding curve to Raydium AMM.',
+ inputSchema: {
+ type: 'object',
+ properties: { limit: { type: 'integer', minimum: 1, maximum: 50, default: 10 } },
+ },
+ },
+ {
+ name: 'getKingOfTheHill',
+ description: 'Highest-market-cap token still on the bonding curve.',
+ inputSchema: { type: 'object', properties: {} },
+ },
+ {
+ name: 'kol_radar',
+ description:
+ 'gmgn radar signals: early-detection patterns filtered by category, sorted by score desc.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ category: {
+ type: 'string',
+ enum: ['pump-fun', 'new-mints', 'volume-spike'],
+ default: 'pump-fun',
+ },
+ limit: { type: 'integer', minimum: 1, maximum: 100, default: 20 },
+ },
+ },
+ },
+ {
+ name: 'getCreatorProfile',
+ description: 'All tokens by a creator wallet, with rug-pull risk flags.',
+ inputSchema: {
+ type: 'object',
+ properties: { creator: { type: 'string' } },
+ required: ['creator'],
+ },
+ },
+ {
+ name: 'getTokenHolders',
+ description: 'Top holders of a token with concentration analysis (on-chain).',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ mint: { type: 'string' },
+ limit: { type: 'integer', minimum: 1, maximum: 20, default: 10 },
+ network: { type: 'string', enum: ['mainnet', 'devnet'], default: 'mainnet' },
+ },
+ required: ['mint'],
+ },
+ },
+];
+
+export function rpcError(code, message) {
+ const err = new Error(message);
+ err.rpcCode = code;
+ return err;
+}
+
+export function rpcEnvelope(id, result, errObj) {
+ if (errObj) {
+ return { jsonrpc: '2.0', id: id ?? null, error: errObj };
+ }
+ return { jsonrpc: '2.0', id: id ?? null, result };
+}
diff --git a/src/pump/pumpkit-claims.js b/src/pump/pumpkit-claims.js
new file mode 100644
index 000000000..6a9e1f237
--- /dev/null
+++ b/src/pump/pumpkit-claims.js
@@ -0,0 +1,137 @@
+/**
+ * Pumpkit claims — pump.fun fee-claim monitor
+ *
+ * Exports:
+ * watchClaims({ creator, sinceTs, onClaim, signal, network })
+ * listRecentClaims({ creator, limit, network })
+ *
+ * Transport: polls Solana RPC (getSignaturesForAddress + getParsedTransaction).
+ * No external indexer required; works browser + Node.
+ */
+
+import { SOLANA_RPC } from '../erc8004/solana-deploy.js';
+
+// The three pump.fun on-chain programs that emit fee-claim instructions.
+const PUMP_PROGRAMS = new Set([
+ '6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P', // Pump bonding curve
+ 'pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA', // PumpSwap AMM
+ 'pfeeUxB6jkeY1Hxd7CsFCAjcbHA9rWtchMGdZ6VojVZ', // PumpFees (social)
+]);
+
+const POLL_INTERVAL_MS = 15_000;
+
+async function getConn(network = 'mainnet') {
+ const { Connection } = await import('@solana/web3.js');
+ return new Connection(SOLANA_RPC[network] || SOLANA_RPC.mainnet, 'confirmed');
+}
+
+function _hasPumpIx(tx) {
+ const inner = tx.meta?.innerInstructions?.flatMap((i) => i.instructions) ?? [];
+ return [...(tx.transaction.message.instructions ?? []), ...inner].some((ix) =>
+ PUMP_PROGRAMS.has(ix.programId?.toString?.()),
+ );
+}
+
+function _lamportsDelta(tx, creator) {
+ const accounts = tx.transaction.message.accountKeys;
+ const idx = accounts.findIndex((a) => a.pubkey.toString() === creator);
+ if (idx === -1) return 0;
+ return (tx.meta.postBalances[idx] ?? 0) - (tx.meta.preBalances[idx] ?? 0);
+}
+
+function _parseClaim(tx, signature, creator) {
+ const lamports = _lamportsDelta(tx, creator);
+ const mint = tx.meta.postTokenBalances?.[0]?.mint ?? null;
+ return {
+ signature,
+ mint,
+ lamports,
+ ts: tx.blockTime ?? Math.floor(Date.now() / 1000),
+ };
+}
+
+/**
+ * Returns the last `limit` pump.fun fee-claim events for the creator wallet,
+ * newest first. Each event: { signature, mint, lamports, ts }.
+ *
+ * @param {{ creator: string, limit?: number, network?: string }} opts
+ */
+export async function listRecentClaims({ creator, limit = 20, network = 'mainnet' }) {
+ const { PublicKey } = await import('@solana/web3.js');
+ const conn = await getConn(network);
+ const pk = new PublicKey(creator);
+
+ const sigInfos = await conn.getSignaturesForAddress(pk, { limit: Math.min(100, limit * 4) });
+ const results = [];
+
+ for (const { signature } of sigInfos) {
+ if (results.length >= limit) break;
+ let tx;
+ try {
+ tx = await conn.getParsedTransaction(signature, {
+ maxSupportedTransactionVersion: 0,
+ commitment: 'confirmed',
+ });
+ } catch {
+ continue;
+ }
+ if (!tx || !_hasPumpIx(tx)) continue;
+ if (_lamportsDelta(tx, creator) <= 0) continue;
+ results.push(_parseClaim(tx, signature, creator));
+ }
+
+ return results;
+}
+
+/**
+ * Subscribes to pump.fun fee-claim events for `creator` wallet.
+ * Calls onClaim({ signature, mint, lamports, ts }) for each new claim.
+ * Resolves when the AbortSignal fires.
+ *
+ * @param {{ creator: string, sinceTs?: number, onClaim: Function, signal?: AbortSignal, network?: string }} opts
+ */
+export async function watchClaims({ creator, sinceTs = 0, onClaim, signal, network = 'mainnet' }) {
+ const seen = new Set();
+ let lastTs = sinceTs;
+
+ const poll = async () => {
+ let claims;
+ try {
+ claims = await listRecentClaims({ creator, limit: 20, network });
+ } catch {
+ return;
+ }
+ for (const claim of claims) {
+ if (seen.has(claim.signature) || claim.ts <= lastTs) continue;
+ seen.add(claim.signature);
+ try {
+ await onClaim(claim);
+ } catch {
+ // onClaim errors must not kill the poll loop
+ }
+ }
+ if (claims.length) {
+ lastTs = Math.max(lastTs, ...claims.map((c) => c.ts));
+ }
+ };
+
+ await poll();
+
+ if (signal?.aborted) return;
+
+ await new Promise((resolve) => {
+ const iv = setInterval(async () => {
+ if (signal?.aborted) {
+ clearInterval(iv);
+ resolve();
+ return;
+ }
+ await poll();
+ }, POLL_INTERVAL_MS);
+
+ signal?.addEventListener('abort', () => {
+ clearInterval(iv);
+ resolve();
+ });
+ });
+}
diff --git a/src/pump/pumpkit-whale.js b/src/pump/pumpkit-whale.js
new file mode 100644
index 000000000..9d7dd4375
--- /dev/null
+++ b/src/pump/pumpkit-whale.js
@@ -0,0 +1,99 @@
+// Whale-trade watcher for pump.fun tokens.
+//
+// Subscribes to on-chain logs for the pump bonding-curve program, decodes
+// TradeEvent with the Anchor Borsh coder, and fires onTrade() for any trade
+// whose USD value meets the minUsd threshold.
+//
+// All heavy imports are lazy so the module cold-starts cheaply.
+
+const RPC_MAINNET = 'https://api.mainnet-beta.solana.com';
+const PUMP_PROGRAM = '6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P';
+const LAMPORTS_PER_SOL = 1_000_000_000;
+const NATIVE_SOL = 'So11111111111111111111111111111111111111112';
+const PRICE_URL = `https://api.jup.ag/price/v2?ids=${NATIVE_SOL}`;
+const PRICE_TTL_MS = 60_000;
+
+let _cachedSolPrice = 0;
+let _priceAt = 0;
+
+async function fetchSolPrice() {
+ if (Date.now() - _priceAt < PRICE_TTL_MS && _cachedSolPrice > 0) return _cachedSolPrice;
+ try {
+ const r = await fetch(PRICE_URL);
+ const d = await r.json();
+ const p = Number(d?.data?.[NATIVE_SOL]?.price ?? 0);
+ if (p > 0) {
+ _cachedSolPrice = p;
+ _priceAt = Date.now();
+ }
+ } catch {}
+ return _cachedSolPrice || 150; // rough fallback if price API is down
+}
+
+/**
+ * Subscribe to pump.fun trade events for a specific mint.
+ * Calls onTrade for every buy/sell whose USD value is >= minUsd.
+ * Returns after the subscription is set up; runs until signal fires.
+ *
+ * @param {{ mint: string, minUsd?: number, onTrade: Function, signal: AbortSignal }} opts
+ */
+export async function watchWhaleTrades({ mint, minUsd = 5000, onTrade, signal }) {
+ const [{ Connection, PublicKey }, { EventParser, BorshCoder }, { PUMP_PROGRAM_ID, pumpIdl }] =
+ await Promise.all([
+ import('@solana/web3.js'),
+ import('@coral-xyz/anchor'),
+ import('@nirholas/pump-sdk'),
+ ]);
+
+ if (signal?.aborted) return;
+
+ const connection = new Connection(RPC_MAINNET, 'confirmed');
+ const coder = new BorshCoder(pumpIdl);
+ const parser = new EventParser(PUMP_PROGRAM_ID, coder);
+ const mintStr = mint instanceof PublicKey ? mint.toBase58() : String(mint);
+ const programPk = new PublicKey(PUMP_PROGRAM);
+
+ const solPrice = await fetchSolPrice();
+ if (signal?.aborted) return;
+
+ let subId = null;
+
+ const cleanup = () => {
+ if (subId !== null) {
+ connection.removeOnLogsListener(subId).catch(() => {});
+ subId = null;
+ }
+ };
+
+ signal?.addEventListener('abort', cleanup);
+
+ subId = connection.onLogs(
+ programPk,
+ (logInfo) => {
+ if (signal?.aborted) {
+ cleanup();
+ return;
+ }
+ if (logInfo.err) return;
+ try {
+ for (const event of parser.parseLogs(logInfo.logs)) {
+ if (event.name !== 'TradeEvent') continue;
+ const { mint: evMint, isBuy, solAmount, user, timestamp } = event.data;
+ if (evMint.toString() !== mintStr) continue;
+ const sol = Number(solAmount.toString()) / LAMPORTS_PER_SOL;
+ const usd = sol * solPrice;
+ if (usd < minUsd) continue;
+ onTrade({
+ signature: logInfo.signature,
+ wallet: user.toString(),
+ sideBuy: isBuy,
+ usd,
+ sol,
+ ts: Number(timestamp.toString()) * 1000,
+ });
+ }
+ } catch {}
+ },
+ 'confirmed',
+ );
+}
diff --git a/src/pump/telegram-delivery.js b/src/pump/telegram-delivery.js
new file mode 100644
index 000000000..b11373d85
--- /dev/null
+++ b/src/pump/telegram-delivery.js
@@ -0,0 +1,33 @@
+// Required env: TELEGRAM_BOT_TOKEN — obtain from Telegram @BotFather
+
+const KIND_LABEL = {
+ mint: 'New Mint',
+ whale: 'Whale Move',
+ claim: 'Claim',
+ graduation: 'Graduation',
+};
+
+export async function sendTelegramSignal({ botToken, chatId, signal }) {
+ const text = formatSignal(signal);
+ const url = `https://api.telegram.org/bot${botToken}/sendMessage`;
+ const res = await fetch(url, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ chat_id: chatId, text, parse_mode: 'Markdown' }),
+ });
+ if (!res.ok) {
+ const body = await res.text();
+ throw Object.assign(new Error(`Telegram API ${res.status}: ${body}`), { status: 502 });
+ }
+ const data = await res.json();
+ return { ok: true, messageId: data.result.message_id };
+}
+
+function formatSignal({ kind, mint, summary, refs, ts }) {
+ const label = KIND_LABEL[kind] ?? kind;
+ const time = ts ? new Date(ts).toUTCString() : new Date().toUTCString();
+ let msg = `*${label}*\n\`${mint}\`\n\n${summary}`;
+ if (refs?.length) msg += '\n\n' + refs.map((r) => `• ${r}`).join('\n');
+ msg += `\n\n_${time}_`;
+ return msg;
+}
diff --git a/src/pump/vanity-keygen.js b/src/pump/vanity-keygen.js
new file mode 100644
index 000000000..7043be3e4
--- /dev/null
+++ b/src/pump/vanity-keygen.js
@@ -0,0 +1,61 @@
+// Vanity Solana keypair generator.
+// Iterates Keypair.generate() until publicKey matches both prefix and suffix.
+// Single-threaded; suitable for short suffixes (≤4 chars) on server.
+
+import { Keypair } from '@solana/web3.js';
+
+/**
+ * @param {Object} opts
+ * @param {string} [opts.suffix]
+ * @param {string} [opts.prefix]
+ * @param {boolean} [opts.caseSensitive]
+ * @param {number} [opts.maxAttempts]
+ * @param {AbortSignal} [opts.signal]
+ * @returns {Promise<{publicKey: string, secretKey: Uint8Array, attempts: number, ms: number}|null>}
+ */
+export async function generateVanityKey({
+ suffix = '',
+ prefix = '',
+ caseSensitive = false,
+ maxAttempts = 5_000_000,
+ signal,
+} = {}) {
+ if (!suffix && !prefix) throw new Error('at least one of suffix or prefix is required');
+
+ const normalize = caseSensitive ? (s) => s : (s) => s.toLowerCase();
+ const wantSuffix = normalize(suffix);
+ const wantPrefix = normalize(prefix);
+
+ const start = Date.now();
+ let attempts = 0;
+
+ // Yield to the event loop every 10k iterations so abort signals are checked
+ // and the process stays responsive.
+ const YIELD_EVERY = 10_000;
+
+ while (attempts < maxAttempts) {
+ if (signal?.aborted) return null;
+
+ const batchEnd = Math.min(attempts + YIELD_EVERY, maxAttempts);
+ while (attempts < batchEnd) {
+ const kp = Keypair.generate();
+ const addr = normalize(kp.publicKey.toBase58());
+ attempts++;
+ if (
+ (!wantPrefix || addr.startsWith(wantPrefix)) &&
+ (!wantSuffix || addr.endsWith(wantSuffix))
+ ) {
+ return {
+ publicKey: kp.publicKey.toBase58(),
+ secretKey: kp.secretKey,
+ attempts,
+ ms: Date.now() - start,
+ };
+ }
+ }
+ // Allow the event loop to process abort / timer signals.
+ await new Promise((r) => setImmediate(r));
+ }
+
+ return null;
+}
diff --git a/src/skill-manifest.js b/src/skill-manifest.js
new file mode 100644
index 000000000..45f0190ce
--- /dev/null
+++ b/src/skill-manifest.js
@@ -0,0 +1,43 @@
+/**
+ * Converts a JSON Schema properties object into the simplified args map.
+ * Required properties → 'type', optional → 'type?'
+ *
+ * @param {Object|undefined} inputSchema
+ * @returns {Record<string, string>}
+ */
+function schemaToArgs(inputSchema) {
+ if (!inputSchema?.properties) return {};
+ const required = new Set(inputSchema.required || []);
+ const args = {};
+ for (const [key, prop] of Object.entries(inputSchema.properties)) {
+ const type = prop.type || 'any';
+ args[key] = required.has(key) ? type : `${type}?`;
+ }
+ return args;
+}
+
+/**
+ * Build a portable skill manifest from a list of SkillDef objects.
+ * Skills without a description are omitted with a console.warn.
+ *
+ * @param {{ agentId: string, version: string, skills: Array }} opts
+ * @returns {{ agent: { id: string, version: string }, skills: Array }}
+ */
+export function buildSkillManifest({ agentId, version, skills }) {
+ const entries = [];
+ for (const skill of skills) {
+ if (!skill.description) {
+ console.warn(`[skill-manifest] Skill "${skill.name}" has no description — omitting`);
+ continue;
+ }
+ entries.push({
+ name: skill.name,
+ description: skill.description,
+ args: schemaToArgs(skill.inputSchema),
+ });
+ }
+ return {
+ agent: { id: agentId, version },
+ skills: entries,
+ };
+}
diff --git a/src/social/lexicon.json b/src/social/lexicon.json
new file mode 100644
index 000000000..cc4721060
--- /dev/null
+++ b/src/social/lexicon.json
@@ -0,0 +1,18 @@
+{
+ "positive": [
+ "moon", "bullish", "pump", "buy", "long", "rocket", "ath", "gains", "profit",
+ "green", "breakout", "surge", "accumulate", "hodl", "wagmi", "lfg", "undervalued",
+ "gem", "alpha", "rally", "huge", "explode", "soar", "launch", "flying", "mooning",
+ "up", "rise", "rising", "win", "winning", "rich", "wealth", "opportunity",
+ "strong", "strength", "potential", "promising", "excited", "amazing", "great",
+ "🚀", "🔥", "💎", "🙌", "💰", "📈", "🤑", "😍"
+ ],
+ "negative": [
+ "crash", "bearish", "dump", "sell", "short", "rekt", "scam", "rug", "loss",
+ "red", "down", "fear", "dead", "ngmi", "panic", "liquidated", "ponzi", "bubble",
+ "fraud", "overvalued", "collapse", "plummet", "tank", "falling", "fail", "failed",
+ "avoid", "danger", "warning", "careful", "risky", "risk", "exit", "dumping",
+ "sell-off", "selloff", "worthless", "broken", "bad", "terrible", "horrible",
+ "🐻", "📉", "💀", "😱", "🤡", "⚠️"
+ ]
+}
diff --git a/src/social/sentiment.js b/src/social/sentiment.js
new file mode 100644
index 000000000..2b9db8411
--- /dev/null
+++ b/src/social/sentiment.js
@@ -0,0 +1,72 @@
+import lexiconData from './lexicon.json' with { type: 'json' };
+
+const POS_TERMS = lexiconData.positive.map((t) => t.toLowerCase());
+const NEG_TERMS = lexiconData.negative.map((t) => t.toLowerCase());
+
+function countMatches(text, terms) {
+ const lower = text.toLowerCase();
+ let count = 0;
+ for (const term of terms) {
+ let idx = 0;
+ while ((idx = lower.indexOf(term, idx)) !== -1) {
+ count++;
+ idx += term.length;
+ }
+ }
+ return count;
+}
+
+/**
+ * Score sentiment for a batch of social posts using a deterministic lexicon.
+ * @param {Array<{id?: string, ts?: string|number, text: string, author?: string}>} posts
+ * @returns {{
+ * score: number,
+ * posPct: number,
+ * negPct: number,
+ * neuPct: number,
+ * count: number,
+ * examples: { pos: string[], neg: string[] }
+ * }}
+ */
+export function scoreSentiment(posts) {
+ if (!Array.isArray(posts) || posts.length === 0) {
+ return { score: 0, posPct: 0, negPct: 0, neuPct: 100, count: 0, examples: { pos: [], neg: [] } };
+ }
+
+ let posCount = 0;
+ let negCount = 0;
+ let neuCount = 0;
+ const posExamples = [];
+ const negExamples = [];
+
+ for (const post of posts) {
+ const text = String(post.text || '');
+ const p = countMatches(text, POS_TERMS);
+ const n = countMatches(text, NEG_TERMS);
+
+ if (p > n) {
+ posCount++;
+ if (posExamples.length < 3) posExamples.push(text);
+ } else if (n > p) {
+ negCount++;
+ if (negExamples.length < 3) negExamples.push(text);
+ } else {
+ neuCount++;
+ }
+ }
+
+ const total = posts.length;
+ const score = total > 0 ? (posCount - negCount) / total : 0;
+ const posPct = (posCount / total) * 100;
+ const negPct = (negCount / total) * 100;
+ const neuPct = (neuCount / total) * 100;
+
+ return {
+ score: Math.round(score * 1000) / 1000,
+ posPct: Math.round(posPct * 10) / 10,
+ negPct: Math.round(negPct * 10) / 10,
+ neuPct: Math.round(neuPct * 10) / 10,
+ count: total,
+ examples: { pos: posExamples, neg: negExamples },
+ };
+}
diff --git a/tests/kol-radar.test.js b/tests/kol-radar.test.js
new file mode 100644
index 000000000..036111218
--- /dev/null
+++ b/tests/kol-radar.test.js
@@ -0,0 +1,51 @@
+import { describe, it, expect } from 'vitest';
+import { getRadarSignals } from '../src/kol/radar.js';
+
+describe('getRadarSignals', () => {
+ it('returns default pump-fun category sorted by score desc', async () => {
+ const results = await getRadarSignals();
+ expect(results.length).toBeGreaterThan(0);
+ results.forEach((r) => expect(r.signalType).toBe('pump-fun'));
+ for (let i = 1; i < results.length; i++) {
+ expect(results[i - 1].score).toBeGreaterThanOrEqual(results[i].score);
+ }
+ });
+
+ it('filters by volume-spike category', async () => {
+ const results = await getRadarSignals({ category: 'volume-spike' });
+ expect(results.length).toBeGreaterThan(0);
+ results.forEach((r) => expect(r.signalType).toBe('volume-spike'));
+ });
+
+ it('filters by new-mints category', async () => {
+ const results = await getRadarSignals({ category: 'new-mints' });
+ expect(results.length).toBeGreaterThan(0);
+ results.forEach((r) => expect(r.signalType).toBe('new-mints'));
+ });
+
+ it('caps limit at 100', async () => {
+ const results = await getRadarSignals({ category: 'pump-fun', limit: 1000 });
+ expect(results.length).toBeLessThanOrEqual(100);
+ });
+
+ it('respects explicit limit smaller than available entries', async () => {
+ const results = await getRadarSignals({ category: 'volume-spike', limit: 2 });
+ expect(results.length).toBeLessThanOrEqual(2);
+ });
+
+ it('result entries have required fields', async () => {
+ const results = await getRadarSignals({ category: 'new-mints' });
+ results.forEach((r) => {
+ expect(r).toHaveProperty('mint');
+ expect(r).toHaveProperty('name');
+ expect(r).toHaveProperty('symbol');
+ expect(r).toHaveProperty('signalType');
+ expect(r).toHaveProperty('score');
+ expect(r).toHaveProperty('ts');
+ });
+ });
+
+ it('throws on unknown category', async () => {
+ await expect(getRadarSignals({ category: 'unknown' })).rejects.toThrow(/Unknown category/);
+ });
+});
diff --git a/tests/kol-wallet-pnl.test.js b/tests/kol-wallet-pnl.test.js
new file mode 100644
index 000000000..05441382a
--- /dev/null
+++ b/tests/kol-wallet-pnl.test.js
@@ -0,0 +1,145 @@
+import { describe, it, expect } from 'vitest';
+import { computeWalletPnl, getWalletPnl, WINDOW_SECONDS } from '../src/kol/wallet-pnl.js';
+
+// ── FIFO P&L fixture ──────────────────────────────────────────────────────────
+//
+// Timeline (all within a 7d window):
+// t=1000: Buy 1000 TOKENA for 1 SOL @ $100/SOL → costBasis $100
+// t=2000: Sell 600 TOKENA for 0.9 SOL @ $110/SOL → proceeds $99
+// Consume lot: 600/1000 * $100 = $60 cost
+// Realized P&L = $99 - $60 = +$39
+// Remaining: 400 tokens, $40 costBasis
+// t=3000: Buy 200 TOKENB for 0.2 SOL @ $120/SOL → costBasis $24
+//
+// currentPrices: TOKENA=$0.05/token, TOKENB=$0.05/token
+// TOKENA unrealized = 400 * $0.05 - $40 = $20 - $40 = -$20
+// TOKENB unrealized = 200 * $0.05 - $24 = $10 - $24 = -$14
+//
+// totals:
+// realizedUsd = $39
+// unrealizedUsd = -$34
+// totalUsd = $5
+// winRate = 1/1 = 1.0 (one closed trade, winner)
+// trades = 3
+
+const NOW = Math.floor(Date.now() / 1000);
+const FIXTURE_TRADES = [
+ { type: 'buy', mint: 'TOKENA', tokenAmount: 1000, solAmount: 1.0, usdPrice: 100, timestamp: NOW - 5000 },
+ { type: 'sell', mint: 'TOKENA', tokenAmount: 600, solAmount: 0.9, usdPrice: 110, timestamp: NOW - 4000 },
+ { type: 'buy', mint: 'TOKENB', tokenAmount: 200, solAmount: 0.2, usdPrice: 120, timestamp: NOW - 3000 },
+];
+
+const CURRENT_PRICES = { TOKENA: 0.05, TOKENB: 0.05 };
+
+describe('computeWalletPnl — FIFO math', () => {
+ it('computes correct realized P&L', () => {
+ const r = computeWalletPnl({ trades: FIXTURE_TRADES, currentPrices: CURRENT_PRICES });
+ expect(r.realizedUsd).toBeCloseTo(39, 6);
+ });
+
+ it('computes correct unrealized P&L', () => {
+ const r = computeWalletPnl({ trades: FIXTURE_TRADES, currentPrices: CURRENT_PRICES });
+ expect(r.unrealizedUsd).toBeCloseTo(-34, 6);
+ });
+
+ it('computes correct total P&L', () => {
+ const r = computeWalletPnl({ trades: FIXTURE_TRADES, currentPrices: CURRENT_PRICES });
+ expect(r.totalUsd).toBeCloseTo(5, 6);
+ });
+
+ it('reports correct win rate', () => {
+ const r = computeWalletPnl({ trades: FIXTURE_TRADES, currentPrices: CURRENT_PRICES });
+ expect(r.winRate).toBeCloseTo(1.0);
+ });
+
+ it('counts all trades in window', () => {
+ const r = computeWalletPnl({ trades: FIXTURE_TRADES, currentPrices: CURRENT_PRICES });
+ expect(r.trades).toBe(3);
+ });
+
+ it('lists open positions with correct cost basis', () => {
+ const r = computeWalletPnl({ trades: FIXTURE_TRADES, currentPrices: CURRENT_PRICES });
+ expect(r.openPositions).toHaveLength(2);
+
+ const tokena = r.openPositions.find((p) => p.mint === 'TOKENA');
+ expect(tokena).toBeDefined();
+ expect(tokena.tokens).toBe(400);
+ expect(tokena.costUsd).toBeCloseTo(40, 6);
+
+ const tokenb = r.openPositions.find((p) => p.mint === 'TOKENB');
+ expect(tokenb).toBeDefined();
+ expect(tokenb.tokens).toBe(200);
+ expect(tokenb.costUsd).toBeCloseTo(24, 6);
+ });
+});
+
+describe('computeWalletPnl — edge cases', () => {
+ it('returns zeros for an empty trade list', () => {
+ const r = computeWalletPnl({ trades: [] });
+ expect(r.realizedUsd).toBe(0);
+ expect(r.unrealizedUsd).toBe(0);
+ expect(r.totalUsd).toBe(0);
+ expect(r.winRate).toBe(0);
+ expect(r.trades).toBe(0);
+ expect(r.openPositions).toHaveLength(0);
+ });
+
+ it('excludes trades outside the time window', () => {
+ const stale = [
+ { type: 'buy', mint: 'TOKENA', tokenAmount: 1000, solAmount: 1, usdPrice: 100, timestamp: 1 },
+ { type: 'sell', mint: 'TOKENA', tokenAmount: 500, solAmount: 0.8, usdPrice: 110, timestamp: 2 },
+ ];
+ const r = computeWalletPnl({ trades: stale, windowSecs: WINDOW_SECONDS['24h'] });
+ // Both trades are far outside 24h — should be excluded.
+ expect(r.trades).toBe(0);
+ expect(r.realizedUsd).toBe(0);
+ });
+
+ it('handles a losing trade (negative realized P&L)', () => {
+ const losing = [
+ { type: 'buy', mint: 'TOKENX', tokenAmount: 1000, solAmount: 1.0, usdPrice: 100, timestamp: NOW - 100 },
+ { type: 'sell', mint: 'TOKENX', tokenAmount: 1000, solAmount: 0.5, usdPrice: 90, timestamp: NOW - 50 },
+ ];
+ const r = computeWalletPnl({ trades: losing });
+ // proceeds = 0.5 * 90 = $45; cost = $100; realized = -$55
+ expect(r.realizedUsd).toBeCloseTo(-55, 6);
+ expect(r.winRate).toBe(0);
+ });
+
+ it('ignores a sell with no preceding buy', () => {
+ const orphanSell = [
+ { type: 'sell', mint: 'UNKNOWN', tokenAmount: 500, solAmount: 1, usdPrice: 100, timestamp: NOW - 100 },
+ ];
+ const r = computeWalletPnl({ trades: orphanSell });
+ expect(r.realizedUsd).toBe(0);
+ expect(r.openPositions).toHaveLength(0);
+ });
+});
+
+describe('getWalletPnl — integration with injected fetch', () => {
+ it('uses injected _fetchTrades and returns wallet + window in result', async () => {
+ const mockFetch = async () => FIXTURE_TRADES;
+ const r = await getWalletPnl({ wallet: 'WALLET123', window: '7d', _fetchTrades: mockFetch });
+ expect(r.wallet).toBe('WALLET123');
+ expect(r.window).toBe('7d');
+ expect(r.realizedUsd).toBeCloseTo(39, 6);
+ });
+
+ it('returns zero P&L for an empty wallet (no trades)', async () => {
+ const mockFetch = async () => [];
+ const r = await getWalletPnl({ wallet: 'EMPTY_WALLET', _fetchTrades: mockFetch });
+ expect(r.realizedUsd).toBe(0);
+ expect(r.unrealizedUsd).toBe(0);
+ expect(r.openPositions).toHaveLength(0);
+ });
+
+ it('defaults window to 7d', async () => {
+ const mockFetch = async () => [];
+ const r = await getWalletPnl({ wallet: 'W', _fetchTrades: mockFetch });
+ expect(r.window).toBe('7d');
+ });
+
+ it('throws when wallet is missing', async () => {
+ await expect(getWalletPnl({ _fetchTrades: async () => [] })).rejects.toThrow();
+ });
+});
diff --git a/tests/pump-channel-feed.test.js b/tests/pump-channel-feed.test.js
new file mode 100644
index 000000000..dee503eca
--- /dev/null
+++ b/tests/pump-channel-feed.test.js
@@ -0,0 +1,169 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// ── upstream source mocks ─────────────────────────────────────────────────────
+
+const mintsMock = vi.fn();
+const whalesMock = vi.fn();
+const claimsMock = vi.fn();
+
+vi.mock('../api/_lib/channel-feed-sources.js', () => ({
+ getMints: (...a) => mintsMock(...a),
+ getWhales: (...a) => whalesMock(...a),
+ getClaims: (...a) => claimsMock(...a),
+}));
+
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ limits: { mcpIp: vi.fn(async () => ({ success: true })) },
+ clientIp: vi.fn(() => '127.0.0.1'),
+}));
+
+vi.mock('../api/_lib/env.js', () => ({
+ env: { APP_ORIGIN: 'http://test', ISSUER: 'http://test', MCP_RESOURCE: 'http://test' },
+}));
+
+const { default: handler } = await import('../api/pump/channel-feed.js');
+
+// ── helpers ────────────────────────────────────────────────────────────────────
+
+function mockRes() {
+ const res = {
+ statusCode: 200,
+ headers: {},
+ body: null,
+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
+ getHeader(k) { return this.headers[k.toLowerCase()]; },
+ end(b) { this.body = b; },
+ };
+ return res;
+}
+
+function mockReq(search = '') {
+ return {
+ method: 'GET',
+ headers: { host: 'localhost' },
+ url: `/api/pump/channel-feed${search}`,
+ };
+}
+
+// ── tests ──────────────────────────────────────────────────────────────────────
+
+describe('channel-feed endpoint', () => {
+ beforeEach(() => {
+ mintsMock.mockReset();
+ whalesMock.mockReset();
+ claimsMock.mockReset();
+ mintsMock.mockResolvedValue([]);
+ whalesMock.mockResolvedValue([]);
+ claimsMock.mockResolvedValue([]);
+ });
+
+ it('returns 200 with items array', async () => {
+ mintsMock.mockResolvedValueOnce([
+ { signature: 'sig1', mint: 'MINT1', timestamp: 1000, name: 'Alpha', symbol: 'ALPHA' },
+ ]);
+
+ const res = mockRes();
+ await handler(mockReq(), res);
+
+ expect(res.statusCode).toBe(200);
+ const body = JSON.parse(res.body);
+ expect(body).toHaveProperty('items');
+ expect(Array.isArray(body.items)).toBe(true);
+ expect(body.items[0]).toMatchObject({ kind: 'mint', mint: 'MINT1', signature: 'sig1' });
+ });
+
+ it('dedupes items sharing a signature across sources', async () => {
+ mintsMock.mockResolvedValueOnce([
+ { signature: 'dup', mint: 'MINT1', timestamp: 1000 },
+ ]);
+ whalesMock.mockResolvedValueOnce([
+ { signature: 'dup', mint: 'MINT1', timestamp: 1000 }, // duplicate
+ { signature: 'unique', mint: 'MINT2', timestamp: 2000 },
+ ]);
+
+ const res = mockRes();
+ await handler(mockReq(), res);
+
+ const body = JSON.parse(res.body);
+ expect(body.items).toHaveLength(2);
+ const sigs = body.items.map((i) => i.signature);
+ expect(sigs).toContain('dup');
+ expect(sigs).toContain('unique');
+ expect(sigs.filter((s) => s === 'dup')).toHaveLength(1);
+ });
+
+ it('sorts newest first by ts', async () => {
+ mintsMock.mockResolvedValueOnce([
+ { signature: 'old', mint: 'M1', timestamp: 100 },
+ { signature: 'new', mint: 'M2', timestamp: 9000 },
+ ]);
+
+ const res = mockRes();
+ await handler(mockReq(), res);
+
+ const body = JSON.parse(res.body);
+ expect(body.items[0].signature).toBe('new');
+ expect(body.items[1].signature).toBe('old');
+ });
+
+ it('kinds=mint,claim excludes whale events', async () => {
+ mintsMock.mockResolvedValueOnce([
+ { signature: 'mint1', mint: 'M1', timestamp: 100 },
+ ]);
+ whalesMock.mockResolvedValueOnce([
+ { signature: 'whale1', mint: 'M2', timestamp: 200 },
+ ]);
+ claimsMock.mockResolvedValueOnce([
+ { tx_signature: 'claim1', mint: 'M3', timestamp: 300 },
+ ]);
+
+ const res = mockRes();
+ await handler(mockReq('?kinds=mint,claim'), res);
+
+ const body = JSON.parse(res.body);
+ const kinds = body.items.map((i) => i.kind);
+ expect(kinds).not.toContain('whale');
+ expect(kinds).toContain('mint');
+ expect(kinds).toContain('claim');
+ // whale source should not have been called (or its results excluded)
+ const hasWhale = body.items.some((i) => i.signature === 'whale1');
+ expect(hasWhale).toBe(false);
+ });
+
+ it('respects limit param', async () => {
+ mintsMock.mockResolvedValueOnce(
+ Array.from({ length: 30 }, (_, i) => ({
+ signature: `s${i}`,
+ mint: `M${i}`,
+ timestamp: i,
+ })),
+ );
+
+ const res = mockRes();
+ await handler(mockReq('?limit=5'), res);
+
+ const body = JSON.parse(res.body);
+ expect(body.items.length).toBeLessThanOrEqual(5);
+ });
+
+ it('normalizes tx_signature fallback', async () => {
+ claimsMock.mockResolvedValueOnce([
+ { tx_signature: 'claimsig', mint: 'CM1', timestamp: 500 },
+ ]);
+
+ const res = mockRes();
+ await handler(mockReq(), res);
+
+ const body = JSON.parse(res.body);
+ const claim = body.items.find((i) => i.kind === 'claim');
+ expect(claim?.signature).toBe('claimsig');
+ });
+
+ it('returns empty items when all sources are empty', async () => {
+ const res = mockRes();
+ await handler(mockReq(), res);
+
+ const body = JSON.parse(res.body);
+ expect(body.items).toEqual([]);
+ });
+});
diff --git a/tests/pump-telegram-delivery.test.js b/tests/pump-telegram-delivery.test.js
new file mode 100644
index 000000000..aca12f7e3
--- /dev/null
+++ b/tests/pump-telegram-delivery.test.js
@@ -0,0 +1,117 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { Readable } from 'node:stream';
+
+const fetchMock = vi.fn();
+vi.stubGlobal('fetch', fetchMock);
+
+// ── helpers ────────────────────────────────────────────────────────────────
+function makeReq(body) {
+ const stream = body
+ ? Readable.from([Buffer.from(JSON.stringify(body))])
+ : Readable.from([]);
+ stream.method = 'POST';
+ stream.url = '/api/pump/deliver-telegram';
+ stream.headers = { host: 'localhost', 'content-type': 'application/json' };
+ return stream;
+}
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: '',
+ writableEnded: false,
+ setHeader(k, v) {
+ this.headers[k.toLowerCase()] = v;
+ },
+ end(chunk) {
+ if (chunk !== undefined) this.body += chunk;
+ this.writableEnded = true;
+ },
+ };
+}
+
+async function callEndpoint(body) {
+ const { default: handler } = await import('../api/pump/deliver-telegram.js');
+ const res = makeRes();
+ await handler(makeReq(body), res);
+ return { res, json: res.body ? JSON.parse(res.body) : null };
+}
+
+const SIGNAL = {
+ kind: 'mint',
+ mint: 'TokenMint123abc',
+ summary: 'New token launched with 1 SOL',
+ ts: 1700000000000,
+};
+
+beforeEach(() => {
+ fetchMock.mockReset();
+ delete process.env.TELEGRAM_BOT_TOKEN;
+});
+
+// ── sendTelegramSignal ─────────────────────────────────────────────────────
+
+describe('sendTelegramSignal', () => {
+ it('posts to the correct URL with POST method and Markdown parse_mode', async () => {
+ fetchMock.mockResolvedValueOnce({
+ ok: true,
+ json: async () => ({ result: { message_id: 42 } }),
+ });
+ const { sendTelegramSignal } = await import('../src/pump/telegram-delivery.js');
+ const result = await sendTelegramSignal({
+ botToken: 'bot123',
+ chatId: '-100456',
+ signal: SIGNAL,
+ });
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ const [url, opts] = fetchMock.mock.calls[0];
+ expect(url).toBe('https://api.telegram.org/botbot123/sendMessage');
+ expect(opts.method).toBe('POST');
+ const sent = JSON.parse(opts.body);
+ expect(sent.chat_id).toBe('-100456');
+ expect(sent.parse_mode).toBe('Markdown');
+ expect(typeof sent.text).toBe('string');
+ expect(result).toEqual({ ok: true, messageId: 42 });
+ });
+
+ it('throws on a non-2xx Telegram response', async () => {
+ fetchMock.mockResolvedValueOnce({
+ ok: false,
+ status: 400,
+ text: async () => 'Bad Request',
+ });
+ const { sendTelegramSignal } = await import('../src/pump/telegram-delivery.js');
+ await expect(
+ sendTelegramSignal({ botToken: 'bot123', chatId: '1', signal: SIGNAL }),
+ ).rejects.toThrow(/400/);
+ });
+});
+
+// ── POST /api/pump/deliver-telegram ────────────────────────────────────────
+
+describe('POST /api/pump/deliver-telegram', () => {
+ it('returns 500 when TELEGRAM_BOT_TOKEN is not set', async () => {
+ const { res, json } = await callEndpoint({ chatId: '123', signal: SIGNAL });
+ expect(res.statusCode).toBe(500);
+ expect(json.error_description).toMatch(/TELEGRAM_BOT_TOKEN/);
+ });
+
+ it('returns 400 when chatId is missing', async () => {
+ process.env.TELEGRAM_BOT_TOKEN = 'test-token';
+ const { res } = await callEndpoint({ signal: SIGNAL });
+ expect(res.statusCode).toBe(400);
+ });
+
+ it('returns 200 with ok and messageId on success', async () => {
+ process.env.TELEGRAM_BOT_TOKEN = 'test-token';
+ fetchMock.mockResolvedValueOnce({
+ ok: true,
+ json: async () => ({ result: { message_id: 99 } }),
+ });
+ const { res, json } = await callEndpoint({ chatId: '-100789', signal: SIGNAL });
+ expect(res.statusCode).toBe(200);
+ expect(json).toEqual({ ok: true, messageId: 99 });
+ });
+});
diff --git a/tests/pumpfun-ported-skills.test.js b/tests/pumpfun-ported-skills.test.js
new file mode 100644
index 000000000..3ef9f2177
--- /dev/null
+++ b/tests/pumpfun-ported-skills.test.js
@@ -0,0 +1,200 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// vi.hoisted ensures these are available inside vi.mock factories (which are hoisted).
+const { mockValidateInvoicePayment, mockGetInvoiceIdPDA } = vi.hoisted(() => ({
+ mockValidateInvoicePayment: vi.fn(),
+ mockGetInvoiceIdPDA: vi.fn(),
+}));
+
+vi.mock('@pump-fun/agent-payments-sdk', () => {
+ class PumpAgent {
+ validateInvoicePayment(...args) { return mockValidateInvoicePayment(...args); }
+ buildAcceptPaymentInstructions() { return Promise.resolve([]); }
+ }
+ return { PumpAgent, getInvoiceIdPDA: mockGetInvoiceIdPDA };
+});
+
+vi.mock('@solana/web3.js', () => {
+ class PublicKey {
+ constructor(val) { this._val = String(val); }
+ toBase58() { return this._val; }
+ }
+ class Connection {}
+ class Transaction { add() {} }
+ return { PublicKey, Connection, Transaction, LAMPORTS_PER_SOL: 1_000_000_000 };
+});
+
+vi.mock('bn.js', () => ({ default: function BN(v) { this.v = v; this.toString = () => String(v); } }));
+vi.mock('@solana/spl-token', () => ({ TOKEN_PROGRAM_ID: 'TokenProgramId' }));
+
+vi.mock('../src/erc8004/solana-deploy.js', () => ({
+ detectSolanaWallet: vi.fn(() => null),
+ SOLANA_RPC: {
+ mainnet: 'https://api.mainnet-beta.solana.com',
+ devnet: 'https://api.devnet.solana.com',
+ },
+}));
+
+// Stub heavier SDKs loaded lazily by other skills — handlers for these skills are
+// never called in this test file, but the module must import cleanly.
+vi.mock('@pump-fun/pump-sdk', () => ({ PumpSdk: class {}, OnlinePumpSdk: class {} }));
+vi.mock('@pump-fun/pump-swap-sdk', () => ({ OnlinePumpAmmSdk: class {}, canonicalPumpPoolPda: vi.fn() }));
+vi.mock('../src/pump/channel-feed.js', () => ({ fetchChannelFeed: vi.fn() }));
+vi.mock('../src/pump/pumpkit-claims.js', () => ({ listRecentClaims: vi.fn() }));
+vi.mock('../src/kol/wallet-pnl.js', () => ({ getWalletPnl: vi.fn() }));
+
+const { registerPumpFunSkills } = await import('../src/agent-skills-pumpfun.js');
+
+function makeRegistry() {
+ const map = new Map();
+ return {
+ register(spec) { map.set(spec.name, spec); },
+ get(name) { return map.get(name); },
+ perform: vi.fn(),
+ };
+}
+
+// ── pumpfun-verify-payment ────────────────────────────────────────────────────
+
+describe('pumpfun-verify-payment', () => {
+ let registry;
+
+ beforeEach(() => {
+ registry = makeRegistry();
+ registerPumpFunSkills(registry);
+ mockValidateInvoicePayment.mockReset();
+ });
+
+ it('registers with correct schema', () => {
+ const skill = registry.get('pumpfun-verify-payment');
+ expect(skill).toBeDefined();
+ expect(skill.mcpExposed).toBe(true);
+ const req = skill.inputSchema.required;
+ expect(req).toContain('agentMint');
+ expect(req).toContain('user');
+ expect(req).toContain('currencyMint');
+ expect(req).toContain('amount');
+ expect(req).toContain('memo');
+ expect(req).toContain('startTime');
+ expect(req).toContain('endTime');
+ });
+
+ it('returns verified:true when validateInvoicePayment resolves true', async () => {
+ mockValidateInvoicePayment.mockResolvedValueOnce(true);
+ const skill = registry.get('pumpfun-verify-payment');
+ const result = await skill.handler({
+ agentMint: 'AgentMint1111111111111111111111111111111111',
+ user: 'UserWallet111111111111111111111111111111111',
+ currencyMint: 'USDC11111111111111111111111111111111111111',
+ amount: 1_000_000,
+ memo: 42,
+ startTime: 1700000000,
+ endTime: 1700086400,
+ });
+ expect(result.success).toBe(true);
+ expect(result.data.verified).toBe(true);
+ expect(result.output).toMatch(/confirmed/);
+ });
+
+ it('returns verified:false when validateInvoicePayment resolves false', async () => {
+ mockValidateInvoicePayment.mockResolvedValueOnce(false);
+ const skill = registry.get('pumpfun-verify-payment');
+ const result = await skill.handler({
+ agentMint: 'AgentMint1111111111111111111111111111111111',
+ user: 'UserWallet111111111111111111111111111111111',
+ currencyMint: 'USDC11111111111111111111111111111111111111',
+ amount: 1_000_000,
+ memo: 42,
+ startTime: 1700000000,
+ endTime: 1700086400,
+ });
+ expect(result.success).toBe(true);
+ expect(result.data.verified).toBe(false);
+ expect(result.output).toMatch(/not confirmed/);
+ });
+
+ it('rejects amount <= 0 before calling the SDK', async () => {
+ const skill = registry.get('pumpfun-verify-payment');
+ const result = await skill.handler({
+ agentMint: 'A', user: 'B', currencyMint: 'C',
+ amount: 0, memo: 1, startTime: 1000, endTime: 2000,
+ });
+ expect(result.success).toBe(false);
+ expect(mockValidateInvoicePayment).not.toHaveBeenCalled();
+ });
+
+ it('rejects endTime <= startTime before calling the SDK', async () => {
+ const skill = registry.get('pumpfun-verify-payment');
+ const result = await skill.handler({
+ agentMint: 'A', user: 'B', currencyMint: 'C',
+ amount: 1, memo: 1, startTime: 2000, endTime: 1000,
+ });
+ expect(result.success).toBe(false);
+ expect(mockValidateInvoicePayment).not.toHaveBeenCalled();
+ });
+});
+
+// ── pumpfun-invoice-pda ───────────────────────────────────────────────────────
+
+describe('pumpfun-invoice-pda', () => {
+ let registry;
+
+ beforeEach(() => {
+ registry = makeRegistry();
+ registerPumpFunSkills(registry);
+ mockGetInvoiceIdPDA.mockReset();
+ });
+
+ it('registers with correct schema', () => {
+ const skill = registry.get('pumpfun-invoice-pda');
+ expect(skill).toBeDefined();
+ expect(skill.mcpExposed).toBe(true);
+ const req = skill.inputSchema.required;
+ ['agentMint', 'currencyMint', 'amount', 'memo', 'startTime', 'endTime'].forEach((f) =>
+ expect(req).toContain(f),
+ );
+ });
+
+ it('returns the PDA address and bump', async () => {
+ const fakePda = { toBase58: () => 'InvoicePDA1111111111111111111111111111111111' };
+ mockGetInvoiceIdPDA.mockReturnValueOnce([fakePda, 255]);
+
+ const skill = registry.get('pumpfun-invoice-pda');
+ const result = await skill.handler({
+ agentMint: 'AgentMint1111111111111111111111111111111111',
+ currencyMint: 'USDC11111111111111111111111111111111111111',
+ amount: 1_000_000,
+ memo: 42,
+ startTime: 1700000000,
+ endTime: 1700086400,
+ });
+ expect(result.success).toBe(true);
+ expect(result.data.pda).toBe('InvoicePDA1111111111111111111111111111111111');
+ expect(result.data.bump).toBe(255);
+ expect(result.output).toMatch(/InvoicePDA/);
+ });
+
+ it('passes all six parameters to getInvoiceIdPDA in correct order', async () => {
+ const fakePda = { toBase58: () => 'PDA' };
+ mockGetInvoiceIdPDA.mockReturnValueOnce([fakePda, 254]);
+
+ const skill = registry.get('pumpfun-invoice-pda');
+ await skill.handler({
+ agentMint: 'MINT_A',
+ currencyMint: 'CURRENCY_B',
+ amount: 500,
+ memo: 7,
+ startTime: 100,
+ endTime: 200,
+ });
+
+ expect(mockGetInvoiceIdPDA).toHaveBeenCalledOnce();
+ const [tm, cm, amount, memo, start, end] = mockGetInvoiceIdPDA.mock.calls[0];
+ expect(tm.toBase58()).toBe('MINT_A');
+ expect(cm.toBase58()).toBe('CURRENCY_B');
+ expect(amount).toBe(500);
+ expect(memo).toBe(7);
+ expect(start).toBe(100);
+ expect(end).toBe(200);
+ });
+});
diff --git a/tests/skill-manifest.test.js b/tests/skill-manifest.test.js
new file mode 100644
index 000000000..f578a8339
--- /dev/null
+++ b/tests/skill-manifest.test.js
@@ -0,0 +1,106 @@
+import { describe, it, expect, vi } from 'vitest';
+import { buildSkillManifest } from '../src/skill-manifest.js';
+
+// Mock the pumpfun skill registrars so the test doesn't need Solana SDK deps
+vi.mock('../src/agent-skills-pumpfun.js', () => ({ registerPumpFunSkills: () => {} }));
+vi.mock('../src/agent-skills-pumpfun-watch.js', () => ({ registerPumpFunWatchSkills: () => {} }));
+vi.mock('../src/agent-skills-pumpfun-autonomous.js', () => ({
+ registerPumpFunAutonomousSkills: () => {},
+}));
+vi.mock('../src/agent-skills-pumpfun-compose.js', () => ({
+ registerPumpFunComposeSkills: () => {},
+}));
+vi.mock('../src/agent-skills-pumpfun-hooks.js', () => ({ attachPumpFunMemoryHooks: () => {} }));
+
+const { AgentSkills } = await import('../src/agent-skills.js');
+const _stub = { emit: () => {}, on: () => {}, off: () => {}, add: () => 'id', query: () => [] };
+const _skills = new AgentSkills(_stub, _stub);
+
+const SAMPLE_SKILLS = [
+ {
+ name: 'test.full',
+ description: 'A test skill with args',
+ inputSchema: {
+ type: 'object',
+ required: ['mint'],
+ properties: {
+ mint: { type: 'string' },
+ limit: { type: 'number' },
+ },
+ },
+ },
+ {
+ name: 'test.nodesc',
+ // intentionally no description
+ inputSchema: { type: 'object', properties: {} },
+ },
+];
+
+describe('buildSkillManifest', () => {
+ it('returns the documented shape', () => {
+ const manifest = buildSkillManifest({
+ agentId: 'test-agent',
+ version: '1.0.0',
+ skills: SAMPLE_SKILLS,
+ });
+
+ expect(manifest).toMatchObject({
+ agent: { id: 'test-agent', version: '1.0.0' },
+ skills: expect.any(Array),
+ });
+ });
+
+ it('omits skills without a description and emits a warning', () => {
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const manifest = buildSkillManifest({
+ agentId: 'test-agent',
+ version: '1.0.0',
+ skills: SAMPLE_SKILLS,
+ });
+
+ const names = manifest.skills.map((s) => s.name);
+ expect(names).toContain('test.full');
+ expect(names).not.toContain('test.nodesc');
+ expect(warnSpy).toHaveBeenCalledOnce();
+ warnSpy.mockRestore();
+ });
+
+ it('marks required args without ? and optional args with ?', () => {
+ const manifest = buildSkillManifest({
+ agentId: 'test-agent',
+ version: '1.0.0',
+ skills: [SAMPLE_SKILLS[0]],
+ });
+
+ expect(manifest.skills[0].args).toEqual({
+ mint: 'string',
+ limit: 'number?',
+ });
+ });
+
+ it('handles a skill with no inputSchema', () => {
+ const manifest = buildSkillManifest({
+ agentId: 'test-agent',
+ version: '1.0.0',
+ skills: [{ name: 'bare', description: 'no schema' }],
+ });
+
+ expect(manifest.skills[0].args).toEqual({});
+ });
+
+ it('every registered skill with a description appears in the manifest', () => {
+ const manifest = buildSkillManifest({
+ agentId: '3d-agent',
+ version: '0.0.0',
+ skills: _skills.list(),
+ });
+
+ const manifestNames = new Set(manifest.skills.map((s) => s.name));
+ const expected = _skills.list().filter((s) => s.description);
+
+ expect(expected.length).toBeGreaterThan(0);
+ for (const skill of expected) {
+ expect(manifestNames.has(skill.name)).toBe(true);
+ }
+ });
+});