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
Wire intel_confirmed sniper trigger, coin classifier, trader stats; club audio
nirholasc0581771d010
diff --git a/api/_lib/migrations/20260615070000_sniper_intel_trigger.sql b/api/_lib/migrations/20260615070000_sniper_intel_trigger.sqlnew file mode 100644index 000000000..11834607a--- /dev/null+++ b/api/_lib/migrations/20260615070000_sniper_intel_trigger.sql@@ -0,0 +1,49 @@+-- Migration: add the "intel_confirmed" trigger + intel filters to the sniper.+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/20260615070000_sniper_intel_trigger.sql+-- Idempotent.+--+-- The Coin Intelligence Engine (workers/agent-sniper/intel) finishes observing a+-- coin ~90s after launch and produces a quality score + bundle/organic/dev+-- signals. A new-mint snipe can't wait that long, so this adds a third trigger:+--+-- trigger = 'intel_confirmed' — the sniper buys AFTER the observation window,+-- only when the finished intel clears the owner's quality/bundle/concentration+-- gates. Slower than a raw snipe, dramatically safer: it trades confirmed+-- organic launches, not coin-flips. Routes through the SAME executor and+-- position-lifecycle path as the other triggers.++begin;++-- Extend the trigger enums. The inline column checks from the first_claim+-- migration are named <table>_<column>_check; drop and re-add with the new value.+alter table agent_sniper_strategies drop constraint if exists agent_sniper_strategies_trigger_check;+alter table agent_sniper_strategies+ add constraint agent_sniper_strategies_trigger_check+ check (trigger in ('new_mint', 'first_claim', 'intel_confirmed'));++alter table agent_sniper_positions drop constraint if exists agent_sniper_positions_entry_trigger_check;+alter table agent_sniper_positions+ add constraint agent_sniper_positions_entry_trigger_check+ check (entry_trigger in ('new_mint', 'first_claim', 'intel_confirmed'));++-- Intel gates (null = ignore). Applied to intel_confirmed strategies; also+-- available as bonus filters for the other triggers once intel exists for a mint.+alter table agent_sniper_strategies+ add column if not exists min_quality_score int+ check (min_quality_score is null or (min_quality_score >= 0 and min_quality_score <= 100)),+ -- reject coins whose bundle likelihood exceeds this (0..1). Default-safe via app layer.+ add column if not exists max_bundle_score numeric+ check (max_bundle_score is null or (max_bundle_score >= 0 and max_bundle_score <= 1)),+ -- reject coins where a single wallet captured more than this share of net buys (0..1).+ add column if not exists max_concentration_top1 numeric+ check (max_concentration_top1 is null or (max_concentration_top1 >= 0 and max_concentration_top1 <= 1)),+ -- skip coins where the dev sold inside the observation window.+ add column if not exists avoid_dev_dump boolean not null default true,+ -- restrict to specific categories (meme/tech/ai/...). null/empty = any.+ add column if not exists allowed_categories text[];++create index if not exists agent_sniper_strategies_intel+ on agent_sniper_strategies (enabled, kill_switch)+ where enabled = true and kill_switch = false and trigger = 'intel_confirmed';++commit;diff --git a/api/_lib/trader-stats.js b/api/_lib/trader-stats.jsindex a75514da8..44affafb0 100644--- a/api/_lib/trader-stats.js+++ b/api/_lib/trader-stats.js@@ -398,7 +398,18 @@ export async function getTraderStats({ agentId, network, window = 'all', now = D* agents — if it ever grows past a few hundred active traders per window, move the* grouping into SQL with a windowed aggregate.*/-export async function getLeaderboard({ network, window = '30d', limit = 100, now = Date.now() }) {+export const LEADERBOARD_SORTS = new Set(['score', 'pnl', 'winrate', 'roi']);++const SORT_COMPARATORS = {+ score: (a, b) => b.score - a.score || b.realized_pnl_sol - a.realized_pnl_sol,+ pnl: (a, b) => b.realized_pnl_sol - a.realized_pnl_sol || b.score - a.score,+ winrate: (a, b) => b.win_rate - a.win_rate || b.closed - a.closed,+ roi: (a, b) => b.roi_pct - a.roi_pct || b.realized_pnl_sol - a.realized_pnl_sol,+};++export async function getLeaderboard({+ network, window = '30d', limit = 100, sort = 'score', verifiedOnly = false, now = Date.now(),+}) {const start = windowStartIso(window, now);const rows = start? await sql`@@ -469,10 +480,10 @@ export async function getLeaderboard({ network, window = '30d', limit = 100, nowlast_active_at: m.last_active_at,};})- // Primary rank: score. Tie-break by realized SOL so a higher absolute book wins.- .sort((a, b) => b.score - a.score || b.realized_pnl_sol - a.realized_pnl_sol)+ .filter((r) => (verifiedOnly ? r.verified : true))+ .sort(SORT_COMPARATORS[sort] || SORT_COMPARATORS.score).slice(0, limit).map((r, i) => ({ rank: i + 1, ...r }));- return { network, window, sol_usd: solUsd, leaderboard: board, t: now };+ return { network, window, sort, sol_usd: solUsd, leaderboard: board, t: now };}diff --git a/api/sniper/leaderboard.js b/api/sniper/leaderboard.jsindex 8b12a3ec6..6d7b351ae 100644--- a/api/sniper/leaderboard.js+++ b/api/sniper/leaderboard.js@@ -1,17 +1,23 @@/*** Agent Sniper — public leaderboard + recent trades.*- * GET /api/sniper/leaderboard?network=mainnet+ * GET /api/sniper/leaderboard?network=mainnet&window=30d&sort=score&verified=1*- * Ranks agents by realized P&L from agent_sniper_positions and returns the most- * recent closed trades + currently-open positions for the /play arena's initial- * render. Public + IP rate-limited — the on-chain tx signatures are the proof,- * so the whole point is that anyone can watch.+ * Ranks agents by their composite TraderScore (or a chosen metric) over a time+ * window, computed by the shared trader-stats truth layer so this board and the+ * /trader/:id profile can never disagree. Also returns the most recent closed+ * trades + currently-open positions for the /play arena's initial render. Public+ * + IP rate-limited — the on-chain tx signatures are the proof, so the whole+ * point is that anyone can watch.+ *+ * Backward-compatible: every field the arena already reads is still present; the+ * board rows are now a SUPERSET (win_rate, score, verified, roi_pct, drawdown, …).*/import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { sql } from '../_lib/db.js';+import { getLeaderboard, WINDOWS, LEADERBOARD_SORTS } from '../_lib/trader-stats.js';const NETWORKS = new Set(['mainnet', 'devnet']);@@ -29,26 +35,16 @@ export default wrap(async (req, res) => {const rl = await limits.mcpIp(clientIp(req));if (!rl.success) return rateLimited(res, rl);- const url = new URL(req.url, `http://${req.headers.host || 'x'}`);- const network = NETWORKS.has(url.searchParams.get('network')) ? url.searchParams.get('network') : 'mainnet';+ const params = new URL(req.url, `http://${req.headers.host || 'x'}`).searchParams;+ const network = NETWORKS.has(params.get('network')) ? params.get('network') : 'mainnet';+ // Default 'all' preserves the arena's historical lifetime ranking; the flagship+ // /leaderboard page requests an explicit window.+ const window = WINDOWS.has(params.get('window')) ? params.get('window') : 'all';+ const sort = LEADERBOARD_SORTS.has(params.get('sort')) ? params.get('sort') : 'score';+ const verifiedOnly = params.get('verified') === '1' || params.get('verified') === 'true';- const [board, recent, open] = await Promise.all([- sql`- select p.agent_id, p.wallet,- a.name as agent_name, a.avatar_url as agent_avatar, a.profile_image_url as agent_image,- count(*) filter (where p.status = 'closed') as closed,- count(*) filter (where p.status in ('open','opening','closing')) as open_positions,- count(*) filter (where p.exit_reason = 'take_profit') as wins,- coalesce(sum(p.realized_pnl_lamports),0)::text as realized_pnl_lamports,- coalesce(avg(p.realized_pnl_pct) filter (where p.status = 'closed'),0)::float as avg_pnl_pct,- max(p.realized_pnl_pct) filter (where p.status = 'closed')::float as best_pnl_pct- from agent_sniper_positions p- join agent_identities a on a.id = p.agent_id- where p.network = ${network}- group by p.agent_id, p.wallet, a.name, a.avatar_url, a.profile_image_url- order by sum(p.realized_pnl_lamports) desc nulls last- limit 100- `,+ const [boardResult, recent, open] = await Promise.all([+ getLeaderboard({ network, window, sort, verifiedOnly, limit: 100 }),sql`select p.id, p.agent_id, a.name as agent_name, p.mint, p.symbol, p.name,p.entry_quote_lamports, p.exit_quote_lamports, p.realized_pnl_lamports,@@ -71,21 +67,6 @@ export default wrap(async (req, res) => {`,]);- const leaderboard = board.map((r, i) => ({- rank: i + 1,- agent_id: r.agent_id,- agent_name: r.agent_name,- image: r.agent_image || r.agent_avatar || null,- wallet: r.wallet,- closed: Number(r.closed),- open_positions: Number(r.open_positions),- wins: Number(r.wins),- realized_pnl_lamports: r.realized_pnl_lamports,- realized_pnl_sol: Number(BigInt(r.realized_pnl_lamports)) / 1e9,- avg_pnl_pct: r.avg_pnl_pct != null ? Number(r.avg_pnl_pct) : 0,- best_pnl_pct: r.best_pnl_pct != null ? Number(r.best_pnl_pct) : null,- }));-const trades = recent.map((t) => ({id: t.id,agent_id: t.agent_id,@@ -121,5 +102,14 @@ export default wrap(async (req, res) => {};});- return json(res, 200, { network, leaderboard, trades, positions, t: Date.now() });+ return json(res, 200, {+ network,+ window,+ sort,+ sol_usd: boardResult.sol_usd,+ leaderboard: boardResult.leaderboard,+ trades,+ positions,+ t: Date.now(),+ }, { 'cache-control': 'public, max-age=10, s-maxage=20' });});diff --git a/api/sniper/trader.js b/api/sniper/trader.jsnew file mode 100644index 000000000..da244f843--- /dev/null+++ b/api/sniper/trader.js@@ -0,0 +1,47 @@+/**+ * Trader profile — full track record for one agent.+ *+ * GET /api/sniper/trader?agent_id=<uuid>&network=mainnet&window=30d+ *+ * Powers the /trader/:id page and the Proof tab: composite score, every headline+ * metric, the full closed-trade history (each row carrying its on-chain buy/sell+ * Solscan links), and the currently-open positions with live unrealized P&L. All+ * numbers come from agent_sniper_positions via the shared trader-stats truth+ * layer, so the profile and the leaderboard can never disagree.+ *+ * Public + IP rate-limited — the tx signatures ARE the proof, so anyone may read.+ */++import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { getTraderStats, WINDOWS } from '../_lib/trader-stats.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;++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const params = new URL(req.url, `http://${req.headers.host || 'x'}`).searchParams;+ const agentId = (params.get('agent_id') || params.get('agent') || '').trim();+ const network = NETWORKS.has(params.get('network')) ? params.get('network') : 'mainnet';+ const window = WINDOWS.has(params.get('window')) ? params.get('window') : 'all';++ if (!UUID_RE.test(agentId)) {+ return error(res, 400, 'invalid_agent', 'agent_id must be a valid agent UUID');+ }++ const stats = await getTraderStats({ agentId, network, window });+ if (!stats) {+ return error(res, 404, 'not_found', 'No such agent, or it is not public.');+ }+ if (!stats.agent.is_public) {+ return error(res, 404, 'not_found', 'No such agent, or it is not public.');+ }++ return json(res, 200, stats, { 'cache-control': 'public, max-age=15, s-maxage=30' });+});diff --git a/pages/club.html b/pages/club.htmlindex b258fecba..dd2ab3236 100644--- a/pages/club.html+++ b/pages/club.html@@ -622,6 +622,79 @@/* ── Entrance controller UI ─────────────────────────── *//* Sit above the scene canvas (9400), below the cover card (9500). */+ /* Journey progress — where you are on the walk in (Alley → Stage). */+ .club-journey {+ position: fixed;+ left: 50%;+ top: 18px;+ transform: translateX(-50%) translateY(-10px);+ z-index: 9445;+ padding: 8px 16px;+ border-radius: 999px;+ background: rgba(8, 5, 12, 0.6);+ border: 1px solid rgba(255, 59, 214, 0.18);+ backdrop-filter: blur(10px);+ -webkit-backdrop-filter: blur(10px);+ box-shadow: 0 10px 34px -14px rgba(0, 0, 0, 0.85);+ pointer-events: none;+ opacity: 0;+ transition: opacity 0.6s ease, transform 0.6s ease;+ }+ .club-journey.is-visible { opacity: 1; transform: translateX(-50%) translateY(0); }+ .club-journey-steps {+ display: flex;+ align-items: center;+ margin: 0;+ padding: 0;+ list-style: none;+ }+ .club-journey-step {+ display: flex;+ align-items: center;+ gap: 7px;+ color: var(--text-3, #7c5d92);+ font: 600 11px/1 'Inter', system-ui, sans-serif;+ letter-spacing: 0.08em;+ text-transform: uppercase;+ transition: color 0.5s ease;+ }+ .club-journey-step:not(:first-child) { margin-left: 10px; }+ .club-journey-step:not(:first-child)::before {+ content: "";+ width: 16px;+ height: 1px;+ margin-right: 10px;+ background: linear-gradient(90deg, rgba(255, 59, 214, 0.12), rgba(255, 59, 214, 0.32));+ }+ .cj-dot {+ width: 8px;+ height: 8px;+ border-radius: 50%;+ background: rgba(255, 255, 255, 0.14);+ transition: background 0.5s ease, box-shadow 0.5s ease;+ }+ .club-journey-step.is-done { color: var(--text-2, #c2a8d8); }+ .club-journey-step.is-done .cj-dot { background: rgba(255, 59, 214, 0.5); }+ .club-journey-step.is-active { color: #fff; }+ .club-journey-step.is-active .cj-dot {+ background: var(--accent, #ff3bd6);+ box-shadow: 0 0 12px 1px rgba(255, 59, 214, 0.9);+ animation: cjPulse 1.8s ease-in-out infinite;+ }+ @keyframes cjPulse {+ 0%, 100% { box-shadow: 0 0 10px 0 rgba(255, 59, 214, 0.6); }+ 50% { box-shadow: 0 0 16px 3px rgba(255, 59, 214, 1); }+ }+ @media (max-width: 560px) {+ .cj-label { display: none; }+ .club-journey-step:not(:first-child) { margin-left: 7px; }+ .club-journey-step:not(:first-child)::before { width: 10px; margin-right: 7px; }+ }+ @media (prefers-reduced-motion: reduce) {+ .club-journey-step.is-active .cj-dot { animation: none; }+ .club-journey { transition: opacity 0.6s ease; }+ }+.club-controls-hint {position: fixed;left: 50%;@@ -1412,7 +1485,15 @@pay. Sits behind the cover card, above the pole stage. --><canvas id="club-door-canvas" class="club-door-canvas" aria-hidden="true"></canvas>- <!-- Controller UI for the alley (toggled by src/club-entrance.js). -->+ <!-- Controller UI for the walk in (toggled by src/club-entrance.js). -->+ <nav id="club-journey" class="club-journey" aria-label="Walk-in progress">+ <ol class="club-journey-steps">+ <li class="club-journey-step" data-step="0"><span class="cj-dot"></span><span class="cj-label">Alley</span></li>+ <li class="club-journey-step" data-step="1"><span class="cj-dot"></span><span class="cj-label">Gallery</span></li>+ <li class="club-journey-step" data-step="2"><span class="cj-dot"></span><span class="cj-label">Clubhouse</span></li>+ <li class="club-journey-step" data-step="3"><span class="cj-dot"></span><span class="cj-label">Stage</span></li>+ </ol>+ </nav><div id="club-controls-hint" class="club-controls-hint" role="status" aria-live="polite"></div><button id="club-door-prompt" type="button" class="club-door-prompt" aria-label="Enter the club">Enter the club <kbd>E</kbd>diff --git a/src/club-entrance-audio.js b/src/club-entrance-audio.jsnew file mode 100644index 000000000..328d955d9--- /dev/null+++ b/src/club-entrance-audio.js@@ -0,0 +1,110 @@+// Approaching the club — the sound of a venue you can hear before you can see.+//+// A bass-forward loop sits behind the alley walls, heavily low-passed so only+// the deepest thump leaks out. As you walk toward the door the filter opens and+// the level rises — muffled-through-brick becomes here-it-is — and the moment+// the cover settles it bows out so the pole-stage anthem (src/club.js) owns the+// night. One self-contained Web Audio graph, armed on your first input (autoplay+// policy), and silent-failing throughout: audio is enhancement, never a gate.+//+// bufferSource(loop) → lowpass(cutoff↑ with proximity) → master(gain↑) → out+//+// Reuses a venue loop already on disk (built by scripts/build-club-audio.mjs) —+// no new assets, no third-party samples.++const SOURCES = ['/club/audio/thriller.ogg', '/club/audio/thriller.mp3'];++// Far down the alley vs. standing in the doorway. Far = subsonic rumble only;+// near = louder and brighter as the doorway opens the sound up.+const FAR = { cutoff: 230, gain: 0.0 };+const NEAR = { cutoff: 1650, gain: 0.6 };++const lerp = (a, b, t) => a + (b - a) * t;+const clamp01 = (v) => (v < 0 ? 0 : v > 1 ? 1 : v);++export class ClubApproachAudio {+ constructor() {+ this.ctx = null;+ this.master = null;+ this.filter = null;+ this.source = null;+ this.buffer = null;+ this.proximity = 0; // eased 0 (far) … 1 (at the door)+ this._target = 0;+ this._handingOff = false;+ this._armed = false;+ this._disposed = false;+ }++ // First real user gesture (a keypress or drag). Idempotent; unlocks the+ // AudioContext that autoplay policy otherwise keeps suspended.+ arm() {+ if (this._armed || this._disposed) return;+ this._armed = true;+ this._start().catch(() => {});+ }++ async _start() {+ const Ctx = window.AudioContext || window.webkitAudioContext;+ if (!Ctx) return;+ this.ctx = new Ctx();+ if (this.ctx.state === 'suspended') { try { await this.ctx.resume(); } catch {} }++ this.master = this.ctx.createGain();+ this.master.gain.value = 0.0001;+ this.filter = this.ctx.createBiquadFilter();+ this.filter.type = 'lowpass';+ this.filter.frequency.value = FAR.cutoff;+ this.filter.Q.value = 0.6;+ this.filter.connect(this.master);+ this.master.connect(this.ctx.destination);++ this.buffer = await this._load();+ if (!this.buffer || this._disposed) return;++ const src = this.ctx.createBufferSource();+ src.buffer = this.buffer;+ src.loop = true;+ src.connect(this.filter);+ try { src.start(); } catch { return; }+ this.source = src;+ }++ async _load() {+ for (const url of SOURCES) {+ try {+ const res = await fetch(url, { cache: 'force-cache' });+ if (!res.ok) continue;+ return await this.ctx.decodeAudioData(await res.arrayBuffer());+ } catch { /* try the next encoding */ }+ }+ return null;+ }++ // p in [0,1]: how close you are to the door (1 = right at it).+ setProximity(p) { this._target = clamp01(p); }++ // Cover paid — fade out; the anthem takes it from here.+ handOff() { this._handingOff = true; }++ // Per-frame: ease toward the target proximity (or zero while handing off)+ // and map it onto the filter cutoff + level with click-free ramps.+ update(dt) {+ if (!this.ctx || this._disposed) return;+ const goal = this._handingOff ? 0 : this._target;+ this.proximity += (goal - this.proximity) * (1 - Math.exp(-4 * dt));+ const now = this.ctx.currentTime;+ this.filter.frequency.setTargetAtTime(lerp(FAR.cutoff, NEAR.cutoff, this.proximity), now, 0.08);+ this.master.gain.setTargetAtTime(Math.max(0.0001, lerp(FAR.gain, NEAR.gain, this.proximity)), now, 0.08);+ if (this._handingOff && this.proximity < 0.01) this.dispose();+ }++ dispose() {+ if (this._disposed) return;+ this._disposed = true;+ try { this.source?.stop(); } catch {}+ try { this.source?.disconnect(); } catch {}+ try { this.ctx?.close(); } catch {}+ this.ctx = this.master = this.filter = this.source = null;+ }+}diff --git a/src/club-entrance.js b/src/club-entrance.jsindex 8e0a8d7c1..2628f12a3 100644--- a/src/club-entrance.js+++ b/src/club-entrance.js@@ -167,6 +167,9 @@ async function start(canvasEl) {));composer.addPass(new EffectPass(camera, new SMAAEffect()));+ // Muffled club bass that swells as you near the door (armed on first input).+ const approachAudio = new ClubApproachAudio();+const loader = gltfLoader(renderer);// The journey, in order. You free-walk every one of these — no auto-walk.@@ -273,6 +276,7 @@ async function start(canvasEl) {doorGlow.position.copy(path.door).setY(1.6);camYaw = Math.atan2(path.dir.x, path.dir.z);updateCamera(1);+ setJourneyStep(venueIndex);}// ── Input ──────────────────────────────────────────────────────────────@@ -281,6 +285,7 @@ async function start(canvasEl) {const look = { id: null, x: 0, y: 0, moved: false };const onKeyDown = (e) => {+ approachAudio.arm();const k = e.key.toLowerCase();if (k === 'e') { tryEnter(); return; }if (['w', 'a', 's', 'd', 'arrowup', 'arrowdown', 'arrowleft', 'arrowright'].includes(k)) {@@ -298,6 +303,7 @@ async function start(canvasEl) {const joyKnob = document.getElementById('club-joystick-knob');const onPointerDown = (e) => {+ approachAudio.arm();if (!inputEnabled) return;const leftZone = isTouch && e.clientX < window.innerWidth * 0.4;if (leftZone && !joy.active) {@@ -356,6 +362,8 @@ async function start(canvasEl) {setHint();showHint(true);showJoystick(isTouch);+ showJourney(true);+ setJourneyStep(venueIndex);// Hint + prompt copy track where you are in the journey: the alley door takes// the cover, the final place opens the stage, the rest just lead onward.@@ -438,6 +446,7 @@ async function start(canvasEl) {stepAvatar(ix, iz, dt);anim.update(dt);updateCamera(dt);+ approachAudio.update(dt);// Key light + proximity prompt follow the avatar in the alley.key.position.set(rig.position.x, 5, rig.position.z + 1);@@ -453,6 +462,11 @@ async function start(canvasEl) {}doorGlow.intensity = inRange ? 3.2 : 1.4;doorMarker.pulse(now / 1000, inRange);+ // Outside the club, the bass leaks louder the closer you get to the+ // door, and the neon glows a touch hotter as you arrive.+ const near = clamp(1 - d / 12, 0, 1);+ if (currentCover) approachAudio.setProximity(near);+ bloomEffect.intensity = 1.2 + near * 0.7;}switch (phase) {@@ -550,6 +564,7 @@ async function start(canvasEl) {if (phase !== 'walk') return;paid = true;currentCover = false;+ approachAudio.handOff(); // the anthem (src/club.js) takes the night from hereshowPrompt(false); showHint(false); showJoystick(false);advance();}@@ -584,10 +599,22 @@ async function start(canvasEl) {function showPrompt(v) { toggle('club-door-prompt', v); }function showHint(v) { toggle('club-controls-hint', v); }function showJoystick(v) { toggle('club-joystick', v); }+function showJourney(v) { toggle('club-journey', v); }function toggle(id, v) {const el = document.getElementById(id);if (el) el.classList.toggle('is-visible', !!v);}+// Light the step you're on (Alley/Gallery/Clubhouse/Stage); earlier steps read+// as done. `i` is the venue index; SEQUENCE.length marks arrival at the stage.+function setJourneyStep(i) {+ const el = document.getElementById('club-journey');+ if (!el) return;+ el.querySelectorAll('.club-journey-step').forEach((s) => {+ const n = Number(s.dataset.step);+ s.classList.toggle('is-done', n < i);+ s.classList.toggle('is-active', n === i);+ });+}// ── Scene helpers ────────────────────────────────────────────────────────────diff --git a/src/pump/bundle-detect.js b/src/pump/bundle-detect.jsnew file mode 100644index 000000000..90ae38d09--- /dev/null+++ b/src/pump/bundle-detect.js@@ -0,0 +1,174 @@+/**+ * pump/bundle-detect.js+ * ---------------------+ * Pure analytics over a coin's early trade footprint. No I/O — the coin-intel+ * worker feeds in aggregated per-wallet stats (and a wallet→funder map it+ * resolved from the chain), and these functions derive the organic-vs-bundle+ * signals and the composite intel score the sniper reads. Pure so every number+ * is unit-testable and identical in the worker and the API.+ *+ * A "trader" is one row per wallet for one coin:+ * { wallet, buy_lamports, sell_lamports, buy_count, sell_count, is_dev }+ * amounts are plain numbers (lamports). Volumes for a fresh launch stay well+ * inside Number.MAX_SAFE_INTEGER (1 SOL = 1e9; 9e15 ≈ 9M SOL).+ */++function num(v) {+ const n = Number(v);+ return Number.isFinite(n) ? n : 0;+}+function pct(part, whole) {+ if (!(whole > 0)) return 0;+ return Math.round((part / whole) * 1000) / 10; // 1 decimal+}+function clamp(n, lo, hi) {+ return Math.max(lo, Math.min(hi, n));+}++/**+ * Roll a coin's per-wallet rows up into headline metrics.+ * @param {Array} traders+ * @returns {object} metrics+ */+export function summarizeTraders(traders) {+ const rows = Array.isArray(traders) ? traders : [];+ let unique_buyers = 0,+ unique_sellers = 0,+ total_buys = 0,+ total_sells = 0,+ buy_volume = 0,+ sell_volume = 0,+ largest_buy = 0,+ dev_buy = 0;+ let dev_sold = false;+ let topBuyerVol = 0;++ for (const t of rows) {+ const b = num(t.buy_lamports);+ const s = num(t.sell_lamports);+ const bc = num(t.buy_count);+ const sc = num(t.sell_count);+ if (b > 0) unique_buyers++;+ if (s > 0) unique_sellers++;+ total_buys += bc;+ total_sells += sc;+ buy_volume += b;+ sell_volume += s;+ if (b > largest_buy) largest_buy = b;+ if (b > topBuyerVol) topBuyerVol = b;+ if (t.is_dev) {+ dev_buy = b;+ if (s > 0) dev_sold = true;+ }+ }++ const avg_buy = unique_buyers > 0 ? Math.round(buy_volume / unique_buyers) : 0;+ return {+ unique_buyers,+ unique_sellers,+ total_buys,+ total_sells,+ buy_volume,+ sell_volume,+ net_volume: buy_volume - sell_volume,+ largest_buy,+ avg_buy,+ dev_buy,+ dev_sold,+ dev_buy_pct: pct(dev_buy, buy_volume),+ top_buyer_pct: pct(topBuyerVol, buy_volume),+ };+}++/**+ * Cluster wallets that share a funding source ("bubblemaps-lite"): a single+ * funder backing ≥2 of a coin's buyers is the classic bundle signature.+ *+ * @param {Array} traders per-wallet rows (need buy_lamports + wallet)+ * @param {Map<string,string>|object} funderOf wallet → funder address (null/absent = unknown)+ * @returns {{ bundle_detected, bundle_wallet_count, bundle_buy_pct, cluster_count }}+ */+export function detectBundle(traders, funderOf) {+ const rows = Array.isArray(traders) ? traders : [];+ const lookup = funderOf instanceof Map ? (w) => funderOf.get(w) : (w) => funderOf?.[w];++ // funder → [wallets buying through it]+ const byFunder = new Map();+ let buy_volume = 0;+ const buyVol = new Map();+ for (const t of rows) {+ const b = num(t.buy_lamports);+ buy_volume += b;+ if (b <= 0) continue;+ buyVol.set(t.wallet, b);+ const f = lookup(t.wallet);+ if (!f) continue;+ if (!byFunder.has(f)) byFunder.set(f, []);+ byFunder.get(f).push(t.wallet);+ }++ let bundleWallets = new Set();+ let cluster_count = 0;+ for (const [, wallets] of byFunder) {+ if (wallets.length >= 2) {+ cluster_count++;+ for (const w of wallets) bundleWallets.add(w);+ }+ }++ let bundledVol = 0;+ for (const w of bundleWallets) bundledVol += buyVol.get(w) || 0;++ return {+ bundle_detected: bundleWallets.size > 0,+ bundle_wallet_count: bundleWallets.size,+ bundle_buy_pct: pct(bundledVol, buy_volume),+ cluster_count,+ };+}++/**+ * 0 (heavily bundled / concentrated) … 100 (clean, broad, organic).+ * Transparent penalties so a strategy author can reason about the gate.+ */+export function organicScore(metrics, bundle) {+ let score = 100;+ // shared-funder bundling is the heaviest penalty — dollar-for-dollar.+ score -= num(bundle?.bundle_buy_pct);+ // single-wallet dominance above a quarter of buy volume.+ const top = num(metrics?.top_buyer_pct);+ if (top > 25) score -= (top - 25) * 0.8;+ // dev hoarding above half the buy volume.+ const dev = num(metrics?.dev_buy_pct);+ if (dev > 50) score -= (dev - 50) * 0.6;+ // a launch nobody else has touched yet is not "organic", just empty.+ const buyers = num(metrics?.unique_buyers);+ if (buyers < 5) score -= (5 - buyers) * 8;+ // dev already dumping into the first buyers.+ if (metrics?.dev_sold) score -= 15;+ return clamp(Math.round(score), 0, 100);+}++// Classifications that read as "someone built something", nudged up slightly.+const SUBSTANTIVE = new Set(['tech', 'utility', 'community', 'culture']);++/**+ * Composite 0..100 the sniper gates on. Organic quality is the backbone;+ * socials, a confident classification, and real buyer breadth add to it.+ */+export function intelScore({ metrics, bundle, organic, hasSocials, classification, confidence }) {+ const org = organic != null ? num(organic) : organicScore(metrics, bundle);+ let score = org * 0.6; // organic is 60% of the weight++ // buyer breadth (capped) — up to 20 pts for ≥20 distinct buyers.+ const buyers = num(metrics?.unique_buyers);+ score += clamp(buyers, 0, 20);++ // socials present and a confident category each add headroom.+ if (hasSocials) score += 8;+ const conf = num(confidence);+ if (classification && classification !== 'other') score += clamp(conf * 8, 0, 8);+ if (SUBSTANTIVE.has(classification)) score += 4;++ return clamp(Math.round(score), 0, 100);+}diff --git a/src/pump/coin-classifier.js b/src/pump/coin-classifier.jsnew file mode 100644index 000000000..c54b2e0e1--- /dev/null+++ b/src/pump/coin-classifier.js@@ -0,0 +1,137 @@+/**+ * pump/coin-classifier.js+ * -----------------------+ * Classify a pump.fun coin from its launch metadata (name, symbol, description,+ * socials). The real path is an LLM call through the platform's free-first+ * provider chain (Groq/OpenRouter/NVIDIA before any paid key). If every provider+ * is unavailable the keyword heuristic takes over — classification NEVER fails+ * and never blocks the intel pipeline (operating rule 9). The heuristic is pure+ * and exported so it's unit-testable on its own.+ */++export const TAXONOMY = [+ 'meme', // generic internet meme+ 'news_meme', // riffs on a current news story / event+ 'culture', // a cultural moment or trend+ 'community', // community / social / fan token+ 'animal', // animal-themed (dog, cat, frog, …)+ 'celebrity', // a person / celebrity+ 'political', // politics / elections / policy+ 'tech', // technology, AI, infra, DeFi, tooling+ 'utility', // a coin with a stated product/use+ 'other',+];++const KEYWORDS = {+ animal: ['dog', 'doge', 'shib', 'inu', 'cat', 'kitty', 'pepe', 'frog', 'toad', 'monkey', 'ape', 'bear', 'bull', 'hippo', 'penguin', 'duck', 'goat', 'wif', 'bonk', 'pup', 'hamster'],+ tech: ['ai', 'gpt', 'agent', 'protocol', 'network', 'chain', 'infra', 'zk', 'defi', 'swap', 'dex', 'oracle', 'data', 'compute', 'node', 'sdk', 'llm', 'model', 'bot', 'quant', 'rollup', 'layer', 'rwa', 'depin'],+ political: ['trump', 'biden', 'maga', 'election', 'president', 'senate', 'congress', 'putin', 'war', 'gov', 'policy', 'vote', 'kamala', 'potus'],+ community: ['dao', 'community', 'fam', 'gang', 'society', 'club', 'army', 'holders', 'fren', 'frens'],+ culture: ['meme', 'vibe', 'based', 'wagmi', 'gm', 'moon', 'lambo', 'degen', 'culture', 'trend', 'viral'],+ celebrity: ['elon', 'musk', 'kanye', 'taylor', 'drake', 'mrbeast', 'ronaldo', 'messi'],+};++const haystack = (coin) =>+ `${coin?.name || ''} ${coin?.symbol || ''} ${coin?.description || ''}`.toLowerCase();++/**+ * Keyword classifier. Pure, deterministic, no I/O. The fallback AND a useful+ * source of `tags` the LLM result is merged with.+ * @returns {{classification, confidence, tags, theme, source}}+ */+export function heuristicClassify(coin) {+ const text = haystack(coin);+ const tags = [];+ const hits = {};+ for (const [cat, words] of Object.entries(KEYWORDS)) {+ for (const w of words) {+ // word-boundary-ish: avoid 'ai' matching 'rain'.+ const re = new RegExp(`(^|[^a-z])${w}([^a-z]|$)`, 'i');+ if (re.test(text)) {+ hits[cat] = (hits[cat] || 0) + 1;+ tags.push(w);+ }+ }+ }+ const ranked = Object.entries(hits).sort((a, b) => b[1] - a[1]);+ let classification = 'meme';+ let confidence = 0.4;+ if (ranked.length) {+ classification = ranked[0][0];+ // culture keywords are weak meme-adjacent signals — only win if alone.+ if (classification === 'culture' && ranked.length > 1) classification = ranked[1][0];+ confidence = clamp(0.45 + ranked[0][1] * 0.1, 0.4, 0.7);+ }+ return {+ classification,+ confidence,+ tags: [...new Set(tags)].slice(0, 8),+ theme: ranked.length ? `${classification} signals: ${tags.slice(0, 3).join(', ')}` : 'unclassified meme',+ source: 'heuristic',+ };+}++const SYSTEM = `You classify newly-launched pump.fun (Solana) coins from their metadata. Reply with ONLY a compact JSON object, no markdown, no prose:+{"classification": <one of: ${TAXONOMY.join(', ')}>, "confidence": <0..1>, "tags": [<up to 6 short lowercase tags>], "theme": "<≤12 word description of the coin's angle>"}+Rules: "news_meme" = references a current real-world news story/event. "culture" = a broad cultural trend/moment. "community" = a fan/social/community token. "tech" = AI, infra, DeFi, or a real tool. "utility" = states a concrete product. Pick the single best fit; use "other" only if nothing fits.`;++/**+ * Classify a coin. Tries the LLM; falls back to the heuristic on any failure.+ * @param {{name,symbol,description,twitter,telegram,website}} coin+ * @param {{track?:object, timeoutMs?:number}} [opts]+ * @returns {Promise<{classification,confidence,tags,theme,source,model}>}+ */+export async function classifyCoin(coin, opts = {}) {+ const base = heuristicClassify(coin);+ try {+ const { llmComplete } = await import('../../api/_lib/llm.js');+ const user = JSON.stringify({+ name: coin?.name || null,+ symbol: coin?.symbol || null,+ description: (coin?.description || '').slice(0, 600) || null,+ has_twitter: !!coin?.twitter,+ has_telegram: !!coin?.telegram,+ has_website: !!coin?.website,+ });+ const res = await llmComplete({+ system: SYSTEM,+ user,+ maxTokens: 200,+ timeoutMs: opts.timeoutMs ?? 12_000,+ track: { tool: 'coin-intel-classify', ...(opts.track || {}) },+ });+ const parsed = parseJson(res.text);+ if (parsed && TAXONOMY.includes(parsed.classification)) {+ const tags = Array.isArray(parsed.tags) ? parsed.tags : [];+ return {+ classification: parsed.classification,+ confidence: clamp(Number(parsed.confidence), 0, 1) || 0.6,+ // union the model's tags with the heuristic's keyword hits.+ tags: [...new Set([...tags, ...base.tags].map((t) => String(t).toLowerCase().slice(0, 24)))].slice(0, 8),+ theme: String(parsed.theme || base.theme).slice(0, 120),+ source: `llm:${res.provider}`,+ model: res.model,+ };+ }+ } catch {+ // fall through to heuristic — never throw out of classify.+ }+ return { ...base, model: null };+}++function parseJson(text) {+ if (!text) return null;+ const m = String(text).match(/\{[\s\S]*\}/);+ if (!m) return null;+ try {+ return JSON.parse(m[0]);+ } catch {+ return null;+ }+}++function clamp(n, lo, hi) {+ const x = Number(n);+ if (!Number.isFinite(x)) return lo;+ return Math.max(lo, Math.min(hi, x));+}diff --git a/src/three-economy.js b/src/three-economy.jsindex 0e3546d16..c62732511 100644--- a/src/three-economy.js+++ b/src/three-economy.js@@ -212,6 +212,8 @@ function injectStyles() {.ec-stat .v { font-size:28px; font-weight:820; letter-spacing:-.02em; font-variant-numeric:tabular-nums; }.ec-stat .v .sym { font-size:14px; font-weight:600; color:var(--muted); margin-left:5px; }.ec-stat .k { color:var(--muted); font-size:12.5px; margin-top:5px; }+ .ec-stamp { margin-top:14px; font-size:12px; color:var(--muted-2); display:flex; align-items:center; gap:7px; }+ .ec-stamp::before { content:''; width:6px; height:6px; border-radius:50%; background:var(--green); box-shadow:0 0 8px var(--green); }/* Verify wallets */.ec-wallets { display:grid; gap:13px; grid-template-columns:repeat(auto-fit,minmax(260px,1fr)); }@@ -224,7 +226,7 @@ function injectStyles() {.ec-wallet .wbal .sym { font-size:13px; color:var(--muted); margin-left:5px; font-weight:600; }.ec-wallet .waddr { font-family:ui-monospace,Menlo,monospace; font-size:11.5px; color:var(--accent); }- /* Reflections + projector */+ /* Rewards (value returned) + projector */.ec-reflect { display:grid; gap:16px; grid-template-columns:1.1fr .9fr; align-items:start; }@media (max-width:760px){ .ec-reflect{ grid-template-columns:1fr; } }.ec-card { border:1px solid var(--line); border-radius:16px; padding:22px;@@ -232,10 +234,14 @@ function injectStyles() {.ec-reflect-big { font-size:38px; font-weight:850; letter-spacing:-.025em; color:var(--green);font-variant-numeric:tabular-nums; }.ec-reflect-sub { color:var(--muted); font-size:13.5px; margin-top:4px; }- .ec-reflect-list { margin-top:16px; border-top:1px solid var(--line); }- .ec-reflect-row { display:flex; justify-content:space-between; gap:12px; padding:11px 0; font-size:13px;- border-bottom:1px solid var(--line); }- .ec-reflect-row:last-child { border-bottom:none; }+ .ec-reflect-table { width:100%; border-collapse:collapse; margin-top:16px; font-size:13px; }+ .ec-reflect-table th { text-align:left; font-weight:600; color:var(--muted-2); font-size:11px;+ text-transform:uppercase; letter-spacing:.06em; padding:0 0 8px; border-bottom:1px solid var(--line); }+ .ec-reflect-table th:last-child { text-align:right; }+ .ec-reflect-table td { padding:10px 0; border-bottom:1px solid var(--line); font-variant-numeric:tabular-nums; }+ .ec-reflect-table tr:last-child td { border-bottom:none; }+ .ec-txlink { color:var(--green); font-weight:600; font-size:12px; }+ .ec-txlink:hover { text-decoration:underline; }.ec-tag { font-size:10.5px; font-weight:700; text-transform:uppercase; letter-spacing:.05em; padding:2px 8px;border-radius:999px; }.ec-tag.paid { background:rgba(110,231,168,.12); color:var(--green); }@@ -615,21 +621,27 @@ function reflectedHTML(stats) {const total = fmtCompact(atomicsToTokens(r.total_atomics ?? '0', dec));let history;if (!r.recent?.length) {- history = `<p class="ec-muted" style="margin-top:14px;font-size:13px">Distributions begin once the rewards pool funds. Every run will appear here with an on-chain transaction you can verify — value returned to holders, never destroyed.</p>`;+ history = `<p class="ec-muted" style="margin-top:14px;font-size:13px">Distributions begin once the rewards pool funds. Every run will appear here as a row with an on-chain transaction you can open — value returned to holders, never destroyed.</p>`;} else {- history = `<div class="ec-reflect-list">${r.recent+ // A real <table> for accessibility + copy/paste; completed runs link to the tx.+ const rows = r.recent.map((d) => {const amt = fmtCompact(atomicsToTokens(d.distributed_atomics ?? '0', dec));const when = d.created_at ? new Date(d.created_at).toLocaleDateString('en-US', { month: 'short', day: 'numeric' }) : '';const paid = d.status === 'completed';- return `<div class="ec-reflect-row"><span class="ec-muted">${esc(when)}</span><span>${esc(amt)} $THREE → ${d.holder_count} holders</span><span class="ec-tag ${paid ? 'paid' : 'planned'}">${paid ? 'paid' : 'planned'}</span></div>`;+ const tx = Array.isArray(d.tx_signatures) && d.tx_signatures[0] ? d.tx_signatures[0] : null;+ const verify = tx+ ? `<a href="https://solscan.io/tx/${esc(tx)}" target="_blank" rel="noopener" class="ec-txlink">verify ↗</a>`+ : `<span class="ec-tag ${paid ? 'paid' : 'planned'}">${paid ? 'paid' : 'planned'}</span>`;+ return `<tr><td class="ec-muted">${esc(when)}</td><td>${esc(amt)} $THREE</td><td class="ec-muted">${d.holder_count} holders</td><td style="text-align:right">${verify}</td></tr>`;})- .join('')}</div>`;+ .join('');+ history = `<table class="ec-reflect-table"><thead><tr><th>Date</th><th>Returned</th><th>To</th><th></th></tr></thead><tbody>${rows}</tbody></table>`;}return `<div class="ec-card"><div class="ec-reflect-big" id="ec-reflect-total">${esc(total)} <span style="font-size:18px;color:var(--muted)">$THREE</span></div>- <div class="ec-reflect-sub">returned to holders across ${r.run_count} distribution${r.run_count === 1 ? '' : 's'} — we never burn supply</div>+ <div class="ec-reflect-sub">returned to holders across ${r.run_count} distribution${r.run_count === 1 ? '' : 's'} — funded by usage fees, never minted, never burned</div>${history}</div><div class="ec-card ec-proj">@@ -863,8 +875,8 @@ function wireProjector(stats) {if (eligibleSupply > 0 && reflectedTotal > 0) earned = (bag / eligibleSupply) * reflectedTotal;out.innerHTML = `Holding <b>${fmtCompact(bag)} $THREE</b>${bagUsd != null ? ` <span class="ec-muted">(${fmtUsd(bagUsd)})</span>` : ''}<br/>` +(earned != null && earned > 0- ? `you'd have earned <b>≈ ${fmtCompact(earned)} $THREE</b> from reflections so far — and a fee discount on everything you buy.`- : `<span class="ec-muted">earns a share of every future reflection, plus a fee discount that grows with your tier.</span>`);+ ? `would have earned <b>≈ ${fmtCompact(earned)} $THREE</b> from past distributions — plus a fee discount on everything you buy. <span class="ec-muted">(historical, not a forecast)</span>`+ : `<span class="ec-muted">earns a pro-rata share of every future distribution, plus a fee discount that grows with your tier.</span>`);};range.addEventListener('input', update);update();@@ -995,28 +1007,22 @@ async function load(root) {setErr('ec-catalog', 'Price catalog is temporarily unavailable.');});+ // The tier ladder is always-on info content, so render the baseline immediately+ // (never an empty/error box), then enhance with the holder's live "current" tier+ // + progress when the authed call succeeds. A signed-out or failed call simply+ // leaves the informative ladder in place.+ const tiersEl = document.getElementById('ec-tiers');+ if (tiersEl) tiersEl.innerHTML = tiersHTML({ ladder: DEFAULT_LADDER, tier: null, next: null });getJSON(`${API}/tier`).then((t) => {DISCOUNT_BPS = Number(t?.tier?.discount_bps) || 0;- const el = document.getElementById('ec-tiers');- if (el) el.innerHTML = tiersHTML(t);+ if (tiersEl && t?.ladder?.length) tiersEl.innerHTML = tiersHTML(t);// Re-render the price detail now that the discount is known.const sel = document.querySelector('.ec-px-item.sel');if (sel) sel.click();})- .catch((e) => {- if (e.status === 401 || e.status === 403) {- const el = document.getElementById('ec-tiers');- // Render the ladder without a "current" marker, plus a sign-in nudge.- if (el)- el.innerHTML = tiersHTML({- ladder: DEFAULT_LADDER,- tier: null,- next: null,- });- } else {- setErr('ec-tiers', 'Tier info is temporarily unavailable.');- }+ .catch(() => {+ /* keep the baseline ladder — it's informative without auth */});wireNameStudio(root);diff --git a/tests/trader-stats.test.js b/tests/trader-stats.test.jsnew file mode 100644index 000000000..05ef23c15--- /dev/null+++ b/tests/trader-stats.test.js@@ -0,0 +1,169 @@+/**+ * Trader track-record truth layer — pure-metric tests.+ *+ * Every assertion is hand-computed from the fixture below so the math can never+ * silently drift. computeTraderMetrics is pure (no DB, no network), so these run+ * fast and deterministically.+ */++import { describe, it, expect } from 'vitest';+import { computeTraderMetrics, windowStartIso, WINDOWS } from '../api/_lib/trader-stats.js';++const SOL = 1e9; // lamports per SOL++// Four closed positions + one open. Ordered so the equity curve has a clear,+// hand-checkable drawdown: +2 → +1.5 (−0.5 from peak 2 = 25%) → +2.0 → +2.01.+const FIXTURE = [+ // closed: A +2 SOL (+200%), 120s hold+ {+ status: 'closed', mint: 'AAAA', symbol: 'A', realized_pnl_lamports: String(2 * SOL),+ realized_pnl_pct: 200, entry_quote_lamports: String(1 * SOL), exit_quote_lamports: String(3 * SOL),+ opened_at: '2026-01-01T00:00:00.000Z', closed_at: '2026-01-01T00:02:00.000Z', buy_sig: 'b1', sell_sig: 's1',+ },+ // closed: B −0.5 SOL (−50%), 300s hold (the loser — never hidden)+ {+ status: 'closed', mint: 'BBBB', symbol: 'B', realized_pnl_lamports: String(-0.5 * SOL),+ realized_pnl_pct: -50, entry_quote_lamports: String(1 * SOL), exit_quote_lamports: String(0.5 * SOL),+ opened_at: '2026-01-01T00:03:00.000Z', closed_at: '2026-01-01T00:08:00.000Z', buy_sig: 'b2', sell_sig: 's2',+ },+ // closed: C +0.5 SOL (+50%), 60s hold+ {+ status: 'closed', mint: 'CCCC', symbol: 'C', realized_pnl_lamports: String(0.5 * SOL),+ realized_pnl_pct: 50, entry_quote_lamports: String(1 * SOL), exit_quote_lamports: String(1.5 * SOL),+ opened_at: '2026-01-01T00:09:00.000Z', closed_at: '2026-01-01T00:10:00.000Z', buy_sig: 'b3', sell_sig: 's3',+ },+ // closed: D +0.01 SOL (+1%), 10s hold → churn (fast in-and-out, near-flat)+ {+ status: 'closed', mint: 'DDDD', symbol: 'D', realized_pnl_lamports: String(0.01 * SOL),+ realized_pnl_pct: 1, entry_quote_lamports: String(1 * SOL), exit_quote_lamports: String(1.01 * SOL),+ opened_at: '2026-01-01T00:11:00.000Z', closed_at: '2026-01-01T00:11:10.000Z', buy_sig: 'b4', sell_sig: 's4',+ },+ // open: E, entry 1 SOL, now worth 1.5 SOL → +0.5 SOL unrealized+ {+ status: 'open', mint: 'EEEE', symbol: 'E', entry_quote_lamports: String(1 * SOL),+ last_value_lamports: String(1.5 * SOL), opened_at: '2026-01-01T00:15:00.000Z', buy_sig: 'b5',+ },+];++describe('computeTraderMetrics', () => {+ const m = computeTraderMetrics(FIXTURE, { solUsd: 200 });++ it('counts closed and open positions separately', () => {+ expect(m.closed_count).toBe(4);+ expect(m.open_count).toBe(1);+ });++ it('computes wins, losses, and win rate', () => {+ expect(m.wins).toBe(3);+ expect(m.losses).toBe(1);+ expect(m.win_rate).toBe(0.75);+ });++ it('sums realized P&L exactly in SOL and prices it to USD', () => {+ // 2 − 0.5 + 0.5 + 0.01 = 2.01 SOL+ expect(m.realized_pnl_sol).toBeCloseTo(2.01, 6);+ expect(m.realized_pnl_usd).toBeCloseTo(402, 2); // 2.01 × 200+ });++ it('tracks open exposure and unrealized P&L', () => {+ expect(m.open_exposure_sol).toBeCloseTo(1, 6);+ expect(m.unrealized_pnl_sol).toBeCloseTo(0.5, 6);+ expect(m.unrealized_pnl_usd).toBeCloseTo(100, 2);+ });++ it('computes profit factor (gross profit / gross loss)', () => {+ // (2 + 0.5 + 0.01) / 0.5 = 5.02+ expect(m.profit_factor).toBeCloseTo(5.02, 2);+ });++ it('computes ROI against invested capital', () => {+ // 2.01 / 4 × 100 = 50.25%+ expect(m.roi_pct).toBeCloseTo(50.25, 1);+ });++ it('reports best/worst/avg trade pct', () => {+ expect(m.best_pnl_pct).toBe(200);+ expect(m.worst_pnl_pct).toBe(-50);+ expect(m.avg_pnl_pct).toBeCloseTo(50.25, 1); // (200 − 50 + 50 + 1) / 4+ });++ it('computes max drawdown from the realized equity curve', () => {+ // peak +2, trough +1.5 → 0.5 SOL drop = 25% of peak+ expect(m.max_drawdown_sol).toBeCloseTo(0.5, 6);+ expect(m.max_drawdown_pct).toBeCloseTo(25, 5);+ });++ it('computes hold-time stats', () => {+ expect(m.avg_hold_seconds).toBe(123); // (120+300+60+10)/4 = 122.5 → 123+ expect(m.median_hold_seconds).toBe(90); // sorted [10,60,120,300] → (60+120)/2+ });++ it('counts unique coins and flags churn heuristically', () => {+ expect(m.unique_coins).toBe(4);+ expect(m.churn_pct).toBeCloseTo(25, 5); // 1 of 4 closed is churn+ });++ it('does NOT grant the verified badge below the trade threshold', () => {+ expect(m.verified).toBe(false); // only 4 closed, badge needs >= 12+ });++ it('produces a bounded composite score', () => {+ expect(m.score).toBeGreaterThan(0);+ expect(m.score).toBeLessThanOrEqual(100);+ });++ it('records first/last active timestamps', () => {+ expect(m.first_active_at).toBe('2026-01-01T00:00:00.000Z');+ expect(m.last_active_at).toBe('2026-01-01T00:15:00.000Z'); // open E opened latest+ });+});++describe('computeTraderMetrics — degenerate inputs', () => {+ it('handles an empty book without throwing and regresses score to neutral', () => {+ const m = computeTraderMetrics([], { solUsd: 200 });+ expect(m.closed_count).toBe(0);+ expect(m.open_count).toBe(0);+ expect(m.win_rate).toBe(0);+ expect(m.realized_pnl_sol).toBe(0);+ expect(m.realized_pnl_usd).toBe(0);+ expect(m.verified).toBe(false);+ expect(m.score).toBe(42); // confidence 0 → fully regressed to NEUTRAL_RAW+ });++ it('omits USD fields when no SOL price is available', () => {+ const m = computeTraderMetrics(FIXTURE, { solUsd: null });+ expect(m.realized_pnl_sol).toBeCloseTo(2.01, 6); // SOL stays exact+ expect(m.realized_pnl_usd).toBeNull();+ expect(m.unrealized_pnl_usd).toBeNull();+ });++ it('handles an all-losses book (zero gross profit → profit factor 0)', () => {+ const losses = [+ { status: 'closed', mint: 'X', realized_pnl_lamports: String(-1 * SOL), realized_pnl_pct: -40,+ entry_quote_lamports: String(1 * SOL), opened_at: '2026-01-01T00:00:00Z', closed_at: '2026-01-01T00:05:00Z' },+ ];+ const m = computeTraderMetrics(losses, { solUsd: 200 });+ expect(m.wins).toBe(0);+ expect(m.win_rate).toBe(0);+ expect(m.profit_factor).toBe(0);+ expect(m.realized_pnl_sol).toBeCloseTo(-1, 6);+ });+});++describe('windowStartIso', () => {+ const NOW = Date.parse('2026-06-15T12:00:00.000Z');++ it('returns null for the all-time window', () => {+ expect(windowStartIso('all', NOW)).toBeNull();+ });++ it('computes the lower bound for 24h / 7d / 30d', () => {+ expect(windowStartIso('24h', NOW)).toBe(new Date(NOW - 86_400_000).toISOString());+ expect(windowStartIso('7d', NOW)).toBe(new Date(NOW - 604_800_000).toISOString());+ expect(windowStartIso('30d', NOW)).toBe(new Date(NOW - 2_592_000_000).toISOString());+ });++ it('exposes the supported window set', () => {+ expect([...WINDOWS].sort()).toEqual(['24h', '30d', '7d', 'all']);+ });+});diff --git a/workers/agent-sniper/config.js b/workers/agent-sniper/config.jsindex 31b66d609..68424efa5 100644--- a/workers/agent-sniper/config.js+++ b/workers/agent-sniper/config.js@@ -76,5 +76,17 @@ export function loadConfig() {// observed (a per-strategy first_claim_max_age_seconds overrides it). Keeps// a worker restart / backfill from sniping a stale claim.claimMaxAgeSeconds: Math.max(30, num('SNIPER_CLAIM_MAX_AGE_S', 300)),+ // ── coin intelligence engine ────────────────────────────────────────────+ // Observe every new coin's first seconds of trading, classify it, persist+ // signals, and drive intel_confirmed strategies. On by default — it's the+ // platform's eyes. Set SNIPER_INTEL=0 to disable (e.g. a trade-only worker).+ intel: bool('SNIPER_INTEL', true),+ // Observation window per coin before signals are finalized (ms).+ intelWindowMs: Math.max(15_000, num('SNIPER_INTEL_WINDOW_MS', 90_000)),+ // Max coins observed simultaneously — a backstop on memory + WS subs.+ intelMaxConcurrent: Math.max(50, num('SNIPER_INTEL_MAX_CONCURRENT', 400)),+ // Refine classification with the LLM (free-first). Off by default: the+ // deterministic heuristic is instant and free; LLM adds ~1 call per coin.+ intelLlm: bool('SNIPER_INTEL_LLM', false),};}diff --git a/workers/agent-sniper/index.js b/workers/agent-sniper/index.jsindex 974992fb8..f8dc2b067 100644--- a/workers/agent-sniper/index.js+++ b/workers/agent-sniper/index.js@@ -13,10 +13,12 @@ import { connectPumpFunFeed } from '../../api/_lib/pumpfun-ws-feed.js';import { loadConfig } from './config.js';import { log } from './log.js';import { refreshStrategies, cachedStrategies, logStrategyLoad } from './strategy-store.js';-import { scoreMint } from './scorer.js';+import { scoreMint, scoreIntel } from './scorer.js';import { executeBuy } from './executor.js';import { runPositionSweep } from './positions.js';import { startFirstClaimWatch } from './first-claim-watch.js';+import { startIntelWatcher } from './intel/watcher.js';+import { getLearnedWeights } from './intel/store.js';// ── global buy throttle (sliding 60s window) ─────────────────────────────────function makeThrottle(maxPerMin) {@@ -89,6 +91,42 @@ async function main() {let stopFeed = connectPumpFunFeed({ kind: 'mint', signal: abort.signal, onEvent });log.info('feed connected', {});+ // Coin Intelligence Engine: observe every new coin's first seconds, classify+ // it, persist signals, and drive intel_confirmed strategies on a finished+ // verdict. Separate WS (dynamic per-mint trade subscriptions) from the snipe+ // feed above. Read-only on the chain — it never trades, only watches.+ let stopIntel = () => {};+ if (cfg.intel) {+ const onIntel = (rec) => {+ if (draining || cfg.globalKill) return;+ const strategies = cachedStrategies();+ for (const strat of strategies) {+ if ((strat.trigger || 'new_mint') !== 'intel_confirmed') continue;+ if (strat.network !== cfg.network) continue;+ getLearnedWeights(cfg.network)+ .then((weights) => {+ const { pass, score, reasons } = scoreIntel(rec, strat, weights);+ if (!pass) return;+ log.info('intel candidate', { agent: strat.agent_id, mint: rec.mint, symbol: rec.symbol, score, reasons });+ queue.push(() => executeBuy({+ cfg, strat, throttle,+ mint: { mint: rec.mint, symbol: rec.symbol, name: rec.name, entry_trigger: 'intel_confirmed', trigger_ref: rec.mint },+ }));+ })+ .catch((err) => log.error('intel score failed', { mint: rec.mint, err: err?.message }));+ }+ };+ stopIntel = startIntelWatcher({+ network: cfg.network,+ windowMs: cfg.intelWindowMs,+ maxConcurrent: cfg.intelMaxConcurrent,+ useLlm: cfg.intelLlm,+ signal: abort.signal,+ onIntel,+ });+ log.info('intel watcher started', { windowMs: cfg.intelWindowMs, llm: cfg.intelLlm });+ }+// First-claim trigger: polls the on-chain fee-claim stream and snipes a// creator's coin on their first-ever reward claim. Shares the buy queue +// global throttle with the new-mint path, and halts new buys on drain/kill.@@ -135,6 +173,7 @@ async function main() {clearInterval(watchdogTimer);try { stopClaimWatch?.(); } catch {}try { stopFeed?.(); } catch {}+ try { stopIntel?.(); } catch {}abort.abort();// Give in-flight buys a moment to settle (Neon HTTP is stateless — nothing// else to close).diff --git a/workers/agent-sniper/intel/classify.js b/workers/agent-sniper/intel/classify.jsindex 69c6ffcd9..1ea744a71 100644--- a/workers/agent-sniper/intel/classify.js+++ b/workers/agent-sniper/intel/classify.js@@ -106,11 +106,11 @@ function parseJson(text) {** @returns {Promise<{category, tags, narrative, is_news_meme, confidence, source}>}*/-export async function classifyCoin(coin = {}, { timeoutMs = 12_000 } = {}) {+export async function classifyCoin(coin = {}, { timeoutMs = 12_000, useLlm = true } = {}) {const seed = heuristicClassify(coin);- // Nothing to feed an LLM with — keep the heuristic.- if (!coin.name && !coin.symbol && !coin.description) {+ // LLM disabled (cost control), or nothing to feed it — keep the heuristic.+ if (!useLlm || (!coin.name && !coin.symbol && !coin.description)) {return { ...seed, narrative: null, is_news_meme: false };}diff --git a/workers/agent-sniper/intel/learn.js b/workers/agent-sniper/intel/learn.jsnew file mode 100644index 000000000..b4775adcb--- /dev/null+++ b/workers/agent-sniper/intel/learn.js@@ -0,0 +1,198 @@+// Coin Intelligence — the learning loop.+//+// Watching is only half of "learns from watching". Here we:+// 1. labelOutcomes() — revisit observed coins after the fact and record what+// actually happened (graduated / pumped / flat / rugged) as ground truth.+// 2. trainWeights() — correlate each launch-time signal with good outcomes+// and persist per-signal weights the scorer reads. The dataset grows, the+// weights sharpen, the sniper's judgment improves. No black box: weights+// are plain correlations anyone can inspect.+//+// Run both from a cron (see api/cron or the worker loop). Pure-math helpers are+// exported for testing.++const PUMPFUN_COIN_API = 'https://frontend-api-v3.pump.fun/coins';+const FETCH_TIMEOUT_MS = 4_000;++// Signals we train on — all are ~0..1 (or normalized below). Counts are excluded;+// their information is already captured by the ratio signals.+export const TRAINABLE_SIGNALS = [+ 'organic_score', 'bundle_score', 'snipe_ratio', 'coordination_score',+ 'timing_entropy', 'concentration_top1', 'concentration_top5', 'concentration_top10',+ 'fresh_wallet_ratio', 'bubblemap_connectivity',+];++let _sqlPromise = null;+async function getSql() {+ if (_sqlPromise) return _sqlPromise;+ _sqlPromise = import('../../../api/_lib/db.js').then((m) => m.sql).catch(() => null);+ return _sqlPromise;+}++async function fetchCoin(mint) {+ const ctrl = new AbortController();+ const tid = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS);+ try {+ const r = await fetch(`${PUMPFUN_COIN_API}/${encodeURIComponent(mint)}`, {+ signal: ctrl.signal,+ headers: { accept: 'application/json', 'user-agent': 'three.ws-coin-intel/1' },+ });+ if (!r.ok) return null;+ return await r.json();+ } catch { return null; } finally { clearTimeout(tid); }+}++function isGraduated(c) {+ return c?.complete === true || !!c?.raydium_pool || !!c?.pump_swap_pool;+}++/**+ * Decide the outcome bucket for one coin from its current pump.fun state and the+ * market cap we recorded when we first saw it.+ * @returns {{ outcome, graduated, rugged, ath_multiple, last_market_cap_usd, ath_market_cap_usd }}+ */+export function deriveOutcome(coin, mcSolFirstSeen) {+ if (!coin) return { outcome: 'unknown', graduated: null, rugged: null, ath_multiple: null, last_market_cap_usd: null, ath_market_cap_usd: null };++ const graduated = isGraduated(coin);+ const usdMc = typeof coin.usd_market_cap === 'number' ? coin.usd_market_cap : null;+ const solMc = typeof coin.market_cap === 'number' ? coin.market_cap : null;+ const athUsd = typeof coin.ath_market_cap === 'number' ? coin.ath_market_cap+ : typeof coin.ath_market_cap_usd === 'number' ? coin.ath_market_cap_usd : usdMc;++ // Derive the coin's own SOL price (usd/sol) to keep the multiple unit-consistent+ // with the SOL market cap we stored at first sight.+ const solPrice = usdMc != null && solMc ? usdMc / solMc : null;+ const athSol = athUsd != null && solPrice ? athUsd / solPrice : null;+ const ath_multiple = athSol != null && mcSolFirstSeen > 0 ? athSol / mcSolFirstSeen : null;+ const lastMultiple = solMc != null && mcSolFirstSeen > 0 ? solMc / mcSolFirstSeen : null;++ let rugged = false;+ let outcome;+ if (graduated) outcome = 'graduated';+ else if (ath_multiple != null && ath_multiple >= 3) outcome = 'pumped';+ else if (lastMultiple != null && lastMultiple <= 0.25) { outcome = 'rugged'; rugged = true; }+ else if (usdMc != null && usdMc < 3_000) { outcome = 'rugged'; rugged = true; }+ else outcome = 'flat';++ return { outcome, graduated, rugged, ath_multiple, last_market_cap_usd: usdMc, ath_market_cap_usd: athUsd };+}++/**+ * Label coins observed ≥ minAgeMinutes ago that have no outcome yet.+ * @returns {Promise<{ labeled: number }>}+ */+export async function labelOutcomes({ network = 'mainnet', limit = 100, minAgeMinutes = 60 } = {}) {+ const sql = await getSql();+ if (!sql) return { labeled: 0 };++ const rows = await sql`+ select i.mint, i.signals+ from pump_coin_intel i+ left join pump_coin_outcomes o on o.mint = i.mint+ where i.network = ${network}+ and o.mint is null+ and i.first_seen_at <= now() - (${minAgeMinutes} || ' minutes')::interval+ order by i.first_seen_at asc+ limit ${Math.max(1, Math.min(500, limit | 0))}+ `;++ let labeled = 0;+ for (const row of rows) {+ const mcSol = Number(row.signals?.mc_sol_first_seen) || 0;+ const coin = await fetchCoin(row.mint);+ const o = deriveOutcome(coin, mcSol);+ try {+ await sql`+ insert into pump_coin_outcomes (+ mint, graduated, rugged, ath_market_cap_usd, ath_multiple,+ last_market_cap_usd, outcome+ ) values (+ ${row.mint}, ${o.graduated}, ${o.rugged}, ${o.ath_market_cap_usd},+ ${o.ath_multiple}, ${o.last_market_cap_usd}, ${o.outcome}+ )+ on conflict (mint) do update set+ graduated = excluded.graduated, rugged = excluded.rugged,+ ath_market_cap_usd = excluded.ath_market_cap_usd,+ ath_multiple = excluded.ath_multiple,+ last_market_cap_usd = excluded.last_market_cap_usd,+ outcome = excluded.outcome, labeled_at = now()+ `;+ labeled++;+ } catch (err) {+ console.warn('[coin-intel] label outcome failed:', err?.message);+ }+ }+ return { labeled };+}++// Pearson correlation of a signal against a binary good/bad label. Returns 0+// when there's no variance (degenerate) — a 0 weight, i.e. "no information".+export function correlation(pairs) {+ const xs = [], ys = [];+ for (const [x, y] of pairs) {+ if (x == null || !Number.isFinite(x)) continue;+ xs.push(x); ys.push(y);+ }+ const n = xs.length;+ if (n < 5) return 0;+ const mx = xs.reduce((a, b) => a + b, 0) / n;+ const my = ys.reduce((a, b) => a + b, 0) / n;+ let num = 0, dx = 0, dy = 0;+ for (let i = 0; i < n; i++) {+ const ex = xs[i] - mx, ey = ys[i] - my;+ num += ex * ey; dx += ex * ex; dy += ey * ey;+ }+ if (dx === 0 || dy === 0) return 0;+ const r = num / Math.sqrt(dx * dy);+ return Number.isFinite(r) ? Math.max(-1, Math.min(1, r)) : 0;+}++/**+ * Recompute per-signal weights from all labeled coins and persist them.+ * "good" = graduated or pumped. Skips quietly until there's enough signal.+ * @returns {Promise<{ trained: boolean, sample_size: number, weights?: object }>}+ */+export async function trainWeights({ network = 'mainnet', minSamples = 50 } = {}) {+ const sql = await getSql();+ if (!sql) return { trained: false, sample_size: 0 };++ const rows = await sql`+ select i.signals, o.outcome+ from pump_coin_intel i+ join pump_coin_outcomes o on o.mint = i.mint+ where i.network = ${network} and o.outcome <> 'unknown'+ `;+ if (rows.length < minSamples) return { trained: false, sample_size: rows.length };++ const labels = rows.map((r) => (r.outcome === 'graduated' || r.outcome === 'pumped') ? 1 : 0);+ const weights = {};+ for (const key of TRAINABLE_SIGNALS) {+ const pairs = rows.map((r, i) => [r.signals?.[key], labels[i]]);+ weights[key] = Number(correlation(pairs).toFixed(4));+ }++ await sql`+ insert into pump_intel_weights (network, weights, sample_size)+ values (${network}, ${JSON.stringify(weights)}::jsonb, ${rows.length})+ `;+ return { trained: true, sample_size: rows.length, weights };+}++/**+ * Turn signals + learned weights into a 0..1 learned score the scorer can blend.+ * With no weights yet, returns null so the scorer falls back to its baseline.+ */+export function learnedScore(signals, weights) {+ if (!weights || !signals) return null;+ let dot = 0, used = 0;+ for (const key of TRAINABLE_SIGNALS) {+ const w = weights[key];+ const v = signals[key];+ if (w == null || v == null || !Number.isFinite(v)) continue;+ dot += w * v; used++;+ }+ if (!used) return null;+ // Logistic squash to 0..1.+ return Number((1 / (1 + Math.exp(-dot))).toFixed(4));+}diff --git a/workers/agent-sniper/intel/watcher.js b/workers/agent-sniper/intel/watcher.jsindex 26beb3b9a..17e8ee8dd 100644--- a/workers/agent-sniper/intel/watcher.js+++ b/workers/agent-sniper/intel/watcher.js@@ -62,6 +62,7 @@ export function startIntelWatcher({network = 'mainnet',windowMs = 90_000,maxConcurrent = 400,+ useLlm = false,signal,onIntel,} = {}) {@@ -167,7 +168,7 @@ export function startIntelWatcher({twitter: obs.meta.twitter,telegram: obs.meta.telegram,website: obs.meta.website,- });+ }, { useLlm });const record = {mint,diff --git a/workers/agent-sniper/scorer.js b/workers/agent-sniper/scorer.jsindex 77842119b..01d766f47 100644--- a/workers/agent-sniper/scorer.js+++ b/workers/agent-sniper/scorer.js@@ -5,6 +5,8 @@// `reasons` always explains the verdict — kept on skipped events too so the// logs show WHY a mint was passed over, which is what you stare at when tuning.+import { learnedScore } from './intel/learn.js';+function n(v) {if (v == null) return null;const x = Number(v);@@ -61,3 +63,61 @@ export function scoreMint(mint, strat) {return { pass: true, score, reasons };}++/**+ * Decide whether to buy a coin AFTER the Coin Intelligence Engine has finished+ * observing it. Drives `trigger='intel_confirmed'` strategies. Unlike scoreMint+ * (which fires blind on the create event), this has the full picture: bundle+ * likelihood, organic score, concentration, dev behaviour, classification, and+ * the learned weights. It can afford to be picky — a passed-over coin costs+ * nothing, a bundle-rug costs real SOL.+ *+ * @param {object} rec finished intel record (from intel/watcher.js)+ * @param {object} strat agent_sniper_strategies row (trigger=intel_confirmed)+ * @param {object|null} weights learned weights (from intel/store.getLearnedWeights)+ * @returns {{ pass: boolean, score: number, reasons: string[] }}+ */+export function scoreIntel(rec, strat, weights = null) {+ const reasons = [];+ const s = rec?.signals || {};++ // ── hard gates ───────────────────────────────────────────────────────────+ const minQ = n(strat.min_quality_score);+ if (minQ != null && (rec.quality_score == null || rec.quality_score < minQ)) {+ return { pass: false, score: 0, reasons: [`quality_below_min:${rec.quality_score}`] };+ }+ const maxBundle = n(strat.max_bundle_score);+ if (maxBundle != null && s.bundle_score != null && s.bundle_score > maxBundle) {+ return { pass: false, score: 0, reasons: [`bundle_above_max:${s.bundle_score}`] };+ }+ const maxConc = n(strat.max_concentration_top1);+ if (maxConc != null && s.concentration_top1 != null && s.concentration_top1 > maxConc) {+ return { pass: false, score: 0, reasons: [`whale_concentration:${s.concentration_top1}`] };+ }+ // avoid_dev_dump defaults true (column default) — treat undefined as true.+ if (strat.avoid_dev_dump !== false && s.dev_sold) {+ return { pass: false, score: 0, reasons: ['dev_dumped'] };+ }+ const cats = Array.isArray(strat.allowed_categories) ? strat.allowed_categories.filter(Boolean) : [];+ if (cats.length && rec.category && !cats.includes(rec.category)) {+ return { pass: false, score: 0, reasons: [`category_excluded:${rec.category}`] };+ }+ // Reuse the new-mint hard filters that still apply post-observation.+ if (strat.require_socials && !(rec.twitter || rec.telegram || rec.website)) {+ return { pass: false, score: 0, reasons: ['no_socials'] };+ }++ // ── score: baseline quality + learned model + organic, minus risk ─────────+ let score = (rec.quality_score ?? 0) / 100;+ reasons.push(`quality:${rec.quality_score}`);+ if (s.organic_score != null) { score += s.organic_score * 0.5; reasons.push(`organic:${s.organic_score}`); }+ if (s.bundle_score != null) { score -= s.bundle_score * 0.5; if (s.bundle_score >= 0.4) reasons.push(`bundle:${s.bundle_score}`); }++ const learned = learnedScore(s, weights);+ if (learned != null) { score += learned; reasons.push(`learned:${learned}`); }++ if (rec.category) reasons.push(`cat:${rec.category}`);+ for (const flag of rec.risk_flags || []) reasons.push(`flag:${flag}`);++ return { pass: true, score: Number(score.toFixed(4)), reasons };+}