Skip to content

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

feat: add KOL trades API and widget, implement watch whales functionality

nirholas23e77bfbf191
diff --git a/api/kol/trades.js b/api/kol/trades.js
new file mode 100644
index 000000000..b9610836a
--- /dev/null
+++ b/api/kol/trades.js
@@ -0,0 +1,30 @@
+// GET /api/kol/trades?mint=<mint>&limit=<n>
+//
+// Returns recent trades for a Solana token mint filtered to smart-money wallets.
+// Wallet qualification rule: minimum $10 000 cumulative realised P&L (see
+// src/kol/wallets.js).
+//
+// TODO: wire up a real trade source (Helius enriched-transactions, Birdeye,
+// or a self-hosted indexer). Today the trades array is always empty.
+
+import { cors, error, json, method, wrap } from '../_lib/http.js';
+import { KOL_WALLETS } from '../../src/kol/wallets.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const url = new URL(req.url, 'http://x');
+ const mint = url.searchParams.get('mint');
+ const limit = Math.min(100, Math.max(1, Number(url.searchParams.get('limit') || '20')));
+
+ if (!mint) return error(res, 400, 'validation_error', 'mint is required');
+
+ // TODO: query enriched transactions for `mint` from indexer, filter to
+ // KOL_WALLETS addresses, map to the trade shape below.
+ // Trade shape: { time: ISO8601, side: 'buy'|'sell', wallet: string,
+ // usd: number, source: 'kol'|'whale'|'smart-money' }
+ const trades = [];
+
+ return json(res, 200, { mint, trades, wallets: KOL_WALLETS.length });
+});
diff --git a/src/pump/first-claims.js b/src/pump/first-claims.js
new file mode 100644
index 000000000..a299ff0b7
--- /dev/null
+++ b/src/pump/first-claims.js
@@ -0,0 +1,57 @@
+/**
+ * pump/first-claims.js
+ * ---------------------
+ * First-time creator fee claim data.
+ *
+ * Exports:
+ * filterFirstClaims(allClaims, sinceTs, limit) — pure dedupe, no I/O
+ * fetchFirstClaims({ sinceTs, limit }) — browser fetch → API
+ *
+ * "First-time" means the creator has no observed claim before sinceTs.
+ * allClaims must span a wider lookback window so prior claimers are visible.
+ */
+
+const API_PATH = '/api/pump/first-claims';
+
+/**
+ * Pure dedupe: from a flat list of claims spanning a wide lookback window,
+ * return only first-time claimers — creators whose earliest observed claim
+ * falls at or after sinceTs (i.e. they have no prior claim in the dataset).
+ *
+ * @param {Array<{creator:string, mint:string, signature:string, lamports:number, ts:number}>} allClaims
+ * @param {number} sinceTs Unix seconds — boundary for "prior claim"
+ * @param {number} [limit]
+ * @returns {Array<{creator, mint, signature, lamports, ts}>} newest first
+ */
+export function filterFirstClaims(allClaims, sinceTs, limit = 50) {
+ // Find each creator's earliest observed claim across the full dataset.
+ const earliest = new Map();
+ for (const c of allClaims) {
+ const prev = earliest.get(c.creator);
+ if (!prev || c.ts < prev.ts) earliest.set(c.creator, c);
+ }
+
+ const result = [];
+ for (const firstClaim of earliest.values()) {
+ // Exclude if the earliest claim predates sinceTs — they've claimed before.
+ if (firstClaim.ts >= sinceTs) result.push(firstClaim);
+ }
+
+ return result.sort((a, b) => b.ts - a.ts).slice(0, limit);
+}
+
+/**
+ * Browser entry point. Calls GET /api/pump/first-claims and returns
+ * { items: [...] }.
+ *
+ * @param {{ sinceTs: number, limit?: number }} opts
+ */
+export async function fetchFirstClaims({ sinceTs, limit = 50 }) {
+ const params = new URLSearchParams({
+ sinceTs: String(sinceTs),
+ limit: String(Math.min(50, Math.max(1, limit))),
+ });
+ const r = await fetch(`${API_PATH}?${params}`, { credentials: 'include' });
+ if (!r.ok) throw new Error(`first-claims: ${r.status}`);
+ return r.json();
+}
diff --git a/src/pump/pump-swap-quote.js b/src/pump/pump-swap-quote.js
new file mode 100644
index 000000000..2c0ba1cb4
--- /dev/null
+++ b/src/pump/pump-swap-quote.js
@@ -0,0 +1,123 @@
+/**
+ * Read-only AMM swap quote using @pump-fun/pump-swap-sdk.
+ * No signing, no transaction sending.
+ */
+
+import { SOLANA_RPC } from '../erc8004/solana-deploy.js';
+
+const WSOL = 'So11111111111111111111111111111111111111112';
+const QUOTE_TTL_MS = 10_000;
+
+// Module cache — loaded once, reused across calls.
+let _mods = null;
+
+async function loadMods() {
+ if (!_mods) {
+ const [amm, web3, BNMod] = await Promise.all([
+ import('@pump-fun/pump-swap-sdk'),
+ import('@solana/web3.js'),
+ import('bn.js'),
+ ]);
+ _mods = { amm, web3, BN: BNMod.default || BNMod };
+ }
+ return _mods;
+}
+
+/**
+ * Get a read-only price quote for a pump AMM swap.
+ *
+ * @param {object} opts
+ * @param {string} opts.inputMint Base58 mint address. One side must be wSOL.
+ * @param {string} opts.outputMint Base58 mint address.
+ * @param {number|string} opts.amountIn Input amount in raw base units (lamports for SOL).
+ * @param {number} [opts.slippageBps=100]
+ * @returns {Promise<{amountOut: string, priceImpactBps: number, route: string, expiresAtMs: number}>}
+ */
+export async function quoteSwap({ inputMint, outputMint, amountIn, slippageBps = 100 }) {
+ const { amm, web3, BN } = await loadMods();
+ const { canonicalPumpPoolPda, OnlinePumpAmmSdk, buyQuoteInput, sellBaseInput } = amm;
+ const { Connection, PublicKey } = web3;
+
+ let inputPk, outputPk;
+ try {
+ inputPk = new PublicKey(inputMint);
+ } catch {
+ throw new Error(`Invalid inputMint: ${inputMint}`);
+ }
+ try {
+ outputPk = new PublicKey(outputMint);
+ } catch {
+ throw new Error(`Invalid outputMint: ${outputMint}`);
+ }
+
+ const amountBn = new BN(String(amountIn));
+
+ // wSOL is always the quote token in canonical pump AMM pools.
+ let baseMintPk, direction;
+ if (inputMint === WSOL) {
+ baseMintPk = outputPk;
+ direction = 'quoteToBase';
+ } else if (outputMint === WSOL) {
+ baseMintPk = inputPk;
+ direction = 'baseToQuote';
+ } else {
+ throw new Error(`One of inputMint or outputMint must be wSOL (${WSOL})`);
+ }
+
+ const connection = new Connection(SOLANA_RPC.mainnet, 'confirmed');
+ const sdk = new OnlinePumpAmmSdk(connection);
+ const poolKey = canonicalPumpPoolPda(baseMintPk);
+
+ let state;
+ try {
+ // SystemProgram as dummy user — user ATAs will be null, which is fine for quoting.
+ state = await sdk.swapSolanaState(poolKey, new PublicKey('11111111111111111111111111111111'));
+ } catch (err) {
+ throw new Error(`Pool unavailable for ${baseMintPk.toBase58()}: ${err.message}`);
+ }
+
+ const { globalConfig, feeConfig, pool, poolBaseAmount, poolQuoteAmount, baseMintAccount } = state;
+ const slippage = slippageBps / 10_000;
+ const shared = {
+ slippage,
+ baseReserve: poolBaseAmount,
+ quoteReserve: poolQuoteAmount,
+ globalConfig,
+ baseMintAccount,
+ baseMint: pool.baseMint,
+ coinCreator: pool.coinCreator,
+ creator: pool.creator,
+ feeConfig,
+ };
+
+ let amountOut, priceImpactBps;
+
+ if (direction === 'quoteToBase') {
+ const result = buyQuoteInput({ quote: amountBn, ...shared });
+ amountOut = result.base;
+ // impact = (execPrice / spotPrice − 1) × 10000
+ // execPrice = amountIn / amountOut; spotPrice = quoteReserve / baseReserve
+ const num = amountBn.mul(poolBaseAmount);
+ const denom = amountOut.mul(poolQuoteAmount);
+ priceImpactBps = denom.isZero()
+ ? 0
+ : Math.max(0, num.muln(10_000).div(denom).subn(10_000).toNumber());
+ } else {
+ const result = sellBaseInput({ base: amountBn, ...shared });
+ amountOut = result.uiQuote;
+ // impact = (1 − execPrice / spotPrice) × 10000
+ // spotPrice = quoteReserve / baseReserve; execPrice = amountOut / amountIn
+ const spot = poolQuoteAmount.mul(amountBn);
+ const exec = amountOut.mul(poolBaseAmount);
+ 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() + QUOTE_TTL_MS,
+ };
+}
diff --git a/src/widgets/kol-trades.js b/src/widgets/kol-trades.js
new file mode 100644
index 000000000..af95301fe
--- /dev/null
+++ b/src/widgets/kol-trades.js
@@ -0,0 +1,209 @@
+/**
+ * KOL / smart-money trades widget.
+ *
+ * Polls GET /api/kol/trades?mint=…&limit=… every `refreshMs` and renders a
+ * table of buy/sell events from tracked wallets.
+ *
+ * Exported functions:
+ * renderTrades(trades) — pure, returns HTML string (testable in node)
+ * mountKolTradesWidget(root, opts) — full mount with polling + cleanup
+ *
+ * The <three-ws-widget type="kol-trades" mint="…"> custom element is registered
+ * at the bottom of this file when running in a browser.
+ */
+
+const SOURCE_BADGE = {
+ kol: { label: 'KOL', color: '#a78bfa' },
+ whale: { label: 'Whale', color: '#60a5fa' },
+ 'smart-money': { label: 'Smart $', color: '#34d399' },
+};
+
+const STYLES = `
+.kol-trades {
+ font: 13px/1.5 ui-sans-serif, system-ui, -apple-system, sans-serif;
+ color: #e5e5e5;
+ padding: 0.75rem 0;
+}
+.kol-trades-head {
+ font-size: 0.7rem; letter-spacing: 0.06em; text-transform: uppercase;
+ color: rgba(255,255,255,0.45); margin-bottom: 0.5rem; padding: 0 0.5rem;
+}
+.kol-trades-row {
+ display: grid;
+ grid-template-columns: 3.5rem 2.5rem 1fr 4rem 4rem;
+ align-items: center; gap: 0.4rem;
+ padding: 0.3rem 0.5rem; border-radius: 6px;
+ transition: background 0.1s;
+}
+.kol-trades-row:hover { background: rgba(255,255,255,0.04); }
+.kol-trades-time { font-size: 0.7rem; color: rgba(255,255,255,0.4); font-variant-numeric: tabular-nums; }
+.kol-trades-side { font-size: 0.75rem; font-weight: 600; }
+.kol-trades-wallet {
+ font-family: ui-monospace, monospace; font-size: 0.72rem;
+ color: rgba(180,210,255,0.75); text-decoration: none; overflow: hidden; text-overflow: ellipsis;
+}
+.kol-trades-wallet:hover { color: rgba(180,210,255,1); text-decoration: underline; }
+.kol-trades-usd { font-size: 0.78rem; text-align: right; font-variant-numeric: tabular-nums; }
+.kol-trades-tag {
+ font-size: 0.65rem; font-weight: 600; letter-spacing: 0.04em;
+ text-align: right; text-transform: uppercase;
+}
+.kol-trades-empty {
+ text-align: center; padding: 1.5rem 0.5rem;
+ color: rgba(255,255,255,0.4); font-size: 0.82rem;
+}
+`;
+
+let _stylesInjected = false;
+function injectStyles(doc) {
+ if (_stylesInjected) return;
+ _stylesInjected = true;
+ const tag = doc.createElement('style');
+ tag.textContent = STYLES;
+ doc.head.appendChild(tag);
+}
+
+function shortAddr(s, n = 4) {
+ if (!s || s.length < n * 2 + 1) return s || '';
+ return `${s.slice(0, n)}…${s.slice(-n)}`;
+}
+
+function timeAgo(iso) {
+ if (!iso) return '';
+ const ms = Date.now() - new Date(iso).getTime();
+ if (ms < 60_000) return `${Math.max(1, Math.floor(ms / 1000))}s`;
+ if (ms < 3_600_000) return `${Math.floor(ms / 60_000)}m`;
+ if (ms < 86_400_000) return `${Math.floor(ms / 3_600_000)}h`;
+ return `${Math.floor(ms / 86_400_000)}d`;
+}
+
+function fmtUsd(n) {
+ if (n == null) return '—';
+ const v = Number(n);
+ if (v >= 1_000_000) return `$${(v / 1_000_000).toFixed(2)}M`;
+ if (v >= 1_000) return `$${(v / 1_000).toFixed(1)}K`;
+ return `$${v.toFixed(2)}`;
+}
+
+function escHtml(s) {
+ return String(s ?? '').replace(/[&<>"']/g, (c) =>
+ ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]),
+ );
+}
+
+function rowHtml(trade) {
+ const side = trade.side === 'buy' ? 'buy' : 'sell';
+ const sideColor = side === 'buy' ? '#34d399' : '#f87171';
+ const sideLabel = side === 'buy' ? 'Buy' : 'Sell';
+ const solscanUrl = `https://solscan.io/account/${escHtml(trade.wallet)}`;
+ const badge = SOURCE_BADGE[trade.source] || SOURCE_BADGE['smart-money'];
+ return `<div class="kol-trades-row">
+ <span class="kol-trades-time">${escHtml(timeAgo(trade.time))}</span>
+ <span class="kol-trades-side" style="color:${sideColor}">${sideLabel}</span>
+ <a class="kol-trades-wallet" href="${solscanUrl}" target="_blank" rel="noopener noreferrer">${escHtml(shortAddr(trade.wallet))}</a>
+ <span class="kol-trades-usd">${escHtml(fmtUsd(trade.usd))}</span>
+ <span class="kol-trades-tag" style="color:${badge.color}">${escHtml(badge.label)}</span>
+ </div>`;
+}
+
+/** Pure renderer — returns an HTML string. Exported for unit testing. */
+export function renderTrades(trades) {
+ if (!trades || trades.length === 0) {
+ return '<div class="kol-trades-empty">No smart-money activity yet for this token.</div>';
+ }
+ return `<div class="kol-trades-head">Smart Money</div>${trades.map(rowHtml).join('')}`;
+}
+
+/**
+ * Mount the KOL trades widget inside `rootEl`.
+ * @param {HTMLElement} rootEl
+ * @param {{ mint?: string, limit?: number, refreshMs?: number }} opts
+ * @returns {{ destroy(): void }}
+ */
+export function mountKolTradesWidget(rootEl, opts = {}) {
+ const mint = opts.mint || '';
+ const limit = Number(opts.limit ?? 20);
+ const refreshMs = Number(opts.refreshMs ?? 30_000);
+
+ const doc = rootEl.ownerDocument ?? (typeof document !== 'undefined' ? document : null);
+ if (!doc) return { destroy() {} };
+
+ injectStyles(doc);
+
+ const container = doc.createElement('div');
+ container.className = 'kol-trades';
+ rootEl.appendChild(container);
+
+ let timer = null;
+ let destroyed = false;
+
+ async function poll() {
+ if (destroyed) return;
+ if (!mint) {
+ container.innerHTML = renderTrades([]);
+ return;
+ }
+ try {
+ const resp = await fetch(
+ `/api/kol/trades?mint=${encodeURIComponent(mint)}&limit=${limit}`,
+ );
+ if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
+ const data = await resp.json();
+ if (!destroyed) container.innerHTML = renderTrades(data.trades ?? []);
+ } catch {
+ // silent — no unhandled rejection on unmount / network failure
+ }
+ }
+
+ poll();
+ timer = setInterval(poll, refreshMs);
+
+ return {
+ destroy() {
+ destroyed = true;
+ if (timer) clearInterval(timer);
+ container.remove();
+ },
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Standalone custom element — registered when running in a browser.
+// ---------------------------------------------------------------------------
+if (typeof customElements !== 'undefined' && !customElements.get('three-ws-widget')) {
+ customElements.define(
+ 'three-ws-widget',
+ class ThreeWsWidget extends HTMLElement {
+ static get observedAttributes() {
+ return ['type', 'mint', 'limit', 'refresh-ms'];
+ }
+
+ connectedCallback() {
+ this._mount();
+ }
+
+ disconnectedCallback() {
+ this._ctrl?.destroy();
+ this._ctrl = null;
+ }
+
+ attributeChangedCallback() {
+ if (this.isConnected) {
+ this._ctrl?.destroy();
+ this._ctrl = null;
+ this._mount();
+ }
+ }
+
+ _mount() {
+ const type = this.getAttribute('type');
+ if (type !== 'kol-trades') return;
+ this._ctrl = mountKolTradesWidget(this, {
+ mint: this.getAttribute('mint') || '',
+ limit: Number(this.getAttribute('limit') || '20'),
+ refreshMs: Number(this.getAttribute('refresh-ms') || '30000'),
+ });
+ }
+ },
+ );
+}
diff --git a/tests/carbon-graduations.test.js b/tests/carbon-graduations.test.js
new file mode 100644
index 000000000..f7ec927ce
--- /dev/null
+++ b/tests/carbon-graduations.test.js
@@ -0,0 +1,135 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import bs58 from 'bs58';
+import { CarbonGraduationSource } from '../services/pump-graduations/carbon-source.js';
+
+// ── helpers ───────────────────────────────────────────────────────────────────
+
+const COMPLETE_EVENT_DISCRIMINATOR = Buffer.from([95, 114, 97, 156, 212, 46, 152, 8]);
+
+// Build a minimal valid CompleteEvent log entry.
+// Layout: discriminator(8) user(32) mint(32) bondingCurve(32) timestamp(i64)
+function makeGraduationEntry(mint32Bytes, ts, sig = 'testsig123') {
+ const buf = Buffer.alloc(112);
+ COMPLETE_EVENT_DISCRIMINATOR.copy(buf, 0);
+ // user: bytes 8–39 (zeros — any pubkey)
+ mint32Bytes.copy(buf, 40);
+ // bondingCurve: bytes 72–103 (zeros)
+ buf.writeBigInt64LE(BigInt(ts), 104);
+ return {
+ signature: sig,
+ err: null,
+ logs: [`Program data: ${buf.toString('base64')}`],
+ };
+}
+
+// A well-known 32-byte Solana pubkey used as a mock mint
+const MOCK_MINT_BYTES = Buffer.from(bs58.decode('So11111111111111111111111111111111111111112'));
+const MOCK_MINT = 'So11111111111111111111111111111111111111112';
+const MOCK_SIG = 'testSig1111111111111111111111111111111111111111111111111111111111';
+const MOCK_TS = 1_700_000_000;
+
+// ── tests ─────────────────────────────────────────────────────────────────────
+
+describe('CarbonGraduationSource', () => {
+ let capturedHandler;
+ let mockSubscriber;
+
+ beforeEach(() => {
+ capturedHandler = null;
+ mockSubscriber = vi.fn((programId, handler) => {
+ capturedHandler = handler;
+ return 42; // subscription id
+ });
+ });
+
+ it('calls logSubscriber with the pump program id on start', () => {
+ const src = new CarbonGraduationSource({ logSubscriber: mockSubscriber });
+ src.start(vi.fn());
+ expect(mockSubscriber).toHaveBeenCalledOnce();
+ const [programId] = mockSubscriber.mock.calls[0];
+ expect(programId.toBase58()).toBe('6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P');
+ });
+
+ it('emits graduation event with correct shape on valid log entry', () => {
+ const onGraduation = vi.fn();
+ const src = new CarbonGraduationSource({ logSubscriber: mockSubscriber });
+ src.start(onGraduation);
+
+ capturedHandler(makeGraduationEntry(MOCK_MINT_BYTES, MOCK_TS, MOCK_SIG));
+
+ expect(onGraduation).toHaveBeenCalledOnce();
+ expect(onGraduation.mock.calls[0][0]).toEqual({
+ mint: MOCK_MINT,
+ signature: MOCK_SIG,
+ ts: MOCK_TS,
+ marketCapUsd: null,
+ });
+ });
+
+ it('emitted event shape matches legacy source fields: mint, signature, ts, marketCapUsd', () => {
+ const onGraduation = vi.fn();
+ const src = new CarbonGraduationSource({ logSubscriber: mockSubscriber });
+ src.start(onGraduation);
+ capturedHandler(makeGraduationEntry(MOCK_MINT_BYTES, MOCK_TS, MOCK_SIG));
+
+ const ev = onGraduation.mock.calls[0][0];
+ expect(ev).toHaveProperty('mint');
+ expect(ev).toHaveProperty('signature');
+ expect(ev).toHaveProperty('ts');
+ expect(ev).toHaveProperty('marketCapUsd');
+ expect(typeof ev.mint).toBe('string');
+ expect(typeof ev.signature).toBe('string');
+ expect(typeof ev.ts).toBe('number');
+ });
+
+ it('ignores entries with err set', () => {
+ const onGraduation = vi.fn();
+ const src = new CarbonGraduationSource({ logSubscriber: mockSubscriber });
+ src.start(onGraduation);
+
+ const entry = makeGraduationEntry(MOCK_MINT_BYTES, MOCK_TS, MOCK_SIG);
+ entry.err = { InstructionError: [0, 'Custom'] };
+ capturedHandler(entry);
+
+ expect(onGraduation).not.toHaveBeenCalled();
+ });
+
+ it('ignores entries without Program data log lines', () => {
+ const onGraduation = vi.fn();
+ const src = new CarbonGraduationSource({ logSubscriber: mockSubscriber });
+ src.start(onGraduation);
+
+ capturedHandler({ signature: MOCK_SIG, err: null, logs: ['Program log: some other log'] });
+
+ expect(onGraduation).not.toHaveBeenCalled();
+ });
+
+ it('ignores duplicate signatures', () => {
+ const onGraduation = vi.fn();
+ const src = new CarbonGraduationSource({ logSubscriber: mockSubscriber });
+ src.start(onGraduation);
+
+ const entry = makeGraduationEntry(MOCK_MINT_BYTES, MOCK_TS, MOCK_SIG);
+ capturedHandler(entry);
+ capturedHandler(entry);
+
+ expect(onGraduation).toHaveBeenCalledOnce();
+ });
+
+ it('ignores Program data with wrong discriminator', () => {
+ const onGraduation = vi.fn();
+ const src = new CarbonGraduationSource({ logSubscriber: mockSubscriber });
+ src.start(onGraduation);
+
+ const buf = Buffer.alloc(112);
+ // discriminator bytes intentionally wrong
+ buf[0] = 0xff;
+ capturedHandler({
+ signature: MOCK_SIG,
+ err: null,
+ logs: [`Program data: ${buf.toString('base64')}`],
+ });
+
+ expect(onGraduation).not.toHaveBeenCalled();
+ });
+});
diff --git a/tests/pumpkit-whale.test.js b/tests/pumpkit-whale.test.js
new file mode 100644
index 000000000..f4a7ccab1
--- /dev/null
+++ b/tests/pumpkit-whale.test.js
@@ -0,0 +1,193 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// vi.hoisted creates variables before the mock factories run (needed because
+// vi.mock is hoisted above import statements).
+const state = vi.hoisted(() => ({
+ logCallback: null,
+ fakeEvents: [],
+}));
+
+vi.mock('@solana/web3.js', () => ({
+ Connection: vi.fn(() => ({
+ onLogs: vi.fn((_, cb) => {
+ state.logCallback = cb;
+ return 1; // subscription id
+ }),
+ removeOnLogsListener: vi.fn().mockResolvedValue(undefined),
+ })),
+ PublicKey: vi.fn((s) => ({
+ toString: () => s,
+ toBase58: () => s,
+ })),
+}));
+
+vi.mock('@coral-xyz/anchor', () => ({
+ BorshCoder: vi.fn(() => ({})),
+ EventParser: vi.fn(() => ({
+ parseLogs: vi.fn(() => state.fakeEvents),
+ })),
+}));
+
+vi.mock('@nirholas/pump-sdk', () => ({
+ PUMP_PROGRAM_ID: { toString: () => '6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P' },
+ pumpIdl: {},
+}));
+
+globalThis.fetch = vi.fn().mockResolvedValue({
+ json: () =>
+ Promise.resolve({
+ data: { So11111111111111111111111111111111111111112: { price: 100 } },
+ }),
+});
+
+const { watchWhaleTrades } = await import('../src/pump/pumpkit-whale.js');
+
+function makeTrade(mintStr, solLamports, isBuy = true) {
+ return {
+ name: 'TradeEvent',
+ data: {
+ mint: { toString: () => mintStr },
+ isBuy,
+ solAmount: { toString: () => String(solLamports) },
+ user: { toString: () => 'wallet1234567890' },
+ timestamp: { toString: () => '1700000000' },
+ },
+ };
+}
+
+const MINT = 'TESTMINT1111111111111111111111111111111111';
+
+describe('watchWhaleTrades', () => {
+ beforeEach(() => {
+ state.logCallback = null;
+ state.fakeEvents = [];
+ });
+
+ function fireLog(signature = 'sig1') {
+ state.logCallback?.({ signature, logs: [], err: null });
+ }
+
+ it('calls onTrade for trades >= minUsd', async () => {
+ const trades = [];
+ const ac = new AbortController();
+
+ // 60 SOL × $100/SOL = $6000 ≥ $5000
+ state.fakeEvents = [makeTrade(MINT, 60_000_000_000)];
+
+ await watchWhaleTrades({ mint: MINT, minUsd: 5000, onTrade: (t) => trades.push(t), signal: ac.signal });
+
+ fireLog();
+
+ expect(trades).toHaveLength(1);
+ expect(trades[0].usd).toBeGreaterThanOrEqual(5000);
+ expect(trades[0].sideBuy).toBe(true);
+ expect(trades[0].signature).toBe('sig1');
+ expect(trades[0].sol).toBeCloseTo(60);
+
+ ac.abort();
+ });
+
+ it('skips trades below minUsd', async () => {
+ const trades = [];
+ const ac = new AbortController();
+
+ // 0.01 SOL × $100 = $1 < $5000
+ state.fakeEvents = [makeTrade(MINT, 10_000_000)];
+
+ await watchWhaleTrades({ mint: MINT, minUsd: 5000, onTrade: (t) => trades.push(t), signal: ac.signal });
+
+ fireLog();
+
+ expect(trades).toHaveLength(0);
+
+ ac.abort();
+ });
+
+ it('skips TradeEvents for a different mint', async () => {
+ const trades = [];
+ const ac = new AbortController();
+
+ state.fakeEvents = [makeTrade('OTHERMINT1111111111111111111111111111111111', 60_000_000_000)];
+
+ await watchWhaleTrades({ mint: MINT, minUsd: 5000, onTrade: (t) => trades.push(t), signal: ac.signal });
+
+ fireLog();
+
+ expect(trades).toHaveLength(0);
+
+ ac.abort();
+ });
+
+ it('skips errored log entries', async () => {
+ const trades = [];
+ const ac = new AbortController();
+
+ state.fakeEvents = [makeTrade(MINT, 60_000_000_000)];
+
+ await watchWhaleTrades({ mint: MINT, minUsd: 5000, onTrade: (t) => trades.push(t), signal: ac.signal });
+
+ // Simulate a log with an error — should be ignored
+ state.logCallback?.({ signature: 'sig1', logs: [], err: new Error('rpc error') });
+
+ expect(trades).toHaveLength(0);
+
+ ac.abort();
+ });
+
+ it('skips non-TradeEvent Anchor events', async () => {
+ const trades = [];
+ const ac = new AbortController();
+
+ state.fakeEvents = [{ name: 'CreateEvent', data: {} }];
+
+ await watchWhaleTrades({ mint: MINT, minUsd: 5000, onTrade: (t) => trades.push(t), signal: ac.signal });
+
+ fireLog();
+
+ expect(trades).toHaveLength(0);
+
+ ac.abort();
+ });
+
+ it('calls onTrade for sell trades that meet minUsd', async () => {
+ const trades = [];
+ const ac = new AbortController();
+
+ state.fakeEvents = [makeTrade(MINT, 100_000_000_000, false)]; // 100 SOL sell
+
+ await watchWhaleTrades({ mint: MINT, minUsd: 5000, onTrade: (t) => trades.push(t), signal: ac.signal });
+
+ fireLog();
+
+ expect(trades).toHaveLength(1);
+ expect(trades[0].sideBuy).toBe(false);
+ expect(trades[0].usd).toBeGreaterThanOrEqual(5000);
+
+ ac.abort();
+ });
+
+ it('does not fire after abort', async () => {
+ const trades = [];
+ const ac = new AbortController();
+
+ state.fakeEvents = [makeTrade(MINT, 60_000_000_000)];
+
+ await watchWhaleTrades({ mint: MINT, minUsd: 5000, onTrade: (t) => trades.push(t), signal: ac.signal });
+
+ ac.abort();
+ fireLog(); // fires after abort
+
+ expect(trades).toHaveLength(0);
+ });
+
+ it('cleans up the onLogs listener on abort', async () => {
+ const { Connection } = await import('@solana/web3.js');
+ const mockInstance = new Connection();
+
+ const ac = new AbortController();
+ await watchWhaleTrades({ mint: MINT, minUsd: 5000, onTrade: () => {}, signal: ac.signal });
+ ac.abort();
+
+ expect(mockInstance.removeOnLogsListener).toHaveBeenCalled();
+ });
+});
diff --git a/tests/studio-launch-panel.test.js b/tests/studio-launch-panel.test.js
new file mode 100644
index 000000000..c6319725c
--- /dev/null
+++ b/tests/studio-launch-panel.test.js
@@ -0,0 +1,102 @@
+import { describe, it, expect, vi } from 'vitest';
+import { validateLaunchForm, handleLaunchSubmit } from '../public/studio/launch-panel.js';
+
+const VALID = { name: 'My Token', symbol: 'MTK', description: 'A test token', initialBuy: '0.5', feeTier: 'standard' };
+
+describe('validateLaunchForm — required fields', () => {
+ it('fails when name is empty', () => {
+ const { ok, errors } = validateLaunchForm({ ...VALID, name: '' });
+ expect(ok).toBe(false);
+ expect(errors.name).toBeTruthy();
+ });
+
+ it('fails when name is whitespace only', () => {
+ const { ok, errors } = validateLaunchForm({ ...VALID, name: ' ' });
+ expect(ok).toBe(false);
+ expect(errors.name).toBeTruthy();
+ });
+
+ it('fails when symbol is empty', () => {
+ const { ok, errors } = validateLaunchForm({ ...VALID, symbol: '' });
+ expect(ok).toBe(false);
+ expect(errors.symbol).toBeTruthy();
+ });
+
+ it('fails when description is empty', () => {
+ const { ok, errors } = validateLaunchForm({ ...VALID, description: '' });
+ expect(ok).toBe(false);
+ expect(errors.description).toBeTruthy();
+ });
+
+ it('fails all three required fields at once', () => {
+ const { ok, errors } = validateLaunchForm({ name: '', symbol: '', description: '' });
+ expect(ok).toBe(false);
+ expect(errors.name).toBeTruthy();
+ expect(errors.symbol).toBeTruthy();
+ expect(errors.description).toBeTruthy();
+ });
+
+ it('passes when all required fields are filled', () => {
+ const { ok, errors } = validateLaunchForm(VALID);
+ expect(ok).toBe(true);
+ expect(Object.keys(errors)).toHaveLength(0);
+ });
+});
+
+describe('validateLaunchForm — initialBuy', () => {
+ it('rejects a negative initialBuy', () => {
+ const { ok, errors } = validateLaunchForm({ ...VALID, initialBuy: '-1' });
+ expect(ok).toBe(false);
+ expect(errors.initialBuy).toBeTruthy();
+ });
+
+ it('accepts zero initialBuy', () => {
+ const { ok } = validateLaunchForm({ ...VALID, initialBuy: '0' });
+ expect(ok).toBe(true);
+ });
+
+ it('accepts a positive initialBuy', () => {
+ const { ok } = validateLaunchForm({ ...VALID, initialBuy: '2.5' });
+ expect(ok).toBe(true);
+ });
+
+ it('accepts an absent initialBuy (optional field)', () => {
+ const { name, symbol, description, feeTier } = VALID;
+ const { ok } = validateLaunchForm({ name, symbol, description, feeTier });
+ expect(ok).toBe(true);
+ });
+
+ it('rejects a non-numeric initialBuy', () => {
+ const { ok, errors } = validateLaunchForm({ ...VALID, initialBuy: 'abc' });
+ expect(ok).toBe(false);
+ expect(errors.initialBuy).toBeTruthy();
+ });
+});
+
+describe('handleLaunchSubmit', () => {
+ it('calls onSubmit with fields when valid', () => {
+ const handler = vi.fn();
+ const result = handleLaunchSubmit(VALID, handler);
+ expect(result.ok).toBe(true);
+ expect(handler).toHaveBeenCalledOnce();
+ expect(handler).toHaveBeenCalledWith(VALID);
+ });
+
+ it('does not call onSubmit when name is missing', () => {
+ const handler = vi.fn();
+ handleLaunchSubmit({ ...VALID, name: '' }, handler);
+ expect(handler).not.toHaveBeenCalled();
+ });
+
+ it('does not call onSubmit when symbol is missing', () => {
+ const handler = vi.fn();
+ handleLaunchSubmit({ ...VALID, symbol: '' }, handler);
+ expect(handler).not.toHaveBeenCalled();
+ });
+
+ it('returns validation errors when form is invalid', () => {
+ const result = handleLaunchSubmit({ name: '', symbol: 'X', description: 'desc' }, () => {});
+ expect(result.ok).toBe(false);
+ expect(result.errors.name).toBeTruthy();
+ });
+});
diff --git a/workers/pump-fun-mcp/README.md b/workers/pump-fun-mcp/README.md
new file mode 100644
index 000000000..b35324f90
--- /dev/null
+++ b/workers/pump-fun-mcp/README.md
@@ -0,0 +1 @@
+Mirror of `/api/pump-fun-mcp`. Deploy: `wrangler deploy`
diff --git a/workers/pump-fun-mcp/wrangler.toml b/workers/pump-fun-mcp/wrangler.toml
new file mode 100644
index 000000000..402adc09c
--- /dev/null
+++ b/workers/pump-fun-mcp/wrangler.toml
@@ -0,0 +1,10 @@
+name = "pump-fun-mcp"
+main = "worker.js"
+compatibility_date = "2025-01-15"
+compatibility_flags = ["nodejs_compat"]
+
+# Secrets — set with: wrangler secret put <NAME>
+# SOLANA_RPC_URL mainnet RPC (default: public endpoint)
+# SOLANA_RPC_URL_DEVNET devnet RPC (default: public endpoint)
+# PUMPFUN_BOT_URL upstream indexer MCP endpoint (optional)
+# PUMPFUN_BOT_TOKEN bearer token for indexer (optional)