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
Add non-custodial copy trading: APIs, copy panel, dashboard, cron fanout, news intel, funder graph
nirholasf22f041fc13b
diff --git a/api/_lib/migrations/20260616130000_coin_intel_smart_money.sql b/api/_lib/migrations/20260616130000_coin_intel_smart_money.sqlnew file mode 100644index 000000000..7c8f134c6--- /dev/null+++ b/api/_lib/migrations/20260616130000_coin_intel_smart_money.sql@@ -0,0 +1,39 @@+-- Migration: extend pump_coin_intel with smart-money + news-meme + cluster columns.+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/20260616130000_coin_intel_smart_money.sql+-- Idempotent (all ADD COLUMN IF NOT EXISTS).+--+-- These columns are populated by the intel watcher's finalize step after the+-- funding-graph enrichment (funder-graph.js) and smart-money cross-reference+-- (smart-money-xref.js) complete. They are the highest-predictive signals:+--+-- smart_money_count — # of buyers with wallet_reputation.smart_money_score >= 65+-- smart_money_score — pedigree-weighted composite for this coin (0..100)+-- smart_money_notable — [{wallet, label, smart_money_score, win_rate, wins, duds}] top 5+-- cluster_count — # of distinct funding clusters (bubblemaps-style)+-- is_news_meme — true when name/description matches a current news headline++begin;++alter table pump_coin_intel+ add column if not exists smart_money_count int not null default 0,+ add column if not exists smart_money_score numeric,+ add column if not exists smart_money_notable jsonb not null default '[]'::jsonb,+ add column if not exists cluster_count int not null default 0,+ add column if not exists is_news_meme boolean not null default false;++-- Fast filter: "show me only coins smart money touched"+create index if not exists pump_coin_intel_smart_money+ on pump_coin_intel (network, smart_money_count desc, first_seen_at desc)+ where smart_money_count > 0;++-- Fast filter: news-meme coins+create index if not exists pump_coin_intel_news_meme+ on pump_coin_intel (network, is_news_meme, first_seen_at desc)+ where is_news_meme = true;++-- Composite: smart money + quality (the sniper's buy-decision query)+create index if not exists pump_coin_intel_sniper_decision+ on pump_coin_intel (network, quality_score desc, smart_money_count desc, first_seen_at desc)+ where quality_score >= 50;++commit;diff --git a/api/_lib/oracle/narrative.js b/api/_lib/oracle/narrative.jsindex c5882abce..1f7acb5d1 100644--- a/api/_lib/oracle/narrative.js+++ b/api/_lib/oracle/narrative.js@@ -6,17 +6,18 @@// the conviction engine weights them differently (see conviction.js narrative// pillar). This module produces that read.//-// Two paths, both REAL — never a mock:-// 1. llmComplete (free providers first per platform policy) returns a strict-// JSON read of category + narrative thesis + a 0–100 virality estimate.-// 2. If the LLM is unavailable or returns garbage, a deterministic keyword-// classifier produces a sane category + baseline virality so the pipeline-// never stalls and never fabricates confidence it doesn't have.+// Three paths, all REAL:+// 1. llmComplete with live news context injected from cryptocurrency.cv — the+// LLM sees matching headlines and writes a precise thesis ("rides today's+// Trump tariff announcement"). Virality is boosted by real news signal.+// 2. llmComplete with no news context (fallback when news fetch fails).+// 3. Deterministic keyword classifier when LLM is unavailable.//// Category set is aligned with the existing pump_coin_intel taxonomy so the two// systems agree; Oracle adds the free-text `narrative` and `virality`.import { llmComplete } from '../llm.js';+import { fetchRelevantHeadlines, viralityBonus } from './news-context.js';export const CATEGORIES = ['meme', 'tech', 'ai', 'culture', 'community',@@ -89,6 +90,7 @@ export function heuristicNarrative(meta = {}) {confidence: bestHits ? clamp(30 + bestHits * 12, 0, 80) / 100 : 0.2,tags,source: 'heuristic',+ news_matched: false,};}@@ -102,24 +104,36 @@ function parseJsonish(text) {try { return JSON.parse(t.slice(start, end + 1)); } catch { return null; }}-const SYSTEM = `You are Oracle, a pump.fun launch analyst. Classify a new token's CULTURAL NARRATIVE from its metadata.+const SYSTEM_BASE = `You are Oracle, a pump.fun launch analyst. Classify a new token's CULTURAL NARRATIVE from its metadata.Return ONLY minified JSON, no prose, with exactly these keys:{"category": one of ["meme","tech","ai","culture","community","political","news","animal","celebrity","utility","unknown"],- "narrative": "one crisp sentence naming the actual thesis/story (e.g. 'rides today's <headline> news', 'CTO community revival', 'AI agent infra')",+ "narrative": "one crisp sentence naming the actual thesis/story (e.g. 'rides today\\'s <headline> news', 'CTO community revival', 'AI agent infra')","virality": integer 0-100 (how likely this catches sustained attention; reward live news hooks, recognizable culture, clean tickers; punish generic/empty),"tags": array of up to 5 short lowercase tags,"confidence": number 0-1}Be decisive. If it's a meme riding a current event, prefer "news". If it's a community/CTO takeover, prefer "community". If empty/spam, category "unknown" with low virality.`;+function buildSystem(headlines) {+ if (!headlines.length) return SYSTEM_BASE;+ const headlineBlock = headlines+ .map((h, i) => `${i + 1}. "${h.title}"${h.published_at ? ` (${h.published_at.slice(0, 10)})` : ''}`)+ .join('\n');+ return `${SYSTEM_BASE}\n\nLIVE CRYPTO HEADLINES RIGHT NOW:\n${headlineBlock}\nIf the token clearly rides one of these headlines, reference it directly in "narrative" and score virality higher (70+).`;+}+/**- * Classify a coin's narrative. Tries the LLM (free-first); on any failure or a- * malformed response, returns the deterministic heuristic. Never throws.+ * Classify a coin's narrative. Tries the LLM with live news context (free-first);+ * on any failure returns the deterministic heuristic. Never throws.*- * @param {object} meta { name, symbol, description, twitter, telegram, website }+ * @param {object} meta { name, symbol, description, twitter, telegram, website, tags }* @param {object} [opts] { timeoutMs }- * @returns {Promise<{category:string, narrative:string, virality:number, confidence:number, tags:string[], source:'llm'|'heuristic'}>}+ * @returns {Promise<{category:string, narrative:string, virality:number, confidence:number, tags:string[], source:'llm'|'heuristic', news_matched:boolean}>}*/export async function classifyNarrative(meta = {}, opts = {}) {+ // Fetch live headlines in parallel with prompt construction — adds real news+ // signal for coins riding current events; safe no-op on network failure.+ const headlines = await fetchRelevantHeadlines(meta).catch(() => []);+const user = JSON.stringify({name: meta.name || null,symbol: meta.symbol || null,@@ -134,22 +148,24 @@ export async function classifyNarrative(meta = {}, opts = {}) {let res;try {res = await llmComplete({- system: SYSTEM,+ system: buildSystem(headlines),user,maxTokens: 220,timeoutMs: opts.timeoutMs ?? 12_000,track: { tool: 'oracle_narrative' },});} catch {- return heuristicNarrative(meta);+ return { ...heuristicNarrative(meta), news_matched: false };}const parsed = parseJsonish(res?.text);- if (!parsed || typeof parsed !== 'object') return heuristicNarrative(meta);+ if (!parsed || typeof parsed !== 'object') return { ...heuristicNarrative(meta), news_matched: false };const category = CATEGORY_SET.has(String(parsed.category)) ? String(parsed.category) : 'unknown';- const virality = clamp(Math.round(Number(parsed.virality)));- if (!Number.isFinite(virality)) return heuristicNarrative(meta);+ // Apply a live-news virality bonus on top of the LLM's own estimate.+ const bonus = viralityBonus(headlines);+ const virality = clamp(Math.round(Number(parsed.virality)) + bonus);+ if (!Number.isFinite(virality)) return { ...heuristicNarrative(meta), news_matched: false };return {category,@@ -158,5 +174,6 @@ export async function classifyNarrative(meta = {}, opts = {}) {confidence: Math.max(0, Math.min(1, Number(parsed.confidence) || 0.5)),tags: Array.isArray(parsed.tags) ? parsed.tags.slice(0, 5).map((t) => String(t).toLowerCase().slice(0, 24)) : [],source: 'llm',+ news_matched: headlines.length > 0,};}diff --git a/api/_lib/oracle/news-context.js b/api/_lib/oracle/news-context.jsnew file mode 100644index 000000000..0202d6d01--- /dev/null+++ b/api/_lib/oracle/news-context.js@@ -0,0 +1,155 @@+// Oracle — live news context from cryptocurrency.cv.+//+// Fetches a window of recent crypto headlines (no API key required — public+// endpoint) and matches them against a coin's name/symbol/tags. When a coin is+// clearly riding a live headline, the narrative classifier gets that context in+// the LLM prompt so it can write a precise thesis ("rides today's Trump tariff+// announcement") instead of guessing. The virality boost applied here is REAL+// signal: a coin whose ticker appears in a trending headline right now has+// genuine attention behind it.+//+// Two tiers:+// 1. fetchRelevantHeadlines(meta) — fetch + filter in one call. Returns the+// top 3 matching headlines (or [] if none). Used by classifyNarrative().+// 2. fetchTrending() — the raw trending topics; used by the cron+// to pre-warm the headline cache before a scoring batch.+//+// Both degrade gracefully: network failure, bad JSON, or any exception returns+// the safe fallback so the narrative pipeline never stalls.++const BASE = 'https://cryptocurrency.cv';+const CACHE_TTL_MS = 90_000; // 90s — fresh enough for live news, lenient on rate limits++/** Module-level news cache so one Vercel invocation shares it across coin scorings. */+const _cache = { headlines: null, trending: null, fetchedAt: 0 };++async function fetchWithTimeout(url, ms = 5000) {+ const ctrl = new AbortController();+ const timer = setTimeout(() => ctrl.abort(), ms);+ try {+ const res = await fetch(url, {+ signal: ctrl.signal,+ headers: { 'User-Agent': 'three.ws-oracle/1.0' },+ });+ if (!res.ok) return null;+ return await res.json();+ } catch {+ return null;+ } finally {+ clearTimeout(timer);+ }+}++/**+ * Fetch recent headlines from cryptocurrency.cv, filtered to categories most+ * relevant to pump.fun launches. Returns array of { title, category, published_at }+ * or [] on failure. Results cached for CACHE_TTL_MS.+ */+async function fetchHeadlines() {+ const now = Date.now();+ if (_cache.headlines && now - _cache.fetchedAt < CACHE_TTL_MS) return _cache.headlines;++ // Parallel fetch of the most relevant categories for pump.fun culture.+ const cats = ['general', 'solana', 'bitcoin', 'defi', 'altl1'];+ const results = await Promise.allSettled(+ cats.map((cat) =>+ fetchWithTimeout(`${BASE}/api/news?category=${cat}&limit=20&quality=any`, 5000),+ ),+ );++ const headlines = [];+ const seen = new Set();+ for (const r of results) {+ if (r.status !== 'fulfilled' || !r.value) continue;+ const items = r.value?.articles || r.value?.data || r.value?.items || [];+ for (const item of items) {+ const title = String(item?.title || item?.headline || '').trim();+ if (!title || seen.has(title)) continue;+ seen.add(title);+ headlines.push({+ title,+ category: item?.category || 'general',+ published_at: item?.published_at || item?.publishedAt || item?.date || null,+ source: item?.source || null,+ });+ }+ }++ if (headlines.length) {+ _cache.headlines = headlines;+ _cache.fetchedAt = now;+ }+ return _cache.headlines || [];+}++/**+ * Fetch trending topics from cryptocurrency.cv. Returns array of strings.+ */+export async function fetchTrending() {+ if (_cache.trending && Date.now() - _cache.fetchedAt < CACHE_TTL_MS) return _cache.trending;+ const data = await fetchWithTimeout(`${BASE}/api/trending?limit=20`, 4000);+ const topics = (data?.topics || data?.trending || data?.items || [])+ .map((t) => (typeof t === 'string' ? t : String(t?.name || t?.topic || '')))+ .filter(Boolean);+ if (topics.length) _cache.trending = topics;+ return _cache.trending || [];+}++// Tokenize a string into lowercase word-level tokens for fuzzy matching.+function tokens(str) {+ return String(str || '').toLowerCase().replace(/[^a-z0-9 ]/g, ' ').split(/\s+/).filter((w) => w.length >= 2);+}++// Score how well a headline matches coin metadata. Returns 0–100.+function matchScore(headline, coinTokens) {+ const hTokens = tokens(headline.title);+ let hits = 0;+ for (const ct of coinTokens) {+ if (ct.length < 2) continue;+ for (const ht of hTokens) {+ if (ht === ct || (ct.length >= 4 && ht.includes(ct))) { hits++; break; }+ }+ }+ return hits;+}++/**+ * Return the top matching recent headlines for a coin. Empty array if none match.+ * Threshold: at least 1 token overlap.+ *+ * @param {{ name?: string, symbol?: string, description?: string, tags?: string[] }} meta+ * @param {number} [maxResults=3]+ * @returns {Promise<Array<{title:string, category:string, published_at:string|null}>>}+ */+export async function fetchRelevantHeadlines(meta = {}, maxResults = 3) {+ try {+ const headlines = await fetchHeadlines();+ if (!headlines.length) return [];++ const coinTokens = tokens(`${meta.name || ''} ${meta.symbol || ''} ${(meta.tags || []).join(' ')}`);+ if (!coinTokens.length) return [];++ const scored = headlines+ .map((h) => ({ ...h, _score: matchScore(h, coinTokens) }))+ .filter((h) => h._score > 0)+ .sort((a, b) => b._score - a._score)+ .slice(0, maxResults);++ return scored.map(({ _score: _, ...h }) => h);+ } catch {+ return [];+ }+}++/**+ * Compute a virality bonus (0–30) from live news context.+ * Called inside classifyNarrative to adjust the base LLM-estimated virality.+ *+ * @param {Array<{title:string}>} headlines matching headlines+ * @returns {number}+ */+export function viralityBonus(headlines) {+ if (!headlines.length) return 0;+ // First match: strong bonus. Additional matches add diminishing signal.+ return Math.min(30, headlines.length * 10 + 5);+}diff --git a/api/_lib/pump-intel/funder-graph.js b/api/_lib/pump-intel/funder-graph.jsnew file mode 100644index 000000000..1f4380f2c--- /dev/null+++ b/api/_lib/pump-intel/funder-graph.js@@ -0,0 +1,187 @@+// Funding-graph tracer for pump.fun wallet clustering.+//+// "Are these wallets connected?" is the literal bubblemaps question. The answer+// is: did they receive SOL from a common source shortly before buying?+//+// Method: for each buyer wallet, fetch its last N Solana system transfers+// (SOL in) via Helius enhanced-txn API and return the sending wallet (the+// "funder"). Wallets sharing a funder are a cluster — coordinated, not organic.+//+// This is the cheapest possible funding graph: one Helius call per wallet, no+// graph DB, no indexer. It correctly identifies the classic bundle attack+// (coordinator funds N fresh wallets → all buy within a slot) and also catches+// insider relationships (dev's own wallet funded the "organic" buyers).+//+// Rate limiting: Helius free tier is 10 req/s sustained. We cap concurrent+// calls and cache results aggressively — a wallet's funder doesn't change.++const HELIUS_API = 'https://api.helius.xyz/v0';+const FUNDER_CACHE_TTL_MS = 6 * 60 * 60 * 1000; // 6h — funders don't change+const MAX_CONCURRENT = 6;+const PER_WALLET_TIMEOUT_MS = 4_000;+const MAX_TXS_TO_SCAN = 10; // earliest relevant txs; funder is usually in first few++// In-process cache: wallet -> { funder, resolvedAt }+const _cache = new Map();++function apiKey() {+ return process.env.HELIUS_API_KEY || '';+}++function cacheGet(wallet) {+ const hit = _cache.get(wallet);+ if (!hit) return undefined;+ if (Date.now() - hit.resolvedAt > FUNDER_CACHE_TTL_MS) { _cache.delete(wallet); return undefined; }+ return hit.funder; // may be null (no funder found) — still cached+}++function cacheSet(wallet, funder) {+ _cache.set(wallet, { funder, resolvedAt: Date.now() });+ // Evict oldest 25% when over 10k+ if (_cache.size > 10_000) {+ const drop = 2_500;+ const it = _cache.keys();+ for (let i = 0; i < drop; i++) _cache.delete(it.next().value);+ }+}++/**+ * Resolve the primary SOL funder for a single wallet.+ * Returns the sender address (string) or null if not found / Helius unavailable.+ */+async function resolveFunder(wallet) {+ const cached = cacheGet(wallet);+ if (cached !== undefined) return cached;++ const k = apiKey();+ if (!k) { cacheSet(wallet, null); return null; }++ try {+ const ctrl = new AbortController();+ const tid = setTimeout(() => ctrl.abort(), PER_WALLET_TIMEOUT_MS);++ const url = `${HELIUS_API}/addresses/${encodeURIComponent(wallet)}/transactions` ++ `?api-key=${k}&limit=${MAX_TXS_TO_SCAN}&type=TRANSFER`;+ const r = await fetch(url, { signal: ctrl.signal });+ clearTimeout(tid);++ if (!r.ok) { cacheSet(wallet, null); return null; }+ const txs = await r.json();+ if (!Array.isArray(txs) || !txs.length) { cacheSet(wallet, null); return null; }++ // Walk transactions oldest-first. We want the FIRST significant SOL-in+ // transfer to this wallet — that's the funder that armed it for the launch.+ // Helius returns newest-first, so we reverse.+ const reversed = [...txs].reverse();++ let funder = null;+ for (const tx of reversed) {+ // Helius enhanced transactions expose nativeTransfers as [{fromUserAccount,+ // toUserAccount, amount}] and accountData as balance changes.+ const transfers = Array.isArray(tx.nativeTransfers) ? tx.nativeTransfers : [];+ for (const t of transfers) {+ if (+ t.toUserAccount === wallet &&+ typeof t.amount === 'number' &&+ t.amount >= 5_000_000 && // ≥0.005 SOL — ignore dust+ t.fromUserAccount &&+ t.fromUserAccount !== wallet+ ) {+ funder = t.fromUserAccount;+ break;+ }+ }+ if (funder) break;+ }++ cacheSet(wallet, funder);+ return funder;+ } catch {+ cacheSet(wallet, null);+ return null;+ }+}++/**+ * Resolve funders for a set of wallets concurrently (capped at MAX_CONCURRENT).+ * Returns Map<wallet, funder|null>.+ *+ * @param {string[]} wallets+ * @returns {Promise<Map<string, string|null>>}+ */+export async function resolveWalletFunders(wallets) {+ const unique = [...new Set(wallets.filter(Boolean))];+ const result = new Map();++ // Serve cache hits immediately — no I/O needed+ const uncached = [];+ for (const w of unique) {+ const hit = cacheGet(w);+ if (hit !== undefined) {+ result.set(w, hit);+ } else {+ uncached.push(w);+ }+ }++ if (!uncached.length || !apiKey()) {+ for (const w of uncached) result.set(w, null);+ return result;+ }++ // Concurrency-limited resolution+ const queue = [...uncached];+ let active = 0;+ let idx = 0;++ await new Promise((resolve) => {+ function next() {+ if (idx >= queue.length && active === 0) { resolve(); return; }+ while (active < MAX_CONCURRENT && idx < queue.length) {+ const wallet = queue[idx++];+ active++;+ resolveFunder(wallet)+ .then((funder) => { result.set(wallet, funder); })+ .catch(() => { result.set(wallet, null); })+ .finally(() => { active--; next(); });+ }+ }+ next();+ });++ return result;+}++/**+ * Build cluster map: group wallets by common funder.+ * Returns { clusters: Map<funder, string[]>, connectivity: number|null }+ *+ * connectivity: share of wallets with a known funder that share the biggest cluster.+ * null if fewer than 3 wallets have resolved funders.+ */+export function buildClusters(funderMap) {+ const byFunder = new Map(); // funder -> [wallets]+ let known = 0;++ for (const [wallet, funder] of funderMap) {+ if (!funder) continue;+ known++;+ if (!byFunder.has(funder)) byFunder.set(funder, []);+ byFunder.get(funder).push(wallet);+ }++ const clusters = new Map([...byFunder].filter(([, ws]) => ws.length >= 2));++ let connectivity = null;+ if (known >= 3) {+ const biggestCluster = clusters.size+ ? Math.max(...[...clusters.values()].map((ws) => ws.length))+ : 0;+ connectivity = Math.round((biggestCluster / known) * 10000) / 10000;+ }++ return { clusters, connectivity };+}++/** Export cache size for monitoring. */+export function funderCacheSize() { return _cache.size; }diff --git a/api/_lib/pump-intel/news-matcher.js b/api/_lib/pump-intel/news-matcher.jsnew file mode 100644index 000000000..977a59dc0--- /dev/null+++ b/api/_lib/pump-intel/news-matcher.js@@ -0,0 +1,175 @@+// Real-time news-meme detection for pump.fun coin classification.+//+// Fetches top crypto headlines from the cryptocurrency.cv public API+// (nirholas/cryptocurrency.cv — free, no key required, real-time aggregator),+// caches them for 2 minutes, then fuzzy-matches a coin's name/symbol/description+// against the headlines. Returns the matched headline + confidence so the+// classifier can set is_news_meme=true with real evidence.+//+// Fallback: if the API is unreachable, the function returns null so the+// caller degrades to the LLM/heuristic path — never blocks the pipeline.++const NEWS_API = 'https://cryptocurrency.cv/api/news';+const TRENDING_API = 'https://cryptocurrency.cv/api/trending';+const CACHE_TTL_MS = 2 * 60_000; // 2-min freshness — headlines move fast+const FETCH_TIMEOUT_MS = 3_000;+const MAX_HEADLINES = 40;++let _cache = null;+let _cacheAt = 0;++/**+ * Fetch + cache the current top crypto headlines.+ * Returns array of { title, summary, url, published_at } or [].+ */+async function getHeadlines() {+ if (_cache && Date.now() - _cacheAt < CACHE_TTL_MS) return _cache;++ const ctrl = new AbortController();+ const tid = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS);++ try {+ // Primary: structured news endpoint+ const r = await fetch(`${NEWS_API}?limit=${MAX_HEADLINES}&format=json`, {+ signal: ctrl.signal,+ headers: { 'accept': 'application/json', 'user-agent': 'three.ws-intel/1' },+ });+ clearTimeout(tid);+ if (r.ok) {+ const d = await r.json();+ // cryptocurrency.cv returns { articles: [...] } or a flat array+ const articles = Array.isArray(d) ? d : (Array.isArray(d?.articles) ? d.articles : []);+ const headlines = articles.slice(0, MAX_HEADLINES).map((a) => ({+ title: String(a.title || a.headline || ''),+ summary: String(a.summary || a.description || a.content || ''),+ url: String(a.url || a.link || ''),+ published_at: a.published_at || a.publishedAt || a.date || null,+ })).filter((h) => h.title.length > 4);+ if (headlines.length) {+ _cache = headlines;+ _cacheAt = Date.now();+ return _cache;+ }+ }+ } catch { clearTimeout(tid); }++ // Fallback: trending endpoint (simpler format)+ const ctrl2 = new AbortController();+ const tid2 = setTimeout(() => ctrl2.abort(), FETCH_TIMEOUT_MS);+ try {+ const r2 = await fetch(TRENDING_API, {+ signal: ctrl2.signal,+ headers: { 'accept': 'application/json', 'user-agent': 'three.ws-intel/1' },+ });+ clearTimeout(tid2);+ if (r2.ok) {+ const d2 = await r2.json();+ const items = Array.isArray(d2) ? d2 : (Array.isArray(d2?.data) ? d2.data : []);+ const headlines = items.slice(0, MAX_HEADLINES).map((a) => ({+ title: String(a.title || a.term || a.keyword || ''),+ summary: '',+ url: '',+ published_at: null,+ })).filter((h) => h.title.length > 2);+ if (headlines.length) {+ _cache = headlines;+ _cacheAt = Date.now();+ return _cache;+ }+ }+ } catch { clearTimeout(tid2); }++ return _cache || []; // stale cache beats nothing+}++// Tokenise to lowercase word stems for matching+function tokens(text) {+ return (text || '')+ .toLowerCase()+ .replace(/[^a-z0-9\s]/g, ' ')+ .split(/\s+/)+ .filter((w) => w.length >= 3 && w.length <= 25);+}++// Jaccard-ish overlap between two token sets, ignoring stop words+const STOP = new Set(['the','and','for','has','are','was','its','with','that','this',+ 'from','have','been','will','they','were','their','also','about','into',+ 'could','coin','token','pump','solana','crypto','blockchain','defi']);++function overlapScore(aToks, bToks) {+ const a = new Set(aToks.filter((t) => !STOP.has(t)));+ const b = new Set(bToks.filter((t) => !STOP.has(t)));+ if (!a.size || !b.size) return 0;+ let hits = 0;+ for (const t of a) { if (b.has(t)) hits++; }+ return hits / Math.min(a.size, b.size);+}++/**+ * Check if a coin's metadata matches a current news headline.+ *+ * @param {{ name, symbol, description }} coin+ * @returns {Promise<{ matched: boolean, headline: string|null, url: string|null, confidence: number }>}+ */+export async function matchNewsHeadline(coin) {+ const fallback = { matched: false, headline: null, url: null, confidence: 0 };+ try {+ const headlines = await getHeadlines();+ if (!headlines.length) return fallback;++ // Build coin token set from all text fields+ const coinText = `${coin.name || ''} ${coin.symbol || ''} ${coin.description || ''}`;+ const coinToks = tokens(coinText);+ if (coinToks.length < 2) return fallback;++ // Also check if the coin name/symbol appears verbatim in a headline+ const coinNameLower = (coin.name || '').toLowerCase();+ const coinSymLower = (coin.symbol || '').toLowerCase().replace(/^\$/, '');++ let bestScore = 0;+ let bestHeadline = null;++ for (const h of headlines) {+ const headlineToks = tokens(`${h.title} ${h.summary}`);+ const headlineFull = `${h.title} ${h.summary}`.toLowerCase();++ // Verbatim match (strongest signal — coin named after the event)+ const verbatim = (coinNameLower.length >= 4 && headlineFull.includes(coinNameLower))+ || (coinSymLower.length >= 3 && headlineFull.includes(coinSymLower));++ const overlap = overlapScore(coinToks, headlineToks);+ const score = verbatim ? Math.max(0.85, overlap) : overlap;++ if (score > bestScore) {+ bestScore = score;+ bestHeadline = h;+ }+ }++ // Threshold: 0.35 overlap or verbatim match → news meme+ if (bestScore >= 0.35 && bestHeadline) {+ return {+ matched: true,+ headline: bestHeadline.title,+ url: bestHeadline.url || null,+ confidence: Math.min(0.95, bestScore),+ };+ }++ return fallback;+ } catch {+ return fallback;+ }+}++/** Force-refresh the headline cache (called by a periodic background task). */+export async function refreshHeadlines() {+ _cache = null;+ _cacheAt = 0;+ return getHeadlines();+}++/** Cache stats for monitoring. */+export function newsCacheAge() {+ return _cache ? Math.round((Date.now() - _cacheAt) / 1000) : null;+}diff --git a/api/_lib/pump-intel/smart-money-xref.js b/api/_lib/pump-intel/smart-money-xref.jsnew file mode 100644index 000000000..502ff53dc--- /dev/null+++ b/api/_lib/pump-intel/smart-money-xref.js@@ -0,0 +1,138 @@+// Smart-money cross-reference for the Coin Intelligence Engine.+//+// At intel-finalize time the watcher passes us the full list of wallets that+// bought the coin. We run ONE batched DB query against wallet_reputation and+// return:+// count — # of "proven" buyers (smart_money_score >= 65)+// score — pedigree-weighted composite (0..100): how much proven money is in this coin+// notable — top 5 proven buyers with their label + win_rate + buy_sol+// top_label — highest-reputation label seen ('smart_money' | 'sniper' | ...)+//+// This is the "smart money just bought" signal. It's the highest-predictive+// single feature in the engine. It runs on EVERY coin in the decision window.+//+// The DB import is lazy — the worker imports this before DATABASE_URL is+// necessarily set, and we return safe zeros rather than crashing.++const SMART_THRESHOLD = 65; // wallet_reputation.smart_money_score >= this → proven+const NOTABLE_LIMIT = 5;++let _sqlPromise = null;+async function getSql() {+ if (_sqlPromise) return _sqlPromise;+ _sqlPromise = import('../db.js')+ .then((m) => m.sql)+ .catch((err) => { console.warn('[smart-money-xref] db import failed:', err?.message); return null; });+ return _sqlPromise;+}++const LAMPORTS_PER_SOL = 1_000_000_000;++/**+ * Cross-reference a list of buyer wallets against wallet_reputation.+ * Returns { count, score, notable, top_label }.+ *+ * @param {string[]} wallets buyer wallet addresses observed in this coin+ * @param {string} [network]+ * @returns {Promise<{ count: number, score: number|null, notable: object[], top_label: string|null }>}+ */+export async function crossReferenceSmartMoney(wallets, network = 'mainnet') {+ const unique = [...new Set((wallets || []).filter(Boolean))];+ const empty = { count: 0, score: null, notable: [], top_label: null };+ if (!unique.length) return empty;++ const sql = await getSql();+ if (!sql) return empty;++ try {+ const rows = await sql`+ select wallet, smart_money_score, label, win_rate, early_win_rate, wins, duds+ from wallet_reputation+ where network = ${network}+ and wallet = any(${unique})+ and smart_money_score >= ${SMART_THRESHOLD}+ order by smart_money_score desc+ limit ${NOTABLE_LIMIT * 2}+ `;++ if (!rows.length) return empty;++ const proven = rows.filter((r) => Number(r.smart_money_score) >= SMART_THRESHOLD);+ if (!proven.length) return empty;++ // Pedigree-weighted composite: sum(score * win_rate) / n, normalised to 0..100+ let weightedSum = 0;+ let totalWeight = 0;+ for (const r of proven) {+ const s = Number(r.smart_money_score) || 0;+ const w = Math.max(0.1, Number(r.win_rate) || 0.1);+ weightedSum += s * w;+ totalWeight += w;+ }+ const compositeScore = totalWeight > 0+ ? Math.min(100, Math.round(weightedSum / totalWeight))+ : null;++ const topLabel = proven[0]?.label || null;++ const notable = proven.slice(0, NOTABLE_LIMIT).map((r) => ({+ wallet: r.wallet,+ label: r.label,+ smart_money_score: Number(r.smart_money_score),+ win_rate: r.win_rate != null ? Math.round(Number(r.win_rate) * 1000) / 1000 : null,+ wins: Number(r.wins) || 0,+ duds: Number(r.duds) || 0,+ }));++ return {+ count: proven.length,+ score: compositeScore,+ notable,+ top_label: topLabel,+ };+ } catch (err) {+ console.warn('[smart-money-xref] query failed:', err?.message);+ return empty;+ }+}++/**+ * Lightweight version for use in the live sniper scorer (called on every mint+ * before the full intel window closes). Cheaper: only looks up the dev wallet+ * and the first few buyers, returns boolean + top hit.+ *+ * @param {string[]} wallets up to 20 wallets+ * @param {string} [network]+ * @returns {Promise<{ hasSmartMoney: boolean, topWallet: object|null }>}+ */+export async function quickSmartMoneyCheck(wallets, network = 'mainnet') {+ const unique = [...new Set((wallets || []).filter(Boolean))].slice(0, 20);+ if (!unique.length) return { hasSmartMoney: false, topWallet: null };++ const sql = await getSql();+ if (!sql) return { hasSmartMoney: false, topWallet: null };++ try {+ const [top] = await sql`+ select wallet, smart_money_score, label, win_rate+ from wallet_reputation+ where network = ${network}+ and wallet = any(${unique})+ and smart_money_score >= ${SMART_THRESHOLD}+ order by smart_money_score desc+ limit 1+ `;+ if (!top) return { hasSmartMoney: false, topWallet: null };+ return {+ hasSmartMoney: true,+ topWallet: {+ wallet: top.wallet,+ label: top.label,+ smart_money_score: Number(top.smart_money_score),+ win_rate: top.win_rate != null ? Number(top.win_rate) : null,+ },+ };+ } catch {+ return { hasSmartMoney: false, topWallet: null };+ }+}diff --git a/api/_lib/pump-platform-fee.js b/api/_lib/pump-platform-fee.jsnew file mode 100644index 000000000..7e8938305--- /dev/null+++ b/api/_lib/pump-platform-fee.js@@ -0,0 +1,171 @@+// Platform trading fee for pump.fun buys and sells routed through three.ws.+//+// Every trade the platform builds (buy-prep / sell-prep) can carry a platform+// fee that matches pump.fun's own trade-fee rate. The fee is a REAL on-chain+// transfer appended to the SAME transaction the user signs — native SOL for+// SOL-paired trades, the quote SPL token (USDC) for USDC-paired trades — sent+// to the platform fee wallet. There is no second signature and no custody: the+// user signs one transaction that does the swap and pays the fee atomically.+//+// Honesty (Rule 1 & 9): the fee is never hidden. prep responses surface a+// `platform_fee` block and the trade UI shows a fee line. The fee applies only+// when BOTH a recipient wallet is configured AND the rate is > 0 — so an+// unconfigured environment (local/preview without a fee wallet) charges nothing+// automatically, which makes flow-testing safe without code changes.+//+// Basis:+// buy → fee on the quote amount spent (charged on top of the trade).+// sell → fee on the expected quote proceeds (taken from the proceeds).++import { PublicKey, SystemProgram } from '@solana/web3.js';+import { SOLANA_USDC_MINT, SOLANA_USDC_MINT_DEVNET } from '../payments/_config.js';+import { resolveSignerPubkey } from './solana-signers.js';++const WSOL_MINT = 'So11111111111111111111111111111111111111112';++// Hard ceiling — a guard so a fat-fingered env can never charge an absurd fee.+const MAX_FEE_BPS = 500; // 5%++/**+ * The platform trade-fee rate in basis points. Defaults to 100 (1%), matching+ * pump.fun's trade fee. Override per-environment with PUMP_PLATFORM_FEE_BPS+ * (e.g. set 0 to disable while testing). Clamped to [0, MAX_FEE_BPS].+ * @returns {number}+ */+export function pumpPlatformFeeBps() {+ const raw = process.env.PUMP_PLATFORM_FEE_BPS;+ const n = raw == null || String(raw).trim() === '' ? 100 : parseInt(raw, 10);+ if (!Number.isFinite(n) || n < 0) return 100;+ return Math.min(n, MAX_FEE_BPS);+}++let _recipientCache = null; // { at, pubkey }+const RECIPIENT_TTL_MS = 60_000;++/**+ * The fee recipient. An explicit PUMP_PLATFORM_FEE_WALLET base58 address wins;+ * otherwise we derive the platform treasury keypair's public key (no secret is+ * exposed — only the pubkey). Returns null when neither is configured, which+ * disables the fee (fail-open to no-charge, never break a trade over fee setup).+ * @returns {Promise<PublicKey|null>}+ */+export async function pumpFeeRecipient() {+ if (_recipientCache && Date.now() - _recipientCache.at < RECIPIENT_TTL_MS) {+ return _recipientCache.pubkey;+ }+ let pubkey = null;+ const explicit = (process.env.PUMP_PLATFORM_FEE_WALLET || '').trim();+ if (explicit) {+ try { pubkey = new PublicKey(explicit); } catch { pubkey = null; }+ }+ if (!pubkey) {+ const r = await resolveSignerPubkey({+ env: 'PLATFORM_TREASURY_KEYPAIR',+ fallbackEnv: 'TREASURY_KEYPAIR',+ });+ if (r.pubkey) {+ try { pubkey = new PublicKey(r.pubkey); } catch { pubkey = null; }+ }+ }+ _recipientCache = { at: Date.now(), pubkey };+ return pubkey;+}++/**+ * Fee in atomic units of the quote asset: floor(gross * bps / 10_000).+ * @param {bigint|number|string} grossAtomics+ * @param {number} [bps]+ * @returns {bigint}+ */+export function pumpFeeAtomics(grossAtomics, bps = pumpPlatformFeeBps()) {+ let g;+ try {+ g = typeof grossAtomics === 'bigint' ? grossAtomics : BigInt(String(grossAtomics ?? '0').split('.')[0]);+ } catch {+ return 0n;+ }+ if (g <= 0n || bps <= 0) return 0n;+ return (g * BigInt(bps)) / 10_000n;+}++/**+ * Build the platform-fee transfer instruction(s) to append to a trade tx, plus+ * a disclosure block for the prep response. Returns null when no fee applies+ * (rate 0, no recipient configured, or a sub-atomic fee).+ *+ * @param {object} o+ * @param {string} o.network 'mainnet' | 'devnet'+ * @param {PublicKey|string} o.payer the trader's wallet (and fee source)+ * @param {boolean} o.isUsdc true for USDC/SPL-quoted trades+ * @param {PublicKey|string} [o.quoteMintPk] the quote mint (USDC trades)+ * @param {PublicKey} [o.quoteTokenProgram] the quote mint's token program+ * @param {bigint|number|string} o.grossAtomics quote spend (buy) / proceeds (sell)+ * @returns {Promise<{ instructions: import('@solana/web3.js').TransactionInstruction[],+ * disclosure: { bps:number, asset:'SOL'|'USDC', amount:string, amount_ui:number,+ * recipient:string, basis:string } } | null>}+ */+export async function buildPlatformFeeInstructions({+ network,+ payer,+ isUsdc,+ quoteMintPk,+ quoteTokenProgram,+ grossAtomics,+ basis = 'trade',+}) {+ const bps = pumpPlatformFeeBps();+ const fee = pumpFeeAtomics(grossAtomics, bps);+ if (fee <= 0n) return null;++ const recipient = await pumpFeeRecipient();+ if (!recipient) return null;++ const payerPk = payer instanceof PublicKey ? payer : new PublicKey(payer);++ if (!isUsdc) {+ const ix = SystemProgram.transfer({+ fromPubkey: payerPk,+ toPubkey: recipient,+ lamports: fee,+ });+ return {+ instructions: [ix],+ disclosure: {+ bps,+ asset: 'SOL',+ amount: fee.toString(),+ amount_ui: Number(fee) / 1e9,+ recipient: recipient.toBase58(),+ basis,+ },+ };+ }++ // USDC (or other SPL quote): move the fee from the trader's quote ATA to the+ // recipient's, creating the recipient ATA idempotently so a first-ever fee+ // always lands. The trader funds the (tiny) ATA rent only on first creation.+ const spl = await import('@solana/spl-token');+ const mintPk = quoteMintPk instanceof PublicKey+ ? quoteMintPk+ : new PublicKey(quoteMintPk || (network === 'devnet' ? SOLANA_USDC_MINT_DEVNET : SOLANA_USDC_MINT));+ const tokenProgram = quoteTokenProgram instanceof PublicKey ? quoteTokenProgram : spl.TOKEN_PROGRAM_ID;+ const payerAta = spl.getAssociatedTokenAddressSync(mintPk, payerPk, true, tokenProgram);+ const recipientAta = spl.getAssociatedTokenAddressSync(mintPk, recipient, true, tokenProgram);+ const instructions = [+ spl.createAssociatedTokenAccountIdempotentInstruction(payerPk, recipientAta, recipient, mintPk, tokenProgram),+ spl.createTransferInstruction(payerAta, recipientAta, payerPk, fee, [], tokenProgram),+ ];+ return {+ instructions,+ disclosure: {+ bps,+ asset: 'USDC',+ amount: fee.toString(),+ amount_ui: Number(fee) / 1e6,+ recipient: recipient.toBase58(),+ basis,+ },+ };+}++export { WSOL_MINT, MAX_FEE_BPS };diff --git a/api/copy/executions.js b/api/copy/executions.jsnew file mode 100644index 000000000..c04c83a00--- /dev/null+++ b/api/copy/executions.js@@ -0,0 +1,92 @@+/**+ * Copy-trading executions — the copier's intent inbox + history.+ *+ * GET /api/copy/executions?status=pending|acted|dismissed|skipped|all&limit=+ * list the signed-in copier's copy intents (newest first), with leader + coin info.+ * POST /api/copy/executions { id, action: 'acted'|'dismissed', tx_signature? }+ * the copier records that they acted on (or dismissed) a pending intent.+ *+ * Non-custodial: marking 'acted' just records that the copier executed it from+ * their own wallet (optionally with the fill signature for their records) — the+ * platform never signs or broadcasts here.+ */++import { cors, json, error, method, wrap, readJson, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';+import { requireCsrf } from '../_lib/csrf.js';+import { sql } from '../_lib/db.js';++const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+const STATUSES = new Set(['pending', 'acted', 'dismissed', 'skipped', 'expired', 'all']);++async function requireUser(req, res) {+ const session = await getSessionUser(req);+ const bearer = session ? null : await authenticateBearer(extractBearer(req));+ if (!session && !bearer) { error(res, 401, 'unauthorized', 'sign in required'); return null; }+ return { userId: session?.id ?? bearer.userId, viaSession: !!session };+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET', 'POST'])) return;++ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const auth = await requireUser(req, res);+ if (!auth) return;+ const { userId } = auth;++ if (req.method === 'GET') {+ const params = new URL(req.url, 'http://x').searchParams;+ const status = STATUSES.has(params.get('status')) ? params.get('status') : 'pending';+ const limit = Math.min(100, Math.max(1, Number(params.get('limit')) || 50));++ // Expire stale pending intents lazily on read so the inbox never shows+ // actionable copies for coins that have long since moved.+ await sql`+ update copy_executions set status = 'expired', updated_at = now()+ where copier_user_id = ${userId} and status = 'pending' and expires_at < now()+ `;++ const rows = status === 'all'+ ? await sql`+ select e.*, a.name as leader_name, a.profile_image_url as leader_image, a.avatar_url as leader_avatar+ from copy_executions e+ join agent_identities a on a.id = e.leader_agent_id+ where e.copier_user_id = ${userId}+ order by e.created_at desc limit ${limit}+ `+ : await sql`+ select e.*, a.name as leader_name, a.profile_image_url as leader_image, a.avatar_url as leader_avatar+ from copy_executions e+ join agent_identities a on a.id = e.leader_agent_id+ where e.copier_user_id = ${userId} and e.status = ${status}+ order by e.created_at desc limit ${limit}+ `;+ return json(res, 200, { executions: rows });+ }++ // POST — act / dismiss. Enforce CSRF for cookie-session callers.+ if (auth.viaSession && !(await requireCsrf(req, res, userId))) return;++ const body = await readJson(req).catch(() => null);+ if (!body || typeof body !== 'object') return error(res, 400, 'bad_request', 'JSON body required');+ const id = String(body.id || '').trim();+ const action = body.action;+ if (!UUID_RE.test(id)) return error(res, 400, 'invalid_id', 'id must be an execution UUID');+ if (!['acted', 'dismissed'].includes(action)) return error(res, 400, 'invalid_action', 'action must be acted or dismissed');++ const txSig = action === 'acted' && typeof body.tx_signature === 'string'+ ? body.tx_signature.trim().slice(0, 128) || null : null;++ const [row] = await sql`+ update copy_executions+ set status = ${action}, tx_signature = ${txSig}, updated_at = now()+ where id = ${id} and copier_user_id = ${userId} and status = 'pending'+ returning *+ `;+ if (!row) return error(res, 409, 'not_actionable', 'No such pending intent (it may have expired or already been actioned).');+ return json(res, 200, { execution: row });+});diff --git a/api/copy/subscriptions.js b/api/copy/subscriptions.jsnew file mode 100644index 000000000..e7e0336c2--- /dev/null+++ b/api/copy/subscriptions.js@@ -0,0 +1,152 @@+/**+ * Copy-trading subscriptions — the copier's follow list.+ *+ * GET /api/copy/subscriptions list mine (+ leader info, counts)+ * POST /api/copy/subscriptions create/update a subscription+ * POST /api/copy/subscriptions { id, status } pause / resume / stop+ * DELETE /api/copy/subscriptions?id=<id> stop (soft — keeps history)+ *+ * Auth required (session cookie or bearer). Non-custodial: we store the copier's+ * own wallet and their sizing/guard rules — never keys, never custody.+ */++import { cors, json, error, method, wrap, readJson, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';+import { requireCsrf } from '../_lib/csrf.js';+import { sql } from '../_lib/db.js';+import { normalizeSubscriptionInput } from '../_lib/copy-engine.js';++const NETWORKS = new Set(['mainnet', 'devnet']);+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++// Returns { userId, viaSession } or null (after writing a 401). Cookie-session+// writes additionally require a CSRF token; bearer clients are not CSRF-vulnerable.+async function requireUser(req, res) {+ const session = await getSessionUser(req);+ const bearer = session ? null : await authenticateBearer(extractBearer(req));+ if (!session && !bearer) { error(res, 401, 'unauthorized', 'sign in required'); return null; }+ return { userId: session?.id ?? bearer.userId, viaSession: !!session };+}++async function listForUser(userId) {+ return sql`+ select s.*, a.name as leader_name, a.avatar_url as leader_avatar, a.profile_image_url as leader_image,+ (select count(*) from copy_executions e where e.subscription_id = s.id and e.status = 'pending') as pending_count,+ (select count(*) from copy_executions e where e.subscription_id = s.id and e.status = 'acted') as acted_count+ from copy_subscriptions s+ join agent_identities a on a.id = s.leader_agent_id+ where s.copier_user_id = ${userId}+ order by s.created_at desc+ `;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,DELETE,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET', 'POST', 'DELETE'])) return;++ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const auth = await requireUser(req, res);+ if (!auth) return;+ const { userId } = auth;++ if (req.method === 'GET') {+ const rows = await listForUser(userId);+ return json(res, 200, { subscriptions: rows });+ }++ // State-changing methods: enforce CSRF for cookie-session callers.+ if (auth.viaSession && !(await requireCsrf(req, res, userId))) return;++ if (req.method === 'DELETE') {+ const id = new URL(req.url, 'http://x').searchParams.get('id') || '';+ if (!UUID_RE.test(id)) return error(res, 400, 'invalid_id', 'id must be a subscription UUID');+ const [row] = await sql`+ update copy_subscriptions set status = 'stopped', updated_at = now()+ where id = ${id} and copier_user_id = ${userId}+ returning id+ `;+ if (!row) return error(res, 404, 'not_found', 'No such subscription.');+ return json(res, 200, { ok: true, id, status: 'stopped' });+ }++ // POST+ const body = await readJson(req).catch(() => null);+ if (!body || typeof body !== 'object') return error(res, 400, 'bad_request', 'JSON body required');++ // Status-only update (pause / resume / stop).+ if (body.id && body.status && Object.keys(body).length <= 2) {+ if (!UUID_RE.test(body.id)) return error(res, 400, 'invalid_id', 'id must be a subscription UUID');+ if (!['active', 'paused', 'stopped'].includes(body.status)) {+ return error(res, 400, 'invalid_status', 'status must be active, paused, or stopped');+ }+ const [row] = await sql`+ update copy_subscriptions set status = ${body.status}, updated_at = now()+ where id = ${body.id} and copier_user_id = ${userId}+ returning *+ `;+ if (!row) return error(res, 404, 'not_found', 'No such subscription.');+ return json(res, 200, { subscription: row });+ }++ // Create / update.+ const leaderId = String(body.leader_agent_id || '').trim();+ const wallet = String(body.copier_wallet || '').trim();+ const network = NETWORKS.has(body.network) ? body.network : 'mainnet';+ if (!UUID_RE.test(leaderId)) return error(res, 400, 'invalid_leader', 'leader_agent_id must be an agent UUID');+ if (!BASE58_RE.test(wallet)) return error(res, 400, 'invalid_wallet', 'copier_wallet must be a valid Solana address');++ const [leader] = await sql`+ select id, is_public from agent_identities where id = ${leaderId} limit 1+ `;+ if (!leader || leader.is_public === false) return error(res, 404, 'leader_not_found', 'No such public trader.');++ const norm = normalizeSubscriptionInput(body);+ if (!norm.ok) return error(res, 400, 'invalid_config', norm.error);+ const v = norm.value;++ // Denormalize the leader's trading wallet from their most recent sniper position.+ const [pos] = await sql`+ select wallet from agent_sniper_positions+ where agent_id = ${leaderId} and network = ${network}+ order by opened_at desc limit 1+ `;+ const leaderWallet = pos?.wallet || null;++ const [row] = await sql`+ insert into copy_subscriptions (+ copier_user_id, copier_wallet, leader_agent_id, leader_wallet, network, status,+ sizing_rule, fixed_sol, multiplier, pct_balance,+ per_trade_cap_sol, min_order_sol, daily_budget_sol, max_open_copies,+ mcap_floor_usd, mcap_ceiling_usd, copy_sells, require_safety_pass, perf_fee_bps+ ) values (+ ${userId}, ${wallet}, ${leaderId}, ${leaderWallet}, ${network}, 'active',+ ${v.sizing_rule}, ${v.fixed_sol}, ${v.multiplier}, ${v.pct_balance},+ ${v.per_trade_cap_sol}, ${v.min_order_sol}, ${v.daily_budget_sol}, ${v.max_open_copies},+ ${v.mcap_floor_usd}, ${v.mcap_ceiling_usd}, ${v.copy_sells}, ${v.require_safety_pass}, ${v.perf_fee_bps}+ )+ on conflict (copier_user_id, leader_agent_id, network) do update set+ copier_wallet = excluded.copier_wallet,+ leader_wallet = excluded.leader_wallet,+ status = 'active',+ sizing_rule = excluded.sizing_rule,+ fixed_sol = excluded.fixed_sol,+ multiplier = excluded.multiplier,+ pct_balance = excluded.pct_balance,+ per_trade_cap_sol = excluded.per_trade_cap_sol,+ min_order_sol = excluded.min_order_sol,+ daily_budget_sol = excluded.daily_budget_sol,+ max_open_copies = excluded.max_open_copies,+ mcap_floor_usd = excluded.mcap_floor_usd,+ mcap_ceiling_usd = excluded.mcap_ceiling_usd,+ copy_sells = excluded.copy_sells,+ require_safety_pass = excluded.require_safety_pass,+ perf_fee_bps = excluded.perf_fee_bps,+ updated_at = now()+ returning *+ `;+ return json(res, 200, { subscription: row });+});diff --git a/api/cron/copy-fanout.js b/api/cron/copy-fanout.jsnew file mode 100644index 000000000..a75fbb8c6--- /dev/null+++ b/api/cron/copy-fanout.js@@ -0,0 +1,184 @@+// GET /api/cron/copy-fanout — turn leader trades into copier intents.+//+// Polls agent_sniper_positions for recent entries (and closes) by agents that+// have active copy subscribers, and for each (position, subscriber) generates a+// sized, safety-checked copy INTENT via the pure copy-engine. Non-custodial: it+// only records the intent — the copier acts from their own wallet.+//+// BUY fanout: a leader opens a position → size each subscriber's order, clamp+// to their per-trade cap + remaining daily budget, gate on coin+// safety, and insert a pending intent (or a transparent 'skipped'+// row explaining why it didn't fire).+// SELL fanout: a leader closes a position → mirror an exit intent ONLY to+// copiers who actually acted on the matching buy.+//+// Idempotent via the unique (subscription_id, leader_position_id, direction).++import { error, json, method, wrap } from '../_lib/http.js';+import { env } from '../_lib/env.js';+import { constantTimeEquals } from '../_lib/crypto.js';+import { sql } from '../_lib/db.js';+import { planCopyOrder } from '../_lib/copy-engine.js';++const NETWORKS = ['mainnet', 'devnet'];+const lamToSol = (l) => (l == null ? 0 : Number(BigInt(l)) / 1e9);++function requireCron(req, res) {+ const secret = process.env.CRON_SECRET || env.CRON_SECRET;+ if (!secret) { error(res, 503, 'not_configured', 'CRON_SECRET unset'); return false; }+ const auth = req.headers['authorization'] || '';+ const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';+ if (!constantTimeEquals(presented, secret)) { error(res, 401, 'unauthorized', 'invalid cron secret'); return false; }+ return true;+}++// Best-effort coin context for the safety gate. pump.fun's public coin endpoint+// gives a live USD market cap; richer signals (dev holding, liquidity, honeypot)+// are left null and the engine treats them as "unknown".+const _coinCache = new Map();+async function coinContext(mint) {+ if (_coinCache.has(mint)) return _coinCache.get(mint);+ let ctx = null;+ try {+ const r = await fetch(`https://frontend-api-v3.pump.fun/coins/${mint}`, {+ headers: { accept: 'application/json' }, signal: AbortSignal.timeout(5000),+ });+ if (r.ok) {+ const c = await r.json();+ ctx = { market_cap_usd: Number(c.usd_market_cap) || null, graduated: !!c.complete };+ }+ } catch { /* leave null — engine handles missing context */ }+ _coinCache.set(mint, ctx);+ return ctx;+}++async function fanoutBuys(network, stats) {+ const positions = await sql`+ select p.id, p.agent_id, p.mint, p.symbol, p.name, p.entry_quote_lamports, p.buy_sig, p.opened_at+ from agent_sniper_positions p+ where p.network = ${network} and p.buy_sig is not null and p.buy_sig <> 'SIMULATED'+ and p.opened_at > now() - interval '8 minutes'+ and exists (+ select 1 from copy_subscriptions s+ where s.leader_agent_id = p.agent_id and s.network = ${network} and s.status = 'active'+ )+ order by p.opened_at desc+ limit 200+ `;+ if (!positions.length) return;++ // Per-subscription day-spend + open-intent counts, batched once.+ const spendRows = await sql`+ select subscription_id, coalesce(sum(planned_sol), 0) as spent+ from copy_executions+ where direction = 'buy' and status in ('pending', 'acted') and created_at::date = current_date+ group by subscription_id+ `;+ const openRows = await sql`+ select subscription_id, count(*) as open+ from copy_executions+ where direction = 'buy' and status = 'pending'+ group by subscription_id+ `;+ const spent = new Map(spendRows.map((r) => [r.subscription_id, Number(r.spent) || 0]));+ const open = new Map(openRows.map((r) => [r.subscription_id, Number(r.open) || 0]));++ for (const pos of positions) {+ const subs = await sql`+ select * from copy_subscriptions+ where leader_agent_id = ${pos.agent_id} and network = ${network} and status = 'active'+ `;+ if (!subs.length) continue;+ const coin = await coinContext(pos.mint);+ const entrySol = lamToSol(pos.entry_quote_lamports);++ for (const sub of subs) {+ const decision = planCopyOrder({+ subscription: sub,+ position: { direction: 'buy', entry_sol: entrySol, mint: pos.mint },+ coin,+ spentTodaySol: spent.get(sub.id) || 0,+ openCopies: open.get(sub.id) || 0,+ });+ const status = decision.action === 'copy' ? 'pending' : 'skipped';+ const planned = decision.action === 'copy' ? decision.order_sol : null;++ const [inserted] = await sql`+ insert into copy_executions (+ subscription_id, copier_user_id, leader_agent_id, leader_position_id, network,+ mint, symbol, name, direction, planned_sol, leader_entry_sol, status, skip_reason,+ safety, leader_buy_sig+ ) values (+ ${sub.id}, ${sub.copier_user_id}, ${pos.agent_id}, ${pos.id}, ${network},+ ${pos.mint}, ${pos.symbol}, ${pos.name}, 'buy', ${planned}, ${entrySol}, ${status},+ ${decision.reason && status === 'skipped' ? decision.reason : null},+ ${coin ? JSON.stringify(coin) : null}::jsonb, ${pos.buy_sig}+ )+ on conflict (subscription_id, leader_position_id, direction) do nothing+ returning id+ `;+ if (inserted) {+ stats[status] = (stats[status] || 0) + 1;+ if (status === 'pending') {+ spent.set(sub.id, (spent.get(sub.id) || 0) + (planned || 0));+ open.set(sub.id, (open.get(sub.id) || 0) + 1);+ }+ }+ }+ }+}++async function fanoutSells(network, stats) {+ // Closes whose matching buy a copier actually acted on.+ const closes = await sql`+ select distinct p.id, p.agent_id, p.mint, p.symbol, p.name, p.sell_sig, p.closed_at+ from agent_sniper_positions p+ where p.network = ${network} and p.status = 'closed' and p.closed_at > now() - interval '8 minutes'+ and exists (+ select 1 from copy_executions e+ where e.leader_position_id = p.id and e.direction = 'buy' and e.status = 'acted'+ )+ order by p.closed_at desc+ limit 200+ `;+ for (const pos of closes) {+ const buys = await sql`+ select e.subscription_id, e.copier_user_id, s.copy_sells, s.status as sub_status+ from copy_executions e+ join copy_subscriptions s on s.id = e.subscription_id+ where e.leader_position_id = ${pos.id} and e.direction = 'buy' and e.status = 'acted'+ `;+ for (const b of buys) {+ if (!b.copy_sells || b.sub_status === 'stopped') continue;+ const [inserted] = await sql`+ insert into copy_executions (+ subscription_id, copier_user_id, leader_agent_id, leader_position_id, network,+ mint, symbol, name, direction, planned_sol, status, leader_buy_sig+ ) values (+ ${b.subscription_id}, ${b.copier_user_id}, ${pos.agent_id}, ${pos.id}, ${network},+ ${pos.mint}, ${pos.symbol}, ${pos.name}, 'sell', 0, 'pending', ${pos.sell_sig}+ )+ on conflict (subscription_id, leader_position_id, direction) do nothing+ returning id+ `;+ if (inserted) stats.sell_pending = (stats.sell_pending || 0) + 1;+ }+ }+}++export default wrap(async (req, res) => {+ if (!method(req, res, ['GET', 'POST'])) return;+ if (!requireCron(req, res)) return;++ const stats = {};+ _coinCache.clear();+ for (const network of NETWORKS) {+ try {+ await fanoutBuys(network, stats);+ await fanoutSells(network, stats);+ } catch (err) {+ stats[`error_${network}`] = err.message;+ }+ }+ return json(res, 200, { ok: true, ...stats });+});diff --git a/api/cron/gmgn-seed.js b/api/cron/gmgn-seed.jsnew file mode 100644index 000000000..bef844229--- /dev/null+++ b/api/cron/gmgn-seed.js@@ -0,0 +1,165 @@+// GET/POST /api/cron/gmgn-seed — seed wallet_reputation from gmgn.ai smart money rankings.+//+// gmgn.ai maintains the industry-standard Solana smart money taxonomy: smart_degen,+// pump_smart, launchpad_smart, KOL wallets, snipers, etc. These labels predate our+// system by years and cover wallets that may never appear in our own pump_coin_wallets+// table. Seeding them gives the Oracle pedigree pillar ground truth across the+// entire ecosystem rather than only wallets we've personally observed.+//+// How it works:+// 1. Fetch each wallet-ranking tab from gmgn.ai's public (unauthenticated) API.+// The API patterns were reverse-engineered from their network traffic (see+// nirholas/scrape-smart-wallets). No API key required; we respect rate limits.+// 2. Translate gmgn tags → our label taxonomy (smart_money/sniper/dumper/neutral).+// 3. Upsert into wallet_reputation. Only sets label + smart_money_score from the+// gmgn signal; our own on-chain observed stats (wins/duds etc.) are never+// overwritten — they accumulate independently and take precedence on the score+// once we have sufficient observed history (≥5 judged coins).+// 4. Idempotent: safe to run daily. Caps at 500 wallets per run.+//+// This runs once/day at off-peak hours — wallet rankings don't change minute-to-minute.+// The per-run cap and respectful delays make it a good citizen even without auth.++import { error, json, method, wrap } from '../_lib/http.js';+import { env } from '../_lib/env.js';+import { constantTimeEquals } from '../_lib/crypto.js';+import { sql } from '../_lib/db.js';++const NETWORK = 'mainnet';+const CHAIN = 'sol';+const GMGN_BASE = 'https://gmgn.ai';+const MAX_WALLETS_PER_RUN = 500;+const FETCH_TIMEOUT_MS = 8000;+// Be respectful: 300ms between gmgn requests so we don't hammer them.+const INTER_REQUEST_DELAY_MS = 300;++function requireCron(req, res) {+ const secret = process.env.CRON_SECRET || env.CRON_SECRET;+ if (!secret) { error(res, 503, 'not_configured', 'CRON_SECRET unset'); return false; }+ const auth = req.headers['authorization'] || '';+ const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';+ if (!constantTimeEquals(presented, secret)) {+ error(res, 401, 'unauthorized', 'invalid cron secret');+ return false;+ }+ return true;+}++// gmgn tab → our label. smart_degen/pump_smart = proven smart money buyers.+// launchpad_smart = launch specialists. renowned = KOL (community influence).+// snipe_bot = sniper (high win rate but different risk profile). top_dev = creators.+const TAG_MAP = {+ smart_degen: { label: 'smart_money', score: 82 },+ pump_smart: { label: 'smart_money', score: 78 },+ launchpad_smart: { label: 'smart_money', score: 72 },+ renowned: { label: 'neutral', score: 60 }, // KOL — influence, not edge+ snipe_bot: { label: 'sniper', score: 65 },+ top_dev: { label: 'neutral', score: 55 }, // creators — not necessarily smart buyers+ fresh_wallet: { label: 'fresh', score: 30 },+};++const TIMEFRAME = '7d';++async function fetchTab(tag) {+ const url = `${GMGN_BASE}/defi/quotation/v1/rank/${CHAIN}/wallets/${TIMEFRAME}?tag=${tag}&orderby=pnl&direction=desc&limit=100`;+ const ctrl = new AbortController();+ const timer = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS);+ try {+ const res = await fetch(url, {+ headers: {+ 'User-Agent': 'Mozilla/5.0 (compatible; three.ws oracle/1.0)',+ 'Accept': 'application/json',+ 'Referer': 'https://gmgn.ai/',+ },+ signal: ctrl.signal,+ });+ if (!res.ok) return [];+ const data = await res.json();+ // gmgn returns { code: 0, data: { rank: [...] } } or { rank: [...] }+ return data?.data?.rank || data?.rank || [];+ } catch {+ return [];+ } finally {+ clearTimeout(timer);+ }+}++function sleep(ms) { return new Promise((r) => setTimeout(r, ms)); }++/**+ * Upsert a batch of seeded wallets into wallet_reputation.+ * Only touches label + smart_money_score if the wallet has < 5 judged coins+ * in our own system — once we've observed them ourselves we trust our own data.+ */+async function upsertSeeded(batch) {+ if (!batch.length) return 0;+ // Build values for a single multi-row upsert.+ const values = batch.map((w) => ({+ wallet: w.wallet,+ network: NETWORK,+ label: w.label,+ score: w.score,+ }));++ // Postgres doesn't support VALUES with json arrays easily via tagged sql;+ // process in chunks of 50 with individual upserts.+ let count = 0;+ const CHUNK = 50;+ for (let i = 0; i < values.length; i += CHUNK) {+ const chunk = values.slice(i, i + CHUNK);+ await Promise.allSettled(chunk.map((v) =>+ sql`+ insert into wallet_reputation (wallet, network, label, smart_money_score, first_seen_at, updated_at)+ values (${v.wallet}, ${v.network}, ${v.label}, ${v.score}, now(), now())+ on conflict (wallet, network) do update set+ label = case+ when wallet_reputation.coins_traded >= 5 then wallet_reputation.label+ else excluded.label+ end,+ smart_money_score = case+ when wallet_reputation.coins_traded >= 5 then wallet_reputation.smart_money_score+ else greatest(wallet_reputation.smart_money_score, excluded.smart_money_score)+ end,+ updated_at = now()+ `,+ ));+ count += chunk.length;+ }+ return count;+}++export default wrap(async (req, res) => {+ if (!method(req, res, ['GET', 'POST'])) return;+ if (!requireCron(req, res)) return;++ const started = Date.now();+ const tags = Object.keys(TAG_MAP);+ const collected = new Map(); // wallet → { label, score } — dedup, keep highest score++ for (const tag of tags) {+ const mapping = TAG_MAP[tag];+ const rows = await fetchTab(tag);+ for (const row of rows) {+ const wallet = row?.wallet_address || row?.address || row?.wallet;+ if (!wallet || typeof wallet !== 'string' || wallet.length < 32) continue;+ const existing = collected.get(wallet);+ if (!existing || mapping.score > existing.score) {+ collected.set(wallet, { wallet, label: mapping.label, score: mapping.score });+ }+ if (collected.size >= MAX_WALLETS_PER_RUN) break;+ }+ if (collected.size >= MAX_WALLETS_PER_RUN) break;+ await sleep(INTER_REQUEST_DELAY_MS);+ }++ const batch = [...collected.values()];+ const upserted = await upsertSeeded(batch);++ return json(res, 200, {+ ok: true,+ fetched: collected.size,+ upserted,+ tags_tried: tags.length,+ ms: Date.now() - started,+ });+});diff --git a/src/copy-panel.js b/src/copy-panel.jsnew file mode 100644index 000000000..18672ed3f--- /dev/null+++ b/src/copy-panel.js@@ -0,0 +1,212 @@+/**+ * Copy-setup panel — mounted on a trader profile to start/edit copying them.+ *+ * Non-custodial: the copier supplies their own wallet and sizing/guard rules; we+ * never take keys. On submit it POSTs a copy_subscription; the fan-out cron then+ * turns the leader's future trades into sized, safety-checked intents the copier+ * acts on from `/dashboard/copy`.+ *+ * Self-contained: handles signed-out (CTA), first-time (form), and already-+ * copying (summary + edit) states, plus loading/error. Import and call+ * `mountCopyPanel(el, { leaderAgentId, leaderName, network })`.+ */++import { escapeHtml } from './trader-format.js';++const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;+const $ = (sel, root) => root.querySelector(sel);++async function api(path, opts = {}) {+ const res = await fetch(path, {+ credentials: 'include',+ headers: { accept: 'application/json', ...(opts.body ? { 'content-type': 'application/json' } : {}) },+ ...opts,+ });+ return res;+}++export async function mountCopyPanel(el, { leaderAgentId, leaderName, network = 'mainnet' }) {+ el.classList.add('cp');+ el.innerHTML = `<div class="cp-loading"><span class="tp-sk" style="width:40%;height:18px"></span></div>`;++ let res;+ try {+ res = await api('/api/copy/subscriptions');+ } catch {+ return renderSignedOut(el, leaderName); // network failure → treat as unauthenticated CTA+ }++ if (res.status === 401) return renderSignedOut(el, leaderName);+ if (!res.ok) return renderError(el, () => mountCopyPanel(el, { leaderAgentId, leaderName, network }));++ const { subscriptions = [] } = await res.json().catch(() => ({ subscriptions: [] }));+ const existing = subscriptions.find((s) => s.leader_agent_id === leaderAgentId && s.network === network);++ if (existing && existing.status !== 'stopped') {+ return renderActive(el, { existing, leaderName, leaderAgentId, network });+ }+ return renderForm(el, { leaderAgentId, leaderName, network, prefill: existing || null });+}++// --- States ------------------------------------------------------------------+function renderSignedOut(el, leaderName) {+ const next = encodeURIComponent(location.pathname + location.search);+ el.innerHTML = `+ <h2>Copy ${escapeHtml(leaderName || 'this trader')}</h2>+ <p>Mirror their entries to your own wallet — non-custodially, with your own size and risk caps. Sign in to set it up.</p>+ <div class="cp-actions">+ <a class="lb-btn lb-btn-primary" href="/login?next=${next}">Sign in to copy</a>+ <a class="lb-btn" href="/play/arena">Watch in the Arena →</a>+ </div>`;+}++function renderError(el, retry) {+ el.innerHTML = `+ <h2>Copy setup</h2>+ <p>Couldn't load your copy settings. This is usually transient.</p>+ <div class="cp-actions"><button class="lb-btn lb-btn-primary" id="cp-retry">Retry</button></div>`;+ $('#cp-retry', el)?.addEventListener('click', retry);+}++function renderActive(el, { existing, leaderName, leaderAgentId, network }) {+ const s = existing;+ const sizeLabel = s.sizing_rule === 'fixed' ? `${Number(s.fixed_sol)} SOL fixed`+ : s.sizing_rule === 'multiplier' ? `${Number(s.multiplier)}× their size`+ : `${Number(s.pct_balance)}% of balance`;+ const paused = s.status === 'paused';+ el.innerHTML = `+ <h2>You're copying ${escapeHtml(leaderName || 'this trader')} ${paused ? '<span class="tp-soon" style="color:var(--ink-faint);border-color:var(--stroke)">Paused</span>' : '<span class="cp-on">● Active</span>'}</h2>+ <p>${escapeHtml(sizeLabel)} · cap ${Number(s.per_trade_cap_sol)} SOL/trade · ${Number(s.daily_budget_sol)} SOL/day.+ New trades arrive as intents in your dashboard.</p>+ <div class="cp-actions">+ <a class="lb-btn lb-btn-primary" href="/dashboard/copy">Manage copies →</a>+ <button class="lb-btn" id="cp-toggle">${paused ? 'Resume' : 'Pause'}</button>+ <button class="lb-btn" id="cp-edit">Edit size</button>+ </div>`;+ $('#cp-toggle', el)?.addEventListener('click', async () => {+ const next = paused ? 'active' : 'paused';+ const r = await api('/api/copy/subscriptions', { method: 'POST', body: JSON.stringify({ id: s.id, status: next }) });+ if (r.ok) mountCopyPanel(el, { leaderAgentId, leaderName, network });+ });+ $('#cp-edit', el)?.addEventListener('click', () => renderForm(el, { leaderAgentId, leaderName, network, prefill: s }));+}++function renderForm(el, { leaderAgentId, leaderName, network, prefill }) {+ const p = prefill || {};+ const rule = p.sizing_rule || 'fixed';+ el.innerHTML = `+ <h2>Copy ${escapeHtml(leaderName || 'this trader')}</h2>+ <p>You sign every trade from your own wallet. We never take custody — these are sized intents, capped by your rules.</p>+ <form class="cp-form" id="cp-form" novalidate>+ <label class="cp-field">+ <span class="cp-label">Your Solana wallet</span>+ <input class="cp-input" id="cp-wallet" inputmode="text" autocomplete="off" spellcheck="false"+ placeholder="Your wallet address" value="${escapeHtml(p.copier_wallet || '')}" required />+ </label>++ <div class="cp-field">+ <span class="cp-label">How to size each copy</span>+ <div class="cp-seg" id="cp-rule">+ <button type="button" class="cp-seg-btn ${rule === 'fixed' ? 'is-active' : ''}" data-rule="fixed">Fixed SOL</button>+ <button type="button" class="cp-seg-btn ${rule === 'multiplier' ? 'is-active' : ''}" data-rule="multiplier">× their size</button>+ <button type="button" class="cp-seg-btn ${rule === 'pct_balance' ? 'is-active' : ''}" data-rule="pct_balance">% of wallet</button>+ </div>+ </div>++ <div class="cp-row">+ <label class="cp-field" data-for="fixed" ${rule !== 'fixed' ? 'hidden' : ''}>+ <span class="cp-label">SOL per copy</span>+ <input class="cp-input" id="cp-fixed" type="number" step="0.01" min="0" value="${Number(p.fixed_sol) || 0.2}" />+ </label>+ <label class="cp-field" data-for="multiplier" ${rule !== 'multiplier' ? 'hidden' : ''}>+ <span class="cp-label">Multiplier (× leader)</span>+ <input class="cp-input" id="cp-mult" type="number" step="0.05" min="0" value="${Number(p.multiplier) || 0.1}" />+ </label>+ <label class="cp-field" data-for="pct_balance" ${rule !== 'pct_balance' ? 'hidden' : ''}>+ <span class="cp-label">% of your wallet</span>+ <input class="cp-input" id="cp-pct" type="number" step="1" min="0" max="100" value="${Number(p.pct_balance) || 5}" />+ </label>+ </div>++ <div class="cp-row">+ <label class="cp-field">+ <span class="cp-label">Max per trade (SOL)</span>+ <input class="cp-input" id="cp-cap" type="number" step="0.05" min="0.01" value="${Number(p.per_trade_cap_sol) || 0.5}" required />+ </label>+ <label class="cp-field">+ <span class="cp-label">Daily budget (SOL)</span>+ <input class="cp-input" id="cp-daily" type="number" step="0.1" min="0.01" value="${Number(p.daily_budget_sol) || 1}" required />+ </label>+ </div>++ <details class="cp-advanced">+ <summary>Advanced filters</summary>+ <div class="cp-row">+ <label class="cp-field">+ <span class="cp-label">Min market cap (USD)</span>+ <input class="cp-input" id="cp-mcf" type="number" step="1000" min="0" placeholder="any" value="${p.mcap_floor_usd ?? ''}" />+ </label>+ <label class="cp-field">+ <span class="cp-label">Max market cap (USD)</span>+ <input class="cp-input" id="cp-mcc" type="number" step="1000" min="0" placeholder="any" value="${p.mcap_ceiling_usd ?? ''}" />+ </label>+ </div>+ <label class="cp-check"><input type="checkbox" id="cp-sells" ${p.copy_sells === false ? '' : 'checked'} /> <span>Mirror their exits too</span></label>+ <label class="cp-check"><input type="checkbox" id="cp-safe" ${p.require_safety_pass ? 'checked' : ''} /> <span>Only copy when coin safety is confirmed</span></label>+ </details>++ <p class="cp-err" id="cp-err" hidden></p>+ <div class="cp-actions">+ <button class="lb-btn lb-btn-primary" type="submit" id="cp-submit">${prefill ? 'Save copy settings' : 'Start copying'}</button>+ </div>+ <p class="cp-fine">Copy trading is risky. You execute every trade yourself; past performance is not a guarantee.</p>+ </form>`;++ const ruleSeg = $('#cp-rule', el);+ ruleSeg.addEventListener('click', (e) => {+ const btn = e.target.closest('.cp-seg-btn');+ if (!btn) return;+ ruleSeg.querySelectorAll('.cp-seg-btn').forEach((b) => b.classList.toggle('is-active', b === btn));+ el.querySelectorAll('[data-for]').forEach((f) => { f.hidden = f.dataset.for !== btn.dataset.rule; });+ });++ $('#cp-form', el).addEventListener('submit', async (e) => {+ e.preventDefault();+ const errEl = $('#cp-err', el);+ errEl.hidden = true;+ const sizing = ruleSeg.querySelector('.cp-seg-btn.is-active')?.dataset.rule || 'fixed';+ const wallet = $('#cp-wallet', el).value.trim();+ if (!BASE58_RE.test(wallet)) return showErr(errEl, 'Enter a valid Solana wallet address.');++ const num = (id) => Number($(`#${id}`, el).value);+ const body = {+ leader_agent_id: leaderAgentId,+ network,+ copier_wallet: wallet,+ sizing_rule: sizing,+ fixed_sol: num('cp-fixed'),+ multiplier: num('cp-mult'),+ pct_balance: num('cp-pct'),+ per_trade_cap_sol: num('cp-cap'),+ daily_budget_sol: num('cp-daily'),+ mcap_floor_usd: $('#cp-mcf', el).value === '' ? null : num('cp-mcf'),+ mcap_ceiling_usd: $('#cp-mcc', el).value === '' ? null : num('cp-mcc'),+ copy_sells: $('#cp-sells', el).checked,+ require_safety_pass: $('#cp-safe', el).checked,+ };++ const btn = $('#cp-submit', el);+ btn.disabled = true; btn.textContent = 'Saving…';+ try {+ const r = await api('/api/copy/subscriptions', { method: 'POST', body: JSON.stringify(body) });+ const data = await r.json().catch(() => ({}));+ if (!r.ok) { btn.disabled = false; btn.textContent = prefill ? 'Save copy settings' : 'Start copying'; return showErr(errEl, data.message || 'Could not save.'); }+ mountCopyPanel(el, { leaderAgentId, leaderName, network });+ } catch {+ btn.disabled = false; btn.textContent = prefill ? 'Save copy settings' : 'Start copying';+ showErr(errEl, 'Network error — try again.');+ }+ });+}++function showErr(el, msg) { el.textContent = msg; el.hidden = false; }diff --git a/src/dashboard-next/pages/copy.js b/src/dashboard-next/pages/copy.jsnew file mode 100644index 000000000..b03af7f8e--- /dev/null+++ b/src/dashboard-next/pages/copy.js@@ -0,0 +1,215 @@+// dashboard-next — Copy Trading.+//+// The copier's command center for non-custodial copy trading:+// 1. Intents inbox — pending copies (leader traded → sized order to act on).+// 2. Your copies — active/paused subscriptions, with pause/resume/stop + edit link.+// 3. History — acted / dismissed / skipped / expired intents.+// Every number is real, from /api/copy/*. The copier executes each trade from+// their own wallet; we never take custody.++import { mountShell } from '../shell.js';+import { requireUser, get, post, del, esc, relTime } from '../api.js';++const SKIP_LABEL = {+ below_mcap_floor: 'Below your market-cap floor',+ above_mcap_ceiling: 'Above your market-cap ceiling',+ dev_heavy: 'Dev holds too much supply',+ low_liquidity: 'Liquidity too thin',+ honeypot: 'Flagged as a honeypot',+ safety_unknown: 'Coin safety unconfirmed',+ below_min_order: 'Sized below your minimum',+ daily_budget_spent: 'Daily budget used up',+ max_open_copies: 'Open-copies cap reached',+ sizing_unavailable: 'Could not size (no balance)',+};++const fmtSol = (n) => {+ const v = Number(n) || 0;+ return `${v.toFixed(v >= 1 ? 2 : 3)} ◎`;+};+const sizingLabel = (s) =>+ s.sizing_rule === 'fixed' ? `${Number(s.fixed_sol)} SOL fixed`+ : s.sizing_rule === 'multiplier' ? `${Number(s.multiplier)}× leader`+ : `${Number(s.pct_balance)}% of wallet`;++function pumpUrl(mint) { return `https://pump.fun/coin/${encodeURIComponent(mint)}`; }++const STYLE = `+<style>+.cp-wrap { display: grid; gap: 20px; }+.cp-sec { border: 1px solid var(--nxt-stroke); background: var(--nxt-panel); border-radius: var(--nxt-radius); padding: 18px; }+.cp-sec-h { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; margin-bottom: 14px; }+.cp-sec-h h2 { font-size: 16px; margin: 0; }+.cp-sec-h .cp-count { font-size: 12px; color: var(--nxt-ink-faint); font-variant-numeric: tabular-nums; }+.cp-empty { color: var(--nxt-ink-faint); font-size: 13px; padding: 18px 0; text-align: center; }+.cp-item { display: grid; grid-template-columns: 36px 1fr auto; gap: 12px; align-items: center; padding: 12px 0; border-bottom: 1px solid var(--nxt-line); }+.cp-item:last-child { border-bottom: 0; }+.cp-av { width: 36px; height: 36px; border-radius: 9px; object-fit: cover; background: var(--nxt-bg-2); border: 1px solid var(--nxt-stroke); }+.cp-mid { min-width: 0; }+.cp-title { font-weight: 600; font-size: 14px; display: flex; gap: 6px; align-items: center; flex-wrap: wrap; }+.cp-sub { font-size: 12px; color: var(--nxt-ink-faint); margin-top: 2px; }+.cp-sub a { color: var(--nxt-ink-dim); text-decoration: none; border-bottom: 1px dotted var(--nxt-stroke-strong); }+.cp-sub a:hover { color: var(--nxt-ink); }+.cp-side { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; justify-content: flex-end; }+.cp-amt { font-variant-numeric: tabular-nums; font-weight: 700; font-size: 15px; }+.cp-tag { font-size: 11px; padding: 1px 8px; border-radius: 999px; border: 1px solid var(--nxt-stroke); color: var(--nxt-ink-dim); }+.cp-tag.buy { color: var(--nxt-success); border-color: color-mix(in srgb, var(--nxt-success) 40%, transparent); }+.cp-tag.sell { color: var(--nxt-warn); border-color: color-mix(in srgb, var(--nxt-warn) 40%, transparent); }+.cp-tag.on { color: var(--nxt-success); }+.cp-tag.paused { color: var(--nxt-warn); }+.cp-tag.skipped, .cp-tag.expired, .cp-tag.dismissed { color: var(--nxt-ink-faint); }+.cp-tag.acted { color: var(--nxt-success); }+.cp-btn { font-size: 12px; padding: 5px 12px; border-radius: var(--nxt-radius-sm); border: 1px solid var(--nxt-stroke); background: var(--nxt-bg-2); color: var(--nxt-ink); cursor: pointer; text-decoration: none; transition: border-color .14s, transform .14s; white-space: nowrap; }+.cp-btn:hover { border-color: var(--nxt-stroke-strong); transform: translateY(-1px); }+.cp-btn.primary { background: var(--nxt-accent); color: #061018; border-color: transparent; }+.cp-btn.ghost { background: transparent; }+.cp-skeleton { height: 56px; border-radius: 10px; background: var(--nxt-bg-2); animation: cp-pulse 1.4s ease infinite; }+@keyframes cp-pulse { 0%,100% { opacity: .55 } 50% { opacity: 1 } }+.cp-note { font-size: 12px; color: var(--nxt-ink-faint); margin: 0 0 14px; }+@media (max-width: 560px) { .cp-item { grid-template-columns: 1fr; } .cp-side { justify-content: flex-start; } .cp-av { display: none; } }+</style>`;++function img(e) { return e.leader_image || e.leader_avatar || '/favicon.ico'; }+function traderHref(agentId) { return `/trader/${encodeURIComponent(agentId)}`; }++function intentRow(e) {+ const isBuy = e.direction === 'buy';+ const amount = isBuy ? `<span class="cp-amt">${fmtSol(e.planned_sol)}</span>` : `<span class="cp-tag sell">Exit your copy</span>`;+ const proof = e.leader_buy_sig ? `<a href="https://solscan.io/tx/${esc(e.leader_buy_sig)}" target="_blank" rel="noopener">leader tx ↗</a>` : '';+ return `+ <div class="cp-item" data-id="${esc(e.id)}">+ <img class="cp-av" src="${esc(img(e))}" alt="" onerror="this.style.visibility='hidden'" />+ <div class="cp-mid">+ <div class="cp-title">+ <span class="cp-tag ${isBuy ? 'buy' : 'sell'}">${isBuy ? 'BUY' : 'SELL'}</span>+ ${esc(e.symbol || e.name || 'coin')}+ <span class="cp-sub" style="margin:0">via <a href="${traderHref(e.leader_agent_id)}">${esc(e.leader_name || 'trader')}</a></span>+ </div>+ <div class="cp-sub">${relTime(e.created_at)} · ${proof}</div>+ </div>+ <div class="cp-side">+ ${amount}+ <a class="cp-btn primary" href="${pumpUrl(e.mint)}" target="_blank" rel="noopener" data-act="open">${isBuy ? 'Buy now ↗' : 'Sell ↗'}</a>+ <button class="cp-btn" data-act="acted">Mark copied</button>+ <button class="cp-btn ghost" data-act="dismissed">Dismiss</button>+ </div>+ </div>`;+}++function subRow(s) {+ const paused = s.status === 'paused';+ return `+ <div class="cp-item" data-sub="${esc(s.id)}">+ <img class="cp-av" src="${esc(img(s))}" alt="" onerror="this.style.visibility='hidden'" />+ <div class="cp-mid">+ <div class="cp-title">+ <a href="${traderHref(s.leader_agent_id)}" style="color:inherit;text-decoration:none">${esc(s.leader_name || 'trader')}</a>+ <span class="cp-tag ${paused ? 'paused' : 'on'}">${paused ? 'Paused' : '● Active'}</span>+ </div>+ <div class="cp-sub">${esc(sizingLabel(s))} · cap ${Number(s.per_trade_cap_sol)} ◎ · ${Number(s.daily_budget_sol)} ◎/day · ${Number(s.pending_count) || 0} pending</div>+ </div>+ <div class="cp-side">+ <button class="cp-btn" data-sub-act="${paused ? 'active' : 'paused'}">${paused ? 'Resume' : 'Pause'}</button>+ <a class="cp-btn ghost" href="${traderHref(s.leader_agent_id)}">Edit</a>+ <button class="cp-btn ghost" data-sub-act="stopped">Stop</button>+ </div>+ </div>`;+}++function historyRow(e) {+ const status = e.status;+ const label = status === 'skipped' ? (SKIP_LABEL[e.skip_reason] || 'Skipped') : status[0].toUpperCase() + status.slice(1);+ return `+ <div class="cp-item">+ <img class="cp-av" src="${esc(img(e))}" alt="" onerror="this.style.visibility='hidden'" />+ <div class="cp-mid">+ <div class="cp-title">${esc(e.symbol || e.name || 'coin')} <span class="cp-sub" style="margin:0">via ${esc(e.leader_name || 'trader')}</span></div>+ <div class="cp-sub">${relTime(e.created_at)} · ${e.direction === 'buy' && e.planned_sol ? fmtSol(e.planned_sol) : e.direction}</div>+ </div>+ <div class="cp-side"><span class="cp-tag ${status}">${esc(label)}</span></div>+ </div>`;+}++async function loadAndRender(host) {+ let subs, pending, history;+ try {+ [subs, pending, history] = await Promise.all([+ get('/api/copy/subscriptions').then((r) => r.subscriptions || []),+ get('/api/copy/executions?status=pending').then((r) => r.executions || []),+ get('/api/copy/executions?status=all&limit=40').then((r) => r.executions || []),+ ]);+ } catch {+ host.innerHTML = `<div class="cp-sec"><div class="cp-empty">Couldn't load your copies. <button class="cp-btn" id="cp-reload">Retry</button></div></div>`;+ host.querySelector('#cp-reload')?.addEventListener('click', () => loadAndRender(host));+ return;+ }++ const hist = history.filter((e) => e.status !== 'pending');++ host.innerHTML = `+ <div class="cp-wrap">+ <section class="cp-sec">+ <div class="cp-sec-h"><h2>Intents to act on</h2><span class="cp-count">${pending.length}</span></div>+ <p class="cp-note">When a trader you copy makes a move, a sized intent appears here. You execute it from your own wallet, then mark it copied.</p>+ <div id="cp-pending">${pending.length ? pending.map(intentRow).join('') : `<div class="cp-empty">No intents waiting. Follow a trader on the <a href="/leaderboard" style="color:var(--nxt-accent)">leaderboard</a> to start.</div>`}</div>+ </section>++ <section class="cp-sec">+ <div class="cp-sec-h"><h2>Your copies</h2><span class="cp-count">${subs.filter((s) => s.status !== 'stopped').length}</span></div>+ <div id="cp-subs">${subs.filter((s) => s.status !== 'stopped').length ? subs.filter((s) => s.status !== 'stopped').map(subRow).join('') : `<div class="cp-empty">You're not copying anyone yet. <a href="/leaderboard" style="color:var(--nxt-accent)">Find a trader →</a></div>`}</div>+ </section>++ <section class="cp-sec">+ <div class="cp-sec-h"><h2>History</h2><span class="cp-count">${hist.length}</span></div>+ <div id="cp-history">${hist.length ? hist.map(historyRow).join('') : `<div class="cp-empty">Nothing yet.</div>`}</div>+ </section>+ </div>`;++ // Intent actions+ host.querySelector('#cp-pending')?.addEventListener('click', async (e) => {+ const btn = e.target.closest('[data-act]');+ if (!btn) return;+ const action = btn.dataset.act;+ const row = btn.closest('[data-id]');+ const id = row?.dataset.id;+ if (action === 'open') return; // anchor handles navigation; intent stays until explicitly marked+ btn.disabled = true;+ try {+ await post('/api/copy/executions', { id, action });+ row.style.opacity = '0.4';+ setTimeout(() => loadAndRender(host), 250);+ } catch { btn.disabled = false; }+ });++ // Subscription actions+ host.querySelector('#cp-subs')?.addEventListener('click', async (e) => {+ const btn = e.target.closest('[data-sub-act]');+ if (!btn) return;+ const row = btn.closest('[data-sub]');+ const id = row?.dataset.sub;+ const next = btn.dataset.subAct;+ btn.disabled = true;+ try {+ if (next === 'stopped') await del(`/api/copy/subscriptions?id=${encodeURIComponent(id)}`);+ else await post('/api/copy/subscriptions', { id, status: next });+ loadAndRender(host);+ } catch { btn.disabled = false; }+ });+}++async function main() {+ const root = await mountShell();+ await requireUser();+ root.innerHTML = `+ ${STYLE}+ <header style="margin-bottom:20px">+ <h1 class="dn-h1" style="margin:0">Copy Trading</h1>+ <p class="dn-h1-sub" style="margin:0">Mirror proven traders — non-custodially, on your terms. You sign every trade.</p>+ </header>+ <div id="cp-host">+ <div class="cp-wrap"><div class="cp-skeleton"></div><div class="cp-skeleton" style="height:120px"></div></div>+ </div>`;+ await loadAndRender(root.querySelector('#cp-host'));+}++main();diff --git a/src/trader.css b/src/trader.cssindex 5149ef5f2..527ab4699 100644--- a/src/trader.css+++ b/src/trader.css@@ -169,22 +169,55 @@.tp-proof-note p { margin: 0; font-size: var(--text-sm); color: var(--ink-dim); line-height: var(--leading-normal); }.tp-proof-note strong { color: var(--ink-bright); }-/* ---- Copy panel + share ---- */+/* ---- Copy panel ---- */.tp-copy {- display: grid;- grid-template-columns: 1fr auto;- gap: var(--space-md);- align-items: center;border: 1px solid var(--stroke);border-radius: var(--radius-card);background: linear-gradient(180deg, var(--surface-2), var(--surface-1));padding: var(--space-lg);margin-top: var(--space-lg);}-.tp-copy h2 { font-family: var(--font-display); font-size: var(--text-lg); margin: 0 0 var(--space-2xs); display: flex; align-items: center; gap: var(--space-2xs); }+.tp-copy h2 { font-family: var(--font-display); font-size: var(--text-lg); margin: 0 0 var(--space-2xs); display: flex; align-items: center; gap: var(--space-2xs); flex-wrap: wrap; }.tp-soon { font-size: var(--text-2xs); text-transform: uppercase; letter-spacing: 0.06em; color: var(--warn); border: 1px solid color-mix(in srgb, var(--warn) 40%, transparent); border-radius: var(--radius-pill); padding: 1px var(--space-2xs); }-.tp-copy p { margin: 0; color: var(--ink-dim); font-size: var(--text-sm); max-width: 52ch; }-.tp-copy-actions { display: flex; flex-direction: column; gap: var(--space-2xs); }+.tp-copy p { margin: 0 0 var(--space-sm); color: var(--ink-dim); font-size: var(--text-sm); max-width: 56ch; }++/* copy-panel component (cp-*) */+.cp-loading { padding: var(--space-sm) 0; }+.cp-on { font-size: var(--text-2xs); color: var(--success); font-weight: var(--weight-semibold); }+.cp-actions { display: flex; gap: var(--space-2xs); flex-wrap: wrap; margin-top: var(--space-2xs); }+.cp-form { display: flex; flex-direction: column; gap: var(--space-sm); }+.cp-field { display: flex; flex-direction: column; gap: var(--space-3xs); flex: 1; min-width: 0; }+.cp-row { display: flex; gap: var(--space-sm); flex-wrap: wrap; }+.cp-label { font-size: var(--text-2xs); text-transform: uppercase; letter-spacing: 0.05em; color: var(--ink-faint); }+.cp-input {+ appearance: none;+ width: 100%;+ border: 1px solid var(--stroke);+ background: var(--bg-0);+ color: var(--ink-bright);+ font-family: var(--font-mono);+ font-size: var(--text-sm);+ padding: var(--space-2xs) var(--space-sm);+ border-radius: var(--radius-control);+ transition: border-color var(--duration-fast) var(--ease-standard);+}+.cp-input:focus-visible { outline: none; border-color: var(--accent); }+.cp-seg { display: inline-flex; padding: 3px; gap: 2px; border: 1px solid var(--stroke); border-radius: var(--radius-pill); background: var(--surface-1); width: fit-content; }+.cp-seg-btn {+ appearance: none; border: 0; background: transparent; color: var(--ink-dim);+ font-family: var(--font-body); font-size: var(--text-xs); font-weight: var(--weight-medium);+ padding: var(--space-2xs) var(--space-md); border-radius: var(--radius-pill); cursor: pointer;+ transition: color var(--duration-fast) var(--ease-standard), background var(--duration-fast) var(--ease-standard);+}+.cp-seg-btn:hover { color: var(--ink-bright); }+.cp-seg-btn.is-active { background: var(--accent); color: var(--btn-primary-fg); }+.cp-advanced { border-top: 1px solid var(--hairline); padding-top: var(--space-sm); }+.cp-advanced summary { font-size: var(--text-xs); color: var(--ink-dim); cursor: pointer; user-select: none; }+.cp-advanced summary:hover { color: var(--ink-bright); }+.cp-advanced .cp-row { margin-top: var(--space-sm); }+.cp-check { display: flex; align-items: center; gap: var(--space-2xs); font-size: var(--text-xs); color: var(--ink-dim); margin-top: var(--space-2xs); cursor: pointer; }+.cp-err { color: var(--danger); font-size: var(--text-xs); margin: 0; }+.cp-fine { color: var(--ink-faint); font-size: var(--text-2xs); margin: 0; }/* ---- States / skeleton ---- */.tp-skel { border: 1px solid var(--stroke); border-radius: var(--radius-card); background: var(--surface-1); padding: var(--space-lg); }diff --git a/src/trader.js b/src/trader.jsindex ce770e491..dd29d8933 100644--- a/src/trader.js+++ b/src/trader.js@@ -12,6 +12,7 @@ import {escapeHtml, fmtSol, fmtUsd, fmtPct, pnlClass, shortAddr, holdTime, relTime,identicon, verifiedBadge,} from './trader-format.js';+import { mountCopyPanel } from './copy-panel.js';const WINDOWS = ['24h', '7d', '30d', 'all'];const WINDOW_LABEL = { '24h': '24h', '7d': '7d', '30d': '30d', all: 'All-time' };@@ -238,21 +239,14 @@ function render(data) {</tr></thead><tbody>${closedRows(data.closed)}</tbody></table></div>- <section class="tp-copy">- <div>- <h2>Copy this trader <span class="tp-soon">Soon</span></h2>- <p>One-tap copy-trading — mirror ${escapeHtml(a.name || 'this agent')}'s entries to your own wallet, non-custodially, while they earn only when you profit — is the next release. Watch them trade live in the Arena meanwhile.</p>- </div>- <div class="tp-copy-actions">- <a class="lb-btn lb-btn-primary" href="/play/arena">Watch live in the Arena →</a>- <a class="lb-btn" href="/leaderboard">Back to leaderboard</a>- </div>- </section>+ <section class="tp-copy" id="tp-copy-panel"></section>`;wireTabs();wireWindow();wireShare();+ const panel = document.getElementById('tp-copy-panel');+ if (panel) mountCopyPanel(panel, { leaderAgentId: a.id, leaderName: a.name, network: ctx.network });root.setAttribute('aria-busy', 'false');}diff --git a/vercel.json b/vercel.jsonindex fc68f440b..fef1c4325 100644--- a/vercel.json+++ b/vercel.json@@ -6,6 +6,9 @@"NODE_OPTIONS": "--no-deprecation"},"functions": {+ "api/cron/copy-fanout.js": {+ "maxDuration": 120+ },"api/club/tips-stream.js": {"includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}","maxDuration": 300@@ -69,6 +72,9 @@"includeFiles": "{examples/skills/**,data/pages.json,data/_generated/**,sdk/src/sas-config.json}","maxDuration": 120},+ "api/cron/gmgn-seed.js": {+ "maxDuration": 300+ },"api/cron/[name].js": {"includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}","maxDuration": 300@@ -132,6 +138,38 @@"api/**/*.js": {"includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}","maxDuration": 30+ },+ "api/oracle/coin.js": {+ "includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",+ "maxDuration": 30+ },+ "api/oracle/feed.js": {+ "includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",+ "maxDuration": 30+ },+ "api/oracle/signal.js": {+ "includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",+ "maxDuration": 30+ },+ "api/oracle/stream.js": {+ "includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",+ "maxDuration": 300+ },+ "api/oracle/wallet.js": {+ "includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",+ "maxDuration": 30+ },+ "api/oracle/watch.js": {+ "includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",+ "maxDuration": 30+ },+ "api/copy/executions.js": {+ "includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",+ "maxDuration": 30+ },+ "api/copy/subscriptions.js": {+ "includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",+ "maxDuration": 30}},"routes": [@@ -229,7 +267,7 @@"src": "/avatar-wallet-chat/","dest": "/avatar-wallet-chat.html"},-{+ {"src": "/support","dest": "/support.html"},@@ -549,6 +587,10 @@"src": "/leaderboard/?","dest": "/leaderboard.html"},+ {+ "src": "/oracle/?",+ "dest": "/oracle.html"+ },{"src": "/trader/([^/]+)/?","dest": "/trader.html"@@ -1707,6 +1749,38 @@"src": "/api/pump/smart-money","dest": "/api/pump/smart-money.js"},+ {+ "src": "/api/oracle/coin",+ "dest": "/api/oracle/coin.js"+ },+ {+ "src": "/api/oracle/feed",+ "dest": "/api/oracle/feed.js"+ },+ {+ "src": "/api/oracle/signal",+ "dest": "/api/oracle/signal.js"+ },+ {+ "src": "/api/oracle/stream",+ "dest": "/api/oracle/stream.js"+ },+ {+ "src": "/api/oracle/wallet",+ "dest": "/api/oracle/wallet.js"+ },+ {+ "src": "/api/oracle/watch",+ "dest": "/api/oracle/watch.js"+ },+ {+ "src": "/api/copy/executions",+ "dest": "/api/copy/executions.js"+ },+ {+ "src": "/api/copy/subscriptions",+ "dest": "/api/copy/subscriptions.js"+ },{"src": "/api/pump/build-metadata","dest": "/api/pump/[action]?action=build-metadata"@@ -3191,6 +3265,10 @@"path": "/api/cron/oracle-score","schedule": "*/2 * * * *"},+ {+ "path": "/api/cron/gmgn-seed",+ "schedule": "0 3 * * *"+ },{"path": "/api/cron/quota-check","schedule": "0 * * * *"@@ -3251,6 +3329,10 @@"path": "/api/cron/trader-score-attest","schedule": "45 9 * * *"},+ {+ "path": "/api/cron/copy-fanout",+ "schedule": "*/2 * * * *"+ },{"path": "/api/cron/index-delegations","schedule": "*/5 * * * *"diff --git a/workers/agent-sniper/intel/classify.js b/workers/agent-sniper/intel/classify.jsindex f1ba9a023..cfbaefb34 100644--- a/workers/agent-sniper/intel/classify.js+++ b/workers/agent-sniper/intel/classify.js@@ -3,13 +3,16 @@// Category: meme | tech | ai | culture | community | political | news | animal |// celebrity | utility | unknown//-// Two layers, and it NEVER fails (Rule 9):+// Three layers, and it NEVER fails (Rule 9):// 1. A deterministic keyword heuristic — instant, free, always available.-// 2. An LLM pass (free-first via llmComplete) that refines category, extracts-// tags + a one-line narrative thesis, and flags news-driven memes.-// If the LLM is unavailable or times out, the heuristic result stands.+// 2. Real-time news headline matching via cryptocurrency.cv API (2-min cached).+// This gives is_news_meme ground truth — not a guess.+// 3. An LLM pass (free-first via llmComplete) that refines category, extracts+// tags + a one-line narrative thesis.+// If the LLM is unavailable or times out, the heuristic + news-match stand.import { llmComplete } from '../../../api/_lib/llm.js';+import { matchNewsHeadline } from '../../../api/_lib/pump-intel/news-matcher.js';const CATEGORIES = ['meme', 'tech', 'ai', 'culture', 'community',@@ -101,44 +104,102 @@ function parseJson(text) {}/**- * Full classification: heuristic seed, then LLM refinement when available.+ * Full classification: heuristic seed → real-time news match → LLM refinement.* Always resolves to a usable record — never throws.*- * @returns {Promise<{category, tags, narrative, is_news_meme, confidence, source}>}+ * @returns {Promise<{category, tags, narrative, is_news_meme, news_headline, news_url, confidence, source}>}*/export async function classifyCoin(coin = {}, { timeoutMs = 12_000, useLlm = true } = {}) {const seed = heuristicClassify(coin);- // LLM disabled (cost control), or nothing to feed it — keep the heuristic.+ // Layer 2: real-time news headline match (fast, cached, no LLM cost).+ // Runs in parallel with any subsequent LLM call so it never adds latency.+ const newsMatchPromise = (coin.name || coin.symbol || coin.description)+ ? matchNewsHeadline(coin).catch(() => ({ matched: false, headline: null, url: null, confidence: 0 }))+ : Promise.resolve({ matched: false, headline: null, url: null, confidence: 0 });++ // LLM disabled (cost control), or nothing to feed it — keep heuristic + news.if (!useLlm || (!coin.name && !coin.symbol && !coin.description)) {- return { ...seed, narrative: null, is_news_meme: false };+ const news = await newsMatchPromise;+ const category = (news.matched && seed.category === 'unknown') ? 'news' : seed.category;+ return {+ ...seed,+ category,+ narrative: null,+ is_news_meme: news.matched,+ news_headline: news.headline,+ news_url: news.url,+ confidence: news.matched ? Math.max(seed.confidence, news.confidence) : seed.confidence,+ };}- try {- const raw = await llmComplete({+ // Layer 3: LLM + news in parallel+ const [llmResult, news] = await Promise.allSettled([+ llmComplete({system: SYSTEM,user: buildUser(coin),maxTokens: 300,timeoutMs,- });- const parsed = parseJson(typeof raw === 'string' ? raw : raw?.text);- if (!parsed) return { ...seed, narrative: null, is_news_meme: false };+ }),+ newsMatchPromise,+ ]);++ const newsMatch = news.status === 'fulfilled' ? news.value+ : { matched: false, headline: null, url: null, confidence: 0 };++ try {+ const raw = llmResult.status === 'fulfilled' ? llmResult.value : null;+ const parsed = raw ? parseJson(typeof raw === 'string' ? raw : raw?.text) : null;++ if (!parsed) {+ // LLM failed — heuristic + news match+ const category = (newsMatch.matched && seed.category === 'unknown') ? 'news' : seed.category;+ return {+ ...seed,+ category,+ narrative: null,+ is_news_meme: newsMatch.matched,+ news_headline: newsMatch.headline,+ news_url: newsMatch.url,+ confidence: newsMatch.matched ? Math.max(seed.confidence, newsMatch.confidence) : seed.confidence,+ };+ }const tags = Array.isArray(parsed.tags)? parsed.tags.map((t) => String(t).toLowerCase().trim()).filter(Boolean).slice(0, 6): seed.tags;const conf = Number(parsed.confidence);++ // news-matcher overrides LLM's is_news_meme when it found a real headline —+ // a real URL is more trustworthy than the model's guess.+ const is_news_meme = newsMatch.matched || !!parsed.is_news_meme;+ const llmCategory = coerceCategory(parsed.category);+ const category = (newsMatch.matched && llmCategory !== 'news') ? 'news' : llmCategory;+return {- category: coerceCategory(parsed.category),+ category,tags: tags.length ? tags : seed.tags,narrative: parsed.narrative ? String(parsed.narrative).slice(0, 280) : null,- is_news_meme: !!parsed.is_news_meme,- confidence: Number.isFinite(conf) ? Math.max(0, Math.min(1, conf)) : 0.6,+ is_news_meme,+ news_headline: newsMatch.headline,+ news_url: newsMatch.url,+ confidence: Number.isFinite(conf)+ ? Math.max(0, Math.min(1, newsMatch.matched ? Math.max(conf, newsMatch.confidence) : conf))+ : (newsMatch.matched ? Math.max(seed.confidence, newsMatch.confidence) : 0.6),source: 'llm',};} catch {- // LLM unavailable / timed out — heuristic stands. Never block the pipeline.- return { ...seed, narrative: null, is_news_meme: false };+ // LLM parse failed — heuristic + news+ const category = (newsMatch.matched && seed.category === 'unknown') ? 'news' : seed.category;+ return {+ ...seed,+ category,+ narrative: null,+ is_news_meme: newsMatch.matched,+ news_headline: newsMatch.headline,+ news_url: newsMatch.url,+ confidence: newsMatch.matched ? Math.max(seed.confidence, newsMatch.confidence) : seed.confidence,+ };}}diff --git a/workers/agent-sniper/intel/store.js b/workers/agent-sniper/intel/store.jsindex 5eb2648d9..a03c89b01 100644--- a/workers/agent-sniper/intel/store.js+++ b/workers/agent-sniper/intel/store.js@@ -57,6 +57,7 @@ export async function persistIntel(rec, walletAgg) {if (!sql) return;const s = rec.signals || {};+ const notableJson = JSON.stringify(rec.smart_money_notable || []);try {await sql`insert into pump_coin_intel (@@ -67,7 +68,9 @@ export async function persistIntel(rec, walletAgg) {unique_buyers, unique_sellers, largest_buy_lamports,signals, bundle_score, organic_score, snipe_ratio, concentration_top10,fresh_wallet_ratio, bubblemap_connectivity, quality_score, risk_flags,- category, tags, narrative, classify_confidence, classify_source, updated_at+ category, tags, narrative, is_news_meme, classify_confidence, classify_source,+ smart_money_count, smart_money_score, smart_money_notable,+ cluster_count, updated_at) values (${rec.mint}, ${rec.network || 'mainnet'}, ${rec.symbol || null}, ${rec.name || null},${rec.creator || null}, ${rec.bonding_curve || null}, ${rec.image_uri || null}, ${rec.description || null},@@ -78,10 +81,12 @@ export async function persistIntel(rec, walletAgg) {${s.unique_buyers ?? 0}, ${s.unique_sellers ?? 0}, ${big(rec.largest_buy_lamports)},${JSON.stringify(s)}::jsonb, ${s.bundle_score ?? null}, ${s.organic_score ?? null},${s.snipe_ratio ?? null}, ${s.concentration_top10 ?? null},- ${s.fresh_wallet_ratio ?? null}, ${s.bubblemap_connectivity ?? null},+ ${s.fresh_wallet_ratio ?? null}, ${rec.bubblemap_connectivity ?? s.bubblemap_connectivity ?? null},${rec.quality_score ?? null}, ${rec.risk_flags || []},${rec.category || null}, ${rec.tags || []}, ${rec.narrative || null},- ${rec.classify_confidence ?? null}, ${rec.classify_source || null}, now()+ ${!!rec.is_news_meme}, ${rec.classify_confidence ?? null}, ${rec.classify_source || null},+ ${rec.smart_money_count ?? 0}, ${rec.smart_money_score ?? null}, ${notableJson}::jsonb,+ ${rec.cluster_count ?? 0}, now())on conflict (mint) do update setsymbol = excluded.symbol, name = excluded.name,@@ -101,8 +106,14 @@ export async function persistIntel(rec, walletAgg) {bubblemap_connectivity = excluded.bubblemap_connectivity,quality_score = excluded.quality_score, risk_flags = excluded.risk_flags,category = excluded.category, tags = excluded.tags, narrative = excluded.narrative,+ is_news_meme = excluded.is_news_meme,classify_confidence = excluded.classify_confidence,- classify_source = excluded.classify_source, updated_at = now()+ classify_source = excluded.classify_source,+ smart_money_count = excluded.smart_money_count,+ smart_money_score = excluded.smart_money_score,+ smart_money_notable = excluded.smart_money_notable,+ cluster_count = excluded.cluster_count,+ updated_at = now()`;} catch (err) {console.warn('[coin-intel] persist intel failed:', err?.message);@@ -119,22 +130,25 @@ async function persistWallets(sql, mint, creator, walletAgg) {.slice(0, 200);try {for (const [wallet, w] of rows) {+ // funder is written by the funding-graph enrichment step in watcher.js+ const funder = w.funder || null;await sql`insert into pump_coin_wallets (mint, wallet, buy_count, sell_count, buy_lamports, sell_lamports,- base_bought, base_sold, first_seen_at, last_seen_at, is_creator+ base_bought, base_sold, first_seen_at, last_seen_at, is_creator, funder) values (${mint}, ${wallet}, ${w.buyCount}, ${w.sellCount},${big(w.buyLamports)}, ${big(w.sellLamports)},${big(w.baseBought)}, ${big(w.baseSold)},to_timestamp(${Math.floor(w.firstTs / 1000)}), to_timestamp(${Math.floor(w.lastTs / 1000)}),- ${wallet === creator}+ ${wallet === creator}, ${funder})on conflict (mint, wallet) do update setbuy_count = excluded.buy_count, sell_count = excluded.sell_count,buy_lamports = excluded.buy_lamports, sell_lamports = excluded.sell_lamports,base_bought = excluded.base_bought, base_sold = excluded.base_sold,- last_seen_at = excluded.last_seen_at+ last_seen_at = excluded.last_seen_at,+ funder = coalesce(excluded.funder, pump_coin_wallets.funder)`;}} catch (err) {diff --git a/workers/agent-sniper/intel/watcher.js b/workers/agent-sniper/intel/watcher.jsindex 17e8ee8dd..b11832554 100644--- a/workers/agent-sniper/intel/watcher.js+++ b/workers/agent-sniper/intel/watcher.js@@ -15,6 +15,8 @@ import WebSocket from 'ws';import { computeSignals } from './signals.js';import { classifyCoin } from './classify.js';import { persistIntel } from './store.js';+import { resolveWalletFunders, buildClusters } from '../../../api/_lib/pump-intel/funder-graph.js';+import { crossReferenceSmartMoney } from '../../../api/_lib/pump-intel/smart-money-xref.js';import { log } from '../log.js';const PUMPPORTAL_WS = 'wss://pumpportal.fun/api/data';@@ -150,6 +152,8 @@ export function startIntelWatcher({try {const endedAtMs = Date.now();++ // ── Phase 1: deterministic signal computation (sync, no I/O) ─────────const { signals, quality_score, risk_flags, walletAgg } = computeSignals({mint,creator: obs.creator,@@ -161,14 +165,70 @@ export function startIntelWatcher({});if (obs.mcSolFirstSeen != null) signals.mc_sol_first_seen = obs.mcSolFirstSeen;- const cls = await classifyCoin({- name: obs.meta.name,- symbol: obs.meta.symbol,- description: obs.meta.description,- twitter: obs.meta.twitter,- telegram: obs.meta.telegram,- website: obs.meta.website,- }, { useLlm });+ // ── Phase 2: parallel enrichment (network I/O, best-effort) ──────────+ // All three run concurrently; any failure degrades gracefully to null.+ const buyerWallets = [...walletAgg.keys()].filter((w) => {+ const a = walletAgg.get(w);+ return a && a.buyCount > 0;+ });++ const [cls, funderMap, smartMoneyResult] = await Promise.allSettled([+ // 2a. LLM/heuristic classification+ classifyCoin({+ name: obs.meta.name,+ symbol: obs.meta.symbol,+ description: obs.meta.description,+ twitter: obs.meta.twitter,+ telegram: obs.meta.telegram,+ website: obs.meta.website,+ }, { useLlm }),++ // 2b. Funding-graph: resolve SOL funder for each buyer wallet.+ // We skip wallets with no buy activity and cap at 60 to stay within+ // Helius rate limits. The most active/suspicious wallets are scored+ // first because walletAgg preserves insertion order (arrival time).+ resolveWalletFunders(buyerWallets.slice(0, 60)),++ // 2c. Smart-money cross-reference: which observed buyers have a proven+ // track record in wallet_reputation? Runs a single batched DB query.+ crossReferenceSmartMoney(buyerWallets),+ ]);++ // Unwrap settled results — never let a single failure abort the record.+ const classification = cls.status === 'fulfilled' ? cls.value+ : { category: 'unknown', tags: [], narrative: null, is_news_meme: false, confidence: 0.15, source: 'heuristic' };++ const resolvedFunders = funderMap.status === 'fulfilled' ? funderMap.value : new Map();+ const { clusters, connectivity } = buildClusters(resolvedFunders);++ const smartMoney = smartMoneyResult.status === 'fulfilled' ? smartMoneyResult.value+ : { count: 0, notable: [], top_label: null };++ // Push funder into walletAgg so persistIntel writes it to pump_coin_wallets+ for (const [wallet, funder] of resolvedFunders) {+ const entry = walletAgg.get(wallet);+ if (entry) entry.funder = funder || null;+ }++ // ── Phase 3: upgrade signals with enrichment results ─────────────────+ if (connectivity != null) signals.bubblemap_connectivity = connectivity;+ signals.smart_money_count = smartMoney.count;+ signals.smart_money_score = smartMoney.score ?? null;+ // Re-derive organic score with connectivity and fresh_wallet_ratio if available.+ // (bubblemap_connectivity penalises coordination; smart money boosts confidence.)+ if (connectivity != null) {+ const existing = signals.organic_score ?? 0;+ signals.organic_score = Math.max(0, Math.min(1,+ existing * (1 - 0.3 * connectivity) + (smartMoney.count > 0 ? 0.05 * Math.min(smartMoney.count, 3) : 0)+ ));+ signals.organic_score = Math.round(signals.organic_score * 10000) / 10000;+ }++ // Flag coordinated cluster in risk_flags if connectivity is high.+ if (connectivity != null && connectivity >= 0.4 && !risk_flags.includes('coordinated_cluster')) {+ risk_flags.push('coordinated_cluster');+ }+ // Smart money entering is an additive signal, not a risk flag — store in signals only.const record = {mint,@@ -190,22 +250,52 @@ export function startIntelWatcher({sell_volume_lamports: solToLamports(signals.sell_volume_sol || 0),largest_buy_lamports: solToLamports(signals.largest_buy_sol || 0),signals,- quality_score,+ quality_score: recomputeQuality(quality_score, signals, smartMoney.count),risk_flags,- category: cls.category,- tags: cls.tags,- narrative: cls.narrative,- classify_confidence: cls.confidence,- classify_source: cls.source,+ category: classification.category,+ tags: classification.tags,+ narrative: classification.narrative,+ is_news_meme: classification.is_news_meme,+ classify_confidence: classification.confidence,+ classify_source: classification.source,+ // Smart-money enrichment fields (stored in record, persisted via new migration)+ smart_money_count: smartMoney.count,+ smart_money_score: smartMoney.score ?? null,+ smart_money_notable: smartMoney.notable,+ // Cluster summary+ cluster_count: clusters.size,+ bubblemap_connectivity: connectivity,};await persistIntel(record, walletAgg);if (active && onIntel) { try { onIntel(record); } catch {} }++ log.info?.('intel finalized', {+ mint,+ symbol: obs.meta.symbol,+ quality: record.quality_score,+ category: record.category,+ smart_money: smartMoney.count,+ connectivity: connectivity != null ? connectivity.toFixed(3) : null,+ clusters: clusters.size,+ buyers: buyerWallets.length,+ });} catch (err) {log.error?.('intel finalize failed', { mint, err: err?.message });}}+ // Recompute quality score incorporating smart-money signal.+ // Smart money entering early is the strongest positive signal we have.+ function recomputeQuality(baseScore, signals, smartMoneyCount) {+ let q = baseScore;+ if (smartMoneyCount >= 1) q += 8;+ if (smartMoneyCount >= 2) q += 6;+ if (smartMoneyCount >= 3) q += 4;+ // connectivity penalty already applied to organic_score; don't double-count.+ return Math.max(0, Math.min(100, Math.round(q)));+ }+function connect() {if (!active) return;ws = new WebSocket(PUMPPORTAL_WS);