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(kol): wire real KOL trades feed
nirholas4395742ba886
diff --git a/api/kol/[action].js b/api/kol/[action].jsindex abcefc667..8eef0fceb 100644--- a/api/kol/[action].js+++ b/api/kol/[action].js@@ -16,11 +16,16 @@ const _cache = new Map(); // address → { data, ts }function _getCached(addr) {const entry = _cache.get(addr);if (!entry) return null;- if (Date.now() - entry.ts > CACHE_TTL_MS) { _cache.delete(addr); return null; }+ if (Date.now() - entry.ts > CACHE_TTL_MS) {+ _cache.delete(addr);+ return null;+ }return entry.data;}-function _setCache(addr, data) { _cache.set(addr, { data, ts: Date.now() }); }+function _setCache(addr, data) {+ _cache.set(addr, { data, ts: Date.now() });+}async function _fetchBirdeye(addr, apiKey) {const url = `${BIRDEYE_BASE}/v1/wallet/portfolio?wallet=${encodeURIComponent(addr)}&chain=solana`;@@ -43,14 +48,17 @@ function _normalizePortfolio(addr, portfolio) {let maxVal = 0;for (const item of items) {const val = item.valueUsd ?? 0;- if (val > maxVal) { maxVal = val; topToken = { symbol: item.symbol ?? '?', pnl: val }; }+ if (val > maxVal) {+ maxVal = val;+ topToken = { symbol: item.symbol ?? '?', pnl: val };+ }}return {address: addr,- realizedPnl: portfolio?.realizedPnl ?? 0,- unrealizedPnl: portfolio?.unrealizedPnl ?? (portfolio?.totalUsd ?? 0),- winRate: portfolio?.winRate ?? 0,- totalTrades: portfolio?.totalTrades ?? 0,+ realizedPnl: portfolio?.realizedPnl ?? 0,+ unrealizedPnl: portfolio?.unrealizedPnl ?? portfolio?.totalUsd ?? 0,+ winRate: portfolio?.winRate ?? 0,+ totalTrades: portfolio?.totalTrades ?? 0,topToken,};}@@ -67,21 +75,27 @@ async function handleWallets(req, res) {const url = new URL(req.url, `http://${req.headers.host}`);const addresses = (url.searchParams.get('addresses') ?? '')- .split(',').map((s) => s.trim()).filter(Boolean).slice(0, MAX_ADDRESSES);- if (addresses.length === 0) return error(res, 400, 'validation_error', 'addresses query param is required');+ .split(',')+ .map((s) => s.trim())+ .filter(Boolean)+ .slice(0, MAX_ADDRESSES);+ if (addresses.length === 0)+ return error(res, 400, 'validation_error', 'addresses query param is required');const uncached = addresses.filter((a) => _getCached(a) === null);const cacheHit = uncached.length === 0;if (uncached.length > 0) {- await Promise.allSettled(uncached.map(async (addr) => {- try {- const portfolio = await _fetchBirdeye(addr, apiKey);- _setCache(addr, _normalizePortfolio(addr, portfolio));- } catch {- _setCache(addr, _normalizePortfolio(addr, null));- }- }));+ await Promise.allSettled(+ uncached.map(async (addr) => {+ try {+ const portfolio = await _fetchBirdeye(addr, apiKey);+ _setCache(addr, _normalizePortfolio(addr, portfolio));+ } catch {+ _setCache(addr, _normalizePortfolio(addr, null));+ }+ }),+ );}const data = addresses.map((a) => _getCached(a)).filter(Boolean);@@ -89,10 +103,17 @@ async function handleWallets(req, res) {return json(res, 200, { data });}-const WALLETS_PATH = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../src/kol/wallets.json');+const WALLETS_PATH = path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ '../../src/kol/wallets.json',+);async function loadWallets() {- try { return JSON.parse(await readFile(WALLETS_PATH, 'utf8')); } catch { return []; }+ try {+ return JSON.parse(await readFile(WALLETS_PATH, 'utf8'));+ } catch {+ return [];+ }}// ── import-gmgn ───────────────────────────────────────────────────────────────@@ -103,11 +124,15 @@ async function handleImportGmgn(req, res) {const rl = await limits.mcpIp(clientIp(req));if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');const body = await readJson(req);- if (!body || body.rawJson == null) return error(res, 400, 'validation_error', 'body.rawJson is required');+ if (!body || body.rawJson == null)+ return error(res, 400, 'validation_error', 'body.rawJson is required');const { parseGmgnSmartWallets } = await import('../../src/kol/gmgn-parser.js');let parsed;- try { parsed = parseGmgnSmartWallets(body.rawJson); }- catch (err) { return error(res, 400, 'validation_error', err.message); }+ try {+ parsed = parseGmgnSmartWallets(body.rawJson);+ } catch (err) {+ return error(res, 400, 'validation_error', err.message);+ }const existing = await loadWallets();const byWallet = new Map(existing.map((w) => [w.wallet, w]));for (const entry of parsed) byWallet.set(entry.wallet, entry);@@ -129,8 +154,12 @@ async function handleLeaderboard(req, res) {const limit = limitRaw != null ? Number(limitRaw) : 25;const { getLeaderboard } = await import('../../src/kol/leaderboard.js');let items;- try { items = await getLeaderboard({ window, limit }); }- catch (err) { if (err.status === 400) return error(res, 400, err.code || 'validation_error', err.message); throw err; }+ try {+ items = await getLeaderboard({ window, limit });+ } catch (err) {+ if (err.status === 400) return error(res, 400, err.code || 'validation_error', err.message);+ throw err;+ }return json(res, 200, { items });}@@ -144,16 +173,29 @@ async function handleTrades(req, res) {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');const { KOL_WALLETS } = await import('../../src/kol/wallets.js');- return json(res, 200, { mint, trades: [], wallets: KOL_WALLETS.length });+ const { fetchKolTrades } = await import('../../src/kol/trades.js');+ let result;+ try {+ result = await fetchKolTrades({ mint, limit });+ } catch (err) {+ return error(+ res,+ err.status || 502,+ err.code || 'provider_unavailable',+ err.message || 'provider error',+ );+ }+ res.setHeader('x-kol-source', result.source || 'unconfigured');+ return json(res, 200, { mint, trades: result.trades, wallets: KOL_WALLETS.length });}// ── dispatcher ────────────────────────────────────────────────────────────────const DISPATCH = {'import-gmgn': handleImportGmgn,- leaderboard: handleLeaderboard,- trades: handleTrades,- wallets: handleWallets,+ leaderboard: handleLeaderboard,+ trades: handleTrades,+ wallets: handleWallets,};export default wrap(async (req, res) => {diff --git a/api/kol/trades.js b/api/kol/trades.jsindex 1e7c427d0..7203af28e 100644--- a/api/kol/trades.js+++ b/api/kol/trades.js@@ -1,5 +1,6 @@import { cors, error, json, method, wrap } from '../_lib/http.js';import { KOL_WALLETS } from '../../src/kol/wallets.js';+import { fetchKolTrades } from '../../src/kol/trades.js';export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS' })) return;@@ -11,5 +12,18 @@ export default wrap(async (req, res) => {if (!mint) return error(res, 400, 'validation_error', 'mint required');- return json(res, 200, { mint, trades: [], wallets: KOL_WALLETS?.length ?? 0 });+ let result;+ try {+ result = await fetchKolTrades({ mint, limit });+ } catch (err) {+ return error(+ res,+ err.status || 502,+ err.code || 'provider_unavailable',+ err.message || 'provider error',+ );+ }++ res.setHeader('x-kol-source', result.source || 'unconfigured');+ return json(res, 200, { mint, trades: result.trades, wallets: KOL_WALLETS?.length ?? 0 });});diff --git a/src/kol/trades.js b/src/kol/trades.jsnew file mode 100644index 000000000..cee340096--- /dev/null+++ b/src/kol/trades.js@@ -0,0 +1,149 @@+// KOL / smart-money trade feed.+//+// Returns recent pump.fun buys/sells made by the tracked KOL_WALLETS for a given+// mint. Source of truth is Helius' enhanced transactions REST API, parsed with+// the exact same parser the realtime webhook path uses (parsePumpTrades), so the+// historical feed and the live webhook stream agree on shape. USD values come+// from the shared SOL/USD price feed; results are cached briefly because this is+// a hot, fast-moving panel.+//+// Shape per trade (superset — the widget reads time/side/wallet/usd/source):+// { wallet, side:'buy'|'sell', amountSol, amountToken, price, signature, ts,+// time, usd, source, label }+// - ts : unix seconds (provider timestamp)+// - time : ISO 8601 string+// - price : SOL per token for the trade (0 when token amount is unknown)+// - usd : USD value of the SOL leg (null when the price feed is unavailable)+// - source : 'kol' | 'whale' | 'smart-money' (derived from the wallet's tags)++import { KOL_WALLETS, getWalletMeta } from './wallets.js';+import { parsePumpTrades } from '../../api/_lib/helius.js';+import { solToUsd } from '../shared/usd-price.js';+import { cacheGet, cacheSet } from '../../api/_lib/cache.js';++const HELIUS_TX_API = 'https://api.helius.xyz/v0/addresses';+const PER_WALLET_LIMIT = 100; // enhanced txns scanned per wallet+const FETCH_TIMEOUT_MS = 8_000;+const CACHE_TTL_S = 5; // trades move fast — a few seconds of memo is plenty++function sourceFromTags(tags = []) {+ if (tags.includes('whale')) return 'whale';+ if (tags.includes('smart-money')) return 'smart-money';+ return 'kol';+}++// Sum the |token amount| of `mint` that moved in/out of `owner` in this txn.+// Helius decodes ui amounts in `tokenTransfers[].tokenAmount`.+function tokenAmountFor(tx, mint, owner) {+ let amt = 0;+ for (const t of tx.tokenTransfers || []) {+ if (t.mint !== mint) continue;+ if (t.fromUserAccount === owner || t.toUserAccount === owner) {+ amt += Math.abs(Number(t.tokenAmount) || 0);+ }+ }+ return amt;+}++async function fetchWalletTxns(wallet, apiKey) {+ const url = `${HELIUS_TX_API}/${wallet}/transactions?api-key=${apiKey}&limit=${PER_WALLET_LIMIT}`;+ const ctrl = new AbortController();+ const timer = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS);+ try {+ const res = await fetch(url, { signal: ctrl.signal });+ if (!res.ok) throw new Error(`helius ${res.status}`);+ const json = await res.json();+ return Array.isArray(json) ? json : [];+ } finally {+ clearTimeout(timer);+ }+}++/**+ * Fetch recent KOL-wallet trades for a mint.+ *+ * @param {{ mint: string, limit?: number }} opts+ * @returns {Promise<{ trades: Array<object>, source: 'helius'|null }>}+ * `source: null` means the feed is unconfigured (no provider key) — an empty+ * list there is "source off", distinct from a configured source that simply+ * returned no matching trades. A configured source that *fails* throws (so the+ * caller emits an error envelope rather than a misleading empty list).+ * @throws {Error & { status: number, code: string }} on bad input / provider failure.+ */+export async function fetchKolTrades({ mint, limit = 20 } = {}) {+ if (!mint) {+ throw Object.assign(new Error('mint is required'), {+ status: 400,+ code: 'validation_error',+ });+ }+ const cap = Math.min(100, Math.max(1, Number(limit) || 20));++ const apiKey = process.env.HELIUS_API_KEY;+ if (!apiKey) {+ console.warn(+ '[kol/trades] HELIUS_API_KEY not set — trade feed unconfigured, returning no trades',+ );+ return { trades: [], source: null };+ }++ const cacheKey = `kol:trades:${mint}:${cap}`;+ const cached = await cacheGet(cacheKey);+ if (cached) return cached;++ // Fan out across wallets. One wallet's provider hiccup must not blank the+ // whole panel, but a total provider outage must surface as an error.+ const results = await Promise.allSettled(+ KOL_WALLETS.map((w) => fetchWalletTxns(w.address, apiKey)),+ );+ if (results.length > 0 && results.every((r) => r.status === 'rejected')) {+ const reason = results[0]?.reason;+ throw Object.assign(+ new Error(`KOL trade provider unavailable: ${reason?.message || 'unknown'}`),+ { status: 502, code: 'provider_unavailable' },+ );+ }++ const raw = [];+ results.forEach((r, i) => {+ if (r.status !== 'fulfilled') return;+ const walletAddr = KOL_WALLETS[i].address;+ for (const tx of r.value) {+ for (const t of parsePumpTrades(tx)) {+ if (t.mint !== mint) continue;+ const owner = t.wallet || walletAddr;+ const amountToken = tokenAmountFor(tx, mint, owner);+ raw.push({+ wallet: owner,+ side: t.side,+ amountSol: t.sol,+ amountToken,+ price: amountToken > 0 ? t.sol / amountToken : 0,+ signature: t.signature,+ ts: t.ts,+ });+ }+ }+ });++ raw.sort((a, b) => b.ts - a.ts);+ const top = raw.slice(0, cap);++ // One shared SOL price for the whole batch (null if the feed is down — the+ // SOL amount still renders, just without a USD equivalent).+ const solUsd = top.length ? await solToUsd(1) : null;+ const trades = top.map((t) => {+ const meta = getWalletMeta(t.wallet);+ return {+ ...t,+ time: new Date(t.ts * 1000).toISOString(),+ usd: solUsd != null ? t.amountSol * solUsd : null,+ source: sourceFromTags(meta?.tags),+ label: meta?.label ?? null,+ };+ });++ const payload = { trades, source: 'helius' };+ await cacheSet(cacheKey, payload, CACHE_TTL_S);+ return payload;+}