Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: Implement pump.fun integration with new tools, reactions, and tests
nirholase56b7a50e3c1
diff --git a/api/kol/import-gmgn.js b/api/kol/import-gmgn.jsnew file mode 100644index 000000000..8a15b8b63--- /dev/null+++ b/api/kol/import-gmgn.js@@ -0,0 +1,57 @@+// POST /api/kol/import-gmgn+// body: { rawJson: <string|object> }+// → { imported: <number>, wallets: [...] }+//+// Merges parsed wallets into src/kol/wallets.json by wallet address (latest wins).+// No auth required; rate-limited by IP.++import { readFile, writeFile } from 'node:fs/promises';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { parseGmgnSmartWallets } from '../../src/kol/gmgn-parser.js';++const WALLETS_PATH = path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ '../../src/kol/wallets.json',+);++async function loadWallets() {+ try {+ return JSON.parse(await readFile(WALLETS_PATH, 'utf8'));+ } catch {+ return [];+ }+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*' })) 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');++ const body = await readJson(req);+ if (!body || body.rawJson == null) {+ return error(res, 400, 'validation_error', 'body.rawJson is required');+ }++ let parsed;+ try {+ parsed = parseGmgnSmartWallets(body.rawJson);+ } catch (err) {+ return error(res, 400, 'validation_error', err.message);+ }++ const existing = await loadWallets();+ const byWallet = new Map(existing.map((w) => [w.wallet, w]));+ for (const entry of parsed) {+ byWallet.set(entry.wallet, entry);+ }+ const merged = [...byWallet.values()];++ await writeFile(WALLETS_PATH, JSON.stringify(merged, null, '\t') + '\n', 'utf8');++ return json(res, 200, { imported: parsed.length, wallets: merged });+});diff --git a/api/pump-fun-mcp.js b/api/pump-fun-mcp.jsindex bd9bb9f6e..30254af76 100644--- a/api/pump-fun-mcp.js+++ b/api/pump-fun-mcp.js@@ -21,186 +21,9 @@ 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 ──────────────────────────────────────────────────────────--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'],- },- },- {- 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'],- },- },--];+import { TOOLS, rpcError, rpcEnvelope } from '../src/pump/mcp-tools.js';+import { generateVanityKey } from '../src/pump/vanity-keygen.js';+import bs58 from 'bs58';// ── On-chain handlers ──────────────────────────────────────────────────────@@ -339,21 +162,8 @@ 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 };+async function handleKolLeaderboard({ window = '7d', limit = 25 }) {+ return getLeaderboard({ window, limit });}// ── Indexer-backed handlers (route through pumpfunMcp) ─────────────────────@@ -432,6 +242,25 @@ async function rawBotCall(tool, args) {}}+async function handleVanityMint({ suffix = '', prefix = '', caseSensitive = false, maxAttempts = 5_000_000 }) {+ if (!suffix && !prefix) throw rpcError(-32602, 'at least one of suffix or prefix is required');+ const ac = new AbortController();+ const timer = setTimeout(() => ac.abort(), 58_000);+ let result;+ try {+ result = await generateVanityKey({ suffix, prefix, caseSensitive, maxAttempts, signal: ac.signal });+ } finally {+ clearTimeout(timer);+ }+ if (!result) throw rpcError(-32003, `no match found in ${maxAttempts} attempts`);+ return {+ publicKey: result.publicKey,+ secretKey: bs58.encode(result.secretKey),+ attempts: result.attempts,+ ms: result.ms,+ };+}+// ── Claims handlers (on-chain) ─────────────────────────────────────────────@@ -441,7 +270,7 @@ const PUMP_CLAIM_PROGRAMS = new Set(['pfeeUxB6jkeY1Hxd7CsFCAjcbHA9rWtchMGdZ6VojVZ',]);-async function fetchClaimsFromChain({ creator, limit = 20, network = 'mainnet', sinceTs = 0 }) {+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 });@@ -480,14 +309,14 @@ async function fetchClaimsFromChain({ creator, limit = 20, network = 'mainnet',async function handleListClaims({ creator, limit = 20, network = 'mainnet' }) {if (!creator) throw rpcError(-32602, 'creator required');- return { creator, network, claims: await fetchClaimsFromChain({ creator, limit, network }) };+ 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 window = Math.min(1_800_000, Math.max(1, Number(durationMs) || 300_000));const sinceTs = Math.floor((Date.now() - window) / 1000);- const claims = await fetchClaimsFromChain({ creator, limit: 50, network, sinceTs });+ const claims = await _fetchClaimsFromChain({ creator, limit: 50, network, sinceTs });return { creator, network, windowMs: window, claims };}@@ -498,7 +327,7 @@ const HANDLERS = {getTokenDetails: handleGetTokenDetails,getTokenHolders: handleGetTokenHolders,kol_radar: handleKolRadar,- kol_wallet_pnl: handleKolWalletPnl,+ kol_leaderboard: handleKolLeaderboard,searchTokens: indexerOrUnavailable('searchTokens'),getTokenTrades: indexerOrUnavailable('getTokenTrades'),getTrendingTokens: indexerOrUnavailable('getTrendingTokens'),@@ -508,21 +337,9 @@ const HANDLERS = {getCreatorProfile: indexerOrUnavailable('getCreatorProfile'),pumpfun_list_claims: handleListClaims,pumpfun_watch_claims: handleWatchClaims,+ pumpfun_vanity_mint: handleVanityMint,};-function rpcError(code, message) {- const err = new Error(message);- err.rpcCode = code;- return err;-}--function rpcEnvelope(id, result, errObj) {- if (errObj) {- return { jsonrpc: '2.0', id: id ?? null, error: errObj };- }- return { jsonrpc: '2.0', id: id ?? null, result };-}-// ── HTTP entrypoint ────────────────────────────────────────────────────────export default wrap(async (req, res) => {diff --git a/package-lock.json b/package-lock.jsonindex e916f97c0..60a14fa31 100644--- a/package-lock.json+++ b/package-lock.json@@ -52,6 +52,7 @@"devDependencies": {"ajv": "^8.17.1","ajv-formats": "^3.0.1",+ "jsdom": "^29.1.0","playwright": "^1.59.1","prettier": "^3.2.5","sharp": "^0.34.5",@@ -88,6 +89,57 @@"ajv": ">=8"}},+ "node_modules/@asamuzakjp/css-color": {+ "version": "5.1.11",+ "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-5.1.11.tgz",+ "integrity": "sha512-KVw6qIiCTUQhByfTd78h2yD1/00waTmm9uy/R7Ck/ctUyAPj+AEDLkQIdJW0T8+qGgj3j5bpNKK7Q3G+LedJWg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@asamuzakjp/generational-cache": "^1.0.1",+ "@csstools/css-calc": "^3.2.0",+ "@csstools/css-color-parser": "^4.1.0",+ "@csstools/css-parser-algorithms": "^4.0.0",+ "@csstools/css-tokenizer": "^4.0.0"+ },+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ }+ },+ "node_modules/@asamuzakjp/dom-selector": {+ "version": "7.1.1",+ "resolved": "https://registry.npmjs.org/@asamuzakjp/dom-selector/-/dom-selector-7.1.1.tgz",+ "integrity": "sha512-67RZDnYRc8H/8MLDgQCDE//zoqVFwajkepHZgmXrbwybzXOEwOWGPYGmALYl9J2DOLfFPPs6kKCqmbzV895hTQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@asamuzakjp/generational-cache": "^1.0.1",+ "@asamuzakjp/nwsapi": "^2.3.9",+ "bidi-js": "^1.0.3",+ "css-tree": "^3.2.1",+ "is-potential-custom-element-name": "^1.0.1"+ },+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ }+ },+ "node_modules/@asamuzakjp/generational-cache": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/@asamuzakjp/generational-cache/-/generational-cache-1.0.1.tgz",+ "integrity": "sha512-wajfB8KqzMCN2KGNFdLkReeHncd0AslUSrvHVvvYWuU8ghncRJoA50kT3zP9MVL0+9g4/67H+cdvBskj9THPzg==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ }+ },+ "node_modules/@asamuzakjp/nwsapi": {+ "version": "2.3.9",+ "resolved": "https://registry.npmjs.org/@asamuzakjp/nwsapi/-/nwsapi-2.3.9.tgz",+ "integrity": "sha512-n8GuYSrI9bF7FFZ/SjhwevlHc8xaVlb/7HmHelnc/PZXBD2ZR49NnN9sMMuDdEGPeeRQ5d0hqlSlEpgCX3Wl0Q==",+ "dev": true,+ "license": "MIT"+ },"node_modules/@avaturn/sdk": {"version": "1.1.4","resolved": "https://registry.npmjs.org/@avaturn/sdk/-/sdk-1.1.4.tgz",@@ -2712,6 +2764,19 @@"node": ">=18"}},+ "node_modules/@bramus/specificity": {+ "version": "2.4.2",+ "resolved": "https://registry.npmjs.org/@bramus/specificity/-/specificity-2.4.2.tgz",+ "integrity": "sha512-ctxtJ/eA+t+6q2++vj5j7FYX3nRu311q1wfYH3xjlLOsczhlhxAg2FWNUXhpGvAw3BWo1xBcvOV6/YLc2r5FJw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "css-tree": "^3.0.0"+ },+ "bin": {+ "specificity": "bin/cli.js"+ }+ },"node_modules/@chenglou/pretext": {"version": "0.0.5","resolved": "https://registry.npmjs.org/@chenglou/pretext/-/pretext-0.0.5.tgz",@@ -2797,6 +2862,146 @@"@solana/web3.js": "^1.69.0"}},+ "node_modules/@csstools/color-helpers": {+ "version": "6.0.2",+ "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-6.0.2.tgz",+ "integrity": "sha512-LMGQLS9EuADloEFkcTBR3BwV/CGHV7zyDxVRtVDTwdI2Ca4it0CCVTT9wCkxSgokjE5Ho41hEPgb8OEUwoXr6Q==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT-0",+ "engines": {+ "node": ">=20.19.0"+ }+ },+ "node_modules/@csstools/css-calc": {+ "version": "3.2.0",+ "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-3.2.0.tgz",+ "integrity": "sha512-bR9e6o2BDB12jzN/gIbjHa5wLJ4UjD1CB9pM7ehlc0ddk6EBz+yYS1EV2MF55/HUxrHcB/hehAyt5vhsA3hx7w==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT",+ "engines": {+ "node": ">=20.19.0"+ },+ "peerDependencies": {+ "@csstools/css-parser-algorithms": "^4.0.0",+ "@csstools/css-tokenizer": "^4.0.0"+ }+ },+ "node_modules/@csstools/css-color-parser": {+ "version": "4.1.0",+ "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-4.1.0.tgz",+ "integrity": "sha512-U0KhLYmy2GVj6q4T3WaAe6NPuFYCPQoE3b0dRGxejWDgcPp8TP7S5rVdM5ZrFaqu4N67X8YaPBw14dQSYx3IyQ==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "@csstools/color-helpers": "^6.0.2",+ "@csstools/css-calc": "^3.2.0"+ },+ "engines": {+ "node": ">=20.19.0"+ },+ "peerDependencies": {+ "@csstools/css-parser-algorithms": "^4.0.0",+ "@csstools/css-tokenizer": "^4.0.0"+ }+ },+ "node_modules/@csstools/css-parser-algorithms": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-4.0.0.tgz",+ "integrity": "sha512-+B87qS7fIG3L5h3qwJ/IFbjoVoOe/bpOdh9hAjXbvx0o8ImEmUsGXN0inFOnk2ChCFgqkkGFQ+TpM5rbhkKe4w==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT",+ "engines": {+ "node": ">=20.19.0"+ },+ "peerDependencies": {+ "@csstools/css-tokenizer": "^4.0.0"+ }+ },+ "node_modules/@csstools/css-syntax-patches-for-csstree": {+ "version": "1.1.3",+ "resolved": "https://registry.npmjs.org/@csstools/css-syntax-patches-for-csstree/-/css-syntax-patches-for-csstree-1.1.3.tgz",+ "integrity": "sha512-SH60bMfrRCJF3morcdk57WklujF4Jr/EsQUzqkarfHXEFcAR1gg7fS/chAE922Sehgzc1/+Tz5H3Ypa1HiEKrg==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT-0",+ "peerDependencies": {+ "css-tree": "^3.2.1"+ },+ "peerDependenciesMeta": {+ "css-tree": {+ "optional": true+ }+ }+ },+ "node_modules/@csstools/css-tokenizer": {+ "version": "4.0.0",+ "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-4.0.0.tgz",+ "integrity": "sha512-QxULHAm7cNu72w97JUNCBFODFaXpbDg+dP8b/oWFAZ2MTRppA3U00Y2L1HqaS4J6yBqxwa/Y3nMBaxVKbB/NsA==",+ "dev": true,+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/csstools"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/csstools"+ }+ ],+ "license": "MIT",+ "engines": {+ "node": ">=20.19.0"+ }+ },"node_modules/@emnapi/runtime": {"version": "1.9.2","resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.9.2.tgz",@@ -3250,6 +3455,24 @@"node": ">=18"}},+ "node_modules/@exodus/bytes": {+ "version": "1.15.0",+ "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.15.0.tgz",+ "integrity": "sha512-UY0nlA+feH81UGSHv92sLEPLCeZFjXOuHhrIo0HQydScuQc8s0A7kL/UdgwgDq8g8ilksmuoF35YVTNphV2aBQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ },+ "peerDependencies": {+ "@noble/hashes": "^1.8.0 || ^2.0.0"+ },+ "peerDependenciesMeta": {+ "@noble/hashes": {+ "optional": true+ }+ }+ },"node_modules/@fastify/otel": {"version": "0.18.0","resolved": "https://registry.npmjs.org/@fastify/otel/-/otel-0.18.0.tgz",@@ -10851,6 +11074,16 @@"integrity": "sha512-V/Hy/X9Vt7f3BbPJEi8BdVFMByHi+jNXrYkW3huaybV/kQ0KJg0Y6PkEMbn+zeT+i+SiKZ/HMqJGIIt4LZDqNQ==","license": "MIT"},+ "node_modules/bidi-js": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.0.3.tgz",+ "integrity": "sha512-RKshQI1R3YQ+n9YJz2QQ147P66ELpa1FQEg20Dk8oW9t2KgLbpDLLp9aGZ7y8WHSshDknG0bknqGw5/tyCs5tw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "require-from-string": "^2.0.2"+ }+ },"node_modules/bigint-buffer": {"version": "1.1.5","resolved": "https://registry.npmjs.org/bigint-buffer/-/bigint-buffer-1.1.5.tgz",@@ -11341,6 +11574,20 @@"node": ">=8"}},+ "node_modules/css-tree": {+ "version": "3.2.1",+ "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-3.2.1.tgz",+ "integrity": "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "mdn-data": "2.27.1",+ "source-map-js": "^1.2.1"+ },+ "engines": {+ "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0"+ }+ },"node_modules/dat.gui": {"version": "0.7.9","resolved": "https://registry.npmjs.org/dat.gui/-/dat.gui-0.7.9.tgz",@@ -11356,6 +11603,58 @@"node": ">= 14"}},+ "node_modules/data-urls": {+ "version": "7.0.0",+ "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-7.0.0.tgz",+ "integrity": "sha512-23XHcCF+coGYevirZceTVD7NdJOqVn+49IHyxgszm+JIiHLoB2TkmPtsYkNWT1pvRSGkc35L6NHs0yHkN2SumA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "whatwg-mimetype": "^5.0.0",+ "whatwg-url": "^16.0.0"+ },+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ }+ },+ "node_modules/data-urls/node_modules/tr46": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/tr46/-/tr46-6.0.0.tgz",+ "integrity": "sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "punycode": "^2.3.1"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/data-urls/node_modules/webidl-conversions": {+ "version": "8.0.1",+ "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz",+ "integrity": "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==",+ "dev": true,+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/data-urls/node_modules/whatwg-url": {+ "version": "16.0.1",+ "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-16.0.1.tgz",+ "integrity": "sha512-1to4zXBxmXHV3IiSSEInrreIlu02vUOvrhxJJH5vcxYTBDAx51cqZiKdyTxlecdKNSjj8EcxGBxNf6Vg+945gw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@exodus/bytes": "^1.11.0",+ "tr46": "^6.0.0",+ "webidl-conversions": "^8.0.1"+ },+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ }+ },"node_modules/data-view-buffer": {"version": "1.0.2","resolved": "https://registry.npmjs.org/data-view-buffer/-/data-view-buffer-1.0.2.tgz",@@ -11427,6 +11726,13 @@}}},+ "node_modules/decimal.js": {+ "version": "10.6.0",+ "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz",+ "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==",+ "dev": true,+ "license": "MIT"+ },"node_modules/decode-uri-component": {"version": "0.4.1","resolved": "https://registry.npmjs.org/decode-uri-component/-/decode-uri-component-0.4.1.tgz",@@ -11576,6 +11882,19 @@"once": "^1.4.0"}},+ "node_modules/entities": {+ "version": "8.0.0",+ "resolved": "https://registry.npmjs.org/entities/-/entities-8.0.0.tgz",+ "integrity": "sha512-zwfzJecQ/Uej6tusMqwAqU/6KL2XaB2VZ2Jg54Je6ahNBGNH6Ek6g3jjNCF0fG9EWQKGZNddNjU5F1ZQn/sBnA==",+ "dev": true,+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=20.19.0"+ },+ "funding": {+ "url": "https://github.com/fb55/entities?sponsor=1"+ }+ },"node_modules/env-paths": {"version": "2.2.1","resolved": "https://registry.npmjs.org/env-paths/-/env-paths-2.2.1.tgz",@@ -12575,6 +12894,19 @@"node": ">= 0.4"}},+ "node_modules/html-encoding-sniffer": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-6.0.0.tgz",+ "integrity": "sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@exodus/bytes": "^1.6.0"+ },+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ }+ },"node_modules/http-proxy-agent": {"version": "7.0.2","resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz",@@ -12991,6 +13323,13 @@"node": ">=0.10.0"}},+ "node_modules/is-potential-custom-element-name": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz",+ "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==",+ "dev": true,+ "license": "MIT"+ },"node_modules/is-regex": {"version": "1.2.1","resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.2.1.tgz",@@ -13335,6 +13674,95 @@"js-yaml": "bin/js-yaml.js"}},+ "node_modules/jsdom": {+ "version": "29.1.0",+ "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-29.1.0.tgz",+ "integrity": "sha512-YNUc7fB9QuvSSQWfrH0xF+TyABkxUwx8sswgIDaCrw4Hol8BghdZDkITtZheRJeMtzWlnTfsM3bBBusRvpO1wg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@asamuzakjp/css-color": "^5.1.11",+ "@asamuzakjp/dom-selector": "^7.1.1",+ "@bramus/specificity": "^2.4.2",+ "@csstools/css-syntax-patches-for-csstree": "^1.1.3",+ "@exodus/bytes": "^1.15.0",+ "css-tree": "^3.2.1",+ "data-urls": "^7.0.0",+ "decimal.js": "^10.6.0",+ "html-encoding-sniffer": "^6.0.0",+ "is-potential-custom-element-name": "^1.0.1",+ "lru-cache": "^11.3.5",+ "parse5": "^8.0.1",+ "saxes": "^6.0.0",+ "symbol-tree": "^3.2.4",+ "tough-cookie": "^6.0.1",+ "undici": "^7.25.0",+ "w3c-xmlserializer": "^5.0.0",+ "webidl-conversions": "^8.0.1",+ "whatwg-mimetype": "^5.0.0",+ "whatwg-url": "^16.0.1",+ "xml-name-validator": "^5.0.0"+ },+ "engines": {+ "node": "^20.19.0 || ^22.13.0 || >=24.0.0"+ },+ "peerDependencies": {+ "canvas": "^3.0.0"+ },+ "peerDependenciesMeta": {+ "canvas": {+ "optional": true+ }+ }+ },+ "node_modules/jsdom/node_modules/lru-cache": {+ "version": "11.3.5",+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.3.5.tgz",+ "integrity": "sha512-NxVFwLAnrd9i7KUBxC4DrUhmgjzOs+1Qm50D3oF1/oL+r1NpZ4gA7xvG0/zJ8evR7zIKn4vLf7qTNduWFtCrRw==",+ "dev": true,+ "license": "BlueOak-1.0.0",+ "engines": {+ "node": "20 || >=22"+ }+ },+ "node_modules/jsdom/node_modules/tr46": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/tr46/-/tr46-6.0.0.tgz",+ "integrity": "sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "punycode": "^2.3.1"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/jsdom/node_modules/webidl-conversions": {+ "version": "8.0.1",+ "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz",+ "integrity": "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==",+ "dev": true,+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/jsdom/node_modules/whatwg-url": {+ "version": "16.0.1",+ "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-16.0.1.tgz",+ "integrity": "sha512-1to4zXBxmXHV3IiSSEInrreIlu02vUOvrhxJJH5vcxYTBDAx51cqZiKdyTxlecdKNSjj8EcxGBxNf6Vg+945gw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@exodus/bytes": "^1.11.0",+ "tr46": "^6.0.0",+ "webidl-conversions": "^8.0.1"+ },+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"+ }+ },"node_modules/jsesc": {"version": "3.1.0","resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz",@@ -13496,6 +13924,13 @@"node": ">= 0.4"}},+ "node_modules/mdn-data": {+ "version": "2.27.1",+ "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz",+ "integrity": "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==",+ "dev": true,+ "license": "CC0-1.0"+ },"node_modules/merge-deep": {"version": "3.0.3","resolved": "https://registry.npmjs.org/merge-deep/-/merge-deep-3.0.3.tgz",@@ -13896,6 +14331,19 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/parse5": {+ "version": "8.0.1",+ "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.0.1.tgz",+ "integrity": "sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "entities": "^8.0.0"+ },+ "funding": {+ "url": "https://github.com/inikulin/parse5?sponsor=1"+ }+ },"node_modules/path-expression-matcher": {"version": "1.5.0","resolved": "https://registry.npmjs.org/path-expression-matcher/-/path-expression-matcher-1.5.0.tgz",@@ -15879,6 +16327,19 @@}}},+ "node_modules/saxes": {+ "version": "6.0.0",+ "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz",+ "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==",+ "dev": true,+ "license": "ISC",+ "dependencies": {+ "xmlchars": "^2.2.0"+ },+ "engines": {+ "node": ">=v12.22.7"+ }+ },"node_modules/semver": {"version": "6.3.1","resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",@@ -16540,6 +17001,13 @@"uuid": "dist/bin/uuid"}},+ "node_modules/symbol-tree": {+ "version": "3.2.4",+ "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz",+ "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==",+ "dev": true,+ "license": "MIT"+ },"node_modules/tar-fs": {"version": "3.1.2","resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.1.2.tgz",@@ -16693,12 +17161,45 @@"node": ">=14.0.0"}},+ "node_modules/tldts": {+ "version": "7.0.29",+ "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.0.29.tgz",+ "integrity": "sha512-JIXCerhudr/N6OWLwLF1HVsTTUo7ry6qHa5eWZEkiMuxsIiAACL55tGLfqfHfoH7QaMQUW8fngD7u7TxWexYQg==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "tldts-core": "^7.0.29"+ },+ "bin": {+ "tldts": "bin/cli.js"+ }+ },+ "node_modules/tldts-core": {+ "version": "7.0.29",+ "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.0.29.tgz",+ "integrity": "sha512-W99NuU7b1DcG3uJ3v9k9VztCH3WialNbBkBft5wCs8V8mexu0XQqaZEYb9l9RNNzK8+3EJ9PKWB0/RUtTQ/o+Q==",+ "dev": true,+ "license": "MIT"+ },"node_modules/toml": {"version": "3.0.0","resolved": "https://registry.npmjs.org/toml/-/toml-3.0.0.tgz","integrity": "sha512-y/mWCZinnvxjTKYhJ+pYxwD0mRLVvOtdS2Awbgxln6iEnt4rk0yBxeSBHkGJcPucRiG0e55mwWp+g/05rsrd6w==","license": "MIT"},+ "node_modules/tough-cookie": {+ "version": "6.0.1",+ "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.0.1.tgz",+ "integrity": "sha512-LktZQb3IeoUWB9lqR5EWTHgW/VTITCXg4D21M+lvybRVdylLrRMnqaIONLVb5mav8vM19m44HIcGq4qASeu2Qw==",+ "dev": true,+ "license": "BSD-3-Clause",+ "dependencies": {+ "tldts": "^7.0.5"+ },+ "engines": {+ "node": ">=16"+ }+ },"node_modules/tr46": {"version": "1.0.1","resolved": "https://registry.npmjs.org/tr46/-/tr46-1.0.1.tgz",@@ -16837,6 +17338,16 @@"integrity": "sha512-Ql87qFHB3s/De2ClA9e0gsnS6zXG27SkTiSJwjCc9MebbfapQfuPzumMIUMi38ezPZVNFcHI9sUIepeQfw8J8Q==","license": "MIT"},+ "node_modules/undici": {+ "version": "7.25.0",+ "resolved": "https://registry.npmjs.org/undici/-/undici-7.25.0.tgz",+ "integrity": "sha512-xXnp4kTyor2Zq+J1FfPI6Eq3ew5h6Vl0F/8d9XU5zZQf1tX9s2Su1/3PiMmUANFULpmksxkClamIZcaUqryHsQ==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=20.18.1"+ }+ },"node_modules/undici-types": {"version": "7.19.2","resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.19.2.tgz",@@ -17271,6 +17782,19 @@"@jridgewell/sourcemap-codec": "^1.5.5"}},+ "node_modules/w3c-xmlserializer": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz",+ "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "xml-name-validator": "^5.0.0"+ },+ "engines": {+ "node": ">=18"+ }+ },"node_modules/webdriver-bidi-protocol": {"version": "0.4.1","resolved": "https://registry.npmjs.org/webdriver-bidi-protocol/-/webdriver-bidi-protocol-0.4.1.tgz",@@ -17284,6 +17808,16 @@"dev": true,"license": "BSD-2-Clause"},+ "node_modules/whatwg-mimetype": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-5.0.0.tgz",+ "integrity": "sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==",+ "dev": true,+ "license": "MIT",+ "engines": {+ "node": ">=20"+ }+ },"node_modules/whatwg-url": {"version": "7.1.0","resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-7.1.0.tgz",@@ -17781,6 +18315,23 @@}}},+ "node_modules/xml-name-validator": {+ "version": "5.0.0",+ "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",+ "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==",+ "dev": true,+ "license": "Apache-2.0",+ "engines": {+ "node": ">=18"+ }+ },+ "node_modules/xmlchars": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz",+ "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==",+ "dev": true,+ "license": "MIT"+ },"node_modules/xtend": {"version": "4.0.2","resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",diff --git a/package.json b/package.jsonindex faddcbf8a..e5a039eab 100644--- a/package.json+++ b/package.json@@ -103,6 +103,7 @@"devDependencies": {"ajv": "^8.17.1","ajv-formats": "^3.0.1",+ "jsdom": "^29.1.0","playwright": "^1.59.1","prettier": "^3.2.5","sharp": "^0.34.5",diff --git a/prompts/repo-integrations/37-pump-integration-tests.md b/prompts/repo-integrations/37-pump-integration-tests.mdnew file mode 100644index 000000000..502465f4f--- /dev/null+++ b/prompts/repo-integrations/37-pump-integration-tests.md@@ -0,0 +1,55 @@+# 37 — Integration tests for the pump.fun surface++**Branch:** `test/pump-integration`+**One PR. Standalone. No other prompt is required to be shipped first.**++## Why it matters++The pump.fun surface (skills + MCP tools + HTTP handlers) has unit tests scattered across files. A single integration test that calls each public surface end-to-end (against mocks) catches contract-level regressions when any one prompt above ships.++## Read these first++| File | Why |+| :--- | :--- |+| [tests/](../../tests/) | Existing tests — match style. |+| [tests/pumpfun-mcp.test.js](../../tests/pumpfun-mcp.test.js) | Closest existing test. |+| [vitest.config.js](../../vitest.config.js) | Test runner config. |+| [api/pump-fun-mcp.js](../../api/pump-fun-mcp.js) | Tool list to assert against. |++## Build this++1. Add `tests/pump-surface-integration.test.js`. The test:+ - Loads the live MCP tool list.+ - For each tool, calls it with a minimal valid payload using mocks for upstream sources (RPC, SDK).+ - Asserts each tool returns a 2xx-shaped result without throwing.+ - Asserts the response shape includes the documented top-level fields.+2. The mock layer lives in `tests/_helpers/pump-mocks.js` (one new helper file). Provide:+ - `withMockedPump(fn)` — patches `globalThis.fetch` and any SDK exports the tools use.+ - Fixture data under `tests/fixtures/pump/*.json`.+3. Run separately from unit tests: tag with `describe.concurrent`, keep total runtime under 5 seconds.++## Out of scope++- Real RPC / SDK calls.+- Coverage targets.+- Editing existing unit tests.++## Acceptance++- [ ] `npx vitest run tests/pump-surface-integration.test.js` passes.+- [ ] Test exercises every MCP tool currently registered.+- [ ] Total runtime under 5s on a clean machine.+- [ ] `npx vite build` passes.++## Test plan++1. Run the test; confirm green.+2. Comment out one tool's registration; rerun; confirm the integration test fails loudly with a clear message.+3. Restore.++## Reporting++- Shipped: …+- Skipped: …+- Tools that could not be tested without real RPC (with reason): …+- Unrelated bugs noticed: …diff --git a/prompts/repo-integrations/38-prompts-index-update.md b/prompts/repo-integrations/38-prompts-index-update.mdnew file mode 100644index 000000000..69b3ccd44--- /dev/null+++ b/prompts/repo-integrations/38-prompts-index-update.md@@ -0,0 +1,45 @@+# 38 — Add repo-integrations to top-level prompts index++**Branch:** `docs/prompts-index-repo-integrations`+**One PR. Standalone. No other prompt is required to be shipped first.**++## Why it matters++The prompts dispatch index ([prompts/INDEX.md](../INDEX.md), [prompts/README.md](../README.md)) lists active bands. The new `repo-integrations/` band needs an entry so future agents pick it up rather than reinventing tasks.++## Read these first++| File | Why |+| :--- | :--- |+| [prompts/INDEX.md](../INDEX.md) | Top-level dispatch index. |+| [prompts/README.md](../README.md) | Active vs archival list. |+| [prompts/repo-integrations/README.md](./README.md) | The new band's own README. |++## Build this++1. Add a single line to [prompts/INDEX.md](../INDEX.md) under "Dispatch order" linking to `repo-integrations/`. Describe in one line: "side lane — feature ports from the user's other GitHub repos. Independent of the priority stack."+2. Add a row to the "Active" table in [prompts/README.md](../README.md) for `repo-integrations/` with status "Active — repo feature ports".+3. Do not change priorities or band order. The new band is a parallel side lane.++## Out of scope++- Renaming or reorganizing existing bands.+- Editing repo-integrations files.++## Acceptance++- [ ] Both index files reference `repo-integrations/`.+- [ ] `prompts/repo-integrations/` is reachable in two clicks from `INDEX.md`.+- [ ] No other content in the index files changed.++## Test plan++1. Render both files in a Markdown previewer; confirm links resolve.+2. Diff the two files; confirm only additions, no edits to existing rows.++## Reporting++- Shipped: …+- Skipped: …+- Broke / regressions: …+- Unrelated bugs noticed: …diff --git a/public/studio/launch-panel.js b/public/studio/launch-panel.jsnew file mode 100644index 000000000..4fb100f8f--- /dev/null+++ b/public/studio/launch-panel.js@@ -0,0 +1,202 @@+// Launch panel for the character studio right column.+// Adds a "launch a token for this agent" form with bonding-curve progress visual.+//+// Public API (pure, testable without DOM):+// validateLaunchForm(fields) → { ok, errors }+// handleLaunchSubmit(fields, onSubmit) → { ok, errors? }+//+// DOM:+// mountLaunchPanel(container, opts) → teardown()++const FEE_TIERS = [+ ['standard', 'Standard (0.25%)'],+ ['boosted', 'Boosted (0.5%)'],+ ['premium', 'Premium (1%)'],+];++/** Validate launch form fields. Returns { ok, errors } — no DOM side-effects. */+export function validateLaunchForm({ name, symbol, description, initialBuy } = {}) {+ const errors = {};+ if (!name?.trim()) errors.name = 'Token name is required';+ if (!symbol?.trim()) errors.symbol = 'Symbol is required';+ if (!description?.trim()) errors.description = 'Description is required';+ if (initialBuy !== '' && initialBuy != null) {+ const n = Number(initialBuy);+ if (isNaN(n) || n < 0) errors.initialBuy = 'Initial buy must be a non-negative number';+ }+ return { ok: Object.keys(errors).length === 0, errors };+}++/** Validate then call onSubmit(fields) if valid. Returns { ok, errors? }. */+export function handleLaunchSubmit(fields, onSubmit) {+ const result = validateLaunchForm(fields);+ if (!result.ok) return result;+ onSubmit(fields);+ return { ok: true };+}++function escHtml(s) {+ return String(s ?? '').replace(+ /[&<>"']/g,+ (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],+ );+}++/**+ * Mount the launch panel into `container`.+ * opts.onSubmit(fields) — called when form passes validation.+ * If omitted, dispatches pump-launch-open CustomEvent (consumed by mountPumpModals+ * when loaded on the same page).+ * Returns a teardown() function.+ */+export function mountLaunchPanel(container, { onSubmit } = {}) {+ const tierOpts = FEE_TIERS.map(+ ([v, l]) => `<option value="${escHtml(v)}">${escHtml(l)}</option>`,+ ).join('');++ container.innerHTML = `+<div class="launch-panel">+ <p class="muted launch-panel-desc">+ Launch a pump.fun bonding-curve token for this agent.+ Fill in the details and submit — you'll sign one transaction with your Solana wallet.+ </p>++ <label class="field">+ <span>Token name <span class="launch-req">*</span></span>+ <input type="text" name="lp-name" maxlength="32" placeholder="My Agent Token" />+ <span class="launch-field-err" id="lp-err-name" hidden></span>+ </label>++ <label class="field">+ <span>Symbol <span class="launch-req">*</span></span>+ <input type="text" name="lp-symbol" maxlength="10" placeholder="AGENT" />+ <span class="launch-field-err" id="lp-err-symbol" hidden></span>+ </label>++ <label class="field">+ <span>Token image</span>+ <input type="file" name="lp-image" accept="image/*" class="launch-file-input" />+ <span class="muted" style="font-size:0.72rem">PNG or JPG — square recommended.</span>+ </label>++ <label class="field">+ <span>Description <span class="launch-req">*</span></span>+ <textarea name="lp-description" rows="3" maxlength="500" placeholder="What does this agent do?"></textarea>+ <span class="launch-field-err" id="lp-err-description" hidden></span>+ </label>++ <label class="field">+ <span>Initial buy (SOL)</span>+ <input type="number" name="lp-initial-buy" min="0" max="50" step="0.01" value="0" />+ <span class="muted" style="font-size:0.72rem">Optional creator buy-in on launch. 0 = no buy.</span>+ <span class="launch-field-err" id="lp-err-initialbuy" hidden></span>+ </label>++ <label class="field">+ <span>Fee tier</span>+ <select name="lp-fee-tier">${tierOpts}</select>+ </label>++ <div class="bonding-curve-preview">+ <div class="bonding-curve-header">+ <span class="muted" style="font-size:0.72rem;text-transform:uppercase;letter-spacing:0.06em">Bonding curve</span>+ <span id="lp-curve-pct" class="bonding-curve-pct">0%</span>+ </div>+ <div class="bonding-curve-track">+ <div class="bonding-curve-fill" id="lp-curve-fill" style="width:0%"></div>+ </div>+ <div class="bonding-curve-labels">+ <span>Genesis</span>+ <span>Graduation ($69k)</span>+ </div>+ </div>++ <div class="launch-field-err" id="lp-err-global" style="margin-bottom:0.5rem" hidden></div>++ <button type="button" class="btn-primary" id="lp-submit" style="width:100%">+ Launch token+ </button>+</div>`;++ const q = (sel) => container.querySelector(sel);++ function getFields() {+ return {+ name: q('[name="lp-name"]').value,+ symbol: q('[name="lp-symbol"]').value.toUpperCase().trim(),+ description: q('[name="lp-description"]').value,+ initialBuy: q('[name="lp-initial-buy"]').value,+ feeTier: q('[name="lp-fee-tier"]').value,+ image: q('[name="lp-image"]').files?.[0] ?? null,+ };+ }++ function clearErrors() {+ for (const el of container.querySelectorAll('.launch-field-err')) {+ el.hidden = true;+ el.textContent = '';+ }+ }++ function showErr(id, msg) {+ const el = q(`#${id}`);+ if (!el) return;+ el.textContent = msg;+ el.hidden = false;+ }++ function updateCurve() {+ const f = getFields();+ const filled = [f.name.trim(), f.symbol.trim(), f.description.trim()].filter(Boolean).length;+ // Visual only: max 72% at form-complete — graduation is on-chain+ const pct = Math.round((filled / 3) * 72);+ q('#lp-curve-fill').style.width = `${pct}%`;+ q('#lp-curve-pct').textContent = `${pct}%`;+ }++ q('[name="lp-name"]').addEventListener('input', updateCurve);+ q('[name="lp-symbol"]').addEventListener('input', updateCurve);+ q('[name="lp-description"]').addEventListener('input', updateCurve);++ q('#lp-submit').addEventListener('click', () => {+ clearErrors();+ const fields = getFields();++ if (typeof onSubmit === 'function') {+ const result = handleLaunchSubmit(fields, onSubmit);+ if (!result.ok) {+ const e = result.errors;+ if (e.name) showErr('lp-err-name', e.name);+ if (e.symbol) showErr('lp-err-symbol', e.symbol);+ if (e.description) showErr('lp-err-description', e.description);+ if (e.initialBuy) showErr('lp-err-initialbuy', e.initialBuy);+ }+ return;+ }++ const { ok, errors } = validateLaunchForm(fields);+ if (!ok) {+ if (errors.name) showErr('lp-err-name', errors.name);+ if (errors.symbol) showErr('lp-err-symbol', errors.symbol);+ if (errors.description) showErr('lp-err-description', errors.description);+ if (errors.initialBuy) showErr('lp-err-initialbuy', errors.initialBuy);+ return;+ }++ // TODO: load pump-modals.js in the studio HTML to enable the full on-chain flow.+ // For now dispatch the event (consumed by mountPumpModals when present) and+ // log so the form submission is visible in the console for smoke testing.+ console.log('[launch-panel] submit', fields);+ if (typeof window !== 'undefined') {+ window.dispatchEvent(+ new CustomEvent('pump-launch-open', {+ detail: { identity: { name: fields.name }, formData: fields },+ }),+ );+ }+ });++ return function teardown() {+ container.innerHTML = '';+ };+}diff --git a/scripts/ingest-gmgn.js b/scripts/ingest-gmgn.jsnew file mode 100644index 000000000..7385d4efd--- /dev/null+++ b/scripts/ingest-gmgn.js@@ -0,0 +1,50 @@+#!/usr/bin/env node+/**+ * Ingest a gmgn.ai smart-wallet dump into src/kol/wallets.json.+ *+ * Usage:+ * node scripts/ingest-gmgn.js path/to/gmgn-dump.json+ */++import { readFile, writeFile } from 'node:fs/promises';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { parseGmgnSmartWallets } from '../src/kol/gmgn-parser.js';++const HERE = path.dirname(fileURLToPath(import.meta.url));+const WALLETS_PATH = path.resolve(HERE, '../src/kol/wallets.json');++async function loadWallets() {+ try {+ return JSON.parse(await readFile(WALLETS_PATH, 'utf8'));+ } catch {+ return [];+ }+}++async function main() {+ const [, , inputPath] = process.argv;+ if (!inputPath) {+ console.error('Usage: node scripts/ingest-gmgn.js <path/to/gmgn-dump.json>');+ process.exitCode = 1;+ return;+ }++ const raw = await readFile(path.resolve(inputPath), 'utf8');+ const parsed = parseGmgnSmartWallets(raw);++ const existing = await loadWallets();+ const byWallet = new Map(existing.map((w) => [w.wallet, w]));+ for (const entry of parsed) {+ byWallet.set(entry.wallet, entry);+ }+ const merged = [...byWallet.values()];++ await writeFile(WALLETS_PATH, JSON.stringify(merged, null, '\t') + '\n', 'utf8');+ console.log(`Imported ${parsed.length} wallets. Total: ${merged.length} in wallets.json`);+}++main().catch((e) => {+ console.error('FAILED:', e.message);+ process.exitCode = 1;+});diff --git a/src/agent-skills-pumpfun-watch.js b/src/agent-skills-pumpfun-watch.jsindex 29ac1fbe7..09daf0f0d 100644--- a/src/agent-skills-pumpfun-watch.js+++ b/src/agent-skills-pumpfun-watch.js@@ -20,6 +20,7 @@*/import { ACTION_TYPES } from './agent-protocol.js';+import { watchClaims } from './pump/pumpkit-claims.js';const FEED_PATH = '/api/agents/pumpfun-feed';const TIER_BADGE = { mega: '🔥🔥', influencer: '🔥', notable: '⭐' };diff --git a/src/agent-skills-pumpfun.js b/src/agent-skills-pumpfun.jsindex 8b6466be0..aabeea387 100644--- a/src/agent-skills-pumpfun.js+++ b/src/agent-skills-pumpfun.js@@ -22,6 +22,7 @@ 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';+import { resolveSnsName, reverseLookupAddress } from './solana/sns.js';const DEFAULT_NETWORK = 'mainnet';const DEFAULT_SLIPPAGE_BPS = 500;@@ -1212,4 +1213,114 @@ export function registerPumpFunSkills(skills) {},});+ // ── social.cashtagSentiment ───────────────────────────────────────────────+ skills.register({+ name: 'social.cashtagSentiment',+ description:+ 'Score sentiment for a batch of cashtag posts. Accepts posts as { id?, ts?, text, author? }[] and returns a digest with score (-1..1), % breakdown, and examples.',+ instruction:+ 'Runs a deterministic lexicon-based sentiment analysis on social posts about a cashtag. No external API required.',+ animationHint: 'inspect',+ voicePattern: 'Analyzing sentiment…',+ mcpExposed: false,+ inputSchema: {+ type: 'object',+ properties: {+ posts: {+ type: 'array',+ description: 'Array of post objects, each with at minimum a `text` field.',+ items: {+ type: 'object',+ properties: {+ id: { type: 'string' },+ ts: { type: 'string' },+ text: { type: 'string' },+ author: { type: 'string' },+ },+ required: ['text'],+ },+ },+ },+ required: ['posts'],+ },+ handler: async (args, _ctx) => {+ const { scoreSentiment } = await import('./social/sentiment.js');+ const result = scoreSentiment(args.posts || []);+ const label =+ result.score > 0.2 ? 'bullish' : result.score < -0.2 ? 'bearish' : 'neutral';+ return {+ success: true,+ output: `Sentiment: ${label} (score ${result.score}, ${result.count} posts — ${result.posPct}% positive, ${result.negPct}% negative, ${result.neuPct}% neutral).`,+ sentiment: result.score,+ data: result,+ };+ },+ });++ // ── solana.resolveSns ─────────────────────────────────────────────────────+ skills.register({+ name: 'solana.resolveSns',+ description: 'Resolve a .sol Solana Name Service domain to its owner wallet address.',+ instruction: 'Forward SNS lookup. Read-only. Returns the owner public key for a .sol name.',+ animationHint: 'inspect',+ voicePattern: 'Resolving {{name}}…',+ mcpExposed: true,+ inputSchema: {+ type: 'object',+ properties: {+ name: { type: 'string', description: '.sol domain name, e.g. "bonfida.sol"' },+ },+ required: ['name'],+ },+ handler: async (args, _ctx) => {+ const address = await resolveSnsName(args.name);+ if (!address) {+ return {+ success: false,+ output: `Could not resolve "${args.name}". Domain may not exist.`,+ sentiment: -0.1,+ };+ }+ return {+ success: true,+ output: `${args.name} → ${address}`,+ sentiment: 0.4,+ data: { name: args.name, address },+ };+ },+ });++ // ── solana.reverseSns ─────────────────────────────────────────────────────+ skills.register({+ name: 'solana.reverseSns',+ description: 'Reverse-lookup a Solana wallet address to its primary .sol domain name.',+ instruction: 'Reverse SNS lookup via the primary/favourite domain. Read-only.',+ animationHint: 'inspect',+ voicePattern: 'Reverse-looking up {{address}}…',+ mcpExposed: true,+ inputSchema: {+ type: 'object',+ properties: {+ address: { type: 'string', description: 'Base58 Solana wallet address' },+ },+ required: ['address'],+ },+ handler: async (args, _ctx) => {+ const name = await reverseLookupAddress(args.address);+ if (!name) {+ return {+ success: false,+ output: `No .sol domain found for ${args.address.slice(0, 8)}…`,+ sentiment: -0.1,+ };+ }+ return {+ success: true,+ output: `${args.address.slice(0, 8)}… → ${name}`,+ sentiment: 0.4,+ data: { address: args.address, name },+ };+ },+ });+}\ No newline at end of filediff --git a/src/components/bonding-curve.js b/src/components/bonding-curve.jsnew file mode 100644index 000000000..77ad4decf--- /dev/null+++ b/src/components/bonding-curve.js@@ -0,0 +1,133 @@+// Bonding-curve SVG component — no deps, no canvas.+// mountBondingCurve(rootEl, { progressPct, marketCapUsd, graduationCapUsd })+// Returns { update, destroy }.++const W = 300, H = 90;+const PL = 10, PR = 10, PT = 8, PB = 20;+const PW = W - PL - PR;+const PH = H - PT - PB;+const BOT = PT + PH;++let _seq = 0;++// Square-root bonding curve: price ∝ sqrt(tokens_sold_fraction).+function _cx(t) { return PL + t * PW; }+function _cy(t) { return PT + PH * (1 - Math.sqrt(Math.max(0, t))); }++const CURVE_PATH = (() => {+ const n = 64;+ let d = '';+ for (let i = 0; i <= n; i++) {+ const t = i / n;+ d += `${i === 0 ? 'M' : 'L'}${_cx(t).toFixed(2)},${_cy(t).toFixed(2)} `;+ }+ return d.trimEnd();+})();++// Full fill shape (curve top + bottom baseline) — clipped per progress.+const FILL_PATH = (() => {+ const n = 64;+ let d = `M${PL.toFixed(2)},${BOT.toFixed(2)} `;+ for (let i = 0; i <= n; i++) {+ const t = i / n;+ d += `L${_cx(t).toFixed(2)},${_cy(t).toFixed(2)} `;+ }+ d += `L${(W - PR).toFixed(2)},${BOT.toFixed(2)} Z`;+ return d;+})();++function _fmt(usd) {+ if (!usd) return '';+ if (usd >= 1e6) return `$${(usd / 1e6).toFixed(1)}M`;+ if (usd >= 1e3) return `$${(usd / 1e3).toFixed(0)}k`;+ return `$${usd.toFixed(0)}`;+}++/**+ * Mount a bonding-curve SVG into rootEl.+ * @param {HTMLElement} rootEl+ * @param {{ progressPct?: number, marketCapUsd?: number, graduationCapUsd?: number }} opts+ * @returns {{ update: (opts: { progressPct?: number, marketCapUsd?: number }) => void, destroy: () => void }}+ */+export function mountBondingCurve(rootEl, {+ progressPct = 0,+ marketCapUsd = 0,+ graduationCapUsd = 69_000,+} = {}) {+ const id = ++_seq;+ const gradId = `bc-g${id}`;+ const clipId = `bc-c${id}`;++ const t0 = Math.max(0, Math.min(1, progressPct / 100));+ const mx0 = _cx(t0);+ const my0 = _cy(t0);+ const capText = marketCapUsd ? _fmt(marketCapUsd) : `${progressPct.toFixed(1)}%`;++ rootEl.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${W} ${H}"+ style="width:100%;height:auto;display:block"+ aria-label="Bonding curve ${progressPct.toFixed(0)}% to graduation">+ <defs>+ <linearGradient id="${gradId}" x1="0" y1="0" x2="0" y2="1">+ <stop offset="0%" stop-color="rgba(106,147,255,0.28)"/>+ <stop offset="100%" stop-color="rgba(106,147,255,0.02)"/>+ </linearGradient>+ <clipPath id="${clipId}">+ <rect class="bc-clip" x="0" y="0" width="${mx0.toFixed(2)}" height="${H}"/>+ </clipPath>+ </defs>+ <line x1="${PL}" y1="${BOT}" x2="${W - PR}" y2="${BOT}"+ stroke="rgba(255,255,255,0.07)" stroke-width="1"/>+ <path d="${FILL_PATH}" fill="url(#${gradId})" stroke="none"+ clip-path="url(#${clipId})"/>+ <path d="${CURVE_PATH}" fill="none"+ stroke="rgba(255,255,255,0.13)" stroke-width="1.5" stroke-linecap="round"/>+ <path d="${CURVE_PATH}" fill="none"+ stroke="rgba(106,147,255,0.85)" stroke-width="2" stroke-linecap="round"+ clip-path="url(#${clipId})"/>+ <line x1="${(W - PR).toFixed(2)}" y1="${PT}"+ x2="${(W - PR).toFixed(2)}" y2="${BOT}"+ stroke="rgba(164,240,188,0.3)" stroke-width="1" stroke-dasharray="3 3"/>+ <g class="bc-marker"+ style="transform:translate(${mx0.toFixed(2)}px,0);transition:transform 0.2s ease">+ <line x1="0" y1="${PT}" x2="0" y2="${BOT}"+ stroke="rgba(255,255,255,0.38)" stroke-width="1" stroke-dasharray="2 2"/>+ <circle cx="0" cy="${my0.toFixed(2)}" r="4"+ fill="#6a93ff" stroke="rgba(255,255,255,0.8)" stroke-width="1.5"/>+ </g>+ <text x="${PL}" y="${H - 5}" font-size="9"+ fill="rgba(255,255,255,0.45)" font-family="ui-monospace,monospace"+ class="bc-cap">${capText}</text>+ <text x="${W - PR}" y="${H - 5}" text-anchor="end" font-size="9"+ fill="rgba(164,240,188,0.55)"+ font-family="ui-monospace,monospace">${_fmt(graduationCapUsd) || '$69k'}</text>+</svg>`;++ const svg = rootEl.querySelector('svg');+ const marker = svg.querySelector('.bc-marker');+ const clip = svg.querySelector('.bc-clip');+ const capLabel = svg.querySelector('.bc-cap');+ const circle = marker.querySelector('circle');++ let _pct = progressPct;+ let _cap = marketCapUsd;++ function update({ progressPct: newPct, marketCapUsd: newCap } = {}) {+ if (newPct !== undefined) _pct = newPct;+ if (newCap !== undefined) _cap = newCap;++ const t = Math.max(0, Math.min(1, _pct / 100));+ const mx = _cx(t);+ const my = _cy(t);++ marker.style.transform = `translate(${mx.toFixed(2)}px, 0)`;+ circle.setAttribute('cy', my.toFixed(2));+ if (clip) clip.setAttribute('width', mx.toFixed(2));+ if (capLabel) capLabel.textContent = _cap ? _fmt(_cap) : `${_pct.toFixed(1)}%`;+ }++ function destroy() {+ rootEl.innerHTML = '';+ }++ return { update, destroy };+}diff --git a/src/element.js b/src/element.jsindex 09443e4f2..9ca7c703a 100644--- a/src/element.js+++ b/src/element.js@@ -10,6 +10,7 @@ import { loadManifest, fetchRelative } from './manifest.js';import { resolveURI } from './ipfs.js';import { resolveAgentById, resolveByAgentId, AgentResolveError } from './agent-resolver.js';import { parseAgentRef, resolveOnchainAgent, toManifest } from './erc8004/resolver.js';+import { attachTradeReactions } from './pump/trade-reactions.js';// BEGIN:EMBED_BRIDGES_IMPORTimport { EmbedActionBridge } from './embed-action-bridge.js';import { protocol, ACTION_TYPES } from './agent-protocol.js';@@ -285,6 +286,7 @@ class Agent3DElement extends HTMLElement {'responsive','background','name-plate',+ 'tracked-mint',];}@@ -307,6 +309,7 @@ class Agent3DElement extends HTMLElement {this._outsideTapHandler = null;this._autoResolvedManifest = false;this._suppressAttrChange = false;+ this._detachTradeReactions = null;}connectedCallback() {@@ -352,6 +355,12 @@ class Agent3DElement extends HTMLElement {this._applyLayout();if (name === 'background') this._applyBackground();if (name === 'name-plate') this._applyNamePlate();+ if (name === 'tracked-mint') {+ this._detachTradeReactions?.();+ this._detachTradeReactions = newVal+ ? attachTradeReactions(this, { mint: newVal })+ : null;+ }if (['src', 'manifest', 'body', 'agent-id'].includes(name)) {// Source change — rebootthis._teardown();@@ -969,6 +978,10 @@ class Agent3DElement extends HTMLElement {}this._mounted = true;+ const _trackedMint = this.getAttribute('tracked-mint');+ if (_trackedMint) {+ this._detachTradeReactions = attachTradeReactions(this, { mint: _trackedMint });+ }// BEGIN:EMBED_BRIDGESif (window !== window.parent) {this._embedBridge = new EmbedActionBridge({@@ -1382,6 +1395,8 @@ class Agent3DElement extends HTMLElement {}this._embedBridge?.stop();this._embedBridge = null;+ this._detachTradeReactions?.();+ this._detachTradeReactions = null;try {this._runtime?.destroy();} catch {}@@ -1419,6 +1434,41 @@ class Agent3DElement extends HTMLElement {this._runtime?.clearConversation();}+ /**+ * Play a named emote. Tries a fallback hint chain before head-bobbing.+ * Emote names: 'cheer', 'flinch', 'celebrate'+ */+ playEmote(name, intensity = 1) {+ const sc = this._scene;+ if (!sc) return false;+ const fallbacks = { cheer: ['cheer', 'celebrate', 'wave'], flinch: ['flinch', 'defeated', 'concern', 'shake'], celebrate: ['celebrate', 'wave'] };+ for (const h of (fallbacks[name] || [name])) {+ if (sc.playAnimationByHint(h)) return true;+ }+ this._headBob(intensity);+ return false;+ }++ _headBob(intensity = 1) {+ const sc = this._scene;+ if (!sc) return;+ const bone = sc._findBone(['Head', 'head', 'mixamorigHead']);+ if (!bone) return;+ const start = performance.now();+ const origX = bone.rotation.x;+ const tick = () => {+ const t = (performance.now() - start) / 800;+ if (t >= 1) {+ bone.rotation.x = origX;+ sc._removeHook(tick);+ return;+ }+ bone.rotation.x = origX + 0.15 * intensity * Math.sin(t * Math.PI * 3);+ sc.viewer.invalidate();+ };+ sc._addHook(tick);+ }+async wave(opts) {return this._scene?.playAnimationByHint('wave', opts);}diff --git a/src/kol/gmgn-parser.js b/src/kol/gmgn-parser.jsnew file mode 100644index 000000000..3a8ad6618--- /dev/null+++ b/src/kol/gmgn-parser.js@@ -0,0 +1,66 @@+// Accepts either the raw gmgn API response ({ data: { rank|wallets|list: [...] } })+// or scrape-smart-wallets normalized output ({ meta, smartMoney, kol, ... }).+// Throws if the format is not recognizable.++/**+ * @param {object|string} rawJson+ * @returns {{ wallet: string, label?: string, pnlUsd?: number, winRate?: number, source: 'gmgn' }[]}+ */+export function parseGmgnSmartWallets(rawJson) {+ const data = typeof rawJson === 'string' ? JSON.parse(rawJson) : rawJson;++ // Raw gmgn API: { data: { rank|wallets|list: [...] } }+ if (data && data.data && typeof data.data === 'object') {+ const list = data.data.rank ?? data.data.wallets ?? data.data.list;+ if (Array.isArray(list)) {+ return list.map(mapEntry).filter(Boolean);+ }+ }++ // scrape-smart-wallets normalized: { meta, smartMoney?, kol?, ... }+ if (data && data.meta && (data.smartMoney || data.kol)) {+ const entries = [];+ addFromWalletsMap(data.smartMoney?.wallets, entries);+ addFromWalletsMap(data.kol?.wallets, entries);+ return entries;+ }++ // Flat array: [{ address|wallet_address, ... }]+ if (Array.isArray(data)) {+ const mapped = data.map(mapEntry).filter(Boolean);+ if (mapped.length > 0 || data.length === 0) return mapped;+ }++ throw new Error(+ 'Unrecognized gmgn dump format. Expected { data: { rank: [...] } } or { meta, smartMoney, ... }.',+ );+}++function mapEntry(entry) {+ const wallet = entry.wallet_address || entry.address;+ if (!wallet) return null;++ const result = { wallet, source: 'gmgn' };++ const label = entry.twitter_name || entry.name || entry.ens;+ if (label) result.label = label;++ const pnlUsd = entry.pnl_7d ?? entry.realized_profit_7d ?? entry.pnl_30d ?? entry.realized_profit_30d;+ if (pnlUsd != null) result.pnlUsd = pnlUsd;++ const winRate = entry.winrate ?? entry.win_rate;+ if (winRate != null) result.winRate = winRate;++ return result;+}++function addFromWalletsMap(walletsMap, out) {+ if (!walletsMap || typeof walletsMap !== 'object') return;+ for (const group of Object.values(walletsMap)) {+ if (!Array.isArray(group)) continue;+ for (const entry of group) {+ const mapped = mapEntry(entry);+ if (mapped) out.push(mapped);+ }+ }+}diff --git a/src/pump/mcp-tools.js b/src/pump/mcp-tools.jsindex ae377bb67..82d5fd09e 100644--- a/src/pump/mcp-tools.js+++ b/src/pump/mcp-tools.js@@ -117,6 +117,90 @@ export const TOOLS = [required: ['mint'],},},+ {+ 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_watch_whales',+ description:+ 'Collect whale trades on a pump.fun token for a short window (max 10 s). Returns all trades whose USD value meets minUsd.',+ 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: 'Collection window in ms (default 5000, max 10000)',+ },+ },+ required: ['mint'],+ },+ },+ {+ name: 'pumpfun_list_claims',+ description:+ 'List recent pump.fun fee-claim events for a creator wallet (on-chain, no indexer needed). Returns signature, mint, lamports, and Unix timestamp for each claim.',+ 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 a look-back window (durationMs). Useful for batch collection after a delay.',+ 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'],+ },+ },+ {+ name: 'sns_resolve',+ description: 'Resolve a .sol Solana Name Service domain to its owner wallet address.',+ inputSchema: {+ type: 'object',+ properties: {+ name: { type: 'string', description: '.sol domain name, e.g. "bonfida.sol"' },+ },+ required: ['name'],+ },+ },+ {+ name: 'sns_reverseLookup',+ description: 'Reverse-lookup a Solana wallet address to its primary .sol domain name.',+ inputSchema: {+ type: 'object',+ properties: {+ address: { type: 'string', description: 'Base58 Solana wallet address' },+ },+ required: ['address'],+ },+ },];export function rpcError(code, message) {diff --git a/src/pump/trade-reactions.js b/src/pump/trade-reactions.jsnew file mode 100644index 000000000..b0cef72e2--- /dev/null+++ b/src/pump/trade-reactions.js@@ -0,0 +1,72 @@+/**+ * Wire pump.fun live trades into avatar reactions.+ *+ * attachTradeReactions(agent, { mint, intensity })+ * Subscribes to trades for `mint` via SSE. On significant events:+ * large buy → agent.playEmote('cheer')+ * large sell → agent.playEmote('flinch')+ * graduation → agent.playEmote('celebrate')+ * "Significant" = top 10% of trade sizes in a rolling 5-min window.+ * Returns a detach function.+ */++const FEED_PATH = '/api/agents/pumpfun-feed';+const WINDOW_MS = 5 * 60 * 1000;+const MIN_SAMPLES = 5;++/** 90th-percentile of `amounts`. Returns Infinity when fewer than MIN_SAMPLES. */+function p90(amounts) {+ if (amounts.length < MIN_SAMPLES) return Infinity;+ const sorted = amounts.slice().sort((a, b) => a - b);+ return sorted[Math.floor(0.9 * sorted.length)];+}++/**+ * @param {object} agent — Agent3DElement with a playEmote(name, intensity) method+ * @param {{ mint: string, intensity?: number, _EventSource?: typeof EventSource }} opts+ * @returns {() => void} detach+ */+export function attachTradeReactions(agent, { mint, intensity = 1, _EventSource = globalThis.EventSource } = {}) {+ if (!mint || !_EventSource) return () => {};++ // Rolling buffer of { amount: number, ts: number }+ const buf = [];++ function flush() {+ const cutoff = Date.now() - WINDOW_MS;+ while (buf.length && buf[0].ts < cutoff) buf.shift();+ }++ function onTrade(msg) {+ let data;+ try { data = JSON.parse(msg.data); } catch { return; }++ const amount = data.solAmount ?? data.sol_amount ?? data.amount ?? 0;+ const isBuy =+ data.txType === 'buy' ||+ data.isBuy === true ||+ data.is_buy === true ||+ data.type === 'buy';++ // Threshold is computed from history; then add the current trade.+ flush();+ const threshold = p90(buf.map((e) => e.amount));+ buf.push({ amount, ts: Date.now() });++ if (threshold === Infinity || amount < threshold) return;++ agent.playEmote(isBuy ? 'cheer' : 'flinch', intensity);+ }++ function onGraduation(msg) {+ try { JSON.parse(msg.data); } catch { return; }+ agent.playEmote('celebrate', intensity);+ }++ const params = new URLSearchParams({ kind: 'trades', mint });+ const es = new _EventSource(`${FEED_PATH}?${params}`, { withCredentials: true });+ es.addEventListener('trade', onTrade);+ es.addEventListener('graduation', onGraduation);++ return () => { es.close(); };+}diff --git a/src/solana/sns.js b/src/solana/sns.jsnew file mode 100644index 000000000..5413068f5--- /dev/null+++ b/src/solana/sns.js@@ -0,0 +1,43 @@+import { Connection, PublicKey } from '@solana/web3.js';+import { resolve, getFavoriteDomain } from '@bonfida/spl-name-service';++const DEFAULT_RPC_URL =+ (typeof process !== 'undefined' && process.env?.SOLANA_RPC_URL) ||+ 'https://api.mainnet-beta.solana.com';++function makeConnection() {+ return new Connection(DEFAULT_RPC_URL, 'confirmed');+}++function stripSol(name) {+ return name.endsWith('.sol') ? name.slice(0, -4) : name;+}++/**+ * Forward lookup: .sol domain name → owner wallet address (base58) or null.+ * @param {string} name - e.g. 'bonfida.sol' or 'bonfida'+ * @returns {Promise<string|null>}+ */+export async function resolveSnsName(name) {+ try {+ const pk = await resolve(makeConnection(), stripSol(name));+ return pk.toBase58();+ } catch {+ return null;+ }+}++/**+ * Reverse lookup: wallet address (base58) → primary .sol domain name or null.+ * @param {string} addr - base58-encoded wallet public key+ * @returns {Promise<string|null>}+ */+export async function reverseLookupAddress(addr) {+ try {+ const owner = new PublicKey(addr);+ const { reverse } = await getFavoriteDomain(makeConnection(), owner);+ return reverse.endsWith('.sol') ? reverse : `${reverse}.sol`;+ } catch {+ return null;+ }+}diff --git a/tests/bonding-curve.test.js b/tests/bonding-curve.test.jsnew file mode 100644index 000000000..2c6cde5d4--- /dev/null+++ b/tests/bonding-curve.test.js@@ -0,0 +1,61 @@+// @vitest-environment jsdom+import { describe, it, expect, beforeEach } from 'vitest';+import { mountBondingCurve } from '../src/components/bonding-curve.js';++describe('mountBondingCurve', () => {+ let container;++ beforeEach(() => {+ container = document.createElement('div');+ });++ it('renders an SVG element', () => {+ mountBondingCurve(container, { progressPct: 0 });+ const svg = container.querySelector('svg');+ expect(svg).toBeTruthy();+ expect(svg.tagName.toLowerCase()).toBe('svg');+ });++ it('SVG contains a curve path and a marker', () => {+ mountBondingCurve(container, { progressPct: 25 });+ expect(container.querySelector('.bc-marker')).toBeTruthy();+ expect(container.querySelectorAll('path').length).toBeGreaterThanOrEqual(1);+ });++ it('update({ progressPct: 50 }) moves the marker to a new x position', () => {+ const { update } = mountBondingCurve(container, { progressPct: 10 });+ const marker = container.querySelector('.bc-marker');+ const before = marker.style.transform;++ update({ progressPct: 50 });++ expect(marker.style.transform).not.toBe(before);+ expect(marker.style.transform).toMatch(/translate/);+ });++ it('update moves the circle cy to reflect the new curve position', () => {+ const { update } = mountBondingCurve(container, { progressPct: 10 });+ const circle = container.querySelector('.bc-marker circle');+ const cyBefore = circle.getAttribute('cy');++ update({ progressPct: 80 });++ expect(circle.getAttribute('cy')).not.toBe(cyBefore);+ });++ it('destroy() empties the container', () => {+ const { destroy } = mountBondingCurve(container, { progressPct: 30 });+ destroy();+ expect(container.innerHTML).toBe('');+ });++ it('renders with default opts', () => {+ mountBondingCurve(container);+ expect(container.querySelector('svg')).toBeTruthy();+ });++ it('shows graduation cap label', () => {+ mountBondingCurve(container, { graduationCapUsd: 69_000 });+ expect(container.innerHTML).toContain('69');+ });+});diff --git a/tests/fixtures/gmgn-dump.json b/tests/fixtures/gmgn-dump.jsonnew file mode 100644index 000000000..94b9ab832--- /dev/null+++ b/tests/fixtures/gmgn-dump.json@@ -0,0 +1,25 @@+{+ "data": {+ "rank": [+ {+ "wallet_address": "So11111111111111111111111111111111111111112",+ "pnl_7d": 12345.67,+ "winrate": 0.75,+ "tags": ["smart_money", "top_trader"],+ "twitter_name": "SmartTrader1"+ },+ {+ "wallet_address": "7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU",+ "pnl_7d": 8901.23,+ "winrate": 0.62,+ "tags": ["kol"],+ "name": "KolTrader2"+ },+ {+ "wallet_address": "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263",+ "realized_profit_7d": 3200.0,+ "win_rate": 0.55+ }+ ]+ }+}diff --git a/tests/fixtures/gmgn-normalized.json b/tests/fixtures/gmgn-normalized.jsonnew file mode 100644index 000000000..6b0b781ed--- /dev/null+++ b/tests/fixtures/gmgn-normalized.json@@ -0,0 +1,50 @@+{+ "meta": {+ "startedAt": "2024-01-15T10:00:00.000Z",+ "finishedAt": "2024-01-15T10:00:45.000Z",+ "chain": "sol",+ "mode": "all",+ "version": "v4.0",+ "success": true,+ "durationMs": 45000,+ "errors": [],+ "missingScripts": []+ },+ "smartMoney": {+ "wallets": {+ "smart_money": [+ {+ "address": "BVxyYhm498L79r4HMQ9sxZ5bi41DmJmeWZ7SCS7Cyvna",+ "pnl_7d": 54321.0,+ "winrate": 0.81,+ "tags": ["smart_money"]+ },+ {+ "address": "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM",+ "pnl_7d": 19876.5,+ "winrate": 0.70,+ "tags": ["smart_money", "top_trader"]+ }+ ]+ },+ "walletDetails": {},+ "walletHoldings": {}+ },+ "kol": {+ "wallets": {+ "kol": [+ {+ "address": "H6ARHf6YXhGYeQfUzQNGk6rDNnLBQKrenN712K4AQJEG",+ "pnl_7d": 7500.0,+ "winrate": 0.65,+ "tags": ["kol"],+ "twitter_name": "kolAlpha"+ }+ ]+ },+ "twitterUsers": [],+ "walletDetails": {},+ "walletHoldings": {}+ },+ "tokens": {}+}diff --git a/tests/gmgn-parser.test.js b/tests/gmgn-parser.test.jsnew file mode 100644index 000000000..aebaf26f2--- /dev/null+++ b/tests/gmgn-parser.test.js@@ -0,0 +1,80 @@+import { describe, it, expect } from 'vitest';+import { readFile } from 'node:fs/promises';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { parseGmgnSmartWallets } from '../src/kol/gmgn-parser.js';++const HERE = path.dirname(fileURLToPath(import.meta.url));++const rawDump = JSON.parse(+ await readFile(path.join(HERE, 'fixtures/gmgn-dump.json'), 'utf8'),+);+const normalizedDump = JSON.parse(+ await readFile(path.join(HERE, 'fixtures/gmgn-normalized.json'), 'utf8'),+);++describe('parseGmgnSmartWallets — raw gmgn API shape', () => {+ it('extracts all three wallets', () => {+ const result = parseGmgnSmartWallets(rawDump);+ expect(result).toHaveLength(3);+ });++ it('maps fields correctly for first entry', () => {+ const [first] = parseGmgnSmartWallets(rawDump);+ expect(first).toEqual({+ wallet: 'So11111111111111111111111111111111111111112',+ label: 'SmartTrader1',+ pnlUsd: 12345.67,+ winRate: 0.75,+ source: 'gmgn',+ });+ });++ it('falls back to realized_profit_7d and win_rate for third entry', () => {+ const result = parseGmgnSmartWallets(rawDump);+ const third = result.find((w) => w.wallet === 'DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263');+ expect(third.pnlUsd).toBe(3200.0);+ expect(third.winRate).toBe(0.55);+ expect(third.label).toBeUndefined();+ });++ it('accepts a JSON string', () => {+ const result = parseGmgnSmartWallets(JSON.stringify(rawDump));+ expect(result).toHaveLength(3);+ expect(result[0].source).toBe('gmgn');+ });+});++describe('parseGmgnSmartWallets — scrape-smart-wallets normalized shape', () => {+ it('extracts wallets from smartMoney and kol sections', () => {+ const result = parseGmgnSmartWallets(normalizedDump);+ expect(result).toHaveLength(3);+ });++ it('maps fields correctly', () => {+ const result = parseGmgnSmartWallets(normalizedDump);+ const kol = result.find((w) => w.wallet === 'H6ARHf6YXhGYeQfUzQNGk6rDNnLBQKrenN712K4AQJEG');+ expect(kol).toEqual({+ wallet: 'H6ARHf6YXhGYeQfUzQNGk6rDNnLBQKrenN712K4AQJEG',+ label: 'kolAlpha',+ pnlUsd: 7500.0,+ winRate: 0.65,+ source: 'gmgn',+ });+ });++ it('sets source to gmgn on all entries', () => {+ const result = parseGmgnSmartWallets(normalizedDump);+ expect(result.every((w) => w.source === 'gmgn')).toBe(true);+ });+});++describe('parseGmgnSmartWallets — error cases', () => {+ it('throws on unrecognized format', () => {+ expect(() => parseGmgnSmartWallets({ foo: 'bar' })).toThrow('Unrecognized');+ });++ it('throws on invalid JSON string', () => {+ expect(() => parseGmgnSmartWallets('not json')).toThrow();+ });+});diff --git a/tests/trade-reactions.test.js b/tests/trade-reactions.test.jsnew file mode 100644index 000000000..bb5cca3d6--- /dev/null+++ b/tests/trade-reactions.test.js@@ -0,0 +1,125 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { attachTradeReactions } from '../src/pump/trade-reactions.js';++// Minimal EventSource mock. close() prevents further _fire() calls (mirrors real behaviour).+class MockEventSource {+ constructor() {+ this._listeners = {};+ this.readyState = 1; // OPEN+ MockEventSource._last = this;+ }+ addEventListener(type, fn) {+ (this._listeners[type] ??= []).push(fn);+ }+ close() {+ this.readyState = 2; // CLOSED+ }+ _fire(type, data) {+ if (this.readyState === 2) return;+ const msg = { data: JSON.stringify(data) };+ for (const fn of (this._listeners[type] ?? [])) fn(msg);+ }+}+MockEventSource._last = null;++function makeAgent() {+ return { playEmote: vi.fn() };+}++/** Fire N buy trades of the given SOL amount through the mock EventSource. */+function seed(es, n, amount) {+ for (let i = 0; i < n; i++) {+ es._fire('trade', { solAmount: amount, txType: 'buy' });+ }+}++describe('attachTradeReactions', () => {+ beforeEach(() => {+ MockEventSource._last = null;+ });++ it('returns a detach function', () => {+ const detach = attachTradeReactions(makeAgent(), { mint: 'ABC', _EventSource: MockEventSource });+ expect(typeof detach).toBe('function');+ detach();+ });++ it('returns no-op when mint is missing', () => {+ const detach = attachTradeReactions(makeAgent(), { _EventSource: MockEventSource });+ expect(typeof detach).toBe('function');+ expect(MockEventSource._last).toBeNull(); // no EventSource created+ detach(); // should not throw+ });++ it('below-threshold trades do not trigger emotes', () => {+ const agent = makeAgent();+ attachTradeReactions(agent, { mint: 'ABC', _EventSource: MockEventSource });+ const es = MockEventSource._last;++ // 5 baseline trades to fill the rolling window+ seed(es, 5, 1.0);+ // 6th trade below the 90th-percentile threshold (1.0) — should not fire+ es._fire('trade', { solAmount: 0.5, txType: 'buy' });++ expect(agent.playEmote).not.toHaveBeenCalled();+ });++ it('above-threshold buy triggers cheer', () => {+ const agent = makeAgent();+ attachTradeReactions(agent, { mint: 'ABC', _EventSource: MockEventSource });+ const es = MockEventSource._last;++ seed(es, 5, 1.0); // baseline: threshold = 1.0+ es._fire('trade', { solAmount: 2.0, txType: 'buy' });++ expect(agent.playEmote).toHaveBeenCalledTimes(1);+ expect(agent.playEmote).toHaveBeenCalledWith('cheer', 1);+ });++ it('above-threshold sell triggers flinch', () => {+ const agent = makeAgent();+ attachTradeReactions(agent, { mint: 'ABC', _EventSource: MockEventSource });+ const es = MockEventSource._last;++ seed(es, 5, 1.0);+ es._fire('trade', { solAmount: 2.0, txType: 'sell' });++ expect(agent.playEmote).toHaveBeenCalledWith('flinch', 1);+ });++ it('graduation always triggers celebrate regardless of threshold', () => {+ const agent = makeAgent();+ attachTradeReactions(agent, { mint: 'ABC', _EventSource: MockEventSource });+ const es = MockEventSource._last;++ // No baseline trades — graduation should still fire+ es._fire('graduation', { mint: 'ABC', symbol: 'TEST' });++ expect(agent.playEmote).toHaveBeenCalledWith('celebrate', 1);+ });++ it('detach stops further triggers', () => {+ const agent = makeAgent();+ const detach = attachTradeReactions(agent, { mint: 'ABC', _EventSource: MockEventSource });+ const es = MockEventSource._last;++ seed(es, 5, 1.0); // fill window, no emotes yet++ detach(); // closes the EventSource++ // A trade that would normally trigger cheer is dropped after detach+ es._fire('trade', { solAmount: 2.0, txType: 'buy' });+ expect(agent.playEmote).not.toHaveBeenCalled();+ });++ it('respects intensity parameter', () => {+ const agent = makeAgent();+ attachTradeReactions(agent, { mint: 'ABC', intensity: 0.5, _EventSource: MockEventSource });+ const es = MockEventSource._last;++ seed(es, 5, 1.0);+ es._fire('trade', { solAmount: 2.0, txType: 'buy' });++ expect(agent.playEmote).toHaveBeenCalledWith('cheer', 0.5);+ });+});diff --git a/tests/vanity-keygen.test.js b/tests/vanity-keygen.test.jsnew file mode 100644index 000000000..feb8cc304--- /dev/null+++ b/tests/vanity-keygen.test.js@@ -0,0 +1,44 @@+import { describe, it, expect } from 'vitest';+import { generateVanityKey } from '../src/pump/vanity-keygen.js';++describe('generateVanityKey', () => {+ it('returns a key whose base58 address ends with the requested suffix', async () => {+ const result = await generateVanityKey({ suffix: 'a' });+ expect(result).not.toBeNull();+ expect(result.publicKey.toLowerCase()).toMatch(/a$/);+ expect(result.attempts).toBeGreaterThan(0);+ expect(result.ms).toBeGreaterThanOrEqual(0);+ expect(result.secretKey).toBeInstanceOf(Uint8Array);+ expect(result.secretKey).toHaveLength(64);+ });++ it('returns a key whose base58 address starts with the requested prefix', async () => {+ const result = await generateVanityKey({ prefix: 'a' });+ expect(result).not.toBeNull();+ expect(result.publicKey.toLowerCase()).toMatch(/^a/);+ });++ it('respects caseSensitive flag for suffix', async () => {+ // Generate without case sensitivity, then verify the address ends with suffix+ // in a case-insensitive comparison.+ const result = await generateVanityKey({ suffix: 'A', caseSensitive: false });+ expect(result).not.toBeNull();+ expect(result.publicKey.toLowerCase()).toMatch(/a$/);+ });++ it('returns null when maxAttempts is 0', async () => {+ const result = await generateVanityKey({ suffix: 'zzz', maxAttempts: 0 });+ expect(result).toBeNull();+ });++ it('throws when neither suffix nor prefix is provided', async () => {+ await expect(generateVanityKey({})).rejects.toThrow();+ });++ it('respects abort signal', async () => {+ const ac = new AbortController();+ ac.abort();+ const result = await generateVanityKey({ suffix: 'a', signal: ac.signal });+ expect(result).toBeNull();+ });+});diff --git a/workers/pump-fun-mcp/worker.js b/workers/pump-fun-mcp/worker.jsnew file mode 100644index 000000000..11263a621--- /dev/null+++ b/workers/pump-fun-mcp/worker.js@@ -0,0 +1,337 @@+// Cloudflare Workers mirror of /api/pump-fun-mcp (Vercel).+//+// Implements the MCP Streamable HTTP transport (JSON-RPC 2.0 over POST).+// Tool definitions are shared with the Vercel handler via src/pump/mcp-tools.js.+// Handler logic is adapted from api/pump-fun-mcp.js — the only differences are:+// • CF Workers fetch handler (Request/Response) instead of Node req/res.+// • Env vars come from the `env` binding parameter, not process.env.+// • No rate limiting (handled at the Cloudflare edge layer).+//+// Secrets (wrangler secret put <NAME>):+// SOLANA_RPC_URL mainnet RPC endpoint (default: public)+// SOLANA_RPC_URL_DEVNET devnet RPC endpoint (default: public)+// PUMPFUN_BOT_URL upstream indexer endpoint (optional)+// PUMPFUN_BOT_TOKEN bearer token for indexer (optional)+//+// Deploy: wrangler deploy++import { TOOLS, rpcError, rpcEnvelope } from '../../src/pump/mcp-tools.js';++// ── Constants ────────────────────────────────────────────────────────────────++const GRADUATION_REAL_SOL_LAMPORTS = 85_000_000_000n;++const CORS_HEADERS = {+ 'access-control-allow-origin': '*',+ 'access-control-allow-methods': 'POST,OPTIONS',+ 'access-control-allow-headers': 'content-type',+};++// ── Solana helpers (adapted for CF Workers env bindings) ─────────────────────++function getRpcUrl(env, network = 'mainnet') {+ if (network === 'devnet') {+ return env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com';+ }+ return env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';+}++function solanaPubkey(s) {+ if (!s) return null;+ try {+ const { PublicKey } = globalThis._solanaWeb3 || {};+ if (PublicKey) return new PublicKey(s);+ return null;+ } catch {+ return null;+ }+}++// ── On-chain handlers ────────────────────────────────────────────────────────++async function handleGetBondingCurve({ mint, network = 'mainnet' }, env) {+ const { Connection, PublicKey } = await import('@solana/web3.js');+ let pk;+ try {+ pk = new PublicKey(mint);+ } catch {+ throw rpcError(-32602, 'invalid mint');+ }++ const conn = new Connection(getRpcUrl(env, network), 'confirmed');+ const { OnlinePumpSdk, PumpSdk } = await import('@pump-fun/pump-sdk');++ let curve;+ try {+ const sdk = new OnlinePumpSdk(conn);+ if (sdk.fetchBuyState) {+ const state = await sdk.fetchBuyState(pk, pk);+ curve = state.bondingCurve;+ } else if (sdk.fetchBondingCurve) {+ curve = await sdk.fetchBondingCurve(pk);+ }+ if (!curve) {+ const sdk2 = new PumpSdk(conn);+ if (sdk2.fetchBondingCurve) curve = await sdk2.fetchBondingCurve(pk);+ }+ } catch (e) {+ throw rpcError(-32004, `bonding curve unavailable: ${e?.message || 'unknown'}`);+ }+ if (!curve) throw rpcError(-32004, 'no bonding curve found for this mint');++ const realSol = BigInt(curve.realSolReserves?.toString?.() ?? '0');+ const realToken = BigInt(curve.realTokenReserves?.toString?.() ?? '0');+ const virtSol = BigInt(curve.virtualSolReserves?.toString?.() ?? '0');+ const virtToken = BigInt(curve.virtualTokenReserves?.toString?.() ?? '0');+ const complete = !!curve.complete;+ const graduationPercent = complete+ ? 100+ : Number((realSol * 10000n) / GRADUATION_REAL_SOL_LAMPORTS) / 100;++ return {+ mint,+ network,+ complete,+ graduationPercent,+ solReserves: (Number(realSol) / 1e9).toFixed(4),+ tokenReserves: realToken.toString(),+ virtualSolReserves: virtSol.toString(),+ virtualTokenReserves: virtToken.toString(),+ };+}++async function handleGetTokenDetails({ mint, network = 'mainnet' }, env) {+ const { Connection, PublicKey } = await import('@solana/web3.js');+ const { MintLayout } = await import('@solana/spl-token');++ let pk;+ try {+ pk = new PublicKey(mint);+ } catch {+ throw rpcError(-32602, 'invalid mint');+ }++ const conn = new Connection(getRpcUrl(env, network), 'confirmed');+ const info = await conn.getAccountInfo(pk);+ if (!info) throw rpcError(-32004, 'mint account not found');+ const mintAccount = MintLayout.decode(info.data);++ const METADATA_PROGRAM = new PublicKey('metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s');+ const [metadataPda] = PublicKey.findProgramAddressSync(+ [Buffer.from('metadata'), METADATA_PROGRAM.toBuffer(), pk.toBuffer()],+ METADATA_PROGRAM,+ );+ let name = null;+ let symbol = null;+ let uri = null;+ try {+ const metaInfo = await conn.getAccountInfo(metadataPda);+ if (metaInfo) {+ const buf = Buffer.from(metaInfo.data);+ let cursor = 1 + 32 + 32;+ const readStr = (max) => {+ const len = buf.readUInt32LE(cursor);+ cursor += 4;+ const slice = buf.slice(cursor, cursor + len);+ cursor += max;+ return slice.toString('utf8').replace(/\0+$/g, '').trim();+ };+ name = readStr(32);+ symbol = readStr(10);+ uri = readStr(200);+ }+ } catch {+ // Metadata is optional.+ }++ return {+ mint,+ name,+ symbol,+ uri,+ decimals: mintAccount.decimals,+ supply: mintAccount.supply.toString(),+ mintAuthority: mintAccount.mintAuthorityOption ? mintAccount.mintAuthority.toString() : null,+ freezeAuthority: mintAccount.freezeAuthorityOption+ ? mintAccount.freezeAuthority.toString()+ : null,+ };+}++async function handleGetTokenHolders({ mint, limit = 10, network = 'mainnet' }, env) {+ const { Connection, PublicKey } = await import('@solana/web3.js');++ let pk;+ try {+ pk = new PublicKey(mint);+ } catch {+ throw rpcError(-32602, 'invalid mint');+ }++ const conn = new Connection(getRpcUrl(env, network), 'confirmed');+ let largest;+ try {+ largest = await conn.getTokenLargestAccounts(pk);+ } catch (e) {+ throw rpcError(-32004, `holders unavailable: ${e?.message || 'rpc error'}`);+ }+ const accounts = (largest?.value || []).slice(0, Math.min(20, Math.max(1, limit)));+ const total = accounts.reduce((sum, a) => sum + Number(a.uiAmount || 0), 0);+ const holders = accounts.map((a) => ({+ address: a.address.toString(),+ amount: a.amount,+ uiAmount: a.uiAmount,+ percent: total > 0 ? (Number(a.uiAmount || 0) / total) * 100 : 0,+ }));+ return {+ mint,+ count: holders.length,+ topHolderPercent: holders[0]?.percent ?? 0,+ holders,+ };+}++// ── Indexer-backed handlers ──────────────────────────────────────────────────++async function rawBotCall(tool, args, env) {+ const url = env.PUMPFUN_BOT_URL;+ if (!url) return { ok: false, error: 'PUMPFUN_BOT_URL not set' };+ const headers = { 'content-type': 'application/json', accept: 'application/json' };+ if (env.PUMPFUN_BOT_TOKEN) headers.authorization = `Bearer ${env.PUMPFUN_BOT_TOKEN}`;+ const ctrl = new AbortController();+ const t = setTimeout(() => ctrl.abort(), 8000);+ try {+ const r = await fetch(url.replace(/\/$/, ''), {+ method: 'POST',+ headers,+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: 1,+ method: 'tools/call',+ params: { name: tool, arguments: args || {} },+ }),+ signal: ctrl.signal,+ });+ if (!r.ok) return { ok: false, error: `bot ${r.status}` };+ const j = await r.json();+ if (j.error) return { ok: false, error: j.error.message || 'rpc error' };+ const payload = j.result?.structuredContent ?? j.result?.content ?? j.result;+ return { ok: true, data: payload };+ } catch (err) {+ return {+ ok: false,+ error: err?.name === 'AbortError' ? 'timeout' : err?.message || 'fetch failed',+ };+ } finally {+ clearTimeout(t);+ }+}++function indexerHandler(name, env) {+ return async (args) => {+ if (!env.PUMPFUN_BOT_URL) {+ throw rpcError(+ -32004,+ `tool "${name}" requires the pump.fun indexer (PUMPFUN_BOT_URL) to be configured`,+ );+ }+ const upstreamMap = {+ searchTokens: { tool: 'searchTokens', args: { query: args.query, limit: args.limit } },+ getTokenTrades: { tool: 'getTokenTrades', args: { mint: args.mint, limit: args.limit } },+ getTrendingTokens: { tool: 'getTrendingTokens', args: { limit: args.limit } },+ getNewTokens: { tool: 'getNewTokens', args: { limit: args.limit } },+ getGraduatedTokens: { tool: 'getGraduatedTokens', args: { limit: args.limit } },+ getKingOfTheHill: { tool: 'getKingOfTheHill', args: {} },+ getCreatorProfile: { tool: 'getCreatorIntel', args: { wallet: args.creator } },+ };+ const upstream = upstreamMap[name];+ if (!upstream) throw rpcError(-32601, `tool "${name}" not implemented`);+ const r = await rawBotCall(upstream.tool, upstream.args, env);+ if (!r.ok) throw rpcError(-32004, r.error || 'indexer error');+ return r.data;+ };+}++// ── Dispatch ─────────────────────────────────────────────────────────────────++function buildHandlers(env) {+ return {+ getBondingCurve: (a) => handleGetBondingCurve(a, env),+ getTokenDetails: (a) => handleGetTokenDetails(a, env),+ getTokenHolders: (a) => handleGetTokenHolders(a, env),+ searchTokens: indexerHandler('searchTokens', env),+ getTokenTrades: indexerHandler('getTokenTrades', env),+ getTrendingTokens: indexerHandler('getTrendingTokens', env),+ getNewTokens: indexerHandler('getNewTokens', env),+ getGraduatedTokens: indexerHandler('getGraduatedTokens', env),+ getKingOfTheHill: indexerHandler('getKingOfTheHill', env),+ getCreatorProfile: indexerHandler('getCreatorProfile', env),+ };+}++// ── HTTP fetch handler ───────────────────────────────────────────────────────++export default {+ async fetch(request, env) {+ if (request.method === 'OPTIONS') {+ return new Response(null, { status: 204, headers: CORS_HEADERS });+ }++ if (request.method !== 'POST') {+ return new Response('method not allowed', { status: 405, headers: CORS_HEADERS });+ }++ const respond = (payload, status = 200) =>+ new Response(JSON.stringify(payload), {+ status,+ headers: { ...CORS_HEADERS, 'content-type': 'application/json' },+ });++ let body;+ try {+ body = await request.json();+ } catch {+ return respond(rpcEnvelope(null, null, { code: -32700, message: 'parse error' }), 400);+ }++ const { id = null, method, params } = body || {};++ if (method === 'initialize') {+ return respond(+ rpcEnvelope(id, {+ protocolVersion: '2024-11-05',+ capabilities: { tools: {} },+ serverInfo: { name: 'pump-fun-mcp-worker', version: '0.1.0' },+ }),+ );+ }++ if (method === 'tools/list') {+ return respond(rpcEnvelope(id, { tools: TOOLS }));+ }++ if (method === 'tools/call') {+ const name = params?.name;+ const args = params?.arguments || {};+ const handlers = buildHandlers(env);+ const handler = handlers[name];+ if (!handler) {+ return respond(rpcEnvelope(id, null, { code: -32601, message: `unknown tool: ${name}` }));+ }+ try {+ const data = await handler(args);+ return respond(+ rpcEnvelope(id, {+ content: [{ type: 'text', text: JSON.stringify(data) }],+ structuredContent: data,+ }),+ );+ } catch (err) {+ const code = err.rpcCode || -32603;+ return respond(rpcEnvelope(id, null, { code, message: err.message || 'tool error' }));+ }+ }++ return respond(rpcEnvelope(id, null, { code: -32601, message: `unknown method: ${method}` }));+ },+};