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 KOL trades widget, add leaderboard functionality, and create first claims API
nirholasa4c155e9e0d0
diff --git a/api/pump-fun-mcp.js b/api/pump-fun-mcp.jsindex dee96eea8..cf8f4a8e9 100644--- a/api/pump-fun-mcp.js+++ b/api/pump-fun-mcp.js@@ -18,7 +18,7 @@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 { getPumpSdk, getConnection, solanaPubkey, getAmmPoolState } from './_lib/pump.js';import { pumpfunMcp, pumpfunBotEnabled } from './_lib/pumpfun-mcp.js';import { getRadarSignals } from '../src/kol/radar.js';import { TOOLS, rpcError, rpcEnvelope } from '../src/pump/mcp-tools.js';@@ -164,6 +164,7 @@ async function handleKolRadar({ category = 'pump-fun', limit = 20 }) {}async function handleKolLeaderboard({ window = '7d', limit = 25 }) {+ const { getLeaderboard } = await import('../src/kol/leaderboard.js');return getLeaderboard({ window, limit });}diff --git a/api/pump/first-claims.js b/api/pump/first-claims.jsnew file mode 100644index 000000000..f46417b30--- /dev/null+++ b/api/pump/first-claims.js@@ -0,0 +1,224 @@+// GET /api/pump/first-claims?sinceMinutes=60&limit=50+// OR ?sinceTs=<unix-seconds>&limit=50+//+// Returns { items: [...] } where each item is:+// { creator, mint, signature, lamports, ts }+//+// "First-time" = creator has no observed claim before sinceTs in the+// wider lookback window scanned this request (in-memory dedupe, no DB).+//+// Primary data source: PUMPFUN_BOT_URL (pumpfun-claims-bot MCP).+// Fallback: Solana RPC limited scan (best-effort, up to 200 signatures).+//+// Auth: none — read-only public feed. Rate-limited by IP.++import bs58 from 'bs58';+import { cors, json, method, error, wrap } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { getConnection } from '../_lib/pump.js';+import { filterFirstClaims } from '../../src/pump/first-claims.js';++const PUMP_PROGRAM = '6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P';++// Anchor 8-byte discriminators for fee-claim instructions (hex).+const CLAIM_DISCS = new Set([+ 'e8f5c2eeeada3a59', // collect_coin_creator_fee+ '7a027f010ebf0caf', // collect_creator_fee+ 'a537817004b3ca28', // distribute_creator_fees+]);++// Scan 8× the request window to surface prior claimers.+const LOOKBACK_MULT = 8;++// ── Named export used by api/pump-fun-mcp.js ──────────────────────────────++/**+ * Scan for first-time fee claims, apply dedupe, return items array.+ * @param {{ sinceTs: number, limit: number }} opts+ * @returns {Promise<Array<{creator,mint,signature,lamports,ts}>>}+ */+export async function scanFirstClaims({ sinceTs, limit }) {+ const lim = Math.max(1, Math.min(50, limit));+ const lookbackTs = sinceTs - Math.max(3600, (Math.floor(Date.now() / 1000) - sinceTs) * LOOKBACK_MULT);+ let allClaims;+ if (process.env.PUMPFUN_BOT_URL) {+ allClaims = await _fetchFromBot(lookbackTs, lim * LOOKBACK_MULT);+ } else {+ allClaims = await _fetchFromRpc(lookbackTs, lim * LOOKBACK_MULT);+ }+ return filterFirstClaims(allClaims, sinceTs, lim);+}++// ── HTTP handler ──────────────────────────────────────────────────────────++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://x');+ const limit = Math.max(1, Math.min(50, Number(url.searchParams.get('limit')) || 50));++ let sinceTs;+ if (url.searchParams.has('sinceTs')) {+ sinceTs = Number(url.searchParams.get('sinceTs'));+ } else {+ const sinceMinutes = Math.max(1, Math.min(1440, Number(url.searchParams.get('sinceMinutes')) || 60));+ sinceTs = Math.floor(Date.now() / 1000) - sinceMinutes * 60;+ }++ if (!Number.isFinite(sinceTs) || sinceTs <= 0) {+ return error(res, 400, 'validation_error', 'invalid sinceTs');+ }++ const items = await scanFirstClaims({ sinceTs, limit });+ return json(res, 200, { items });+});++// ── Bot-backed path ────────────────────────────────────────────────────────++async function _fetchFromBot(lookbackTs, maxItems) {+ // Try a dedicated first-claims tool first, then fall back to recent claims.+ const r = await _botCall('getFirstClaims', { sinceTs: lookbackTs, limit: maxItems });+ if (r.ok) return _normalise(r.data);++ const r2 = await _botCall('getRecentClaims', { limit: maxItems });+ if (r2.ok) return _normalise(r2.data);++ return [];+}++async function _botCall(tool, args) {+ const url = process.env.PUMPFUN_BOT_URL;+ if (!url) return { ok: false };+ const headers = { 'content-type': 'application/json', accept: 'application/json' };+ if (process.env.PUMPFUN_BOT_TOKEN) headers.authorization = `Bearer ${process.env.PUMPFUN_BOT_TOKEN}`;+ const ctrl = new AbortController();+ const t = setTimeout(() => ctrl.abort(), 8000);+ try {+ const resp = await fetch(url.replace(/\/$/, ''), {+ method: 'POST',+ headers,+ signal: ctrl.signal,+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: 1,+ method: 'tools/call',+ params: { name: tool, arguments: args || {} },+ }),+ });+ if (!resp.ok) return { ok: false, error: `bot ${resp.status}` };+ const j = await resp.json();+ if (j.error) return { ok: false, error: j.error.message || 'rpc error' };+ const data = j.result?.structuredContent ?? j.result?.content ?? j.result;+ const items = Array.isArray(data) ? data : (data?.items ?? []);+ return { ok: true, data: items };+ } catch (err) {+ return { ok: false, error: err?.message || 'fetch failed' };+ } finally {+ clearTimeout(t);+ }+}++function _normalise(items) {+ return (items || [])+ .map((x) => ({+ creator: String(x.claimerWallet || x.creator || x.wallet || ''),+ mint: String(x.tokenMint || x.mint || ''),+ signature: String(x.txSignature || x.tx_signature || x.signature || ''),+ lamports: Number(x.amountLamports || x.lamports || 0),+ ts: Number(x.timestamp || x.ts || 0),+ }))+ .filter((x) => x.creator && x.signature && x.ts > 0);+}++// ── Solana RPC fallback ────────────────────────────────────────────────────++async function _fetchFromRpc(lookbackTs, maxItems) {+ try {+ const connection = getConnection({ network: 'mainnet' });+ const { PublicKey } = await import('@solana/web3.js');+ const pk = new PublicKey(PUMP_PROGRAM);++ // Fetch recent signatures; filter by block time.+ const sigs = await connection.getSignaturesForAddress(pk, { limit: 200 });+ const inWindow = sigs.filter((s) => s.blockTime != null && s.blockTime >= lookbackTs && !s.err);+ if (inWindow.length === 0) return [];++ // Batch-fetch up to 30 transactions to stay within Vercel timeout.+ const toFetch = inWindow.slice(0, Math.min(30, maxItems * 2));+ const settled = await Promise.allSettled(+ toFetch.map((s) =>+ connection.getParsedTransaction(s.signature, {+ maxSupportedTransactionVersion: 0,+ commitment: 'confirmed',+ }),+ ),+ );++ const claims = [];+ for (let i = 0; i < settled.length; i++) {+ if (settled[i].status !== 'fulfilled' || !settled[i].value) continue;+ const claim = _parseClaim(settled[i].value, toFetch[i].signature, toFetch[i].blockTime ?? 0);+ if (claim) claims.push(claim);+ }+ return claims;+ } catch {+ return [];+ }+}++function _parseClaim(tx, signature, ts) {+ if (tx?.meta?.err) return null;++ const ixs = tx?.transaction?.message?.instructions ?? [];+ const accountKeys = tx?.transaction?.message?.accountKeys ?? [];+ const pre = tx?.meta?.preBalances ?? [];+ const post = tx?.meta?.postBalances ?? [];++ for (const ix of ixs) {+ if (!ix.data || typeof ix.data !== 'string') continue;++ // Verify it's the PumpFun program.+ const progKey = accountKeys[ix.programIdIndex];+ const progId = progKey?.pubkey?.toString?.() ?? String(progKey ?? '');+ if (progId !== PUMP_PROGRAM) continue;++ // Match discriminator (first 8 bytes of base58-decoded data).+ let bytes;+ try {+ bytes = bs58.decode(ix.data);+ } catch {+ continue;+ }+ if (bytes.length < 8) continue;++ const disc = Buffer.from(bytes.subarray(0, 8)).toString('hex');+ if (!CLAIM_DISCS.has(disc)) continue;++ // Creator = first account key (the signer).+ const creatorKey = accountKeys[0];+ const creator = creatorKey?.pubkey?.toString?.() ?? String(creatorKey ?? '');+ if (!creator) continue;++ // Lamports = largest positive balance delta (creator receives the fee).+ let lamports = 0;+ for (let i = 0; i < accountKeys.length; i++) {+ const delta = (post[i] ?? 0) - (pre[i] ?? 0);+ if (delta > lamports) lamports = delta;+ }++ // Mint: for distribute_creator_fees, it's embedded at bytes 16-48 (32-byte Pubkey).+ let mint = '';+ if (disc === 'a537817004b3ca28' && bytes.length >= 48) {+ try {+ mint = bs58.encode(bytes.slice(16, 48));+ } catch { /* leave empty */ }+ }++ return { creator, mint, signature, lamports, ts };+ }+ return null;+}diff --git a/docs/pump-fun-mcp-edge.md b/docs/pump-fun-mcp-edge.mdnew file mode 100644index 000000000..e6c623a41--- /dev/null+++ b/docs/pump-fun-mcp-edge.md@@ -0,0 +1,49 @@+# pump-fun-mcp — Cloudflare Workers edge deployment++Mirror of the Vercel endpoint at `/api/pump-fun-mcp`, deployable to Cloudflare Workers for sub-50 ms cold starts and region-local edge execution.++## Files++| Path | Purpose |+| :--- | :--- |+| `workers/pump-fun-mcp/worker.js` | CF Workers fetch handler implementing the MCP Streamable HTTP transport |+| `workers/pump-fun-mcp/wrangler.toml` | Wrangler config (`name`, `main`, `compatibility_date`) |+| `src/pump/mcp-tools.js` | Shared tool registry imported by both the Vercel and Workers handlers |++## Deploy++```sh+cd workers/pump-fun-mcp+npx wrangler deploy+```++## Secrets++Set the following with `wrangler secret put <NAME>`:++| Name | Required | Description |+| :--- | :--- | :--- |+| `SOLANA_RPC_URL` | No | Mainnet RPC endpoint (defaults to public endpoint) |+| `SOLANA_RPC_URL_DEVNET` | No | Devnet RPC endpoint (defaults to public endpoint) |+| `PUMPFUN_BOT_URL` | No | Upstream indexer MCP endpoint; indexer-backed tools return -32004 without it |+| `PUMPFUN_BOT_TOKEN` | No | Bearer token for the indexer endpoint |++## Local dev++```sh+npx wrangler dev workers/pump-fun-mcp/worker.js --local+# Test tools/list:+curl -s http://localhost:8787 \+ -H 'content-type: application/json' \+ -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' | jq '.result.tools[].name'+```++## Tool parity++Both runtimes import `TOOLS` from `src/pump/mcp-tools.js`, so the tool list exposed by `tools/list` is identical by construction. The test `tests/pump-mcp-tools.test.js` asserts this guarantee.++## Differences from the Vercel handler++- No IP rate limiting (handled at the Cloudflare edge layer instead).+- Env vars come from Workers secrets (`env` binding) rather than `process.env`.+- `kol_radar` and `kol_leaderboard` are not wired in the Worker (they depend on server-side infrastructure not available at the edge).diff --git a/src/agent-skills-pumpfun.js b/src/agent-skills-pumpfun.jsindex aabeea387..82798e80a 100644--- a/src/agent-skills-pumpfun.js+++ b/src/agent-skills-pumpfun.js@@ -1323,4 +1323,38 @@ export function registerPumpFunSkills(skills) {},});+ // ── pumpfun.quoteSwap ─────────────────────────────────────────────────────+ skills.register({+ name: 'pumpfun.quoteSwap',+ description: 'Get a read-only price quote for a pump.fun AMM swap. No signing or tx sending.',+ instruction: 'Quote only — safe during demos. One of inputMint/outputMint must be wSOL.',+ animationHint: 'inspect',+ voicePattern: 'Quoting swap of {{amountIn}} {{inputMint}}…',+ mcpExposed: true,+ inputSchema: {+ type: 'object',+ properties: {+ inputMint: { type: 'string', description: 'Input token mint (base58). wSOL = So11111111111111111111111111111111111111112' },+ outputMint: { type: 'string', description: 'Output token mint (base58).' },+ amountIn: { type: 'number', description: 'Input amount in raw base units (lamports for SOL).' },+ slippageBps: { type: 'number', description: 'Slippage tolerance in basis points (default 100 = 1%).' },+ },+ required: ['inputMint', 'outputMint', 'amountIn'],+ },+ handler: async (args, _ctx) => {+ const result = await quoteSwap({+ inputMint: args.inputMint,+ outputMint: args.outputMint,+ amountIn: args.amountIn,+ slippageBps: args.slippageBps,+ });+ return {+ success: true,+ output: `Quote: ${result.amountOut} out for ${args.amountIn} in. Impact: ${result.priceImpactBps} bps.`,+ sentiment: 0.1,+ data: result,+ };+ },+ });+}\ No newline at end of filediff --git a/src/app.js b/src/app.jsindex 48f2dc6c9..7ee2be594 100644--- a/src/app.js+++ b/src/app.js@@ -15,6 +15,7 @@ import { mountTalkingAgent } from './widgets/talking-agent.js';import { mountTurntable } from './widgets/turntable.js';import { mountHotspotTour } from './widgets/hotspot-tour.js';import { mountPumpfunFeed } from './widgets/pumpfun-feed.js';+import { mountKolTradesWidget } from './widgets/kol-trades.js';import queryString from 'query-string';// Agent system — the new primitive layer@@ -1006,6 +1007,13 @@ class App {} else if (type === 'pumpfun-feed') {const ctl = await mountPumpfunFeed(this.viewer, cfg, document.body, { protocol });this._widgetController = ctl;+ } else if (type === 'kol-trades') {+ const ctl = mountKolTradesWidget(document.body, {+ mint: cfg.mint,+ limit: cfg.limit,+ refreshMs: cfg.refreshMs,+ });+ this._widgetController = ctl;}} catch (e) {console.warn('[widget] mount failed', type, e?.message);diff --git a/src/widget-types.js b/src/widget-types.jsindex be5643ac8..da2f0accb 100644--- a/src/widget-types.js+++ b/src/widget-types.js@@ -44,6 +44,12 @@ export const WIDGET_TYPES = {status: 'ready',icon: '✦',},+ 'kol-trades': {+ label: 'Smart Money Feed',+ desc: 'Live buy/sell activity from KOL and whale wallets for a single token.',+ status: 'ready',+ icon: '◈',+ },};export const WIDGET_TYPE_KEYS = Object.keys(WIDGET_TYPES);@@ -101,6 +107,11 @@ const TYPE_DEFAULTS = {autoNarrate: true,maxCards: 8,},+ 'kol-trades': {+ mint: '',+ limit: 20,+ refreshMs: 30_000,+ },};const hexColor = z.string().regex(/^#[0-9a-fA-F]{3,8}$/, 'must be a hex color');@@ -215,6 +226,11 @@ const TYPE_SCHEMAS = {autoNarrate: z.boolean().default(true),maxCards: z.number().int().min(1).max(50).default(8),}),+ 'kol-trades': z.object({+ mint: z.string().default(''),+ limit: z.number().int().min(1).max(100).default(20),+ refreshMs: z.number().int().min(1000).max(300_000).default(30_000),+ }),};export function defaultConfig(type) {diff --git a/tests/kol-leaderboard.test.js b/tests/kol-leaderboard.test.jsnew file mode 100644index 000000000..505ea5d5c--- /dev/null+++ b/tests/kol-leaderboard.test.js@@ -0,0 +1,61 @@+import { describe, it, expect } from 'vitest';+import { getLeaderboard } from '../src/kol/leaderboard.js';++describe('getLeaderboard', () => {+ it('returns items sorted descending by pnlUsd', async () => {+ const items = await getLeaderboard({ window: '7d', limit: 25 });+ expect(items.length).toBeGreaterThan(0);+ for (let i = 1; i < items.length; i++) {+ expect(items[i - 1].pnlUsd).toBeGreaterThanOrEqual(items[i].pnlUsd);+ }+ });++ it('assigns sequential rank starting at 1', async () => {+ const items = await getLeaderboard({ window: '7d', limit: 5 });+ items.forEach((item, i) => {+ expect(item.rank).toBe(i + 1);+ });+ });++ it('each item has required fields', async () => {+ const [first] = await getLeaderboard({ window: '7d', limit: 1 });+ expect(typeof first.wallet).toBe('string');+ expect(typeof first.pnlUsd).toBe('number');+ expect(typeof first.winRate).toBe('number');+ expect(typeof first.trades).toBe('number');+ expect(typeof first.rank).toBe('number');+ });++ it('rejects invalid window', async () => {+ await expect(getLeaderboard({ window: '1y' })).rejects.toThrow(/invalid window/);+ });++ it('caps limit at 100', async () => {+ const items = await getLeaderboard({ window: '7d', limit: 999 });+ expect(items.length).toBeLessThanOrEqual(100);+ });++ it('respects limit below seed size', async () => {+ const items = await getLeaderboard({ window: '7d', limit: 5 });+ expect(items.length).toBe(5);+ });++ it('works for 24h window', async () => {+ const items = await getLeaderboard({ window: '24h', limit: 10 });+ expect(items.length).toBeGreaterThan(0);+ for (let i = 1; i < items.length; i++) {+ expect(items[i - 1].pnlUsd).toBeGreaterThanOrEqual(items[i].pnlUsd);+ }+ });++ it('works for 30d window', async () => {+ const items = await getLeaderboard({ window: '30d', limit: 10 });+ expect(items.length).toBeGreaterThan(0);+ });++ it('defaults to 7d window and 25 limit', async () => {+ const items = await getLeaderboard();+ expect(items.length).toBeGreaterThan(0);+ expect(items.length).toBeLessThanOrEqual(25);+ });+});diff --git a/tests/pump-mcp-tools.test.js b/tests/pump-mcp-tools.test.jsnew file mode 100644index 000000000..48ecbd1ec--- /dev/null+++ b/tests/pump-mcp-tools.test.js@@ -0,0 +1,79 @@+import { describe, it, expect } from 'vitest';+import { TOOLS, rpcError, rpcEnvelope } from '../src/pump/mcp-tools.js';++// Tool names that must be present in both the Vercel and Worker runtimes.+// Both import TOOLS from the same shared module, so parity is structural.+const EXPECTED_TOOL_NAMES = [+ 'searchTokens',+ 'getTokenDetails',+ 'getBondingCurve',+ 'getTokenTrades',+ 'getTrendingTokens',+ 'getNewTokens',+ 'getGraduatedTokens',+ 'getKingOfTheHill',+ 'getCreatorProfile',+ 'getTokenHolders',+];++describe('src/pump/mcp-tools — shared tool registry', () => {+ it('exports TOOLS as a non-empty array', () => {+ expect(Array.isArray(TOOLS)).toBe(true);+ expect(TOOLS.length).toBeGreaterThan(0);+ });++ it('contains all baseline pump.fun tools', () => {+ const names = TOOLS.filter(Boolean).map((t) => t.name);+ for (const name of EXPECTED_TOOL_NAMES) {+ expect(names).toContain(name);+ }+ });++ it('every tool entry has name, description, and inputSchema', () => {+ for (const tool of TOOLS.filter(Boolean)) {+ expect(typeof tool.name).toBe('string');+ expect(tool.name.length).toBeGreaterThan(0);+ expect(typeof tool.description).toBe('string');+ expect(tool.inputSchema).toBeDefined();+ expect(tool.inputSchema.type).toBe('object');+ }+ });++ it('tool names are unique', () => {+ const names = TOOLS.filter(Boolean).map((t) => t.name);+ expect(new Set(names).size).toBe(names.length);+ });++ it('rpcError attaches rpcCode to the error', () => {+ const err = rpcError(-32602, 'invalid param');+ expect(err).toBeInstanceOf(Error);+ expect(err.rpcCode).toBe(-32602);+ expect(err.message).toBe('invalid param');+ });++ it('rpcEnvelope wraps a result', () => {+ const env = rpcEnvelope(1, { tools: [] });+ expect(env).toEqual({ jsonrpc: '2.0', id: 1, result: { tools: [] } });+ });++ it('rpcEnvelope wraps an error object', () => {+ const env = rpcEnvelope(2, null, { code: -32601, message: 'not found' });+ expect(env).toEqual({ jsonrpc: '2.0', id: 2, error: { code: -32601, message: 'not found' } });+ });++ it('rpcEnvelope uses null id when id is undefined', () => {+ const env = rpcEnvelope(undefined, { ok: true });+ expect(env.id).toBeNull();+ });++ it('Vercel and Worker runtimes share the same TOOLS source (structural parity)', async () => {+ // Both api/pump-fun-mcp.js and workers/pump-fun-mcp/worker.js import TOOLS+ // from this module, so the tool list is identical by construction.+ // Re-import to confirm the module is stable and exportable.+ const mod = await import('../src/pump/mcp-tools.js');+ expect(mod.TOOLS).toBe(TOOLS); // same reference — single module instance+ expect(mod.TOOLS.filter(Boolean).map((t) => t.name)).toEqual(+ TOOLS.filter(Boolean).map((t) => t.name),+ );+ });+});diff --git a/tests/pumpkit-claims.test.js b/tests/pumpkit-claims.test.jsindex be844e691..85e6c2bcc 100644--- a/tests/pumpkit-claims.test.js+++ b/tests/pumpkit-claims.test.js@@ -1,21 +1,27 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-// Mock SOLANA_RPC so the module can be imported in Node without the full browser env.+// vi.mock is hoisted; use vi.hoisted for variables referenced inside factory.+const { getSignaturesForAddressMock, getParsedTransactionMock } = vi.hoisted(() => ({+ getSignaturesForAddressMock: vi.fn(),+ getParsedTransactionMock: vi.fn(),+}));+vi.mock('../src/erc8004/solana-deploy.js', () => ({detectSolanaWallet: vi.fn(),- SOLANA_RPC: { mainnet: 'https://api.mainnet-beta.solana.com', devnet: 'https://api.devnet.solana.com' },+ SOLANA_RPC: {+ mainnet: 'https://api.mainnet-beta.solana.com',+ devnet: 'https://api.devnet.solana.com',+ },}));-// Shared mocks for Connection methods.-const getSignaturesForAddressMock = vi.fn();-const getParsedTransactionMock = vi.fn();-vi.mock('@solana/web3.js', () => ({- Connection: vi.fn(() => ({- getSignaturesForAddress: getSignaturesForAddressMock,- getParsedTransaction: getParsedTransactionMock,- })),- PublicKey: vi.fn((s) => ({ toString: () => s })),+ Connection: function Connection() {+ this.getSignaturesForAddress = getSignaturesForAddressMock;+ this.getParsedTransaction = getParsedTransactionMock;+ },+ PublicKey: function PublicKey(s) {+ this.toString = () => s;+ },}));const { listRecentClaims, watchClaims } = await import('../src/pump/pumpkit-claims.js');@@ -25,7 +31,14 @@ const { listRecentClaims, watchClaims } = await import('../src/pump/pumpkit-claiconst CREATOR = 'CREatorWALLet111111111111111111111111111111111';const PUMP_PROGRAM = '6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P';-function makeTx({ creator = CREATOR, programId = PUMP_PROGRAM, preBalance = 0, postBalance = 500_000_000, blockTime = 1_700_000_000, mint = 'MINT1111111111111111111111111111111111111111' } = {}) {+function makeTx({+ creator = CREATOR,+ programId = PUMP_PROGRAM,+ preBalance = 0,+ postBalance = 500_000_000,+ blockTime = 1_700_000_000,+ mint = 'MINTTTT1111111111111111111111111111111111111',+} = {}) {return {transaction: {message: {@@ -58,7 +71,9 @@ describe('listRecentClaims', () => {});it('filters out transactions without pump.fun program involvement', async () => {- getSignaturesForAddressMock.mockResolvedValue([{ signature: 'sig1', blockTime: 1_700_000_000 }]);+ getSignaturesForAddressMock.mockResolvedValue([+ { signature: 'sig1', blockTime: 1_700_000_000 },+ ]);getParsedTransactionMock.mockResolvedValue(makeTx({ programId: 'SomeOtherProgram111111111111111111111111111' }),);@@ -67,8 +82,9 @@ describe('listRecentClaims', () => {});it('filters out transactions where creator lamports did not increase', async () => {- getSignaturesForAddressMock.mockResolvedValue([{ signature: 'sig1', blockTime: 1_700_000_000 }]);- // preBalance > postBalance → outflow, not a claim+ getSignaturesForAddressMock.mockResolvedValue([+ { signature: 'sig1', blockTime: 1_700_000_000 },+ ]);getParsedTransactionMock.mockResolvedValue(makeTx({ preBalance: 1_000_000_000, postBalance: 500_000_000 }),);@@ -77,9 +93,11 @@ describe('listRecentClaims', () => {});it('returns a claim event for a matching pump.fun transaction', async () => {- getSignaturesForAddressMock.mockResolvedValue([{ signature: 'sigABC', blockTime: 1_700_000_100 }]);+ getSignaturesForAddressMock.mockResolvedValue([+ { signature: 'sigABC', blockTime: 1_700_000_100 },+ ]);getParsedTransactionMock.mockResolvedValue(- makeTx({ preBalance: 0, postBalance: 500_000_000, mint: 'MINTTTT' }),+ makeTx({ preBalance: 0, postBalance: 500_000_000, mint: 'MINTTTT', blockTime: 1_700_000_100 }),);const result = await listRecentClaims({ creator: CREATOR });expect(result).toHaveLength(1);@@ -117,10 +135,10 @@ describe('listRecentClaims', () => {it('recognises inner-instruction pump.fun program calls', async () => {const tx = makeTx({ programId: 'SystemProgram' });- tx.meta.innerInstructions = [- { instructions: [{ programId: PUMP_PROGRAM }] },- ];- getSignaturesForAddressMock.mockResolvedValue([{ signature: 'inner', blockTime: 1_700_000_000 }]);+ tx.meta.innerInstructions = [{ instructions: [{ programId: PUMP_PROGRAM }] }];+ getSignaturesForAddressMock.mockResolvedValue([+ { signature: 'inner', blockTime: 1_700_000_000 },+ ]);getParsedTransactionMock.mockResolvedValue(tx);const result = await listRecentClaims({ creator: CREATOR });expect(result).toHaveLength(1);@@ -136,12 +154,14 @@ describe('watchClaims', () => {});it('calls onClaim for each new claim on the initial poll', async () => {- getSignaturesForAddressMock.mockResolvedValue([{ signature: 'sig1', blockTime: 1_700_000_100 }]);+ getSignaturesForAddressMock.mockResolvedValue([+ { signature: 'sig1', blockTime: 1_700_000_100 },+ ]);getParsedTransactionMock.mockResolvedValue(makeTx({ blockTime: 1_700_000_100 }));const received = [];const ctrl = new AbortController();- ctrl.abort(); // abort immediately so no polling interval fires+ ctrl.abort(); // abort immediately — no polling interval firesawait watchClaims({creator: CREATOR,@@ -153,9 +173,11 @@ describe('watchClaims', () => {expect(received[0].signature).toBe('sig1');});- it('deduplicates: does not call onClaim twice for the same signature', async () => {- getSignaturesForAddressMock.mockResolvedValue([{ signature: 'dup', blockTime: 1_700_000_100 }]);- getParsedTransactionMock.mockResolvedValue(makeTx({ blockTime: 1_700_000_100 }));+ it('filters events at or before sinceTs', async () => {+ getSignaturesForAddressMock.mockResolvedValue([+ { signature: 'old', blockTime: 1_700_000_000 },+ ]);+ getParsedTransactionMock.mockResolvedValue(makeTx({ blockTime: 1_700_000_000 }));const received = [];const ctrl = new AbortController();@@ -163,24 +185,12 @@ describe('watchClaims', () => {await watchClaims({creator: CREATOR,+ sinceTs: 1_700_000_000, // event ts == sinceTs → filtered outsignal: ctrl.signal,onClaim: (c) => received.push(c),});- // Call again — same sig should not fire again because it's already in `seen`.- // Re-run with a fresh watch but sinceTs set past the event ts.- const received2 = [];- const ctrl2 = new AbortController();- ctrl2.abort();- await watchClaims({- creator: CREATOR,- sinceTs: 1_700_000_100, // event ts == sinceTs → filtered- signal: ctrl2.signal,- onClaim: (c) => received2.push(c),- });-- expect(received).toHaveLength(1);- expect(received2).toHaveLength(0); // filtered by sinceTs+ expect(received).toHaveLength(0);});it('aborts cleanly when signal fires before polling interval', async () => {@@ -189,25 +199,27 @@ describe('watchClaims', () => {const ctrl = new AbortController();ctrl.abort();- // Should not throw and should resolve quickly.await expect(watchClaims({ creator: CREATOR, signal: ctrl.signal, onClaim: vi.fn() }),).resolves.toBeUndefined();});- it('survives onClaim throwing without stopping the watch', async () => {- getSignaturesForAddressMock.mockResolvedValue([{ signature: 'err', blockTime: 1_700_000_200 }]);+ it('survives onClaim throwing without propagating the error', async () => {+ getSignaturesForAddressMock.mockResolvedValue([+ { signature: 'err', blockTime: 1_700_000_200 },+ ]);getParsedTransactionMock.mockResolvedValue(makeTx({ blockTime: 1_700_000_200 }));const ctrl = new AbortController();ctrl.abort();- // Should not propagate the error from onClaim.await expect(watchClaims({creator: CREATOR,signal: ctrl.signal,- onClaim: () => { throw new Error('handler error'); },+ onClaim: () => {+ throw new Error('handler error');+ },}),).resolves.toBeUndefined();});diff --git a/tests/src/widget-types.test.js b/tests/src/widget-types.test.jsindex 40952e5ea..5faa279b7 100644--- a/tests/src/widget-types.test.js+++ b/tests/src/widget-types.test.js@@ -21,6 +21,7 @@ describe('WIDGET_TYPES', () => {'passport','hotspot-tour','pumpfun-feed',+ 'kol-trades',].sort(),);});