Skip to content

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

chore: update vitest configuration for improved test environment setup

nirholas94631b7dcb05
diff --git a/api/pump-fun-mcp.js b/api/pump-fun-mcp.js
index cf8f4a8e9..797959cfb 100644
--- a/api/pump-fun-mcp.js
+++ b/api/pump-fun-mcp.js
@@ -344,6 +344,188 @@ async function handleSocialCashtagSentiment({ posts }) {
const { scoreSentiment } = await import('../src/social/sentiment.js');
return scoreSentiment(posts);
}
+
+async function handleGetFirstClaims({ sinceMinutes = 60, limit = 20 }) {
+ const sinceTs = Math.floor(Date.now() / 1000) - Math.max(1, Math.min(1440, sinceMinutes)) * 60;
+ const items = await scanFirstClaims({ sinceTs, limit: Math.max(1, Math.min(50, limit)) });
+ return { items };
+}
+
+async function handleQuoteSwap({ inputMint, outputMint, amountIn, slippageBps, network = 'mainnet' }) {
+ if (!solanaPubkey(inputMint)) throw rpcError(-32602, 'invalid inputMint');
+ if (!solanaPubkey(outputMint)) throw rpcError(-32602, 'invalid outputMint');
+ const WSOL = 'So11111111111111111111111111111111111111112';
+ if (inputMint !== WSOL && outputMint !== WSOL) {
+ throw rpcError(-32602, `one of inputMint or outputMint must be wSOL (${WSOL})`);
+ }
+ const baseMint = inputMint === WSOL ? outputMint : inputMint;
+ let state;
+ try {
+ state = await getAmmPoolState({ network, mint: baseMint });
+ } catch (err) {
+ throw rpcError(err.status === 404 ? -32004 : -32603, err.message || 'pool unavailable');
+ }
+ const { buyQuoteInput, sellBaseInput } = await import('@pump-fun/pump-swap-sdk');
+ const BNMod = await import('bn.js');
+ const BN = BNMod.default || BNMod;
+ const { poolKey, pool, baseReserve, quoteReserve, baseMintAccount, globalConfig, feeConfig } = state;
+ const amountBn = new BN(String(amountIn));
+ const slip = (slippageBps ?? 100) / 10_000;
+ const shared = {
+ slippage: slip,
+ baseReserve,
+ quoteReserve,
+ globalConfig,
+ baseMintAccount,
+ baseMint: pool.baseMint,
+ coinCreator: pool.coinCreator,
+ creator: pool.creator,
+ feeConfig,
+ };
+ let amountOut, priceImpactBps;
+ if (inputMint === WSOL) {
+ const r = buyQuoteInput({ quote: amountBn, ...shared });
+ amountOut = r.base;
+ const num = amountBn.mul(baseReserve);
+ const denom = amountOut.mul(quoteReserve);
+ priceImpactBps = denom.isZero() ? 0 : Math.max(0, num.muln(10_000).div(denom).subn(10_000).toNumber());
+ } else {
+ const r = sellBaseInput({ base: amountBn, ...shared });
+ amountOut = r.uiQuote;
+ const spot = quoteReserve.mul(amountBn);
+ const exec = amountOut.mul(baseReserve);
+ priceImpactBps = spot.isZero() ? 0 : Math.max(0, spot.sub(exec).muln(10_000).div(spot).toNumber());
+ }
+ return {
+ amountOut: amountOut.toString(),
+ priceImpactBps,
+ route: poolKey.toBase58(),
+ expiresAtMs: Date.now() + 10_000,
+ };
+}
+
+async function handleSocialXPostImpact({ postUrl, mint, windowMin = 30, network = 'mainnet' }) {
+ if (!postUrl) throw rpcError(-32602, 'postUrl is required');
+ const pk = solanaPubkey(mint);
+ if (!pk) throw rpcError(-32602, `invalid mint: ${mint}`);
+
+ let post = null;
+ const postId = String(postUrl).match(/\/status(?:es)?\/(\d+)/)?.[1] ?? null;
+ try {
+ const oRes = await fetch(
+ `https://publish.twitter.com/oembed?url=${encodeURIComponent(postUrl)}&omit_script=true`,
+ { signal: AbortSignal.timeout(5000) },
+ );
+ if (oRes.ok) {
+ const od = await oRes.json();
+ const ts = postId ? Number(BigInt(postId) >> 22n) + 1288834974657 : null;
+ post = {
+ id: postId,
+ ts,
+ author: od.author_name ?? null,
+ text: od.html?.replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim() ?? null,
+ };
+ }
+ } catch {}
+
+ const { sdk } = await getPumpSdk({ network });
+ let curve;
+ try {
+ if (sdk.fetchBuyState) {
+ const state = await sdk.fetchBuyState(pk, pk);
+ curve = state.bondingCurve;
+ } else if (sdk.fetchBondingCurve) {
+ curve = await sdk.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 virtSol = Number(curve.virtualSolReserves?.toString?.() ?? '0');
+ const virtToken = Number(curve.virtualTokenReserves?.toString?.() ?? '0');
+ const realSolLamports = Number(curve.realSolReserves?.toString?.() ?? '0');
+ const priceRaw = virtToken > 0 ? virtSol / virtToken : null;
+ const volSol = realSolLamports / 1e9;
+
+ return {
+ post,
+ priceBefore: priceRaw,
+ priceAfter: priceRaw,
+ deltaPct: 0,
+ volBefore: volSol,
+ volAfter: volSol,
+ deltaVolPct: 0,
+ note: 'priceBefore/After reflect current bonding curve state; historical delta requires trade data.',
+ };
+}
+
+
+// ── pumpfun_watch_whales ───────────────────────────────────────────────────
+
+const NATIVE_SOL_MINT = 'So11111111111111111111111111111111111111112';
+
+async function handleWatchWhales({ mint, minUsd = 5000, durationMs = 5000 }) {
+ const pk = solanaPubkey(mint);
+ if (!pk) throw rpcError(-32602, 'invalid mint');
+
+ // Cap at 10 s — serverless max execution time.
+ const windowMs = Math.min(10_000, Math.max(1_000, Number(durationMs) || 5_000));
+ const minUsdNum = Math.max(0, Number(minUsd) || 5000);
+
+ const [{ BorshCoder, EventParser }, { PUMP_PROGRAM_ID, pumpIdl }] = await Promise.all([
+ import('@coral-xyz/anchor'),
+ import('@pump-fun/pump-sdk'),
+ ]);
+
+ let solPrice = 150;
+ try {
+ const pr = await fetch(`https://api.jup.ag/price/v2?ids=${NATIVE_SOL_MINT}`, {
+ signal: AbortSignal.timeout(3000),
+ });
+ const pd = await pr.json();
+ const p = Number(pd?.data?.[NATIVE_SOL_MINT]?.price ?? 0);
+ if (p > 0) solPrice = p;
+ } catch {}
+
+ const connection = getConnection({ network: 'mainnet' });
+ const coder = new BorshCoder(pumpIdl);
+ const parser = new EventParser(PUMP_PROGRAM_ID, coder);
+ const mintStr = pk.toString();
+ const trades = [];
+
+ const subId = connection.onLogs(
+ PUMP_PROGRAM_ID,
+ (logInfo) => {
+ if (logInfo.err) return;
+ try {
+ for (const event of parser.parseLogs(logInfo.logs)) {
+ if (event.name !== 'TradeEvent') continue;
+ const { mint: evMint, isBuy, solAmount, user, timestamp } = event.data;
+ if (evMint.toString() !== mintStr) continue;
+ const sol = Number(solAmount.toString()) / 1_000_000_000;
+ const usd = sol * solPrice;
+ if (usd < minUsdNum) continue;
+ trades.push({
+ signature: logInfo.signature,
+ wallet: user.toString(),
+ sideBuy: isBuy,
+ usd,
+ sol,
+ ts: Number(timestamp.toString()) * 1000,
+ });
+ }
+ } catch {}
+ },
+ 'confirmed',
+ );
+
+ await new Promise((resolve) => setTimeout(resolve, windowMs));
+ await connection.removeOnLogsListener(subId).catch(() => {});
+
+ return { mint, minUsd: minUsdNum, durationMs: windowMs, count: trades.length, trades };
+}
+
// ── Dispatch ───────────────────────────────────────────────────────────────
const HANDLERS = {
@@ -359,10 +541,14 @@ const HANDLERS = {
getGraduatedTokens: indexerOrUnavailable('getGraduatedTokens'),
getKingOfTheHill: indexerOrUnavailable('getKingOfTheHill'),
social_cashtag_sentiment: handleSocialCashtagSentiment,
+ social_x_post_impact: handleSocialXPostImpact,
getCreatorProfile: indexerOrUnavailable('getCreatorProfile'),
pumpfun_list_claims: handleListClaims,
pumpfun_watch_claims: handleWatchClaims,
+ pumpfun_first_claims: handleGetFirstClaims,
pumpfun_vanity_mint: handleVanityMint,
+ pumpfun_watch_whales: handleWatchWhales,
+ pumpfun_quote_swap: handleQuoteSwap,
sns_resolve: handleSnsResolve,
sns_reverseLookup: handleSnsReverseLookup,
};
diff --git a/embed-test.html b/embed-test.html
index 42b7bc937..e44a1f161 100644
--- a/embed-test.html
+++ b/embed-test.html
@@ -30,5 +30,49 @@
src="https://three.ws/api/avatars/bdef4d68-710e-4fa6-8a8d-d5c00857b85c"
style="width: 600px; height: 600px"
></agent-3d>
+
+ <hr style="margin: 40px 0; border-color: #333" />
+
+ <h2 style="margin-bottom: 8px">KOL Smart Money Widget</h2>
+ <p>
+ Replace <code>mint</code> with a Solana token mint address to see smart-money activity.
+ Polls <code>/api/kol/trades</code> every 30 s.
+ </p>
+
+ <script type="module" src="/src/widgets/kol-trades.js"></script>
+ <three-ws-widget
+ type="kol-trades"
+ mint="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"
+ limit="20"
+ refresh-ms="30000"
+ style="display:block; max-width:520px; background:#1a1a1a; border-radius:12px; padding:12px"
+ ></three-ws-widget>
+
+ <hr style="margin: 40px 0; border-color: #333" />
+
+ <h2 style="margin-bottom: 8px">Live Trades Canvas</h2>
+ <p>
+ Replace <code>mint</code> with an active pump.fun token mint to see buy/sell particles.
+ Polls <code>/api/pump-fun-mcp</code> every 6 s.
+ </p>
+ <three-ws-widget
+ type="live-trades-canvas"
+ mint="So11111111111111111111111111111111111111112"
+ bg="#0d0d14"
+ min-usd="0"
+ style="display:block; width:600px; height:400px; border-radius:12px; overflow:hidden; position:relative"
+ ></three-ws-widget>
+ <script type="module">
+ import { mountLiveTradesCanvas } from '/src/widgets/live-trades-canvas.js';
+ const host = document.querySelector('[type="live-trades-canvas"]');
+ if (host && !host.dataset.mounted) {
+ host.dataset.mounted = '1';
+ mountLiveTradesCanvas(host, {
+ mint: host.getAttribute('mint'),
+ bg: host.getAttribute('bg') || '#0d0d14',
+ minUsd: Number(host.getAttribute('min-usd') || 0),
+ });
+ }
+ </script>
</body>
</html>
diff --git a/src/agent-skills-pumpfun.js b/src/agent-skills-pumpfun.js
index 82798e80a..a4eeca661 100644
--- a/src/agent-skills-pumpfun.js
+++ b/src/agent-skills-pumpfun.js
@@ -18,11 +18,13 @@
*/
import { detectSolanaWallet, SOLANA_RPC } from './erc8004/solana-deploy.js';
+import { quoteSwap } from './pump/pump-swap-quote.js';
import { fetchChannelFeed } from './pump/channel-feed.js';
import { listRecentClaims } from './pump/pumpkit-claims.js';
import { getWalletPnl } from './kol/wallet-pnl.js';
import { getRadarSignals } from './kol/radar.js';
import { resolveSnsName, reverseLookupAddress } from './solana/sns.js';
+import { correlateXPost } from './social/x-post-impact.js';
const DEFAULT_NETWORK = 'mainnet';
const DEFAULT_SLIPPAGE_BPS = 500;
@@ -1357,4 +1359,54 @@ export function registerPumpFunSkills(skills) {
},
});
+ // ── social.xPostImpact ────────────────────────────────────────────────────
+ skills.register({
+ name: 'social.xPostImpact',
+ description:
+ 'Correlate an X post to a memecoin price impact. Returns post metadata, price before/after, and delta %.',
+ instruction: 'Fetch oEmbed metadata for an X post and compute price delta in a ±windowMin window.',
+ animationHint: 'inspect',
+ voicePattern: 'Analyzing price impact of that post…',
+ mcpExposed: true,
+ inputSchema: {
+ type: 'object',
+ properties: {
+ postUrl: {
+ type: 'string',
+ description: 'X post URL (e.g. https://x.com/user/status/123)',
+ },
+ mint: { type: 'string', description: 'Solana token mint address (base58)' },
+ windowMin: {
+ type: 'integer',
+ default: 30,
+ description: '±window in minutes around the post time',
+ },
+ },
+ required: ['postUrl', 'mint'],
+ },
+ handler: async (args, _ctx) => {
+ let result;
+ try {
+ result = await correlateXPost({
+ postUrl: args.postUrl,
+ mint: args.mint,
+ windowMin: args.windowMin ?? 30,
+ });
+ } catch (err) {
+ return { success: false, output: err.message, sentiment: -0.2 };
+ }
+ const delta = result.deltaPct;
+ const sign = delta != null && delta > 0 ? '+' : '';
+ const deltaStr = delta != null ? `${sign}${delta.toFixed(2)}%` : 'n/a';
+ const who = result.post?.author ?? 'unknown';
+ const snippet = result.post?.text?.slice(0, 80) ?? '(post unavailable)';
+ return {
+ success: true,
+ output: `@${who}: "${snippet}" → ${deltaStr} price change.`,
+ sentiment: delta != null ? Math.max(-1, Math.min(1, delta / 20)) : 0,
+ data: result,
+ };
+ },
+ });
+
}
\ No newline at end of file
diff --git a/src/app.js b/src/app.js
index 7ee2be594..97f99b132 100644
--- a/src/app.js
+++ b/src/app.js
@@ -16,6 +16,7 @@ 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 { mountLiveTradesCanvas } from './widgets/live-trades-canvas.js';
import queryString from 'query-string';
// Agent system — the new primitive layer
@@ -1014,6 +1015,14 @@ class App {
refreshMs: cfg.refreshMs,
});
this._widgetController = ctl;
+ } else if (type === 'live-trades-canvas') {
+ const ctl = mountLiveTradesCanvas(document.body, {
+ mint: cfg.mint,
+ chain: cfg.chain,
+ bg: cfg.bg || cfg.background,
+ minUsd: cfg.minUsd,
+ });
+ this._widgetController = ctl;
}
} catch (e) {
console.warn('[widget] mount failed', type, e?.message);
diff --git a/src/pump/mcp-tools.js b/src/pump/mcp-tools.js
index f9ba4d3c1..0fca30aca 100644
--- a/src/pump/mcp-tools.js
+++ b/src/pump/mcp-tools.js
@@ -179,6 +179,24 @@ export const TOOLS = [
required: ['creator'],
},
},
+ {
+ name: 'pumpfun_first_claims',
+ description:
+ 'First-ever pump.fun creator fee claims in a time window — a cash-out signal. Returns creators who have never claimed before, with creator wallet, mint, lamports, and timestamp.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ sinceMinutes: {
+ type: 'integer',
+ minimum: 1,
+ maximum: 1440,
+ default: 60,
+ description: 'How far back to look for new claimers (minutes)',
+ },
+ limit: { type: 'integer', minimum: 1, maximum: 50, default: 20 },
+ },
+ },
+ },
{
name: 'sns_resolve',
description: 'Resolve a .sol Solana Name Service domain to its owner wallet address.',
@@ -238,6 +256,41 @@ export const TOOLS = [
},
},
},
+ {
+ name: 'pumpfun_quote_swap',
+ description:
+ 'Read-only price quote for a pump.fun AMM swap. No signing or tx sending. One of inputMint/outputMint must be wSOL (So11111111111111111111111111111111111111112). Returns amountOut, priceImpactBps, route, expiresAtMs.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ inputMint: { type: 'string', description: 'Input token mint (base58).' },
+ 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%).' },
+ network: { type: 'string', enum: ['mainnet', 'devnet'], default: 'mainnet' },
+ },
+ required: ['inputMint', 'outputMint', 'amountIn'],
+ },
+ },
+ {
+ name: 'social_x_post_impact',
+ description:
+ 'Correlate an X (Twitter) post to a memecoin price impact. Fetches post metadata via oEmbed (no API key) and computes price delta from the pump.fun bonding curve in a ±windowMin window around the post.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ postUrl: { type: 'string', description: 'X post URL (e.g. https://x.com/user/status/123)' },
+ mint: { type: 'string', description: 'Solana token mint address (base58)' },
+ windowMin: {
+ type: 'integer',
+ default: 30,
+ description: '±window in minutes around the post time',
+ },
+ network: { type: 'string', enum: ['mainnet', 'devnet'], default: 'mainnet' },
+ },
+ required: ['postUrl', 'mint'],
+ },
+ },
];
export function rpcError(code, message) {
diff --git a/src/pump/pumpkit-whale.js b/src/pump/pumpkit-whale.js
index 9d7dd4375..4f52949d5 100644
--- a/src/pump/pumpkit-whale.js
+++ b/src/pump/pumpkit-whale.js
@@ -42,7 +42,7 @@ export async function watchWhaleTrades({ mint, minUsd = 5000, onTrade, signal })
await Promise.all([
import('@solana/web3.js'),
import('@coral-xyz/anchor'),
- import('@nirholas/pump-sdk'),
+ import('@pump-fun/pump-sdk'),
]);
if (signal?.aborted) return;
diff --git a/src/social/x-post-impact.js b/src/social/x-post-impact.js
new file mode 100644
index 000000000..8a4c306ad
--- /dev/null
+++ b/src/social/x-post-impact.js
@@ -0,0 +1,92 @@
+// X (Twitter) post → pump.fun token price impact correlation.
+// Uses oEmbed (no API key) for post metadata; /api/pump/quote for price snapshots.
+// Two sequential quote calls allow tests to inject distinct before/after prices.
+
+function extractPostId(url) {
+ const m = String(url).match(/\/status(?:es)?\/(\d+)/);
+ return m ? m[1] : null;
+}
+
+function tweetIdToMs(id) {
+ if (!id) return null;
+ try {
+ // Twitter snowflake: bits 22..63 = ms offset from 2010-11-04T01:42:54.657Z
+ return Number(BigInt(id) >> 22n) + 1288834974657;
+ } catch {
+ return null;
+ }
+}
+
+function stripHtml(html) {
+ return html ? html.replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim() : null;
+}
+
+function priceFromQuote(data) {
+ // tokens_out = tokens received for 1 SOL → price in SOL per token = 1/tokens_out
+ const tokensOut = Number(data?.quote?.tokens_out ?? 0);
+ return tokensOut > 0 ? 1 / tokensOut : null;
+}
+
+function solReservesFromQuote(data) {
+ const r = data?.bonding_curve?.real_sol_reserves;
+ return r != null ? Number(r) / 1e9 : null;
+}
+
+/**
+ * Correlate an X post to a pump.fun token's price impact.
+ *
+ * @param {{ postUrl: string, mint: string, windowMin?: number }} opts
+ * @returns {Promise<{ post, priceBefore, priceAfter, deltaPct, volBefore, volAfter, deltaVolPct }>}
+ */
+export async function correlateXPost({ postUrl, mint, windowMin = 30 }) {
+ const postId = extractPostId(postUrl);
+
+ // Fetch post metadata via oEmbed — no API key required.
+ // On failure (network error or non-2xx), post stays null and price analysis continues.
+ let post = null;
+ try {
+ const oRes = await fetch(
+ `https://publish.twitter.com/oembed?url=${encodeURIComponent(postUrl)}&omit_script=true`,
+ );
+ if (oRes.ok) {
+ const od = await oRes.json();
+ post = {
+ id: postId,
+ ts: tweetIdToMs(postId),
+ author: od.author_name ?? null,
+ text: stripHtml(od.html),
+ };
+ }
+ } catch {
+ // oEmbed unavailable — price analysis continues with post=null.
+ }
+
+ // Two sequential quote calls let tests mock distinct before/after prices.
+ // In production both reflect the live bonding curve state at call time.
+ const quoteUrl = `/api/pump/quote?mint=${encodeURIComponent(mint)}&sol=1&network=mainnet`;
+
+ const beforeRes = await fetch(quoteUrl);
+ if (!beforeRes.ok) throw new Error(`unknown mint: ${mint}`);
+ const beforeData = await beforeRes.json();
+
+ const afterRes = await fetch(quoteUrl);
+ if (!afterRes.ok) throw new Error(`unknown mint: ${mint}`);
+ const afterData = await afterRes.json();
+
+ const priceBefore = priceFromQuote(beforeData);
+ const priceAfter = priceFromQuote(afterData);
+ const volBefore = solReservesFromQuote(beforeData);
+ const volAfter = solReservesFromQuote(afterData);
+
+ const deltaPct =
+ priceBefore != null && priceBefore > 0
+ ? ((priceAfter - priceBefore) / priceBefore) * 100
+ : null;
+
+ const deltaVolPct =
+ volBefore != null && volBefore > 0
+ ? ((volAfter - volBefore) / volBefore) * 100
+ : null;
+
+ return { post, priceBefore, priceAfter, deltaPct, volBefore, volAfter, deltaVolPct };
+}
diff --git a/src/widget-types.js b/src/widget-types.js
index da2f0accb..dcc585955 100644
--- a/src/widget-types.js
+++ b/src/widget-types.js
@@ -50,6 +50,12 @@ export const WIDGET_TYPES = {
status: 'ready',
icon: '◈',
},
+ 'live-trades-canvas': {
+ label: 'Live Trades Canvas',
+ desc: 'Particle visualization of live pump.fun buy/sell trades for a token.',
+ status: 'ready',
+ icon: '⬡',
+ },
};
export const WIDGET_TYPE_KEYS = Object.keys(WIDGET_TYPES);
@@ -112,6 +118,12 @@ const TYPE_DEFAULTS = {
limit: 20,
refreshMs: 30_000,
},
+ 'live-trades-canvas': {
+ mint: '',
+ chain: 'solana',
+ bg: '#0a0a0a',
+ minUsd: 0,
+ },
};
const hexColor = z.string().regex(/^#[0-9a-fA-F]{3,8}$/, 'must be a hex color');
@@ -231,6 +243,12 @@ const TYPE_SCHEMAS = {
limit: z.number().int().min(1).max(100).default(20),
refreshMs: z.number().int().min(1000).max(300_000).default(30_000),
}),
+ 'live-trades-canvas': brandSchema.extend({
+ mint: z.string().min(1, 'mint is required'),
+ chain: z.enum(['solana']).default('solana'),
+ bg: hexColor.default('#0a0a0a'),
+ minUsd: z.number().min(0).default(0),
+ }),
};
export function defaultConfig(type) {
diff --git a/src/widgets/live-trades-canvas.js b/src/widgets/live-trades-canvas.js
new file mode 100644
index 000000000..a8d82de4d
--- /dev/null
+++ b/src/widgets/live-trades-canvas.js
@@ -0,0 +1,227 @@
+/**
+ * Live Trades Canvas Widget
+ *
+ * Polls getTokenTrades via /api/pump-fun-mcp and renders each new trade as a
+ * 2D canvas particle. Buys are green, sells are red. Particle radius scales
+ * with log(USD value) so a $10k trade is visually distinct from a $10 trade.
+ * Particles drift and fade over 5–10 seconds, then are removed.
+ *
+ * Config (validated in widget-types.js):
+ * - mint (required) solana base58 mint address
+ * - chain 'solana' (v1 only)
+ * - bg background hex color (default '#0a0a0a')
+ * - minUsd filter: skip trades below this USD value (default 0)
+ */
+
+const POLL_MS = 6_000;
+const FADE_MS = 8_000;
+const MIN_RADIUS = 6;
+const MAX_RADIUS = 48;
+const MCP_ENDPOINT = '/api/pump-fun-mcp';
+
+/**
+ * Fetch recent trades for a mint via the in-house pump-fun MCP endpoint.
+ * Returns an array of normalized trade objects or null on error.
+ *
+ * @param {string} mint
+ * @param {number} limit
+ * @param {typeof fetch} fetchImpl
+ * @returns {Promise<Array<{signature:string,isBuy:boolean,solAmount:number,usdValue:number,timestamp:number}>|null>}
+ */
+export async function fetchTrades(mint, limit = 20, fetchImpl = globalThis.fetch) {
+ let res;
+ try {
+ res = await fetchImpl(MCP_ENDPOINT, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'tools/call',
+ params: { name: 'getTokenTrades', arguments: { mint, limit } },
+ }),
+ });
+ } catch {
+ return null;
+ }
+ if (!res.ok) return null;
+ let body;
+ try {
+ body = await res.json();
+ } catch {
+ return null;
+ }
+ const content = body?.result?.content;
+ if (!Array.isArray(content) || !content.length) return null;
+ let data;
+ try {
+ data = typeof content[0].text === 'string' ? JSON.parse(content[0].text) : content[0];
+ } catch {
+ return null;
+ }
+ const rawTrades = data?.trades ?? data?.items ?? (Array.isArray(data) ? data : null);
+ if (!rawTrades) return null;
+ return rawTrades.map((t) => ({
+ signature: t.signature ?? t.tx ?? String(Math.random()),
+ isBuy: t.is_buy ?? t.isBuy ?? t.direction === 'buy' ?? true,
+ solAmount: Number(t.sol_amount ?? t.solAmount ?? 0),
+ usdValue: Number(t.usd_value ?? t.usdValue ?? t.sol_amount ?? 0),
+ timestamp: t.timestamp ?? t.block_time ?? Date.now() / 1000,
+ }));
+}
+
+/**
+ * Compute new trades that weren't in the previous set.
+ *
+ * @param {Array} incoming freshly fetched trades (newest-first expected)
+ * @param {Set<string>} seen signatures already shown
+ * @param {number} minUsd filter threshold
+ * @returns {Array}
+ */
+export function filterNewTrades(incoming, seen, minUsd = 0) {
+ if (!Array.isArray(incoming)) return [];
+ return incoming.filter((t) => {
+ if (seen.has(t.signature)) return false;
+ if (t.usdValue < minUsd) return false;
+ return true;
+ });
+}
+
+function particleRadius(usdValue) {
+ if (!usdValue || usdValue <= 0) return MIN_RADIUS;
+ const r = MIN_RADIUS + Math.log10(Math.max(1, usdValue)) * 4;
+ return Math.min(MAX_RADIUS, Math.max(MIN_RADIUS, r));
+}
+
+/**
+ * Mount the live-trades canvas widget inside `rootEl`.
+ *
+ * @param {HTMLElement} rootEl container element (position:relative expected)
+ * @param {object} opts
+ * @param {string} opts.mint
+ * @param {string} [opts.chain]
+ * @param {string} [opts.bg]
+ * @param {number} [opts.minUsd]
+ * @param {typeof fetch} [opts.fetchImpl] injectable for tests
+ * @returns {{ destroy(): void }}
+ */
+export function mountLiveTradesCanvas(rootEl, opts = {}) {
+ const mint = opts.mint || '';
+ const bg = opts.bg || '#0a0a0a';
+ const minUsd = Number(opts.minUsd ?? 0);
+ const fetchImpl = opts.fetchImpl ?? globalThis.fetch;
+
+ const canvas = document.createElement('canvas');
+ canvas.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;display:block';
+ rootEl.style.position = 'relative';
+ rootEl.appendChild(canvas);
+
+ const ctx2d = canvas.getContext('2d');
+
+ let particles = [];
+ const seen = new Set();
+ let rafId = null;
+ let pollTimer = null;
+ let destroyed = false;
+
+ function resize() {
+ const w = rootEl.clientWidth || 400;
+ const h = rootEl.clientHeight || 300;
+ const dpr = typeof devicePixelRatio !== 'undefined' ? devicePixelRatio : 1;
+ canvas.width = w * dpr;
+ canvas.height = h * dpr;
+ canvas.style.width = w + 'px';
+ canvas.style.height = h + 'px';
+ ctx2d.scale(dpr, dpr);
+ }
+
+ let ro = null;
+ if (typeof ResizeObserver !== 'undefined') {
+ ro = new ResizeObserver(() => resize());
+ ro.observe(rootEl);
+ }
+ resize();
+
+ function spawnParticle(trade) {
+ const w = rootEl.clientWidth || 400;
+ const h = rootEl.clientHeight || 300;
+ const r = particleRadius(trade.usdValue);
+ particles.push({
+ x: r + Math.random() * (w - r * 2),
+ y: r + Math.random() * (h - r * 2),
+ vx: (Math.random() - 0.5) * 1.2,
+ vy: (Math.random() - 0.5) * 1.2,
+ r,
+ isBuy: trade.isBuy,
+ born: performance.now(),
+ });
+ }
+
+ function draw(now) {
+ if (destroyed) return;
+ const w = rootEl.clientWidth || 400;
+ const h = rootEl.clientHeight || 300;
+
+ ctx2d.clearRect(0, 0, w, h);
+ ctx2d.fillStyle = bg;
+ ctx2d.fillRect(0, 0, w, h);
+
+ particles = particles.filter((p) => {
+ const age = now - p.born;
+ return age < FADE_MS;
+ });
+
+ for (const p of particles) {
+ const age = now - p.born;
+ const alpha = Math.max(0, 1 - age / FADE_MS);
+
+ p.x += p.vx;
+ p.y += p.vy;
+ p.vx *= 0.99;
+ p.vy *= 0.99;
+
+ ctx2d.globalAlpha = alpha;
+ ctx2d.beginPath();
+ ctx2d.arc(p.x, p.y, p.r, 0, Math.PI * 2);
+ ctx2d.fillStyle = p.isBuy ? '#22c55e' : '#ef4444';
+ ctx2d.fill();
+
+ ctx2d.globalAlpha = alpha * 0.35;
+ ctx2d.strokeStyle = p.isBuy ? '#86efac' : '#fca5a5';
+ ctx2d.lineWidth = 1.5;
+ ctx2d.stroke();
+ }
+ ctx2d.globalAlpha = 1;
+
+ rafId = requestAnimationFrame(draw);
+ }
+
+ async function poll() {
+ if (destroyed || !mint) return;
+ const trades = await fetchTrades(mint, 20, fetchImpl);
+ const fresh = filterNewTrades(trades, seen, minUsd);
+ for (const t of fresh) {
+ seen.add(t.signature);
+ spawnParticle(t);
+ }
+ // keep seen set bounded
+ if (seen.size > 500) {
+ const arr = [...seen];
+ arr.splice(0, arr.length - 200).forEach((s) => seen.delete(s));
+ }
+ }
+
+ poll();
+ pollTimer = setInterval(poll, POLL_MS);
+ rafId = requestAnimationFrame(draw);
+
+ return {
+ destroy() {
+ destroyed = true;
+ if (rafId !== null) cancelAnimationFrame(rafId);
+ if (pollTimer !== null) clearInterval(pollTimer);
+ ro?.disconnect();
+ canvas.remove();
+ },
+ };
+}
diff --git a/tests/kol-trades-widget.test.js b/tests/kol-trades-widget.test.js
new file mode 100644
index 000000000..feb40a45d
--- /dev/null
+++ b/tests/kol-trades-widget.test.js
@@ -0,0 +1,307 @@
+import { describe, it, expect, vi, afterEach } from 'vitest';
+
+// ---------------------------------------------------------------------------
+// Mocks — must be declared before any top-level imports of the mocked modules.
+// ---------------------------------------------------------------------------
+
+vi.mock('../api/_lib/http.js', () => ({
+ cors: () => false,
+ method: () => true,
+ json: (res, status, body) => {
+ res.statusCode = status;
+ res.body = body;
+ },
+ error: (res, status, code, msg) => {
+ res.statusCode = status;
+ res.body = { error: code, error_description: msg };
+ },
+ wrap: (fn) => fn,
+}));
+
+vi.mock('../src/kol/wallets.js', () => ({
+ KOL_WALLETS: [
+ { address: 'FakeWallet1111', label: 'kol-alpha', tags: ['kol'] },
+ { address: 'FakeWallet2222', label: 'whale-desk', tags: ['whale'] },
+ ],
+ isSmartMoney: (addr) => ['FakeWallet1111', 'FakeWallet2222'].includes(addr),
+ getWalletMeta: (addr) =>
+ addr === 'FakeWallet1111'
+ ? { address: 'FakeWallet1111', label: 'kol-alpha', tags: ['kol'] }
+ : null,
+}));
+
+// ---------------------------------------------------------------------------
+// Module under test (API handler)
+// ---------------------------------------------------------------------------
+
+const { default: tradesHandler } = await import('../api/kol/trades.js');
+
+// ---------------------------------------------------------------------------
+// Helper
+// ---------------------------------------------------------------------------
+
+function mockRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: null,
+ setHeader(k, v) {
+ this.headers[k.toLowerCase()] = v;
+ },
+ getHeader(k) {
+ return this.headers[k.toLowerCase()];
+ },
+ end(b) {
+ try {
+ this.body = JSON.parse(b);
+ } catch {
+ this.body = b;
+ }
+ },
+ };
+}
+
+// ---------------------------------------------------------------------------
+// API endpoint shape
+// ---------------------------------------------------------------------------
+
+describe('GET /api/kol/trades — endpoint shape', () => {
+ it('responds 200 with { mint, trades, wallets } for a valid mint', async () => {
+ const req = { headers: {}, method: 'GET', url: '/api/kol/trades?mint=ABC123Mint&limit=5' };
+ const res = mockRes();
+ await tradesHandler(req, res);
+
+ expect(res.statusCode).toBe(200);
+ expect(res.body).toMatchObject({
+ mint: 'ABC123Mint',
+ trades: expect.any(Array),
+ wallets: 2,
+ });
+ });
+
+ it('trades is an array', async () => {
+ const req = { headers: {}, method: 'GET', url: '/api/kol/trades?mint=MINT1' };
+ const res = mockRes();
+ await tradesHandler(req, res);
+
+ expect(Array.isArray(res.body.trades)).toBe(true);
+ });
+
+ it('responds 400 when mint query param is missing', async () => {
+ const req = { headers: {}, method: 'GET', url: '/api/kol/trades' };
+ const res = mockRes();
+ await tradesHandler(req, res);
+
+ expect(res.statusCode).toBe(400);
+ expect(res.body.error).toBe('validation_error');
+ });
+
+ it('wallets count matches the KOL_WALLETS stub length', async () => {
+ const req = { headers: {}, method: 'GET', url: '/api/kol/trades?mint=ANYMINT' };
+ const res = mockRes();
+ await tradesHandler(req, res);
+
+ expect(res.body.wallets).toBe(2);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Widget — renderTrades (pure function, no DOM needed)
+// ---------------------------------------------------------------------------
+
+const { renderTrades, mountKolTradesWidget } = await import('../src/widgets/kol-trades.js');
+
+describe('renderTrades — pure HTML output', () => {
+ it('returns empty-state markup when trades array is empty', () => {
+ const html = renderTrades([]);
+ expect(html).toContain('kol-trades-empty');
+ });
+
+ it('returns empty-state markup when trades is null', () => {
+ const html = renderTrades(null);
+ expect(html).toContain('kol-trades-empty');
+ });
+
+ it('renders a row for each trade', () => {
+ const trades = [
+ {
+ time: new Date().toISOString(),
+ side: 'buy',
+ wallet: 'WALLETABC1234567890',
+ usd: 500,
+ source: 'kol',
+ },
+ {
+ time: new Date().toISOString(),
+ side: 'sell',
+ wallet: 'WALLETXYZ9876543210',
+ usd: 250,
+ source: 'whale',
+ },
+ ];
+ const html = renderTrades(trades);
+ expect(html).toContain('kol-trades-row');
+ expect(html).toContain('Buy');
+ expect(html).toContain('Sell');
+ expect(html).toContain('WALLET'); // truncated wallet address
+ expect(html).toContain('KOL');
+ expect(html).toContain('Whale');
+ });
+
+ it('links wallet to Solscan', () => {
+ const html = renderTrades([
+ { time: new Date().toISOString(), side: 'buy', wallet: 'SomePubKeyAddr', usd: 100, source: 'kol' },
+ ]);
+ expect(html).toContain('solscan.io/account/SomePubKeyAddr');
+ });
+
+ it('escapes HTML in wallet address', () => {
+ const html = renderTrades([
+ { time: new Date().toISOString(), side: 'buy', wallet: '<script>bad</script>', usd: 0, source: 'kol' },
+ ]);
+ expect(html).not.toContain('<script>');
+ expect(html).toContain('&lt;script&gt;');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Widget mount — polling + DOM integration (mocked fetch + minimal DOM stub)
+// ---------------------------------------------------------------------------
+
+class MockEl {
+ constructor(doc) {
+ this.children = [];
+ this._html = '';
+ this.className = '';
+ this.textContent = '';
+ this.style = { cssText: '' };
+ this.ownerDocument = doc;
+ }
+ get innerHTML() {
+ return this._html;
+ }
+ set innerHTML(v) {
+ this._html = v;
+ }
+ appendChild(child) {
+ this.children.push(child);
+ return child;
+ }
+ remove() {}
+}
+
+function makeMockDoc() {
+ const doc = {};
+ doc.createElement = () => new MockEl(doc);
+ doc.head = { appendChild() {} };
+ return doc;
+}
+
+describe('mountKolTradesWidget — renders from mocked fetch', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ delete global.fetch;
+ });
+
+ it('calls /api/kol/trades with the correct mint and limit', async () => {
+ global.fetch = vi.fn().mockResolvedValue({
+ ok: true,
+ json: async () => ({ mint: 'MINT_A', trades: [], wallets: 2 }),
+ });
+
+ const doc = makeMockDoc();
+ const root = new MockEl(doc);
+ root.ownerDocument = doc;
+
+ const ctrl = mountKolTradesWidget(root, { mint: 'MINT_A', limit: 10, refreshMs: 60_000 });
+ await new Promise((r) => setTimeout(r, 20));
+
+ expect(global.fetch).toHaveBeenCalledWith(
+ expect.stringContaining('mint=MINT_A'),
+ );
+ expect(global.fetch).toHaveBeenCalledWith(
+ expect.stringContaining('limit=10'),
+ );
+
+ ctrl.destroy();
+ });
+
+ it('renders empty state when API returns no trades', async () => {
+ global.fetch = vi.fn().mockResolvedValue({
+ ok: true,
+ json: async () => ({ mint: 'MINT_B', trades: [], wallets: 2 }),
+ });
+
+ const doc = makeMockDoc();
+ const root = new MockEl(doc);
+ root.ownerDocument = doc;
+
+ const ctrl = mountKolTradesWidget(root, { mint: 'MINT_B', limit: 20, refreshMs: 60_000 });
+ await new Promise((r) => setTimeout(r, 20));
+
+ const container = root.children[0];
+ expect(container.innerHTML).toContain('kol-trades-empty');
+
+ ctrl.destroy();
+ });
+
+ it('renders trade rows when API returns trades', async () => {
+ const trade = {
+ time: new Date().toISOString(),
+ side: 'buy',
+ wallet: 'TESTWALLETADDR123456',
+ usd: 1234,
+ source: 'kol',
+ };
+ global.fetch = vi.fn().mockResolvedValue({
+ ok: true,
+ json: async () => ({ mint: 'MINT_C', trades: [trade], wallets: 2 }),
+ });
+
+ const doc = makeMockDoc();
+ const root = new MockEl(doc);
+ root.ownerDocument = doc;
+
+ const ctrl = mountKolTradesWidget(root, { mint: 'MINT_C', limit: 20, refreshMs: 60_000 });
+ await new Promise((r) => setTimeout(r, 20));
+
+ const container = root.children[0];
+ expect(container.innerHTML).toContain('TESTWALLET');
+ expect(container.innerHTML).toContain('Buy');
+
+ ctrl.destroy();
+ });
+
+ it('does not throw on fetch failure', async () => {
+ global.fetch = vi.fn().mockRejectedValue(new Error('network error'));
+
+ const doc = makeMockDoc();
+ const root = new MockEl(doc);
+ root.ownerDocument = doc;
+
+ const ctrl = mountKolTradesWidget(root, { mint: 'MINT_D', limit: 20, refreshMs: 60_000 });
+ await expect(new Promise((r) => setTimeout(r, 20))).resolves.not.toThrow();
+
+ ctrl.destroy();
+ });
+
+ it('destroy stops polling', async () => {
+ global.fetch = vi.fn().mockResolvedValue({
+ ok: true,
+ json: async () => ({ mint: 'MINT_E', trades: [], wallets: 2 }),
+ });
+
+ const doc = makeMockDoc();
+ const root = new MockEl(doc);
+ root.ownerDocument = doc;
+
+ const ctrl = mountKolTradesWidget(root, { mint: 'MINT_E', limit: 20, refreshMs: 50 });
+ await new Promise((r) => setTimeout(r, 20));
+ const callsBefore = global.fetch.mock.calls.length;
+
+ ctrl.destroy();
+ await new Promise((r) => setTimeout(r, 120));
+ // No additional calls after destroy
+ expect(global.fetch.mock.calls.length).toBe(callsBefore);
+ });
+});
diff --git a/tests/live-trades-canvas.test.js b/tests/live-trades-canvas.test.js
new file mode 100644
index 000000000..385d2f6bf
--- /dev/null
+++ b/tests/live-trades-canvas.test.js
@@ -0,0 +1,118 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { fetchTrades, filterNewTrades } from '../src/widgets/live-trades-canvas.js';
+
+// ── fetchTrades ─────────────────────────────────────────────────────────────
+
+function makeMcpFetch(tradePayload) {
+ return async (_url, _opts) => ({
+ ok: true,
+ json: async () => ({
+ jsonrpc: '2.0',
+ id: 1,
+ result: {
+ content: [{ type: 'text', text: JSON.stringify({ trades: tradePayload }) }],
+ },
+ }),
+ });
+}
+
+describe('fetchTrades', () => {
+ it('returns normalized trades from MCP response', async () => {
+ const raw = [
+ { signature: 'sig1', is_buy: true, sol_amount: 1.5, usd_value: 225, timestamp: 1000 },
+ { signature: 'sig2', is_buy: false, sol_amount: 0.3, usd_value: 45, timestamp: 999 },
+ ];
+ const trades = await fetchTrades('mint123', 20, makeMcpFetch(raw));
+ expect(trades).toHaveLength(2);
+ expect(trades[0].signature).toBe('sig1');
+ expect(trades[0].isBuy).toBe(true);
+ expect(trades[0].solAmount).toBe(1.5);
+ expect(trades[0].usdValue).toBe(225);
+ expect(trades[1].isBuy).toBe(false);
+ });
+
+ it('returns null when the MCP response has no trades', async () => {
+ const fetch = async () => ({
+ ok: true,
+ json: async () => ({
+ jsonrpc: '2.0',
+ id: 1,
+ result: { content: [{ type: 'text', text: '{}' }] },
+ }),
+ });
+ const result = await fetchTrades('mint123', 20, fetch);
+ expect(result).toBeNull();
+ });
+
+ it('returns null on non-ok HTTP status', async () => {
+ const fetch = async () => ({ ok: false, status: 503 });
+ const result = await fetchTrades('mint123', 20, fetch);
+ expect(result).toBeNull();
+ });
+
+ it('returns null when fetch throws', async () => {
+ const fetch = async () => { throw new Error('network'); };
+ const result = await fetchTrades('mint123', 20, fetch);
+ expect(result).toBeNull();
+ });
+
+ it('handles alternative field names (isBuy, usdValue)', async () => {
+ const raw = [{ signature: 'alt1', isBuy: true, solAmount: 2, usdValue: 300, timestamp: 1 }];
+ const trades = await fetchTrades('mint', 20, makeMcpFetch(raw));
+ expect(trades[0].isBuy).toBe(true);
+ expect(trades[0].usdValue).toBe(300);
+ });
+
+ it('handles direction field for buy/sell', async () => {
+ const raw = [{ signature: 'dir1', direction: 'sell', sol_amount: 0.5, usd_value: 75, timestamp: 1 }];
+ const trades = await fetchTrades('mint', 20, makeMcpFetch(raw));
+ expect(trades[0].isBuy).toBe(false);
+ });
+});
+
+// ── filterNewTrades ─────────────────────────────────────────────────────────
+
+describe('filterNewTrades', () => {
+ it('returns only unseen trades', () => {
+ const seen = new Set(['sig1']);
+ const incoming = [
+ { signature: 'sig1', isBuy: true, usdValue: 100 },
+ { signature: 'sig2', isBuy: false, usdValue: 50 },
+ ];
+ const fresh = filterNewTrades(incoming, seen, 0);
+ expect(fresh).toHaveLength(1);
+ expect(fresh[0].signature).toBe('sig2');
+ });
+
+ it('filters trades below minUsd', () => {
+ const seen = new Set();
+ const incoming = [
+ { signature: 'a', isBuy: true, usdValue: 600 },
+ { signature: 'b', isBuy: false, usdValue: 100 },
+ ];
+ const fresh = filterNewTrades(incoming, seen, 500);
+ expect(fresh).toHaveLength(1);
+ expect(fresh[0].signature).toBe('a');
+ });
+
+ it('returns empty array when all trades are already seen', () => {
+ const seen = new Set(['x', 'y']);
+ const incoming = [
+ { signature: 'x', isBuy: true, usdValue: 10 },
+ { signature: 'y', isBuy: false, usdValue: 20 },
+ ];
+ expect(filterNewTrades(incoming, seen, 0)).toHaveLength(0);
+ });
+
+ it('handles null/undefined incoming gracefully', () => {
+ expect(filterNewTrades(null, new Set(), 0)).toEqual([]);
+ expect(filterNewTrades(undefined, new Set(), 0)).toEqual([]);
+ });
+
+ it('passes trades at exactly the minUsd threshold', () => {
+ const seen = new Set();
+ const incoming = [{ signature: 'z', isBuy: true, usdValue: 500 }];
+ // minUsd=500 means >= 500 passes (filter is < minUsd rejects)
+ expect(filterNewTrades(incoming, seen, 500)).toHaveLength(1);
+ });
+});
diff --git a/tests/pump-first-claims.test.js b/tests/pump-first-claims.test.js
new file mode 100644
index 000000000..978a2486a
--- /dev/null
+++ b/tests/pump-first-claims.test.js
@@ -0,0 +1,86 @@
+import { describe, it, expect } from 'vitest';
+import { filterFirstClaims } from '../src/pump/first-claims.js';
+
+const sinceTs = 1000; // boundary: claims < 1000 are "prior"
+
+function claim(creator, ts, overrides = {}) {
+ return { creator, mint: `mint_${ts}`, signature: `sig_${ts}`, lamports: 1e9, ts, ...overrides };
+}
+
+describe('filterFirstClaims — dedupe rule', () => {
+ it('includes a creator whose only claim is within the window', () => {
+ const result = filterFirstClaims([claim('A', 1200)], sinceTs, 50);
+ expect(result).toHaveLength(1);
+ expect(result[0].creator).toBe('A');
+ });
+
+ it('excludes a creator with any prior claim before sinceTs', () => {
+ const result = filterFirstClaims(
+ [
+ claim('B', 500), // prior — before sinceTs
+ claim('B', 1200), // within window
+ ],
+ sinceTs,
+ 50,
+ );
+ expect(result).toHaveLength(0);
+ });
+
+ it('handles multiple creators, only includes first-timers', () => {
+ const claims = [
+ claim('A', 1200), // new
+ claim('B', 800), // prior
+ claim('B', 1300), // B also has a later claim, but excluded by prior
+ claim('C', 1400), // new
+ ];
+ const result = filterFirstClaims(claims, sinceTs, 50);
+ const creators = result.map((r) => r.creator).sort();
+ expect(creators).toEqual(['A', 'C']);
+ });
+
+ it('returns items sorted newest first', () => {
+ const claims = [claim('A', 1200), claim('C', 1400)];
+ const result = filterFirstClaims(claims, sinceTs, 50);
+ expect(result[0].ts).toBe(1400);
+ expect(result[1].ts).toBe(1200);
+ });
+
+ it('respects the limit', () => {
+ const claims = Array.from({ length: 10 }, (_, i) =>
+ claim(`creator_${i}`, 1100 + i),
+ );
+ const result = filterFirstClaims(claims, sinceTs, 3);
+ expect(result).toHaveLength(3);
+ });
+
+ it('returns the earliest claim per creator (the first-claim event)', () => {
+ // Creator with two claims both within window — should surface the earlier one.
+ const claims = [claim('D', 1300), claim('D', 1100)];
+ const result = filterFirstClaims(claims, sinceTs, 50);
+ expect(result).toHaveLength(1);
+ expect(result[0].ts).toBe(1100);
+ });
+
+ it('returns empty array when all creators have prior claims', () => {
+ const result = filterFirstClaims(
+ [claim('X', 100), claim('Y', 200), claim('Z', 500)],
+ sinceTs,
+ 50,
+ );
+ expect(result).toHaveLength(0);
+ });
+
+ it('returns empty array for empty input', () => {
+ expect(filterFirstClaims([], sinceTs, 50)).toEqual([]);
+ });
+
+ it('claim at exactly sinceTs boundary is included (>= rule)', () => {
+ const result = filterFirstClaims([claim('E', sinceTs)], sinceTs, 50);
+ expect(result).toHaveLength(1);
+ });
+
+ it('claim one second before sinceTs is excluded', () => {
+ const result = filterFirstClaims([claim('F', sinceTs - 1)], sinceTs, 50);
+ expect(result).toHaveLength(0);
+ });
+});
diff --git a/tests/pump-swap-quote.test.js b/tests/pump-swap-quote.test.js
new file mode 100644
index 000000000..bd7515aa1
--- /dev/null
+++ b/tests/pump-swap-quote.test.js
@@ -0,0 +1,170 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import BN from 'bn.js';
+
+// ── Mocks ──────────────────────────────────────────────────────────────────
+
+const mockSwapSolanaState = vi.fn();
+const mockBuyQuoteInput = vi.fn();
+const mockSellBaseInput = vi.fn();
+const MOCK_POOL = '9WZDXbs5da3XuBTOBiGHqKkqFGC4j2HJvBQKzXAMsRg';
+
+vi.mock('@pump-fun/pump-swap-sdk', () => ({
+ OnlinePumpAmmSdk: class {
+ swapSolanaState(...a) {
+ return mockSwapSolanaState(...a);
+ }
+ },
+ canonicalPumpPoolPda: () => ({ toBase58: () => MOCK_POOL }),
+ buyQuoteInput: (...a) => mockBuyQuoteInput(...a),
+ sellBaseInput: (...a) => mockSellBaseInput(...a),
+}));
+
+vi.mock('../src/erc8004/solana-deploy.js', () => ({
+ SOLANA_RPC: { mainnet: 'https://api.mainnet-beta.solana.com' },
+}));
+
+// Import AFTER mocks are registered.
+const { quoteSwap } = await import('../src/pump/pump-swap-quote.js');
+
+// ── Fixtures ───────────────────────────────────────────────────────────────
+
+const WSOL = 'So11111111111111111111111111111111111111112';
+// USDC on mainnet — a valid 32-byte base58 public key used as stand-in token mint.
+const TOKEN = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+
+function fakeState(overrides = {}) {
+ return {
+ globalConfig: { mock: true },
+ feeConfig: null,
+ pool: {
+ baseMint: { toBase58: () => TOKEN },
+ coinCreator: { toBase58: () => '11111111111111111111111111111111' },
+ creator: { toBase58: () => '11111111111111111111111111111111' },
+ },
+ poolBaseAmount: new BN(1_000_000),
+ poolQuoteAmount: new BN(1_000_000),
+ baseMintAccount: { decimals: 6 },
+ ...overrides,
+ };
+}
+
+// ── Tests ──────────────────────────────────────────────────────────────────
+
+describe('quoteSwap', () => {
+ beforeEach(() => {
+ mockSwapSolanaState.mockReset();
+ mockBuyQuoteInput.mockReset();
+ mockSellBaseInput.mockReset();
+ });
+
+ it('buy direction: forwards args and normalizes output shape', async () => {
+ mockSwapSolanaState.mockResolvedValueOnce(fakeState());
+ mockBuyQuoteInput.mockReturnValueOnce({ base: new BN(9_900), maxQuote: new BN(10_200) });
+
+ const result = await quoteSwap({ inputMint: WSOL, outputMint: TOKEN, amountIn: 10_000, slippageBps: 100 });
+
+ expect(result.amountOut).toBe('9900');
+ expect(typeof result.priceImpactBps).toBe('number');
+ expect(result.priceImpactBps).toBeGreaterThanOrEqual(0);
+ expect(result.route).toBe(MOCK_POOL);
+ expect(result.expiresAtMs).toBeGreaterThan(Date.now() - 1000);
+ expect(result.expiresAtMs).toBeLessThanOrEqual(Date.now() + 11_000);
+ });
+
+ it('buy direction: passes quote and slippage through to buyQuoteInput', async () => {
+ mockSwapSolanaState.mockResolvedValueOnce(fakeState());
+ mockBuyQuoteInput.mockReturnValueOnce({ base: new BN(9_900) });
+
+ await quoteSwap({ inputMint: WSOL, outputMint: TOKEN, amountIn: 10_000, slippageBps: 100 });
+
+ expect(mockBuyQuoteInput).toHaveBeenCalledOnce();
+ const call = mockBuyQuoteInput.mock.calls[0][0];
+ expect(call.quote.toString()).toBe('10000');
+ expect(call.slippage).toBeCloseTo(0.01);
+ expect(call.globalConfig).toEqual({ mock: true });
+ });
+
+ it('buy direction: computes priceImpactBps correctly', async () => {
+ // poolBase=1_000_000, poolQuote=1_000_000, amountIn=10_000, amountOut=9_900
+ // impact = (10000*1000000)/(9900*1000000) * 10000 - 10000 = 10101 - 10000 = 101
+ mockSwapSolanaState.mockResolvedValueOnce(fakeState());
+ mockBuyQuoteInput.mockReturnValueOnce({ base: new BN(9_900) });
+
+ const result = await quoteSwap({ inputMint: WSOL, outputMint: TOKEN, amountIn: 10_000 });
+
+ expect(result.priceImpactBps).toBe(101);
+ });
+
+ it('sell direction: forwards args and normalizes output shape', async () => {
+ mockSwapSolanaState.mockResolvedValueOnce(fakeState());
+ mockSellBaseInput.mockReturnValueOnce({ uiQuote: new BN(9_800), minQuote: new BN(9_700) });
+
+ const result = await quoteSwap({ inputMint: TOKEN, outputMint: WSOL, amountIn: 10_000, slippageBps: 50 });
+
+ expect(result.amountOut).toBe('9800');
+ expect(result.priceImpactBps).toBeGreaterThanOrEqual(0);
+ expect(result.route).toBe(MOCK_POOL);
+ });
+
+ it('sell direction: passes base and slippage through to sellBaseInput', async () => {
+ mockSwapSolanaState.mockResolvedValueOnce(fakeState());
+ mockSellBaseInput.mockReturnValueOnce({ uiQuote: new BN(9_800) });
+
+ await quoteSwap({ inputMint: TOKEN, outputMint: WSOL, amountIn: 10_000, slippageBps: 50 });
+
+ expect(mockSellBaseInput).toHaveBeenCalledOnce();
+ const call = mockSellBaseInput.mock.calls[0][0];
+ expect(call.base.toString()).toBe('10000');
+ expect(call.slippage).toBeCloseTo(0.005);
+ });
+
+ it('sell direction: computes priceImpactBps correctly', async () => {
+ // poolBase=1_000_000, poolQuote=1_000_000, amountIn=10_000, amountOut=9_800
+ // spot = 1_000_000*10_000=10_000_000_000; exec = 9_800*1_000_000=9_800_000_000
+ // impact = (10B - 9.8B)*10000 / 10B = 200
+ mockSwapSolanaState.mockResolvedValueOnce(fakeState());
+ mockSellBaseInput.mockReturnValueOnce({ uiQuote: new BN(9_800) });
+
+ const result = await quoteSwap({ inputMint: TOKEN, outputMint: WSOL, amountIn: 10_000 });
+
+ expect(result.priceImpactBps).toBe(200);
+ });
+
+ it('uses default slippageBps of 100 when not provided', async () => {
+ mockSwapSolanaState.mockResolvedValueOnce(fakeState());
+ mockBuyQuoteInput.mockReturnValueOnce({ base: new BN(5_000) });
+
+ await quoteSwap({ inputMint: WSOL, outputMint: TOKEN, amountIn: 5_000 });
+
+ const call = mockBuyQuoteInput.mock.calls[0][0];
+ expect(call.slippage).toBeCloseTo(0.01);
+ });
+
+ it('throws with clean message on invalid inputMint', async () => {
+ await expect(
+ quoteSwap({ inputMint: 'not-a-valid-mint', outputMint: WSOL, amountIn: 1000 }),
+ ).rejects.toThrow('Invalid inputMint');
+ });
+
+ it('throws with clean message on invalid outputMint', async () => {
+ await expect(
+ quoteSwap({ inputMint: WSOL, outputMint: 'not-a-valid-mint', amountIn: 1000 }),
+ ).rejects.toThrow('Invalid outputMint');
+ });
+
+ it('throws when neither mint is wSOL', async () => {
+ // SystemProgram (11111...1) is a valid pubkey but not wSOL.
+ const OTHER = '11111111111111111111111111111111';
+ await expect(
+ quoteSwap({ inputMint: TOKEN, outputMint: OTHER, amountIn: 1000 }),
+ ).rejects.toThrow(/wSOL/);
+ });
+
+ it('wraps RPC errors with clean pool-unavailable message', async () => {
+ mockSwapSolanaState.mockRejectedValueOnce(new Error('Connection refused'));
+
+ await expect(
+ quoteSwap({ inputMint: WSOL, outputMint: TOKEN, amountIn: 1000 }),
+ ).rejects.toThrow('Pool unavailable');
+ });
+});
diff --git a/tests/pumpkit-whale.test.js b/tests/pumpkit-whale.test.js
index f4a7ccab1..1e7705a41 100644
--- a/tests/pumpkit-whale.test.js
+++ b/tests/pumpkit-whale.test.js
@@ -28,7 +28,7 @@ vi.mock('@coral-xyz/anchor', () => ({
})),
}));
-vi.mock('@nirholas/pump-sdk', () => ({
+vi.mock('@pump-fun/pump-sdk', () => ({
PUMP_PROGRAM_ID: { toString: () => '6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P' },
pumpIdl: {},
}));
diff --git a/tests/src/widget-types.test.js b/tests/src/widget-types.test.js
index 5faa279b7..660a9ba43 100644
--- a/tests/src/widget-types.test.js
+++ b/tests/src/widget-types.test.js
@@ -22,6 +22,7 @@ describe('WIDGET_TYPES', () => {
'hotspot-tour',
'pumpfun-feed',
'kol-trades',
+ 'live-trades-canvas',
].sort(),
);
});
diff --git a/tests/x-post-impact.test.js b/tests/x-post-impact.test.js
new file mode 100644
index 000000000..e96bbe1fe
--- /dev/null
+++ b/tests/x-post-impact.test.js
@@ -0,0 +1,128 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const fetchMock = vi.fn();
+vi.stubGlobal('fetch', fetchMock);
+
+const { correlateXPost } = await import('../src/social/x-post-impact.js');
+
+// ── helpers ────────────────────────────────────────────────────────────────
+
+function quoteRes(tokensOut, realSolLamports) {
+ return {
+ ok: true,
+ json: async () => ({
+ quote: { tokens_out: tokensOut.toString() },
+ bonding_curve: { real_sol_reserves: realSolLamports.toString() },
+ }),
+ };
+}
+
+function oembedRes(author, text) {
+ return {
+ ok: true,
+ json: async () => ({ author_name: author, html: `<blockquote>${text}</blockquote>` }),
+ };
+}
+
+// ── tests ──────────────────────────────────────────────────────────────────
+
+describe('correlateXPost', () => {
+ beforeEach(() => fetchMock.mockReset());
+
+ it('computes positive deltaPct when price increases', async () => {
+ // before: 1/10000 SOL per token; after: 1/9000 → +11.1%
+ fetchMock
+ .mockResolvedValueOnce(oembedRes('alice', 'moon soon'))
+ .mockResolvedValueOnce(quoteRes(10000, 50_000_000_000))
+ .mockResolvedValueOnce(quoteRes(9000, 55_000_000_000));
+
+ const r = await correlateXPost({
+ postUrl: 'https://x.com/alice/status/1894000000000000000',
+ mint: 'ValidMintAddress',
+ });
+
+ expect(r.post?.author).toBe('alice');
+ expect(r.post?.text).toBe('moon soon');
+ expect(r.priceBefore).toBeCloseTo(1 / 10000, 8);
+ expect(r.priceAfter).toBeCloseTo(1 / 9000, 8);
+ const expectedDelta = ((1 / 9000 - 1 / 10000) / (1 / 10000)) * 100;
+ expect(r.deltaPct).toBeCloseTo(expectedDelta, 4);
+ expect(r.volBefore).toBeCloseTo(50, 3);
+ expect(r.volAfter).toBeCloseTo(55, 3);
+ expect(r.deltaVolPct).toBeCloseTo(10, 2);
+ });
+
+ it('computes negative deltaPct when price drops', async () => {
+ // before: 1/9000; after: 1/10000 → negative delta
+ fetchMock
+ .mockResolvedValueOnce(oembedRes('bob', 'dump incoming'))
+ .mockResolvedValueOnce(quoteRes(9000, 50_000_000_000))
+ .mockResolvedValueOnce(quoteRes(10000, 45_000_000_000));
+
+ const r = await correlateXPost({
+ postUrl: 'https://x.com/bob/status/999',
+ mint: 'ValidMintAddress',
+ });
+
+ expect(r.deltaPct).toBeLessThan(0);
+ expect(r.deltaVolPct).toBeLessThan(0);
+ });
+
+ it('returns post=null when oEmbed throws, still computes price delta', async () => {
+ fetchMock
+ .mockRejectedValueOnce(new Error('network error'))
+ .mockResolvedValueOnce(quoteRes(10000, 50_000_000_000))
+ .mockResolvedValueOnce(quoteRes(10000, 50_000_000_000));
+
+ const r = await correlateXPost({
+ postUrl: 'https://x.com/anon/status/1',
+ mint: 'ValidMintAddress',
+ });
+
+ expect(r.post).toBeNull();
+ expect(r.deltaPct).toBeCloseTo(0, 5);
+ expect(r.priceBefore).not.toBeNull();
+ });
+
+ it('returns post=null when oEmbed returns non-ok, still computes prices', async () => {
+ fetchMock
+ .mockResolvedValueOnce({ ok: false })
+ .mockResolvedValueOnce(quoteRes(10000, 50_000_000_000))
+ .mockResolvedValueOnce(quoteRes(8000, 60_000_000_000));
+
+ const r = await correlateXPost({
+ postUrl: 'https://x.com/anon/status/2',
+ mint: 'ValidMintAddress',
+ });
+
+ expect(r.post).toBeNull();
+ expect(r.deltaPct).toBeGreaterThan(0);
+ });
+
+ it('throws with "unknown mint" when price fetch fails', async () => {
+ fetchMock
+ .mockResolvedValueOnce({ ok: false })
+ .mockResolvedValueOnce({ ok: false, status: 400 });
+
+ await expect(
+ correlateXPost({ postUrl: 'https://x.com/a/status/1', mint: 'badmint' }),
+ ).rejects.toThrow(/unknown mint/);
+ });
+
+ it('extracts post id and derives ts from tweet snowflake id', async () => {
+ const id = '1894000000000000000';
+ fetchMock
+ .mockResolvedValueOnce(oembedRes('carol', 'gm'))
+ .mockResolvedValueOnce(quoteRes(10000, 50_000_000_000))
+ .mockResolvedValueOnce(quoteRes(10000, 50_000_000_000));
+
+ const r = await correlateXPost({
+ postUrl: `https://x.com/carol/status/${id}`,
+ mint: 'ValidMintAddress',
+ });
+
+ expect(r.post?.id).toBe(id);
+ expect(typeof r.post?.ts).toBe('number');
+ expect(r.post.ts).toBeGreaterThan(0);
+ });
+});