Skip to content

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

Add Coin Intelligence engine, trader stats, /launch page

nirholasfe51d0d2ccf5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d0c21d172..c8afcce59 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
## 2026-06-15
+- **Launch a Coin** (`/launch`) — Mint a coin for your 3D AI agent in one flow — pick an agent, set the name, symbol, and image, then launch on pump.fun straight from your wallet with an optional three.ws-branded vanity mint.
- **Sniper Arena — autonomous AI agents trading live** (`/play/arena`) — Watch three.ws AI agents trade pump.fun autonomously in real time. Live P&L leaderboard, each trade signed by the agent's own wallet and verifiable on-chain.
- **The $THREE Economy** (`/three`) — How three.ws charges in $THREE, the only coin: pay-per-use pricing for AI compute, hold-to-access holder tiers with lower fees, rare *.threews.sol names, and a holder-rewards loop. No burns — every spend funds the treasury or reflects back to holders.
- **After you launch a coin, jump straight to viewing or managing it** — The success screen you see right after launching a coin no longer dead-ends. Alongside the shareable card and copy/share buttons, there's now a clear set of next steps: View in 3D opens your coin as a live, interactive 3D scene; Manage on Dashboard takes you straight to that agent's control panel — with its row highlighted and ready — so you can speak, animate, and manage it; and View on pump.fun opens the coin on pump.fun. Closing the modal no longer forces a full page reload, so the rest of the page updates smoothly in place. (`/pump-dashboard`) `[improvement]`
@@ -24,7 +25,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Homepage Forge is more reliable — no more "busy" on the second model** — The mini Forge on the homepage now runs on the same free Standard lane as the full /forge page. Before, it used the free draft preview, which has tight concurrency and would return a "generator is busy" message on a quick second generation. Now back-to-back prompts hold up — models still land free with no sign-up, and the platform automatically degrades to the faster free lane if the main one is throttled. (`/forge`) `[fix]`
- **Launchpad Studio: pick your avatar from your own agents and the gallery** — Building a launchpad in Launchpad Studio (three.ws/launchpad) no longer means hunting down a model URL by hand. The avatar picker now shows three sections: your own three.ws agents (when you're signed in), the platform avatar gallery with a Show more button to browse deeper, and a collapsed Or enter a URL field for power users who want to paste a custom .glb. Thumbnails load lazily, the selected avatar updates the live 3D preview instantly, and your choice is saved with the published page. (`/launchpad`) `[feature, improvement]`
- **Live coin status — price, market cap and graduation — now unified across the platform** — The launches feed, agent profile token panels, and the in-world agent coin card now share one live coin-status display, so every place that shows a coin reads the same numbers from the same source. Launch cards now stream the coin's real logo, USD price, market cap, a graduation progress ring and time since launch — not just market cap — with the orbital fingerprint as a placeholder until the logo loads. Agent profiles show a live price-and-graduation chip in the token panel and per-coin market caps in the launch history, and the agent home card's market readout is now consistent with the rest of the platform. Each card refreshes on its own and degrades gracefully to a Retry if pump.fun is briefly unreachable. (`/launches`) `[improvement]`
-- **More uploaded avatars can dance** — The built-in animation library can now drive avatars built on CharacterStudio and Unreal Engine skeletons, not just Mixamo/Ready-rig ones. Previously a CharacterStudio or Fortnite-style rig would load but stand frozen because the animation system couldn't match its bone names; now those bones map automatically, so the full set of dances, poses, and idle motion plays on them everywhere avatars appear — the club, the walk view, AR, and the studio. (`/club`) `[improvement]`
+- **More uploaded avatars can dance** — The built-in animation library can now drive avatars built on more skeleton types — including game-engine and other creator-tool rigs — not just the common ones. Previously some uploaded avatars would load but stand frozen because the animation system couldn't match their bone names; now those bones map automatically, so the full set of dances, poses, and idle motion plays on them everywhere avatars appear — the club, the walk view, AR, and the studio. (`/club`) `[improvement]`
- **On-chain model validation for Solana agents** — Solana agents now get the same verifiable, on-chain glTF/model validation that EVM agents get from the ValidationRegistry — no contract to deploy. When you register an agent on Solana, the platform validator fetches your avatar's GLB, runs it through the same Khronos glTF validator behind the model checker, and records the pass/fail result as a signed on-chain attestation (an SPL Memo carrying a SHA-256 proof of the full report and a link to it). The result shows up as a 'model verified' badge on the agent passport, rides on the agent card, and is queryable at /api/agents/solana-validation. Anyone can independently recompute the proof hash from the same GLB to confirm the verdict, and you can re-validate on demand after updating your model. Re-attesting an identical report is idempotent, so no duplicate transactions. `[feature, security]`
- **Pose any avatar — a full motion library on the avatar page** — Every avatar page has a new Pose tab. Open it and the avatar steps onto a live 3D stage you can orbit, with a searchable library of 100+ motions — idle, wave, dance, jump, flex, facepalm and more. Click one and it plays on the avatar instantly, even when the model itself ships no built-in animation: the clips retarget onto its skeleton in your browser. A speed slider and a reset-to-idle control round out the transport. Avatars without a standard humanoid rig get a clear message instead of a broken stage. `[feature]`
- **Pump dashboard alerts now run server-side — fire across devices even with the tab closed** — Alert rules moved from your browser to our servers, so they fire whether or not a dashboard tab is open and follow you across every device you sign in on. Build as many rules as you need: get notified when any token (or a specific mint, or one of your agents' coins) graduates to an AMM, when a coin's market cap rises above or falls below a price you set, when someone places a whale-sized buy, or when one of your agents launches a new coin. Each rule delivers however you want — an in-app notification, a signed webhook POST to your own server, and Telegram — with each channel handled independently so one failing never blocks the others. Per-rule cooldowns and de-duplication prevent alert storms, the dashboard shows when a rule last fired and surfaces any delivery failures, and existing graduation alerts were migrated over automatically. (`/pump-dashboard`) `[feature]`
@@ -48,7 +49,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **The site footer and top pages are now polished on phones** — On mobile the footer's link columns ran off the right edge and got cut off — the contract address and legal links were unreachable — because an old style rule for the 3D viewer's corner credit was hijacking the main footer's layout. The footer now stacks into clean, tappable columns on every page. We also did a mobile pass across the most-used pages — Home, Discover, Create, Forge, Marketplace, Gallery, and Pay — eliminating sideways scrolling, enlarging tap targets to a comfortable size, and stopping form fields from zooming the page when you tap them. `[fix, improvement]`
- **The top navigation is back on every page** — The site header was being clipped to a sliver on most pages — the menu, search, and account controls were cut off and the dropdowns wouldn't open. An old style rule meant for the standalone 3D viewer's compact toolbar was leaking onto the shared navigation, forcing it to a fixed height and hiding everything below it. The viewer rule is now scoped to only the viewer, so the full navigation renders at its natural height across the whole site. `[fix]`
- **There's a cover at the Pole Club door** — The club now has a line outside. Before the room opens you pay a $0.01 USDC cover at the door via x402, and an on-chain bouncer checks the paying wallet — banned wallets are turned away, everyone else gets in with a door tier (newcomer, regular, or VIP) based on their past club nights. Pay once and you're in for the night; reopen the page and the velvet rope drops automatically. The 3D room loads behind the door while you're in line, so it's warm the moment you step in. (`/club`) `[feature]`
-- **Three distinct dancers, now waiting at their poles** — The Pole Club stage no longer sits empty between tips. Three dancers now stand at their own poles, lit and facing the crowd, the moment you arrive — each a different 3D avatar pulled from the gallery (still tinted to her pole's neon color) instead of copies of one model. Tip a pole and that dancer steps onto it and runs her routine, then returns to her stance at the pole. No tip, no dance — same rule, just a stage that looks alive from the first second. Behind the scenes the animation engine now retargets onto CharacterStudio and Unreal-mannequin rigs too, so far more uploaded avatars can actually dance. (`/club`) `[improvement]`
+- **Three distinct dancers, now waiting at their poles** — The Pole Club stage no longer sits empty between tips. Three dancers now stand at their own poles, lit and facing the crowd, the moment you arrive — each a different 3D avatar pulled from the gallery (still tinted to her pole's neon color) instead of copies of one model, and every dancer is auto-scaled to the same height so the lineup reads as a set. Tip a pole and that dancer steps onto it and runs her routine, then returns to her stance at the pole. No tip, no dance — same rule, just a stage that looks alive from the first second. Behind the scenes the animation engine now retargets onto more rig types, so far more uploaded avatars can actually dance. (`/club`) `[improvement]`
- **three.ws can now register itself on-chain on Solana** — Alongside its ERC-8004 identity, three.ws can now mint its own agent on Solana — as a Metaplex Core asset in the official "three.ws Agents" collection, exactly the way agents you deploy through the platform are registered. A one-command tool builds the platform's 3D Agent Card, verifies the avatar's SHA-256 against the exact GLB bytes served (so the model can't be silently swapped), pins the metadata, mints the asset into the collection, and writes the result back into the public discovery documents at three.ws/.well-known so any wallet, explorer, or agent can resolve and verify three.ws. The discovery card and its schema now carry Solana identities (CAIP-10) alongside EVM ones, and the platform agent's on-chain badge links straight to its Solana passport. (`/.well-known/agent-registration.json`) `[feature, infra]`
- **three.ws now registers itself as an on-chain agent (ERC-8004)** — The platform that helps you put your agents on-chain now does the same for itself. three.ws publishes a 3D Agent Card — a verifiable manifest of its name, its default 3D avatar, and its A2A/MCP/x402 service endpoints — at three.ws/.well-known/3d-agent-card.json, and ships a one-command tool that mints the platform agent in the canonical ERC-8004 IdentityRegistry on Base (with a Base Sepolia rehearsal first). The card cryptographically commits to the avatar: the SHA-256 in the card matches the exact GLB bytes served, so any indexer or wallet can independently verify the model hasn't been swapped. Other agents and directories can now discover and trust three.ws the same way three.ws lets them be discovered. `[feature, infra]`
- **USDC-paired agent coins now record and display correct trade amounts** — Coins launched against USDC are now tracked in the right currency end to end. Every buy and sell records which quote asset it actually used and how much of it moved — USDC amounts in USDC, SOL amounts in SOL — instead of quietly storing a USDC trade as if it were SOL and reporting a price and market cap that were off by orders of magnitude. Portfolios now subtotal holdings separately by quote asset, so your SOL positions and USDC positions each get their own value, cost basis, and unrealized P&L with no more mixing of mismatched units. Existing SOL trades are unchanged, and historical rows were backfilled as SOL-paired so nothing shifts. `[fix, feature]`
diff --git a/api/_lib/migrations/20260615060000_coin_intel.sql b/api/_lib/migrations/20260615060000_coin_intel.sql
new file mode 100644
index 000000000..7d3c8399d
--- /dev/null
+++ b/api/_lib/migrations/20260615060000_coin_intel.sql
@@ -0,0 +1,130 @@
+-- Migration: Coin Intelligence Engine — per-coin observation, wallet ledger,
+-- outcome labels, and learned signal weights.
+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/20260615060000_coin_intel.sql
+-- Idempotent.
+--
+-- The intel watcher (workers/agent-sniper/intel) subscribes to each new mint's
+-- live trade stream for an observation window, records every wallet + every
+-- buy/sell, derives bundle/organic/concentration signals, classifies the coin,
+-- and persists here. The sniper scorer reads pump_coin_intel + pump_intel_weights
+-- to decide. The learning loop labels pump_coin_outcomes after the fact and
+-- recomputes pump_intel_weights so judgment improves over time.
+--
+-- All SOL amounts are lamports (numeric(40,0)) to match agent_sniper_*.
+
+begin;
+
+-- ── one row per observed coin ────────────────────────────────────────────────
+create table if not exists pump_coin_intel (
+ mint text primary key,
+ network text not null default 'mainnet' check (network in ('mainnet','devnet')),
+ symbol text,
+ name text,
+ creator text,
+ bonding_curve text,
+ image_uri text,
+ description text,
+ twitter text,
+ telegram text,
+ website text,
+
+ created_at timestamptz, -- coin creation (from feed)
+ first_seen_at timestamptz not null default now(),
+ observation_ended_at timestamptz, -- when the window closed
+ observation_seconds int,
+
+ -- raw aggregates (window)
+ dev_buy_lamports numeric(40, 0), -- creator's initial buy
+ dev_sold boolean not null default false,
+ dev_sell_lamports numeric(40, 0),
+ buy_count int not null default 0,
+ sell_count int not null default 0,
+ buy_volume_lamports numeric(40, 0) not null default 0,
+ sell_volume_lamports numeric(40, 0) not null default 0,
+ unique_buyers int not null default 0,
+ unique_sellers int not null default 0,
+ largest_buy_lamports numeric(40, 0),
+
+ -- derived signals (full structured detail; the columns below are the hot ones)
+ signals jsonb not null default '{}'::jsonb,
+ bundle_score numeric, -- 0..1, coordinated-launch likelihood
+ organic_score numeric, -- 0..1, organic-demand likelihood
+ snipe_ratio numeric, -- 0..1, buy vol in first seconds
+ concentration_top10 numeric, -- 0..1, top-10 net-buy share
+ fresh_wallet_ratio numeric, -- 0..1, null when enrichment off
+ bubblemap_connectivity numeric, -- 0..1, null when enrichment off
+ quality_score int, -- 0..100 composite
+ risk_flags text[] not null default '{}',
+
+ -- classification
+ category text, -- meme|tech|ai|culture|community|...
+ tags text[] not null default '{}',
+ narrative text,
+ classify_confidence numeric,
+ classify_source text, -- 'llm' | 'heuristic'
+
+ updated_at timestamptz not null default now()
+);
+
+create index if not exists pump_coin_intel_recent
+ on pump_coin_intel (first_seen_at desc);
+create index if not exists pump_coin_intel_quality
+ on pump_coin_intel (quality_score desc nulls last, first_seen_at desc);
+create index if not exists pump_coin_intel_category
+ on pump_coin_intel (category, first_seen_at desc);
+create index if not exists pump_coin_intel_creator
+ on pump_coin_intel (creator);
+
+-- ── per-coin per-wallet aggregate (the "who traded it" ledger) ────────────────
+create table if not exists pump_coin_wallets (
+ mint text not null,
+ wallet text not null,
+ buy_count int not null default 0,
+ sell_count int not null default 0,
+ buy_lamports numeric(40, 0) not null default 0,
+ sell_lamports numeric(40, 0) not null default 0,
+ base_bought numeric(40, 0) not null default 0,
+ base_sold numeric(40, 0) not null default 0,
+ first_seen_at timestamptz not null default now(),
+ last_seen_at timestamptz not null default now(),
+ is_creator boolean not null default false,
+ -- wallet-graph enrichment (null until RPC funder lookup runs)
+ funder text,
+ primary key (mint, wallet)
+);
+
+create index if not exists pump_coin_wallets_wallet
+ on pump_coin_wallets (wallet);
+create index if not exists pump_coin_wallets_funder
+ on pump_coin_wallets (funder) where funder is not null;
+
+-- ── ground-truth outcome, labeled after the fact ─────────────────────────────
+create table if not exists pump_coin_outcomes (
+ mint text primary key references pump_coin_intel(mint) on delete cascade,
+ labeled_at timestamptz not null default now(),
+ graduated boolean,
+ rugged boolean,
+ ath_market_cap_usd numeric,
+ ath_multiple numeric, -- ath_mc / mc_at_first_seen
+ last_market_cap_usd numeric,
+ outcome text -- 'graduated'|'pumped'|'flat'|'rugged'|'unknown'
+ check (outcome in ('graduated','pumped','flat','rugged','unknown'))
+);
+
+create index if not exists pump_coin_outcomes_outcome
+ on pump_coin_outcomes (outcome, labeled_at desc);
+
+-- ── learned per-signal weights (the scorer reads the latest row) ─────────────
+create table if not exists pump_intel_weights (
+ id uuid primary key default gen_random_uuid(),
+ network text not null default 'mainnet',
+ -- map of signal_key -> weight (correlation with good outcomes, -1..1)
+ weights jsonb not null default '{}'::jsonb,
+ sample_size int not null default 0,
+ trained_at timestamptz not null default now()
+);
+
+create index if not exists pump_intel_weights_latest
+ on pump_intel_weights (network, trained_at desc);
+
+commit;
diff --git a/api/_lib/trader-stats.js b/api/_lib/trader-stats.js
new file mode 100644
index 000000000..a75514da8
--- /dev/null
+++ b/api/_lib/trader-stats.js
@@ -0,0 +1,478 @@
+/**
+ * Trader track-record truth layer.
+ *
+ * The single source of truth for every "how good is this trader" number on
+ * three.ws — the leaderboard, the trader profile, the Proof tab, the copy-trading
+ * verification badge. Built on `agent_sniper_positions`, which is the canonical
+ * per-position ledger: each row already carries realized P&L (lamports + pct),
+ * entry/exit SOL, hold window (opened_at → closed_at), and the on-chain buy/sell
+ * signatures that PROVE every number. We never invent a metric we can't trace to
+ * a tx.
+ *
+ * Two layers, by design:
+ * - computeTraderMetrics(positions, opts) — PURE. No DB, no network. Deterministic
+ * over an array of position rows. This is what the tests pin to fixtures, and
+ * what guarantees the leaderboard and the profile can never disagree.
+ * - getTraderStats / getLeaderboard — fetch rows, price SOL→USD, attach
+ * identity, then defer all arithmetic to computeTraderMetrics.
+ *
+ * Honesty rules baked in:
+ * - SOL amounts are exact (from chain). USD is an enrichment that degrades to
+ * null if the price feed is down — we never fabricate a dollar figure.
+ * - We do NOT claim "wash detection" we can't do from one-sided position data.
+ * `churn_pct` is an explicit heuristic (near-flat in-and-out churn) and is
+ * named as such.
+ * - Survivorship-honest: closed losers are counted, never hidden.
+ */
+
+import { sql } from './db.js';
+import { solUsdPrice } from './avatar-wallet.js';
+
+const LAMPORTS_PER_SOL = 1e9;
+
+/** Supported leaderboard / profile time windows. */
+export const WINDOWS = new Set(['24h', '7d', '30d', 'all']);
+const WINDOW_MS = { '24h': 86_400_000, '7d': 604_800_000, '30d': 2_592_000_000 };
+
+/** ISO lower-bound for a window, or null for 'all'. `now` injectable for tests. */
+export function windowStartIso(window, now = Date.now()) {
+ const span = WINDOW_MS[window];
+ return span ? new Date(now - span).toISOString() : null;
+}
+
+// --- Score / badge tuning. Transparent, named, tunable. -----------------------
+// A trader's composite score (0–100) is a documented weighted blend of win rate,
+// profit factor, signed realized P&L, consistency (Sharpe-ish), drawdown, and
+// churn — regressed toward neutral until they have enough closed trades to trust.
+const SCORE_WEIGHTS = { winRate: 0.30, profitFactor: 0.22, pnl: 0.26, consistency: 0.12, drawdown: 0.10 };
+const CHURN_SCORE_PENALTY = 0.10; // churn subtracts up to this much from raw score
+const CONFIDENCE_FULL_AT = 14; // closed trades for full statistical confidence
+const NEUTRAL_RAW = 0.42; // unproven traders regress toward this (slightly below mid)
+const PNL_TANH_SOL = 5; // ~5 SOL realized ≈ a strongly positive pnl sub-score
+const SHARPE_TANH = 2; // consistency normalization
+
+// Verification badge ("proven track record") gate — every condition must hold.
+const BADGE = { minClosed: 12, minUniqueCoins: 5, maxChurnPct: 40 };
+
+// Churn heuristic: a position opened and closed inside this window with a
+// near-flat result is in-and-out churn that pads trade counts without real risk.
+const CHURN_HOLD_SECONDS = 25;
+const CHURN_FLAT_PCT = 1.5;
+
+const big = (v) => {
+ try { return Number(BigInt(v)); } catch { return Number(v) || 0; }
+};
+const clamp = (x, lo, hi) => Math.min(hi, Math.max(lo, x));
+const tanh = (x) => Math.tanh(x);
+
+function median(sorted) {
+ if (!sorted.length) return 0;
+ const mid = Math.floor(sorted.length / 2);
+ return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
+}
+
+function stddev(values, mean) {
+ if (values.length < 2) return 0;
+ const variance = values.reduce((a, v) => a + (v - mean) ** 2, 0) / (values.length - 1);
+ return Math.sqrt(variance);
+}
+
+/**
+ * Max drawdown over the realized equity curve (cumulative realized P&L in
+ * lamports, ordered oldest→newest close). Returns both the absolute SOL drop from
+ * a running peak and that drop as a pct of the peak equity. A monotonically
+ * rising book has zero drawdown.
+ */
+function maxDrawdown(closedOrderedLamports) {
+ let equity = 0, peak = 0, maxDropLamports = 0, maxDropPct = 0;
+ for (const pnl of closedOrderedLamports) {
+ equity += pnl;
+ if (equity > peak) peak = equity;
+ const drop = peak - equity;
+ if (drop > maxDropLamports) {
+ maxDropLamports = drop;
+ maxDropPct = peak > 0 ? (drop / peak) * 100 : 0;
+ }
+ }
+ return { sol: maxDropLamports / LAMPORTS_PER_SOL, pct: maxDropPct };
+}
+
+/**
+ * Compute the full metric set for one trader from their position rows.
+ *
+ * @param {Array<object>} positions agent_sniper_positions rows (closed + open).
+ * Required fields per row: status, realized_pnl_lamports, realized_pnl_pct,
+ * entry_quote_lamports, exit_quote_lamports, last_value_lamports, mint,
+ * opened_at, closed_at.
+ * @param {object} [opts]
+ * @param {number|null} [opts.solUsd] USD per SOL, or null to omit USD fields.
+ * @returns {object} canonical metrics — see fields below.
+ */
+export function computeTraderMetrics(positions, { solUsd = null } = {}) {
+ const closed = positions.filter((p) => p.status === 'closed');
+ const open = positions.filter((p) => p.status === 'open' || p.status === 'opening' || p.status === 'closing');
+
+ // --- Realized (closed positions) ---
+ let realizedLamports = 0n;
+ let grossProfit = 0n, grossLoss = 0n; // grossLoss kept positive
+ let wins = 0, losses = 0;
+ let invested = 0n;
+ const pnlPcts = [];
+ const winPcts = [], lossPcts = [];
+ const holdSeconds = [];
+ const coins = new Set();
+ let churn = 0;
+ let bestPct = null, worstPct = null;
+ let firstActive = null, lastActive = null;
+
+ // Oldest→newest by close time for the equity curve.
+ const closedOrdered = [...closed].sort(
+ (a, b) => new Date(a.closed_at || a.opened_at).getTime() - new Date(b.closed_at || b.opened_at).getTime(),
+ );
+ const equityPnls = [];
+
+ for (const p of closedOrdered) {
+ const pnl = BigInt(p.realized_pnl_lamports ?? 0);
+ realizedLamports += pnl;
+ equityPnls.push(big(p.realized_pnl_lamports));
+ if (pnl > 0n) { wins += 1; grossProfit += pnl; } else if (pnl < 0n) { losses += 1; grossLoss += -pnl; }
+ invested += BigInt(p.entry_quote_lamports ?? 0);
+ if (p.mint) coins.add(p.mint);
+
+ const pct = p.realized_pnl_pct != null ? Number(p.realized_pnl_pct) : null;
+ if (pct != null && Number.isFinite(pct)) {
+ pnlPcts.push(pct);
+ if (pct > 0) winPcts.push(pct); else if (pct < 0) lossPcts.push(pct);
+ bestPct = bestPct == null ? pct : Math.max(bestPct, pct);
+ worstPct = worstPct == null ? pct : Math.min(worstPct, pct);
+ }
+
+ const opened = new Date(p.opened_at).getTime();
+ const closedAt = new Date(p.closed_at || p.opened_at).getTime();
+ const held = Math.max(0, (closedAt - opened) / 1000);
+ holdSeconds.push(held);
+ if (held <= CHURN_HOLD_SECONDS && pct != null && Math.abs(pct) <= CHURN_FLAT_PCT) churn += 1;
+
+ if (firstActive == null || opened < firstActive) firstActive = opened;
+ if (lastActive == null || closedAt > lastActive) lastActive = closedAt;
+ }
+
+ // --- Unrealized (open positions) ---
+ let openExposure = 0n;
+ let unrealizedLamports = 0n;
+ for (const p of open) {
+ const entry = BigInt(p.entry_quote_lamports ?? 0);
+ const last = p.last_value_lamports != null ? BigInt(p.last_value_lamports) : entry;
+ openExposure += entry;
+ unrealizedLamports += last - entry;
+ const opened = new Date(p.opened_at).getTime();
+ if (firstActive == null || opened < firstActive) firstActive = opened;
+ if (lastActive == null || opened > lastActive) lastActive = opened;
+ }
+
+ const closedCount = closed.length;
+ const realizedSol = big(realizedLamports.toString()) / LAMPORTS_PER_SOL;
+ const investedSol = big(invested.toString()) / LAMPORTS_PER_SOL;
+ const unrealizedSol = big(unrealizedLamports.toString()) / LAMPORTS_PER_SOL;
+ const openExposureSol = big(openExposure.toString()) / LAMPORTS_PER_SOL;
+
+ const winRate = closedCount ? wins / closedCount : 0;
+ const profitFactor = grossLoss > 0n
+ ? big(grossProfit.toString()) / big(grossLoss.toString())
+ : (grossProfit > 0n ? Infinity : 0);
+ const roiPct = investedSol > 0 ? (realizedSol / investedSol) * 100 : 0;
+ const avgPnlPct = pnlPcts.length ? pnlPcts.reduce((a, v) => a + v, 0) / pnlPcts.length : 0;
+ const avgWinPct = winPcts.length ? winPcts.reduce((a, v) => a + v, 0) / winPcts.length : 0;
+ const avgLossPct = lossPcts.length ? lossPcts.reduce((a, v) => a + v, 0) / lossPcts.length : 0;
+ const holdSorted = [...holdSeconds].sort((a, b) => a - b);
+ const avgHoldSeconds = holdSeconds.length ? holdSeconds.reduce((a, v) => a + v, 0) / holdSeconds.length : 0;
+ const sharpe = pnlPcts.length > 1 ? avgPnlPct / (stddev(pnlPcts, avgPnlPct) || 1) : 0;
+ const churnPct = closedCount ? (churn / closedCount) * 100 : 0;
+ const drawdown = maxDrawdown(equityPnls);
+
+ // --- Composite score (0–100), transparent + confidence-regressed ---
+ const pfComponent = profitFactor === Infinity ? 1 : profitFactor / (profitFactor + 1);
+ const pnlComponent = 0.5 + 0.5 * tanh(realizedSol / PNL_TANH_SOL);
+ const consistencyComponent = 0.5 + 0.5 * tanh(sharpe / SHARPE_TANH);
+ const drawdownComponent = 1 - clamp(drawdown.pct / 100, 0, 1);
+ let raw =
+ SCORE_WEIGHTS.winRate * winRate +
+ SCORE_WEIGHTS.profitFactor * pfComponent +
+ SCORE_WEIGHTS.pnl * pnlComponent +
+ SCORE_WEIGHTS.consistency * consistencyComponent +
+ SCORE_WEIGHTS.drawdown * drawdownComponent;
+ raw = clamp(raw - CHURN_SCORE_PENALTY * clamp(churnPct / 100, 0, 1), 0, 1);
+ const confidence = clamp(closedCount / CONFIDENCE_FULL_AT, 0, 1);
+ const effective = raw * confidence + NEUTRAL_RAW * (1 - confidence);
+ const score = Math.round(100 * effective);
+
+ const verified =
+ closedCount >= BADGE.minClosed &&
+ realizedSol > 0 &&
+ coins.size >= BADGE.minUniqueCoins &&
+ churnPct <= BADGE.maxChurnPct;
+
+ const usd = (sol) => (solUsd != null ? sol * solUsd : null);
+
+ return {
+ score,
+ verified,
+ confidence: Number(confidence.toFixed(3)),
+
+ closed_count: closedCount,
+ open_count: open.length,
+ wins,
+ losses,
+ win_rate: Number(winRate.toFixed(4)),
+
+ realized_pnl_lamports: realizedLamports.toString(),
+ realized_pnl_sol: Number(realizedSol.toFixed(6)),
+ realized_pnl_usd: usd(realizedSol) != null ? Number(usd(realizedSol).toFixed(2)) : null,
+ unrealized_pnl_sol: Number(unrealizedSol.toFixed(6)),
+ unrealized_pnl_usd: usd(unrealizedSol) != null ? Number(usd(unrealizedSol).toFixed(2)) : null,
+
+ invested_sol: Number(investedSol.toFixed(6)),
+ roi_pct: Number(roiPct.toFixed(2)),
+ open_exposure_sol: Number(openExposureSol.toFixed(6)),
+ open_exposure_usd: usd(openExposureSol) != null ? Number(usd(openExposureSol).toFixed(2)) : null,
+
+ profit_factor: profitFactor === Infinity ? null : Number(profitFactor.toFixed(3)),
+ avg_pnl_pct: Number(avgPnlPct.toFixed(2)),
+ avg_win_pct: Number(avgWinPct.toFixed(2)),
+ avg_loss_pct: Number(avgLossPct.toFixed(2)),
+ best_pnl_pct: bestPct != null ? Number(bestPct.toFixed(2)) : null,
+ worst_pnl_pct: worstPct != null ? Number(worstPct.toFixed(2)) : null,
+ sharpe: Number(sharpe.toFixed(3)),
+
+ max_drawdown_sol: Number(drawdown.sol.toFixed(6)),
+ max_drawdown_pct: Number(drawdown.pct.toFixed(2)),
+
+ avg_hold_seconds: Math.round(avgHoldSeconds),
+ median_hold_seconds: Math.round(median(holdSorted)),
+ unique_coins: coins.size,
+ churn_pct: Number(churnPct.toFixed(2)),
+
+ first_active_at: firstActive ? new Date(firstActive).toISOString() : null,
+ last_active_at: lastActive ? new Date(lastActive).toISOString() : null,
+ };
+}
+
+// --- DB layer ---------------------------------------------------------------
+//
+// NOTE: the Neon HTTP driver's tagged template does not compose nested `sql`
+// fragments (a `${sql`…`}` would bind as a parameter), so the position column
+// list is written literally into each query below. It is static SQL with no user
+// input — duplication here is the safe, correct trade-off.
+
+/**
+ * Fetch a trader's positions for a window. Closed positions are window-bounded by
+ * close time; open positions are ALWAYS included (current exposure is "now",
+ * regardless of window).
+ */
+export async function fetchTraderPositions({ agentId, network, window = 'all', now = Date.now() }) {
+ const start = windowStartIso(window, now);
+ return start
+ ? sql`
+ select p.id, p.agent_id, p.wallet, p.mint, p.symbol, p.name, p.status, p.exit_reason,
+ p.entry_quote_lamports, p.exit_quote_lamports, p.last_value_lamports, p.peak_value_lamports,
+ p.realized_pnl_lamports, p.realized_pnl_pct, p.buy_sig, p.sell_sig,
+ p.opened_at, p.closed_at
+ from agent_sniper_positions p
+ where p.agent_id = ${agentId} and p.network = ${network}
+ and (p.status in ('open','opening','closing') or p.closed_at >= ${start})
+ order by coalesce(p.closed_at, p.opened_at) desc
+ `
+ : sql`
+ select p.id, p.agent_id, p.wallet, p.mint, p.symbol, p.name, p.status, p.exit_reason,
+ p.entry_quote_lamports, p.exit_quote_lamports, p.last_value_lamports, p.peak_value_lamports,
+ p.realized_pnl_lamports, p.realized_pnl_pct, p.buy_sig, p.sell_sig,
+ p.opened_at, p.closed_at
+ from agent_sniper_positions p
+ where p.agent_id = ${agentId} and p.network = ${network}
+ order by coalesce(p.closed_at, p.opened_at) desc
+ `;
+}
+
+/** SOL/USD with a short module cache so a burst of stat requests prices once. */
+let _solCache = { usd: null, at: 0 };
+async function cachedSolUsd() {
+ const now = Date.now();
+ if (_solCache.usd != null && now - _solCache.at < 60_000) return _solCache.usd;
+ try {
+ const usd = await solUsdPrice();
+ _solCache = { usd, at: now };
+ return usd;
+ } catch {
+ // Degrade to last known price if we have one, else null (SOL stays exact).
+ return _solCache.usd;
+ }
+}
+
+function solscanUrl(sig, network) {
+ if (!sig || sig === 'SIMULATED') return null;
+ return network === 'devnet' ? `https://solscan.io/tx/${sig}?cluster=devnet` : `https://solscan.io/tx/${sig}`;
+}
+
+/** Shape a closed position for the profile history + Proof tab (every number → tx). */
+export function shapeClosed(p, network) {
+ return {
+ id: p.id,
+ mint: p.mint,
+ symbol: p.symbol,
+ name: p.name,
+ entry_sol: p.entry_quote_lamports != null ? big(p.entry_quote_lamports) / LAMPORTS_PER_SOL : null,
+ exit_sol: p.exit_quote_lamports != null ? big(p.exit_quote_lamports) / LAMPORTS_PER_SOL : null,
+ pnl_sol: p.realized_pnl_lamports != null ? big(p.realized_pnl_lamports) / LAMPORTS_PER_SOL : null,
+ pnl_pct: p.realized_pnl_pct != null ? Number(p.realized_pnl_pct) : null,
+ exit_reason: p.exit_reason,
+ opened_at: p.opened_at,
+ closed_at: p.closed_at,
+ buy_url: solscanUrl(p.buy_sig, network),
+ sell_url: solscanUrl(p.sell_sig, network),
+ };
+}
+
+/** Shape an open position with live unrealized P&L. */
+export function shapeOpen(p, network) {
+ const entry = p.entry_quote_lamports != null ? big(p.entry_quote_lamports) : 0;
+ const last = p.last_value_lamports != null ? big(p.last_value_lamports) : entry;
+ return {
+ id: p.id,
+ mint: p.mint,
+ symbol: p.symbol,
+ name: p.name,
+ entry_sol: entry / LAMPORTS_PER_SOL,
+ current_sol: last / LAMPORTS_PER_SOL,
+ unrealized_pct: entry > 0 ? ((last - entry) / entry) * 100 : 0,
+ opened_at: p.opened_at,
+ buy_url: solscanUrl(p.buy_sig, network),
+ };
+}
+
+/**
+ * Full trader profile: identity + metrics for the window + closed history (proof)
+ * + open positions. Returns null if the agent has no positions on this network.
+ */
+export async function getTraderStats({ agentId, network, window = 'all', now = Date.now() }) {
+ const [idRows, positions, solUsd] = await Promise.all([
+ sql`
+ select id, name, description, avatar_url, profile_image_url, is_public
+ from agent_identities where id = ${agentId} limit 1
+ `,
+ fetchTraderPositions({ agentId, network, window, now }),
+ cachedSolUsd(),
+ ]);
+ const identity = idRows[0];
+ if (!identity) return null;
+
+ const metrics = computeTraderMetrics(positions, { solUsd });
+ const closed = positions.filter((p) => p.status === 'closed').map((p) => shapeClosed(p, network));
+ const open = positions
+ .filter((p) => p.status === 'open' || p.status === 'opening' || p.status === 'closing')
+ .map((p) => shapeOpen(p, network));
+ const wallet = positions[0]?.wallet || null;
+
+ return {
+ agent: {
+ id: identity.id,
+ name: identity.name,
+ description: identity.description || null,
+ image: identity.profile_image_url || identity.avatar_url || null,
+ is_public: identity.is_public !== false,
+ wallet,
+ },
+ network,
+ window,
+ sol_usd: solUsd,
+ metrics,
+ closed,
+ open,
+ };
+}
+
+/**
+ * Leaderboard: every agent with sniper activity in the window, ranked by composite
+ * score. One query pulls all in-window positions; we group by agent and run each
+ * group through the SAME pure `computeTraderMetrics` the profile uses, so the two
+ * surfaces can never disagree. Scale note: the sniper arena is a curated set of
+ * 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() }) {
+ const start = windowStartIso(window, now);
+ const rows = start
+ ? await sql`
+ select p.id, p.agent_id, p.wallet, p.mint, p.symbol, p.name, p.status, p.exit_reason,
+ p.entry_quote_lamports, p.exit_quote_lamports, p.last_value_lamports, p.peak_value_lamports,
+ p.realized_pnl_lamports, p.realized_pnl_pct, p.buy_sig, p.sell_sig,
+ p.opened_at, p.closed_at,
+ a.name as agent_name, a.avatar_url as agent_avatar, a.profile_image_url as agent_image
+ from agent_sniper_positions p
+ join agent_identities a on a.id = p.agent_id
+ where p.network = ${network} and a.is_public is not false
+ and (p.status in ('open','opening','closing') or p.closed_at >= ${start})
+ `
+ : await sql`
+ select p.id, p.agent_id, p.wallet, p.mint, p.symbol, p.name, p.status, p.exit_reason,
+ p.entry_quote_lamports, p.exit_quote_lamports, p.last_value_lamports, p.peak_value_lamports,
+ p.realized_pnl_lamports, p.realized_pnl_pct, p.buy_sig, p.sell_sig,
+ p.opened_at, p.closed_at,
+ a.name as agent_name, a.avatar_url as agent_avatar, a.profile_image_url as agent_image
+ from agent_sniper_positions p
+ join agent_identities a on a.id = p.agent_id
+ where p.network = ${network} and a.is_public is not false
+ `;
+ const solUsd = await cachedSolUsd();
+
+ const byAgent = new Map();
+ for (const r of rows) {
+ let g = byAgent.get(r.agent_id);
+ if (!g) {
+ g = {
+ agent_id: r.agent_id,
+ agent_name: r.agent_name,
+ image: r.agent_image || r.agent_avatar || null,
+ wallet: r.wallet,
+ positions: [],
+ };
+ byAgent.set(r.agent_id, g);
+ }
+ g.positions.push(r);
+ }
+
+ const board = [...byAgent.values()]
+ .map((g) => {
+ const m = computeTraderMetrics(g.positions, { solUsd });
+ return {
+ agent_id: g.agent_id,
+ agent_name: g.agent_name,
+ image: g.image,
+ wallet: g.wallet,
+ score: m.score,
+ verified: m.verified,
+ closed: m.closed_count,
+ open_positions: m.open_count,
+ wins: m.wins,
+ losses: m.losses,
+ win_rate: m.win_rate,
+ realized_pnl_lamports: m.realized_pnl_lamports,
+ realized_pnl_sol: m.realized_pnl_sol,
+ realized_pnl_usd: m.realized_pnl_usd,
+ roi_pct: m.roi_pct,
+ profit_factor: m.profit_factor,
+ avg_pnl_pct: m.avg_pnl_pct,
+ best_pnl_pct: m.best_pnl_pct,
+ max_drawdown_pct: m.max_drawdown_pct,
+ avg_hold_seconds: m.avg_hold_seconds,
+ unique_coins: m.unique_coins,
+ churn_pct: m.churn_pct,
+ last_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)
+ .slice(0, limit)
+ .map((r, i) => ({ rank: i + 1, ...r }));
+
+ return { network, window, sol_usd: solUsd, leaderboard: board, t: now };
+}
diff --git a/data/changelog.json b/data/changelog.json
index 0d1e1a3e4..bc51a97d5 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -39,14 +39,14 @@
{
"date": "2026-06-15",
"title": "Three distinct dancers, now waiting at their poles",
- "summary": "The Pole Club stage no longer sits empty between tips. Three dancers now stand at their own poles, lit and facing the crowd, the moment you arrive — each a different 3D avatar pulled from the gallery (still tinted to her pole's neon color) instead of copies of one model. Tip a pole and that dancer steps onto it and runs her routine, then returns to her stance at the pole. No tip, no dance — same rule, just a stage that looks alive from the first second. Behind the scenes the animation engine now retargets onto CharacterStudio and Unreal-mannequin rigs too, so far more uploaded avatars can actually dance.",
+ "summary": "The Pole Club stage no longer sits empty between tips. Three dancers now stand at their own poles, lit and facing the crowd, the moment you arrive — each a different 3D avatar pulled from the gallery (still tinted to her pole's neon color) instead of copies of one model, and every dancer is auto-scaled to the same height so the lineup reads as a set. Tip a pole and that dancer steps onto it and runs her routine, then returns to her stance at the pole. No tip, no dance — same rule, just a stage that looks alive from the first second. Behind the scenes the animation engine now retargets onto more rig types, so far more uploaded avatars can actually dance.",
"tags": ["improvement"],
"link": "/club"
},
{
"date": "2026-06-15",
"title": "More uploaded avatars can dance",
- "summary": "The built-in animation library can now drive avatars built on CharacterStudio and Unreal Engine skeletons, not just Mixamo/Ready-rig ones. Previously a CharacterStudio or Fortnite-style rig would load but stand frozen because the animation system couldn't match its bone names; now those bones map automatically, so the full set of dances, poses, and idle motion plays on them everywhere avatars appear — the club, the walk view, AR, and the studio.",
+ "summary": "The built-in animation library can now drive avatars built on more skeleton types — including game-engine and other creator-tool rigs — not just the common ones. Previously some uploaded avatars would load but stand frozen because the animation system couldn't match their bone names; now those bones map automatically, so the full set of dances, poses, and idle motion plays on them everywhere avatars appear — the club, the walk view, AR, and the studio.",
"tags": ["improvement"],
"link": "/club"
},
diff --git a/data/pages.json b/data/pages.json
index 62ec758f9..7257b538d 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -416,6 +416,14 @@
"title": "Crypto",
"description": "On-chain features: pay-per-call, token launches, vanity wallets.",
"pages": [
+ {
+ "path": "/launch",
+ "title": "Launch a Coin",
+ "description": "Mint a coin for your 3D AI agent in one flow — pick an agent, set the name, symbol, and image, then launch on pump.fun straight from your wallet with an optional three.ws-branded vanity mint.",
+ "priority": 0.8,
+ "changefreq": "monthly",
+ "added": "2026-06-15"
+ },
{
"path": "/launches",
"title": "Agent Launches",
diff --git a/docs/roadmap/coin-intelligence-engine.md b/docs/roadmap/coin-intelligence-engine.md
new file mode 100644
index 000000000..cd0bc2d1a
--- /dev/null
+++ b/docs/roadmap/coin-intelligence-engine.md
@@ -0,0 +1,83 @@
+# Coin Intelligence Engine
+
+**Status:** Building (foundation landing now). Last updated 2026-06-15.
+**Purpose:** Watch, record, and classify **every** coin launched on pump.fun in real time, derive the signals that separate organic launches from bundles/rugs, and serve that intelligence to user agents in milliseconds so they can act faster than a human ever could.
+
+The autonomous sniper ([workers/agent-sniper/](../../workers/agent-sniper/)) currently scores a coin from **only its mint-creation event** — name, socials, creator history, initial buy. That's a snapshot. This engine adds the missing dimension: **what happens in the first seconds of trading**, which is where bundles, sniper swarms, dev dumps, and organic demand actually reveal themselves.
+
+---
+
+## What it watches (every metric)
+
+For each new mint, the watcher subscribes to its live trade stream (PumpPortal `subscribeTokenTrade`) for an observation window (default 90s) and records:
+
+**Per coin**
+- Dev (creator) initial buy size, and whether the dev sold inside the window (dev dump).
+- Every buy and every sell: trader wallet, SOL size, token amount, timestamp.
+- Buy/sell counts, buy/sell volume, net flow, trade velocity over time.
+- Largest single buy, average + median buy size, buy-size distribution.
+- Unique buyers, unique sellers, unique traders, buyer/seller ratio.
+
+**Derived signals** (see [signals.js](../../workers/agent-sniper/intel/signals.js))
+- **Bundle score** — burst of near-identical buys clustered at launch from many distinct wallets = coordinated bundle, not organic demand.
+- **Snipe ratio** — fraction of buy volume that landed in the first few seconds.
+- **Organic score** — buyer diversity + arrival-time spread (entropy) + healthy size distribution + dev not dumping.
+- **Coordination score** — the inverse: clustering + identical amounts + (when available) a shared funding wallet.
+- **Concentration** — top-wallet / top-5 / top-10 share of net buying (whale capture).
+- **Fresh-wallet ratio** & **bubblemap connectivity** — when wallet-graph enrichment is available (RPC funder lookup), the share of top buyers funded from a common source. Honest by design: left `null`, never faked, when enrichment is off.
+- **Risk flags** — `bundle_launch`, `dev_dumped`, `single_whale`, `low_diversity`, `fresh_wallet_swarm`, `sell_pressure`.
+- **Quality score (0–100)** — a composite the agent reads at a glance.
+
+**Classification** (see [classify.js](../../workers/agent-sniper/intel/classify.js))
+- Category: `meme | tech | ai | culture | community | political | news | animal | celebrity | utility | unknown`.
+- Is it a news-story meme? Tags, narrative, a one-line thesis, and a confidence.
+- LLM-driven (free-first via `llmComplete`), with a deterministic keyword classifier as an always-on fallback so it **never fails** (Rule 9).
+
+---
+
+## How it learns
+
+Watching isn't enough — the engine closes the loop:
+
+1. **Outcome labeling** (`pump_coin_outcomes`) — minutes/hours later, each watched coin is revisited: did it graduate? what ATH multiple? did it rug (price → ~0)? This is the ground truth.
+2. **Weight learning** ([learn.js](../../workers/agent-sniper/intel/learn.js)) — periodically correlate launch-time signals with outcomes and compute per-signal predictive weights, stored in `pump_intel_weights`.
+3. **The scorer reads the weights** — so the sniper's judgment improves as the dataset grows. A signal that historically preceded rugs gets down-weighted automatically; one that preceded graduations gets up-weighted. The platform gets smarter the more coins it watches.
+
+---
+
+## How agents read it (fast)
+
+- **In-memory cache** in the worker ([store.js](../../workers/agent-sniper/intel/store.js)) — the sniper reads intel for a mint with zero I/O on the hot path.
+- **`GET /api/pump/coin-intel?mint=…`** — any agent (user-built, MCP, external) reads the full intel record. `GET /api/pump/coin-intel` returns the live radar feed.
+- **Scorer integration** — `scoreMint(mint, strat, intel)` applies intel vetoes (e.g. confirmed bundle launch) and weighted soft-scoring before a buy.
+
+---
+
+## Data model
+
+| Table | Holds |
+|---|---|
+| `pump_coin_intel` | One row per observed coin: raw aggregates, derived signals (JSONB), classification, quality score. |
+| `pump_coin_wallets` | Per-coin per-wallet aggregate: buy/sell SOL, trade count, net, first/last seen — the "who traded it" ledger and the basis for concentration + bubblemap. |
+| `pump_coin_outcomes` | Ground-truth outcome per coin (graduated / ath_mult / rugged), labeled after the fact. |
+| `pump_intel_weights` | Learned per-signal weights the scorer reads. |
+
+All SOL stored as lamports (`numeric(40,0)`) to match the rest of the sniper schema.
+
+---
+
+## Honesty rules baked in (Rule 1 & 9)
+
+- No metric is ever invented. Wallet-graph/fresh-wallet signals are `null` when enrichment is off — never a placeholder number.
+- Classification always returns *something* (heuristic fallback) so the pipeline can't stall on an LLM outage.
+- Every number traces to a real on-chain trade we observed, persisted in `pump_coin_wallets`.
+
+---
+
+## Build order
+
+1. ✅ Schema, signals, classifier, store, watcher, learning, scorer wiring, serving API, tests. *(foundation)*
+2. Wallet-graph enrichment via RPC funder lookup (turns `bubblemap connectivity` from `null` → live).
+3. The `/radar` UI — live coin intelligence feed.
+4. Backfill outcome labeler cron + first learned-weights pass once enough coins are observed.
+5. MCP tool `pump_coin_intel` so external agents read the same intelligence.
diff --git a/docs/roadmap/pumpfun-trading.md b/docs/roadmap/pumpfun-trading.md
index f2b2c0626..524364ba6 100644
--- a/docs/roadmap/pumpfun-trading.md
+++ b/docs/roadmap/pumpfun-trading.md
@@ -746,3 +746,281 @@ Always explain WHY a step is safe (non-custodial, hard caps, they sign). Answer
in 1-3 short sentences. If they ask for guarantees, say plainly there are none and
point to the verified track record + skin-in-the-game as the honest signal.
```
+
+---
+
+## 15. The Coin Intelligence Engine (the brain)
+
+> This is the system that makes every agent smart. It watches *every* coin that
+> launches on pump.fun, records *every* metric, derives deep signals (bundle vs
+> organic, wallet clusters, dev behavior, smart-money presence), classifies the
+> coin (meme / tech / news-meme / culture / community), and labels outcomes so it
+> **learns which signals actually predict winners over time**. Agents read a
+> single precomputed snapshot per coin in one fast call and act.
+
+The principle: **cheap signals on everything, expensive signals on candidates.**
+~10–20k coins launch on pump.fun per day; we cannot trace a funding graph or run
+an LLM on all of them. So we compute free/cheap signals on the full firehose, and
+escalate to expensive analysis (RPC funding-graph, bubblemaps, LLM classification)
+only for coins that clear a first filter or that an agent/user is actively
+watching. This keeps it fast and affordable while still "recording every coin."
+
+### 15.1 Pipeline (4 stages)
+
+```
+ ┌─ STAGE 1: INGEST (firehose, every coin) ──────────────────────────────┐
+ │ PumpPortal subscribeNewToken → pf_coins row (instant, cheap) │
+ │ Dynamic subscribeTokenTrade → pf_trades for coins in their first │
+ │ ~30–60 min "decision window" (rolling set, capped) │
+ │ subscribeMigration → graduation outcome label │
+ └───────────────────────────────────────────────────────────────────────┘
+ │ first-filter passes (or agent is watching)
+ ▼
+ ┌─ STAGE 2: ENRICH (candidates only, expensive) ────────────────────────┐
+ │ Helius RPC: funding-graph trace → bundle + cluster detection │
+ │ Bubblemaps API (or our own graph): wallet connectivity % │
+ │ pump.fun frontend-api-v3: holders, creator history, reply_count │
+ │ LLM (free-first): classify category + theme + news-meme match │
+ │ pf_wallets lookup: smart-money / sniper / insider / bundler presence │
+ └───────────────────────────────────────────────────────────────────────┘
+ │
+ ▼
+ ┌─ STAGE 3: SCORE + SNAPSHOT (precompute the agent-readable view) ───────┐
+ │ Composite intel_score from signals weighted by historical predictive │
+ │ power (pf_signal_stats). Write snapshot → Redis (sub-50ms reads) + DB. │
+ └───────────────────────────────────────────────────────────────────────┘
+ │
+ ▼
+ ┌─ STAGE 4: LEARN (outcome labeler, closes the loop) ───────────────────┐
+ │ Cron: for each coin past N hours, record ATH mcap, ATH multiple, │
+ │ graduated?, rugged?, time-to-rug, max-drawdown. Update │
+ │ pf_signal_stats (conditional win-rates per signal bucket). Weights │
+ │ feed back into Stage 3. Optionally retrain a model offline. │
+ └───────────────────────────────────────────────────────────────────────┘
+```
+
+### 15.2 Data model (new tables)
+
+All on Neon Postgres (`api/_lib/db.js`), hot snapshots cached in Upstash Redis.
+High-volume `pf_trades` gets time-partitioning + a TTL/rollup so it doesn't grow
+unbounded — we keep raw trades for the decision window + recent history, and roll
+older data into per-coin aggregates in `pf_coin_wallets`.
+
+- **`pf_coins`** — one row per coin ever seen. Identity (mint, name, symbol,
+ creator, uri, socials, created_at, created_slot); launch metrics (dev_initial_buy_sol,
+ supply_bought_at_launch_pct); classification (category, theme_tags[],
+ is_news_meme, news_event, classify_confidence); verdicts (bundle_verdict,
+ bundle_pct, organic_score, cluster_pct, smart_money_count, sniper_count); state
+ (curve_pct, mcap_usd, holders, graduated, rugged); outcomes (ath_mcap_usd,
+ ath_multiple, graduated_at, rug_detected_at, max_drawdown_pct);
+ intel_score; snapshot_jsonb; updated_at.
+- **`pf_trades`** — every buy/sell on watched coins. (mint, wallet, side, sol,
+ tokens, price, slot, signature, ts). Partitioned by day; replay-guarded on
+ signature. Source: PumpPortal per-mint trades + Helius webhook.
+- **`pf_wallets`** — wallet reputation, the crown jewel. (address, first_seen,
+ trades_count, distinct_coins, est_realized_pnl_sol, win_rate,
+ graduated_buys, rug_buys, avg_hold_seconds, labels[] =
+ {smart_money|sniper|insider|bundler|bot|fresh|dev|whale}, cluster_id, funder,
+ score). Rebuilt incrementally as trades land.
+- **`pf_coin_wallets`** — per-coin per-wallet rollup. (mint, wallet, net_tokens,
+ bought_sol, sold_sol, first_buy_slot, is_dev, is_first_slot, is_bundle_member,
+ wallet_label). The compact form agents read for "who's in this coin."
+- **`pf_clusters`** — wallet clusters (bubblemaps-style). (cluster_id, mint,
+ member_wallets[], common_funder, supply_pct, kind = {bundle|insider|organic}).
+- **`pf_signal_stats`** — the learning memory. (signal_key, bucket, sample_size,
+ graduated_rate, rug_rate, median_ath_multiple, baseline_lift, updated_at). This
+ is what lets us say "coins matching this profile graduate 23% of the time vs a
+ 4% baseline" — explainable, honest, and immediately useful before any ML.
+
+### 15.3 The signals we record & derive (every metric, organized)
+
+**Creator / dev signals**
+- prior launches, prior graduations, prior rugs (serial-rugger flag)
+- dev initial buy size (SOL + % of supply)
+- dev current holding %, and **did the dev sell** (and when)
+- dev wallet age + funding source
+
+**Launch-shape signals** (first 1–5 min — the decision window)
+- # buys in first slot / first 10 slots / first minute
+- unique buyer wallets vs total buys (concentration)
+- distribution of buy sizes (a few whales vs many small = different stories)
+- buy/sell ratio early, first-sell timing
+- initial market cap + velocity of mcap growth
+
+**Bundle vs organic** (the question you asked directly)
+- **Bundle detector:** clustered same-slot buys at launch + common funding source
+ + similar amounts → `bundle_pct` (supply captured by the bundle),
+ `bundle_wallet_count`, `bundle_verdict` ∈ {clean | light | heavy}.
+- **Organic score:** many distinct funders + varied buy sizes + aged (not fresh)
+ wallets + real social engagement (reply_count, working socials) → high.
+ Inverse-correlated with bundle. This is the single number a degen wants:
+ "is this real or is it a setup."
+
+**Holder / cluster signals (bubblemaps-style)**
+- top-10 holder concentration %, dev %, cluster supply %
+- connectivity graph: wallets sharing a common funder = one cluster (we build the
+ graph from Helius transfer traces; optionally cross-check Bubblemaps API)
+- # of distinct clusters vs # of holders (more clusters = more organic)
+
+**Wallet-quality signals** (from `pf_wallets` reputation)
+- **smart-money present:** any buyers are known winners → strong positive
+- **sniper present:** wallets that bought in the first slot / bought every recent launch
+- **insider present:** wallets funded right before launch from the dev's funder
+- **bot/fresh ratio:** brand-new wallets with no history
+
+**Classification signals** (LLM + heuristics over name/symbol/desc/image/socials)
+- **category:** meme | tech | AI | animal | political | culture | community |
+ news-meme | celebrity | utility | derivative/copycat
+- **is_news_meme** + the matched news event (check name/desc against trending
+ topics from a news/X-trends source) — "is this riding a news story?"
+- theme tags, copycat detection (is this the 14th "$SAMENAME" today?)
+- virality_potential (heuristic: catchiness + timeliness + social presence)
+
+**Momentum / live signals**
+- trade velocity & acceleration, buy pressure, holder growth rate
+- curve % to graduation + rate of approach
+- net flow (buy SOL − sell SOL) over rolling windows
+
+**Risk flags**
+- mint authority / freeze authority not revoked
+- honeypot / sell-tax (simulate a sell)
+- LP not burned (post-graduation)
+- dev sold, cluster dumping
+
+### 15.4 The learning loop (how it "learns from watching")
+
+1. **Label outcomes.** A cron walks coins older than N hours and records the
+ truth: did it graduate? peak mcap / ATH multiple? did it rug (and how fast)?
+ max drawdown? → `pf_coins` outcome columns.
+2. **Update signal stats.** For each signal bucket (e.g. `bundle_verdict=clean`,
+ `smart_money_count>=1`, `category=news-meme`), recompute graduated_rate,
+ rug_rate, median ATH multiple, and **lift over baseline** → `pf_signal_stats`.
+ This is Naive-Bayes-honest and works from day one: no black box, fully
+ explainable to users ("this profile historically graduates 6× the baseline").
+3. **Reweight the composite score.** Stage-3 `intel_score` weights each live
+ signal by its measured predictive power. As data accrues, weights self-tune.
+4. **(Later) Train a real model.** Once enough labeled history exists, train a
+ gradient-boosted model offline on the full signal vector → outcome, export
+ weights, load them in Stage 3. The statistical layer remains the explainable
+ fallback and the sanity check on the model.
+
+Honest note: this is a *probabilistic edge*, not a crystal ball. The pitch to
+users is exactly your framing — **small buys, lose sometimes, win more than you
+lose because the agent reads a hundred signals in the time you read one.** We
+never promise outcomes; we show the verified hit-rate.
+
+### 15.5 The fast agent read (the payoff)
+
+Agents must read all of this **as fast as a coin appears**. Two access modes:
+
+- **Pull:** `GET /api/pump/intel?mint=<mint>` and MCP tool **`get_coin_intel`** —
+ returns the precomputed snapshot from Redis (sub-50ms), with on-demand compute
+ fallback if the coin is cold. One call gives the agent everything in §15.3 plus
+ the composite score and a plain-language summary.
+- **Push:** an SSE/WS **intel feed** — every new coin emits its snapshot the
+ instant Stage 1+2 complete, so a sniper agent reacts within the decision window
+ without polling. Builds on the existing PumpPortal feed + `trades-stream.js`.
+
+Snapshot shape (`get_coin_intel` returns):
+```json
+{
+ "mint": "<mint>", "ticker": "$TICKER", "age_seconds": 47,
+ "intel_score": 0-100, "verdict": "strong|watch|avoid",
+ "classification": { "category": "news-meme", "news_event": "<event>",
+ "theme_tags": ["..."], "is_copycat": false, "confidence": 0.82 },
+ "launch": { "dev_initial_buy_sol": 2.1, "dev_holding_pct": 4.2, "dev_sold": false,
+ "first_minute_unique_buyers": 38, "buy_sell_ratio": 6.4 },
+ "bundle": { "verdict": "clean", "bundle_pct": 3.1, "bundle_wallets": 2 },
+ "organic_score": 0-100,
+ "clusters": { "count": 31, "top_cluster_supply_pct": 6.0, "cluster_pct_total": 14.2 },
+ "wallets": { "smart_money": 2, "snipers": 5, "insiders": 0, "fresh_ratio": 0.41,
+ "notable": [ { "addr": "abc..", "label": "smart_money", "win_rate": 0.61 } ] },
+ "holders": { "count": 210, "top10_pct": 28.0 },
+ "momentum": { "curve_pct": 64, "velocity": "rising", "net_flow_sol_5m": 12.3 },
+ "risk_flags": ["mint_authority_live"],
+ "history": { "profile_graduated_rate": 0.23, "baseline": 0.04, "lift": 5.7x,
+ "sample_size": 1840 },
+ "summary": "News-meme, clean launch (3% bundle), 2 smart-money buyers, 38 unique buyers in first minute. Profile historically graduates 5.7× baseline. Mint authority not yet revoked.",
+ "computed_at": "<ts>"
+}
+```
+
+The agent's trade prompt (§10) gets one new tool — `get_coin_intel` — and the
+checklist collapses: instead of 6 separate reads, the agent gets the whole
+picture in one call, plus the *historical* odds for this exact profile. That's
+the "read it just as fast and act" you asked for.
+
+### 15.6 Real data sources (no mocks — honest about cost)
+
+- **PumpPortal WS** (free, already wired): new tokens, per-mint trades,
+ migrations. Caveat: no global trade firehose — we dynamically subscribe to
+ trades for coins in their decision window (rolling, capped set). For full
+ coverage at scale, the paid PumpPortal/Bitquery/Shyft pump.fun streams are the
+ upgrade path.
+- **Helius** (already wired via webhook): program-level txn monitoring, RPC for
+ funding-graph traces (bundle/cluster detection), holder reads. Rate-limited —
+ reserve for candidates.
+- **Bubblemaps API** (optional): wallet-connectivity clusters. We can build our
+ own funding graph from Helius first and add Bubblemaps as a cross-check /
+ premium enrichment.
+- **pump.fun frontend-api-v3** (already used): coin + creator-coins + reply_count.
+- **LLM via `llmComplete`** (free-first per policy): classification. Cheap models,
+ cached by mint, candidates only.
+- **News/X-trends source**: for `is_news_meme` matching (a trends API or X
+ search). Real integration, candidates only.
+
+### 15.7 Build order for the brain (slots into §8)
+
+1. **Schema + Stage 1 ingest.** Migration for `pf_coins` / `pf_trades` /
+ `pf_wallets` / `pf_coin_wallets` / `pf_clusters` / `pf_signal_stats`. Extend the
+ existing feed worker to write `pf_coins` on every mint and dynamically
+ subscribe to trades for the decision window. *Ships value immediately: a
+ complete recorded history of every coin.*
+2. **Wallet reputation (`pf_wallets`).** Roll up trades into per-wallet stats +
+ labels. Unlocks the highest-signal feature: "smart money just bought."
+3. **Bundle + cluster detector (Stage 2).** Helius funding-graph on candidates →
+ bundle_verdict, organic_score, clusters.
+4. **Classifier (Stage 2).** LLM category + news-meme on candidates.
+5. **Snapshot + `get_coin_intel` + intel SSE (Stage 3).** The fast agent read.
+6. **Outcome labeler + `pf_signal_stats` (Stage 4).** The learning loop. Now the
+ score self-improves and we can show historical hit-rates.
+7. **Wire into the scorer + agent prompts.** Replace the crude additive score in
+ `workers/agent-sniper/scorer.js` with the intel_score, and add `get_coin_intel`
+ to the trade prompt.
+
+### 15.8 Two new prompts for the brain
+
+**Coin Classifier** (Stage-2 LLM, one coin → taxonomy)
+```
+You classify a freshly-launched Solana memecoin from its metadata. You output a
+strict taxonomy verdict, nothing else. You are given: name, symbol, description,
+image caption, and any socials/links.
+
+Return JSON:
+{
+ "category": "meme|tech|ai|animal|political|culture|community|news-meme|celebrity|utility|copycat",
+ "is_news_meme": bool, "news_event": "<the real event it references, or null>",
+ "theme_tags": ["..."], // short, lowercase, e.g. ["dog","election","layer2"]
+ "is_copycat": bool, // does this ride an existing coin's name/brand?
+ "virality_potential": "low|med|high",
+ "rationale": "one sentence",
+ "confidence": 0.0-1.0
+}
+Rules: judge ONLY from the supplied metadata — do not invent backstory. If a
+"news_event" isn't clearly referenced, set it null and is_news_meme=false. Never
+reference any token other than the one supplied or $THREE. Lower confidence when
+the metadata is thin or ambiguous; do not guess to seem decisive.
+```
+
+**Intel Analyst** (turns the raw snapshot into the agent's plain-language read)
+```
+You convert a coin-intel snapshot (JSON) into a 2-3 sentence read a trader can
+act on in seconds. Lead with the verdict, then the 2-3 signals that most drive
+it, then the single biggest risk. Quote real numbers from the snapshot only.
+
+Never soften a red flag. If bundle_verdict is heavy, dev sold, or mint authority
+is live, say so first. If smart-money or a clean organic launch is the story,
+say that. End with the historical odds for this profile if present
+("this profile graduated 5.7× baseline over 1,840 samples"). No hype, no
+promises, no token other than this one or $THREE.
+```
diff --git a/pages/launch.html b/pages/launch.html
new file mode 100644
index 000000000..298ff6e40
--- /dev/null
+++ b/pages/launch.html
@@ -0,0 +1,150 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Launch a Coin — mint a token for your 3D agent · three.ws</title>
+ <meta
+ name="description"
+ content="Launch a coin for your 3D AI agent in one flow. Pick an agent, set the name, symbol, and image, then mint on pump.fun straight from your wallet — with an optional three.ws-branded vanity mint."
+ />
+ <meta name="robots" content="index, follow" />
+ <link rel="canonical" href="https://three.ws/launch" />
+
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:title" content="Launch a Coin — mint a token for your 3D agent" />
+ <meta
+ property="og:description"
+ content="Pick an agent, set name + symbol + image, and mint a coin on pump.fun straight from your wallet."
+ />
+ <meta property="og:url" content="https://three.ws/launch" />
+ <meta property="og:image" content="https://three.ws/og-image.png" />
+ <meta property="og:image:width" content="1200" />
+ <meta property="og:image:height" content="630" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <meta name="twitter:title" content="Launch a Coin — mint a token for your 3D agent" />
+ <meta
+ name="twitter:description"
+ content="Pick an agent, set name + symbol + image, and mint a coin on pump.fun straight from your wallet."
+ />
+ <meta name="twitter:image" content="https://three.ws/og-image.png" />
+
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />
+ <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />
+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
+ <link rel="manifest" href="/site.webmanifest" />
+ <link rel="stylesheet" href="/style.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <link rel="stylesheet" href="/mobile.css" />
+
+ <style>
+ .lc-page {
+ min-height: 100vh;
+ display: flex;
+ flex-direction: column;
+ }
+ .lc-main {
+ flex: 1;
+ width: 100%;
+ max-width: 880px;
+ margin: 0 auto;
+ padding: 1.5rem 1rem 4rem;
+ box-sizing: border-box;
+ }
+ .lc-breadcrumb {
+ font-size: 0.78rem;
+ color: rgba(255, 255, 255, 0.4);
+ margin-bottom: 1.4rem;
+ display: flex;
+ gap: 0.45rem;
+ align-items: center;
+ flex-wrap: wrap;
+ }
+ .lc-breadcrumb a {
+ color: rgba(255, 255, 255, 0.55);
+ text-decoration: none;
+ }
+ .lc-breadcrumb a:hover {
+ color: #a4f0bc;
+ }
+ .lc-hero {
+ text-align: center;
+ margin-bottom: 1.8rem;
+ }
+ .lc-hero h1 {
+ font-size: clamp(1.7rem, 4.5vw, 2.5rem);
+ font-weight: 700;
+ letter-spacing: -0.02em;
+ margin: 0 0 0.6rem;
+ background: linear-gradient(180deg, #fff, rgba(255, 255, 255, 0.62));
+ -webkit-background-clip: text;
+ background-clip: text;
+ -webkit-text-fill-color: transparent;
+ }
+ .lc-hero p {
+ font-size: clamp(0.92rem, 2vw, 1.05rem);
+ color: rgba(255, 255, 255, 0.55);
+ line-height: 1.6;
+ max-width: 38ch;
+ margin: 0 auto;
+ }
+ .lc-hero .lc-pill {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.4rem;
+ font-size: 0.72rem;
+ font-weight: 600;
+ letter-spacing: 0.04em;
+ color: #c8f0d8;
+ background: rgba(164, 240, 188, 0.08);
+ border: 1px solid rgba(164, 240, 188, 0.22);
+ border-radius: 999px;
+ padding: 0.3rem 0.7rem;
+ margin-bottom: 1rem;
+ }
+ .lc-pill-dot {
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: #a4f0bc;
+ box-shadow: 0 0 6px rgba(164, 240, 188, 0.6);
+ }
+ </style>
+ </head>
+ <body class="lc-page">
+ <header><div id="nav-container"></div></header>
+ <script src="/nav.js"></script>
+
+ <main class="lc-main" id="main-content">
+ <nav class="lc-breadcrumb" aria-label="Breadcrumb">
+ <a href="/">three.ws</a>
+ <span aria-hidden="true">/</span>
+ <a href="/launches">Launches</a>
+ <span aria-hidden="true">/</span>
+ <span>Launch a Coin</span>
+ </nav>
+
+ <section class="lc-hero">
+ <span class="lc-pill"><span class="lc-pill-dot"></span> Powered by pump.fun</span>
+ <h1>Launch a Coin</h1>
+ <p>Pick your agent, set the name, symbol, and image — then mint on-chain straight from your wallet.</p>
+ </section>
+
+ <div id="launch-root"></div>
+ </main>
+
+ <div id="footer-container"></div>
+ <script src="/footer.js"></script>
+
+ <script type="module">
+ import { mountLaunchCoin } from '/launch/launch.js';
+ mountLaunchCoin(document.getElementById('launch-root'));
+ </script>
+ <script src="/brand.js" defer></script>
+ </body>
+</html>
diff --git a/public/changelog.json b/public/changelog.json
index ea6621d0e..424a4a68f 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,11 +1,21 @@
{
- "generated_at": "2026-06-15T21:48:52.845Z",
+ "generated_at": "2026-06-15T22:01:36.793Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
"url": "https://three.ws"
},
"entries": [
+ {
+ "date": "2026-06-15",
+ "type": "launch",
+ "title": "Launch a Coin",
+ "summary": "Mint a coin for your 3D AI agent in one flow — pick an agent, set the name, symbol, and image, then launch on pump.fun straight from your wallet with an optional three.ws-branded vanity mint.",
+ "link": "/launch",
+ "tags": [
+ "launch"
+ ]
+ },
{
"date": "2026-06-15",
"type": "launch",
@@ -193,7 +203,7 @@
"date": "2026-06-15",
"type": "update",
"title": "More uploaded avatars can dance",
- "summary": "The built-in animation library can now drive avatars built on CharacterStudio and Unreal Engine skeletons, not just Mixamo/Ready-rig ones. Previously a CharacterStudio or Fortnite-style rig would load but stand frozen because the animation system couldn't match its bone names; now those bones map automatically, so the full set of dances, poses, and idle motion plays on them everywhere avatars appear — the club, the walk view, AR, and the studio.",
+ "summary": "The built-in animation library can now drive avatars built on more skeleton types — including game-engine and other creator-tool rigs — not just the common ones. Previously some uploaded avatars would load but stand frozen because the animation system couldn't match their bone names; now those bones map automatically, so the full set of dances, poses, and idle motion plays on them everywhere avatars appear — the club, the walk view, AR, and the studio.",
"link": "/club",
"tags": [
"improvement"
@@ -439,7 +449,7 @@
"date": "2026-06-15",
"type": "update",
"title": "Three distinct dancers, now waiting at their poles",
- "summary": "The Pole Club stage no longer sits empty between tips. Three dancers now stand at their own poles, lit and facing the crowd, the moment you arrive — each a different 3D avatar pulled from the gallery (still tinted to her pole's neon color) instead of copies of one model. Tip a pole and that dancer steps onto it and runs her routine, then returns to her stance at the pole. No tip, no dance — same rule, just a stage that looks alive from the first second. Behind the scenes the animation engine now retargets onto CharacterStudio and Unreal-mannequin rigs too, so far more uploaded avatars can actually dance.",
+ "summary": "The Pole Club stage no longer sits empty between tips. Three dancers now stand at their own poles, lit and facing the crowd, the moment you arrive — each a different 3D avatar pulled from the gallery (still tinted to her pole's neon color) instead of copies of one model, and every dancer is auto-scaled to the same height so the lineup reads as a set. Tip a pole and that dancer steps onto it and runs her routine, then returns to her stance at the pole. No tip, no dance — same rule, just a stage that looks alive from the first second. Behind the scenes the animation engine now retargets onto more rig types, so far more uploaded avatars can actually dance.",
"link": "/club",
"tags": [
"improvement"
diff --git a/public/changelog.xml b/public/changelog.xml
index 949b8cfb2..aeca51ea3 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -6,6 +6,14 @@
<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/>
<description>What's new on three.ws — features, improvements, and releases, newest first.</description>
<language>en</language>
+ <item>
+ <title>Launch a Coin</title>
+ <link>https://three.ws/launch</link>
+ <guid isPermaLink="false">2026-06-15:Launch a Coin</guid>
+ <pubDate>Mon, 15 Jun 2026 12:00:00 GMT</pubDate>
+ <category>launch</category>
+ <description>Mint a coin for your 3D AI agent in one flow — pick an agent, set the name, symbol, and image, then launch on pump.fun straight from your wallet with an optional three.ws-branded vanity mint.</description>
+ </item>
<item>
<title>Sniper Arena — autonomous AI agents trading live</title>
<link>https://three.ws/play/arena</link>
@@ -156,7 +164,7 @@
<guid isPermaLink="false">2026-06-15:More uploaded avatars can dance</guid>
<pubDate>Mon, 15 Jun 2026 12:00:00 GMT</pubDate>
<category>improvement</category>
- <description>The built-in animation library can now drive avatars built on CharacterStudio and Unreal Engine skeletons, not just Mixamo/Ready-rig ones. Previously a CharacterStudio or Fortnite-style rig would load but stand frozen because the animation system couldn't match its bone names; now those bones map automatically, so the full set of dances, poses, and idle motion plays on them everywhere avatars appear — the club, the walk view, AR, and the studio.</description>
+ <description>The built-in animation library can now drive avatars built on more skeleton types — including game-engine and other creator-tool rigs — not just the common ones. Previously some uploaded avatars would load but stand frozen because the animation system couldn't match their bone names; now those bones map automatically, so the full set of dances, poses, and idle motion plays on them everywhere avatars appear — the club, the walk view, AR, and the studio.</description>
</item>
<item>
<title>On-chain model validation for Solana agents</title>
@@ -348,7 +356,7 @@
<guid isPermaLink="false">2026-06-15:Three distinct dancers, now waiting at their poles</guid>
<pubDate>Mon, 15 Jun 2026 12:00:00 GMT</pubDate>
<category>improvement</category>
- <description>The Pole Club stage no longer sits empty between tips. Three dancers now stand at their own poles, lit and facing the crowd, the moment you arrive — each a different 3D avatar pulled from the gallery (still tinted to her pole's neon color) instead of copies of one model. Tip a pole and that dancer steps onto it and runs her routine, then returns to her stance at the pole. No tip, no dance — same rule, just a stage that looks alive from the first second. Behind the scenes the animation engine now retargets onto CharacterStudio and Unreal-mannequin rigs too, so far more uploaded avatars can actually dance.</description>
+ <description>The Pole Club stage no longer sits empty between tips. Three dancers now stand at their own poles, lit and facing the crowd, the moment you arrive — each a different 3D avatar pulled from the gallery (still tinted to her pole's neon color) instead of copies of one model, and every dancer is auto-scaled to the same height so the lineup reads as a set. Tip a pole and that dancer steps onto it and runs her routine, then returns to her stance at the pole. No tip, no dance — same rule, just a stage that looks alive from the first second. Behind the scenes the animation engine now retargets onto more rig types, so far more uploaded avatars can actually dance.</description>
</item>
<item>
<title>three.ws can now register itself on-chain on Solana</title>
diff --git a/public/features.json b/public/features.json
index 2cbb2290d..8253f8ddd 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-15T21:48:52.829Z",
+ "generated_at": "2026-06-15T22:01:36.771Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
@@ -506,6 +506,16 @@
"title": "Crypto",
"description": "On-chain features: pay-per-call, token launches, vanity wallets.",
"pages": [
+ {
+ "path": "/launch",
+ "title": "Launch a Coin",
+ "description": "Mint a coin for your 3D AI agent in one flow — pick an agent, set the name, symbol, and image, then launch on pump.fun straight from your wallet with an optional three.ws-branded vanity mint.",
+ "added": "2026-06-15",
+ "auth": null,
+ "indexable": true,
+ "tags": [],
+ "showcase": false
+ },
{
"path": "/launches",
"title": "Agent Launches",
diff --git a/public/launch/launch.js b/public/launch/launch.js
new file mode 100644
index 000000000..f9b000918
--- /dev/null
+++ b/public/launch/launch.js
@@ -0,0 +1,204 @@
+// Standalone "Launch a Coin" experience for /launch.
+//
+// Reuses the real, production launch flow from /studio/launch-panel.js
+// (metadata upload → on-chain prep → wallet signing → confirmation polling,
+// vanity-mint grinding, agent-wallet or connected-wallet funding). This page
+// only adds the surrounding chrome: an agent picker that decides which avatar
+// the coin is minted for, plus loading / empty / signed-out states. The panel
+// owns everything else.
+//
+// A coin on three.ws is always launched *for* an agent, so the panel refuses
+// to mint without a real (non-demo) avatar selected. When the visitor is
+// signed out or has no avatars, getAvatar() returns null and the panel renders
+// its own guided onboarding (which links to the agent builder).
+
+import { mountLaunchPanel } from '/studio/launch-panel.js';
+
+const PICKER_CSS = `
+.lc-shell{display:grid;grid-template-columns:minmax(0,300px) minmax(0,440px);gap:1.5rem;
+ align-items:start;justify-content:center;max-width:780px;margin:0 auto;padding:1rem}
+@media (max-width:760px){.lc-shell{grid-template-columns:1fr;gap:1.1rem;padding:.5rem}}
+
+.lc-col-h{font-size:.72rem;font-weight:600;letter-spacing:.06em;text-transform:uppercase;
+ color:rgba(255,255,255,.4);margin:0 0 .65rem}
+.lc-pick{display:flex;flex-direction:column;gap:.4rem;position:sticky;top:1rem}
+@media (max-width:760px){.lc-pick{position:static}}
+
+.lc-card{display:flex;align-items:center;gap:.7rem;padding:.55rem .65rem;border-radius:11px;
+ cursor:pointer;text-align:left;width:100%;background:rgba(255,255,255,.025);
+ border:1px solid rgba(255,255,255,.07);color:#fff;transition:all .15s;font:inherit}
+.lc-card:hover:not(.on){background:rgba(255,255,255,.05);border-color:rgba(255,255,255,.14)}
+.lc-card.on{background:rgba(164,240,188,.08);border-color:rgba(164,240,188,.34);
+ box-shadow:0 0 0 1px rgba(164,240,188,.12)}
+.lc-card:focus-visible{outline:2px solid rgba(164,240,188,.6);outline-offset:2px}
+.lc-thumb{width:42px;height:42px;border-radius:9px;object-fit:cover;flex-shrink:0;
+ background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.08)}
+.lc-thumb-ph{width:42px;height:42px;border-radius:9px;flex-shrink:0;display:flex;
+ align-items:center;justify-content:center;font-size:1.15rem;font-weight:700;
+ color:rgba(164,240,188,.7);background:rgba(164,240,188,.08);border:1px solid rgba(164,240,188,.16)}
+.lc-meta{min-width:0;flex:1}
+.lc-name{font-size:.86rem;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
+.lc-sub{font-size:.68rem;color:rgba(255,255,255,.4);margin-top:.12rem;white-space:nowrap;
+ overflow:hidden;text-overflow:ellipsis}
+.lc-coined{flex-shrink:0;font-size:.6rem;font-weight:600;letter-spacing:.04em;color:#a4f0bc;
+ background:rgba(164,240,188,.1);border:1px solid rgba(164,240,188,.22);border-radius:6px;
+ padding:.18rem .4rem}
+
+.lc-skel{height:56px;border-radius:11px;background:linear-gradient(100deg,
+ rgba(255,255,255,.03) 30%,rgba(255,255,255,.07) 50%,rgba(255,255,255,.03) 70%);
+ background-size:200% 100%;animation:lc-shimmer 1.3s linear infinite}
+@keyframes lc-shimmer{0%{background-position:200% 0}100%{background-position:-200% 0}}
+
+.lc-pick-cta{margin-top:.35rem;display:block;text-align:center;padding:.55rem;border-radius:9px;
+ font-size:.78rem;text-decoration:none;color:rgba(255,255,255,.5);background:rgba(255,255,255,.025);
+ border:1px dashed rgba(255,255,255,.12);transition:all .15s}
+.lc-pick-cta:hover{color:rgba(164,240,188,.85);border-color:rgba(164,240,188,.3);
+ background:rgba(164,240,188,.05)}
+
+.lc-signin{font-size:.74rem;color:rgba(255,255,255,.45);line-height:1.55;padding:.6rem .7rem;
+ border-radius:9px;background:rgba(255,255,255,.025);border:1px solid rgba(255,255,255,.07)}
+.lc-signin a{color:rgba(164,240,188,.8);text-decoration:none}
+.lc-signin a:hover{color:#a4f0bc}
+`;
+
+const esc = (s) =>
+ String(s ?? '').replace(/[&<>"']/g, (c) =>
+ ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c],
+ );
+
+const state = { user: null, avatars: [], avatarId: null, loading: true };
+let launchPanel = null;
+let pickerEl = null;
+
+function currentAvatar() {
+ return state.avatars.find((a) => a.id === state.avatarId) || null;
+}
+
+async function fetchMe() {
+ try {
+ const res = await fetch('/api/auth/me', { credentials: 'include' });
+ if (!res.ok) return null;
+ const { user } = await res.json();
+ return user || null;
+ } catch {
+ return null;
+ }
+}
+
+async function fetchAvatars() {
+ try {
+ const res = await fetch('/api/avatars?limit=100', { credentials: 'include' });
+ if (!res.ok) return [];
+ const { avatars = [] } = await res.json();
+ return avatars;
+ } catch {
+ return [];
+ }
+}
+
+function renderPicker() {
+ if (!pickerEl) return;
+
+ if (state.loading) {
+ pickerEl.innerHTML =
+ '<p class="lc-col-h">Choose your agent</p>' +
+ Array(3).fill('<div class="lc-skel"></div>').join('');
+ return;
+ }
+
+ // Signed out, or signed in with no avatars → let the panel's guided state
+ // lead; the picker just nudges the next concrete action.
+ if (!state.avatars.length) {
+ pickerEl.innerHTML =
+ '<p class="lc-col-h">Choose your agent</p>' +
+ (state.user
+ ? '<a class="lc-pick-cta" href="/create-agent">+ Create your first agent</a>'
+ : '<div class="lc-signin">A coin launches for one of your agents. ' +
+ '<a href="/login?next=/launch">Sign in</a> to pick an agent, or ' +
+ '<a href="/create-agent">create one</a> first.</div>');
+ return;
+ }
+
+ const cards = state.avatars
+ .map((a) => {
+ const on = a.id === state.avatarId;
+ const thumb = a.thumbnail_url
+ ? `<img class="lc-thumb" src="${esc(a.thumbnail_url)}" alt="" loading="lazy" />`
+ : `<span class="lc-thumb-ph" aria-hidden="true">${esc((a.name || 'A').trim().charAt(0).toUpperCase())}</span>`;
+ const sub = a.slug ? `@${esc(a.slug)}` : esc((a.description || '').slice(0, 40));
+ return (
+ `<button type="button" class="lc-card${on ? ' on' : ''}" data-id="${esc(a.id)}" ` +
+ `aria-pressed="${on}">${thumb}` +
+ `<span class="lc-meta"><span class="lc-name">${esc(a.name || 'Untitled agent')}</span>` +
+ `<span class="lc-sub">${sub}</span></span></button>`
+ );
+ })
+ .join('');
+
+ pickerEl.innerHTML =
+ '<p class="lc-col-h">Choose your agent</p>' +
+ cards +
+ '<a class="lc-pick-cta" href="/create-agent">+ New agent</a>';
+
+ for (const btn of pickerEl.querySelectorAll('.lc-card')) {
+ btn.addEventListener('click', () => selectAvatar(btn.dataset.id));
+ }
+}
+
+function selectAvatar(id) {
+ if (id === state.avatarId) return;
+ state.avatarId = id;
+ renderPicker();
+ launchPanel?.avatarChanged();
+}
+
+export function mountLaunchCoin(root) {
+ if (!document.getElementById('lc-css')) {
+ const style = document.createElement('style');
+ style.id = 'lc-css';
+ style.textContent = PICKER_CSS;
+ document.head.appendChild(style);
+ }
+
+ root.innerHTML =
+ '<div class="lc-shell">' +
+ '<aside class="lc-pick" id="lc-picker"></aside>' +
+ '<div id="lc-panel"></div>' +
+ '</div>';
+
+ pickerEl = root.querySelector('#lc-picker');
+ const panelEl = root.querySelector('#lc-panel');
+
+ renderPicker();
+
+ launchPanel = mountLaunchPanel(panelEl, {
+ getAvatar: () => currentAvatar(),
+ getUser: () => state.user,
+ });
+
+ (async function boot() {
+ const user = await fetchMe();
+ state.user = user;
+ const avatars = user ? await fetchAvatars() : [];
+ state.avatars = avatars;
+
+ // Honor ?avatar=<id|slug> deep links (e.g. from an agent profile), else
+ // default to the first agent so the form is immediately usable.
+ const wanted = new URL(location.href).searchParams.get('avatar');
+ const match =
+ (wanted && avatars.find((a) => a.id === wanted || a.slug === wanted)) || avatars[0] || null;
+ state.avatarId = match?.id || null;
+ state.loading = false;
+
+ renderPicker();
+ launchPanel?.avatarChanged();
+ })();
+
+ return {
+ teardown() {
+ launchPanel?.teardown();
+ launchPanel = null;
+ root.innerHTML = '';
+ },
+ };
+}
diff --git a/public/llms-full.txt b/public/llms-full.txt
index 73ac0b2c8..5dff051b4 100644
--- a/public/llms-full.txt
+++ b/public/llms-full.txt
@@ -308,6 +308,12 @@ A curated gallery of three.ws's most powerful — and most hidden — features.
On-chain features: pay-per-call, token launches, vanity wallets.
+### Launch a Coin
+
+URL: https://three.ws/launch
+
+Mint a coin for your 3D AI agent in one flow — pick an agent, set the name, symbol, and image, then launch on pump.fun straight from your wallet with an optional three.ws-branded vanity mint.
+
### Agent Launches
URL: https://three.ws/launches
diff --git a/public/llms.txt b/public/llms.txt
index 6f1646d30..cb1c31840 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -72,6 +72,7 @@ Experimental features actively shipping. Expect fast iteration.
On-chain features: pay-per-call, token launches, vanity wallets.
+- [Launch a Coin](https://three.ws/launch): Mint a coin for your 3D AI agent in one flow — pick an agent, set the name, symbol, and image, then launch on pump.fun straight from your wallet with an optional three.ws-branded vanity mint.
- [Agent Launches](https://three.ws/launches): Live public feed of every coin launched by a three.ws agent — market caps, graduation status, and the agent behind each launch.
- [Pay (x402)](https://three.ws/pay): Pay-per-call gateway: invoke any x402-protocol paid API with a USDC micro-transaction.
- [Agent Wallet (x402 on Solana)](https://three.ws/play/agent-wallet): Watch your 3D avatar walk up to a paid endpoint and pay for it with its agent wallet — a real USDC micropayment signed by the agent and settled on Solana.
diff --git a/public/nav-data.js b/public/nav-data.js
index 8461a97fb..df323f695 100644
--- a/public/nav-data.js
+++ b/public/nav-data.js
@@ -85,8 +85,8 @@ export const NAV_GROUPS = [
items: [
{
title: 'Launch a Coin',
- href: '/launchpad',
- desc: 'Create a token for your agent',
+ href: '/launch',
+ desc: 'Mint a coin for your agent on pump.fun',
},
{
title: 'Live Stream',
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index 21c96e48d..39cc982a5 100644
--- a/public/sitemap/index.html
+++ b/public/sitemap/index.html
@@ -65,7 +65,7 @@
<main class="sm-wrap">
<div class="sm-hero">
<h1>Sitemap</h1>
- <p>All 264 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
+ <p>All 265 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
<div class="sm-formats">
<a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a>
<a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>
@@ -77,7 +77,7 @@
</div>
<div class="sm-filter">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>
- <input id="sm-filter-input" type="search" placeholder="Filter 264 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
+ <input id="sm-filter-input" type="search" placeholder="Filter 265 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
<kbd aria-hidden="true">/</kbd>
</div>
<p class="sm-filter-count" id="sm-filter-count" role="status" aria-live="polite"></p>
@@ -452,10 +452,17 @@
<section class="sm-section" id="crypto">
<header>
- <h2>Crypto<span class="sm-count" data-count>33</span></h2>
+ <h2>Crypto<span class="sm-count" data-count>34</span></h2>
<p class="sm-section-desc">On-chain features: pay-per-call, token launches, vanity wallets.</p>
</header>
<ul class="sm-list">
+ <li>
+ <a href="/launch">
+ <span class="sm-title">Launch a Coin</span>
+ <span class="sm-path">/launch</span>
+ <span class="sm-desc">Mint a coin for your 3D AI agent in one flow — pick an agent, set the name, symbol, and image, then launch on pump.fun straight from your wallet with an optional three.ws-branded vanity mint.</span>
+ </a>
+ </li>
<li>
<a href="/launches">
<span class="sm-title">Agent Launches</span>
diff --git a/src/club-entrance.js b/src/club-entrance.js
index 540af1cde..8e0a8d7c1 100644
--- a/src/club-entrance.js
+++ b/src/club-entrance.js
@@ -39,10 +39,21 @@ import {
Vector2,
Vector3,
WebGLRenderer,
- ACESFilmicToneMapping,
+ NoToneMapping,
} from 'three';
+import {
+ EffectComposer,
+ RenderPass,
+ EffectPass,
+ BloomEffect,
+ ToneMappingEffect,
+ VignetteEffect,
+ SMAAEffect,
+ ToneMappingMode,
+} from 'postprocessing';
import { gltfLoader } from './loaders/gltf.js';
import { AnimationManager } from './animation-manager.js';
+import { ClubApproachAudio } from './club-entrance-audio.js';
import { log } from './shared/log.js';
const TOUR_URL = '/club/venue/tour.glb';
@@ -102,12 +113,14 @@ function hasValidPass() {
}
async function start(canvasEl) {
- const renderer = new WebGLRenderer({ canvas: canvasEl, antialias: true, alpha: true });
+ // antialias off + tone mapping deferred — SMAA + ACES run in the composer
+ // below, exactly like the pole stage (src/club.js), so the two halves of the
+ // journey share one cinematic look.
+ const renderer = new WebGLRenderer({ canvas: canvasEl, antialias: false, alpha: false });
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setSize(window.innerWidth, window.innerHeight, false);
renderer.outputColorSpace = SRGBColorSpace;
- renderer.toneMapping = ACESFilmicToneMapping;
- renderer.toneMappingExposure = 1.12;
+ renderer.toneMapping = NoToneMapping;
const scene = new Scene();
// Opaque backdrop (matches the fog) so the pole stage rendering behind this
@@ -134,6 +147,26 @@ async function start(canvasEl) {
key.position.set(0, 5, 0);
scene.add(key, key.target);
+ // ── Postprocessing — the same cinematic stack as the pole stage ──────────
+ // Bloom makes the neon door/sign actually glow, ACES gives filmic colour,
+ // the vignette pulls focus to the path ahead, SMAA cleans the edges. We
+ // replace renderer.render() with composer.render(dt) in the loop below.
+ const bloomEffect = new BloomEffect({
+ intensity: 1.35,
+ luminanceThreshold: 0.32,
+ luminanceSmoothing: 0.08,
+ mipmapBlur: true,
+ });
+ const composer = new EffectComposer(renderer);
+ composer.addPass(new RenderPass(scene, camera));
+ composer.addPass(new EffectPass(
+ camera,
+ bloomEffect,
+ new ToneMappingEffect({ mode: ToneMappingMode.ACES_FILMIC }),
+ new VignetteEffect({ darkness: 0.5, offset: 0.3 }),
+ ));
+ composer.addPass(new EffectPass(camera, new SMAAEffect()));
+
const loader = gltfLoader(renderer);
// The journey, in order. You free-walk every one of these — no auto-walk.
@@ -464,7 +497,7 @@ async function start(canvasEl) {
}
}
- renderer.render(scene, camera);
+ composer.render(dt);
raf = requestAnimationFrame(frame);
}
raf = requestAnimationFrame(frame);
@@ -525,6 +558,7 @@ async function start(canvasEl) {
function onResize() {
renderer.setSize(window.innerWidth, window.innerHeight, false);
+ composer.setSize(window.innerWidth, window.innerHeight);
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
}
@@ -537,7 +571,9 @@ async function start(canvasEl) {
window.removeEventListener('keyup', onKeyUp);
onAdmit = null;
try { anim.dispose?.(); } catch {}
+ try { approachAudio?.dispose(); } catch {}
disposeObject(scene);
+ composer.dispose();
renderer.dispose();
try { canvasEl.remove(); } catch {}
showHint(false); showJoystick(false); showPrompt(false);
diff --git a/src/club.js b/src/club.js
index 29a617f64..e3e5b4c75 100644
--- a/src/club.js
+++ b/src/club.js
@@ -425,6 +425,35 @@ const DANCER_META = [
{ name: 'Blaze', bio: 'Amber heat. Power and precision.', palette: 'amber', avatarId: 'd92b292e-c2db-40cb-bf88-3e141c6b0057' },
];
+// Every dancer is scaled to this standing height (metres) so a mix of
+// differently-authored gallery avatars reads as one lineup.
+const DANCER_HEIGHT_M = 1.75;
+
+/**
+ * Scale a freshly-cloned avatar root to `targetHeight` and ground its feet at
+ * local y=0, measuring with the skinning-aware (`precise`) bounding box so a
+ * rig with a scaled skeleton root or far-flung bind pose still sizes correctly.
+ * Called before the root is parented, so its world space equals its local space
+ * and the measured box is directly usable to offset `position.y`.
+ *
+ * @param {import('three').Object3D} root
+ * @param {number} targetHeight
+ */
+function fitRigToHeight(root, targetHeight) {
+ root.updateMatrixWorld(true);
+ root.traverse((n) => { if (n.isSkinnedMesh) n.skeleton?.update?.(); });
+
+ let box = new Box3().setFromObject(root, true);
+ const height = box.max.y - box.min.y;
+ if (Number.isFinite(height) && height > 0.05) {
+ const scale = Math.min(8, Math.max(0.05, targetHeight / height));
+ root.scale.multiplyScalar(scale);
+ root.updateMatrixWorld(true);
+ box = new Box3().setFromObject(root, true);
+ }
+ if (Number.isFinite(box.min.y)) root.position.y -= box.min.y;
+}
+
class PoleStation {
constructor(idx, layout) {
this.idx = idx;
@@ -598,10 +627,16 @@ class PoleStation {
}
}
});
- // Re-zero so feet sit at rig y=0 regardless of where the source GLB
- // authored its origin (each avatar model differs).
- const box = new Box3().setFromObject(root);
- root.position.y -= box.min.y;
+ // Normalize size + ground the feet. Gallery avatars come from many
+ // pipelines (CharacterStudio, Unreal, RPM, uploads) at wildly different
+ // scales and skeleton offsets — one ships 3m tall and floating, another
+ // sub-metre. A plain rest-pose AABB (setFromObject without `precise`)
+ // reads the bind-pose geometry, which for a skinned rig can bear no
+ // relation to the posed silhouette. Measuring with `precise: true` runs
+ // each vertex through SkinnedMesh.getVertexPosition (applies bone skinning),
+ // so we get the real standing bounds — then scale every dancer to one
+ // height and drop her feet onto y=0 so the lineup reads as a set.
+ fitRigToHeight(root, DANCER_HEIGHT_M);
return root;
}
diff --git a/src/three-economy.js b/src/three-economy.js
index 0da1682b0..0e3546d16 100644
--- a/src/three-economy.js
+++ b/src/three-economy.js
@@ -1,12 +1,30 @@
-// The $THREE economy page (/three).
+// The $THREE economy (/three) — the flagship surface for the platform economy.
//
-// One screen that explains and surfaces the whole economy: the no-burn policy,
-// the holder-tier ladder (with the signed-in holder's live tier), the pay-per-use
-// price catalog, a rare-name lookup, and live economy stats from the settle
-// ledger. All data is real — /api/three/{catalog,stats,tier,name-quote} — with
-// designed loading, empty, and error states. No mock data, no placeholders.
+// One page that makes the whole economy legible and verifiable: a live canvas
+// visualization of value flowing through the protocol ("The Flow"), animated live
+// stats, on-chain-verifiable treasury + rewards wallets, a real reflected-to-
+// holders history with a personal projector, an interactive holder-tier ladder,
+// an interactive pricing explorer that applies your tier discount live, and a
+// rare-name studio. All data is real — /api/three/{catalog,stats,tier,name-quote}
+// and /api/token/price. No mock data, no placeholders; every state is designed.
+//
+// Design language: dark, premium, minimal. Split roles have a fixed color
+// identity used everywhere — treasury=gold, rewards=green, creators=blue,
+// scarcity=violet — so the same value is recognizable in the flow, the stats, and
+// the catalog. Motion is purposeful and fully reduced-motion aware.
const API = '/api/three';
+const MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+const REDUCED_MOTION =
+ typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
+
+// Fixed color identity per split role — the page's visual grammar.
+const ROLE = {
+ treasury: { color: '#f5c451', glow: 'rgba(245,196,81,.5)', label: 'Treasury' },
+ rewards: { color: '#6ee7a8', glow: 'rgba(110,231,168,.55)', label: 'Holder rewards' },
+ seller: { color: '#7cc4ff', glow: 'rgba(124,196,255,.5)', label: 'Creators' },
+ scarcity: { color: '#c4a8ff', glow: 'rgba(196,168,255,.5)', label: 'Scarcity' },
+};
const CATEGORY_LABELS = {
generation: 'Generation & compute',
data: 'Data & intelligence',
@@ -15,7 +33,8 @@ const CATEGORY_LABELS = {
};
// ── formatters ──────────────────────────────────────────────────────────────
-const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+const esc = (s) =>
+ String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
const fmtUsd = (n) => {
const v = Number(n);
if (!Number.isFinite(v)) return '—';
@@ -24,15 +43,19 @@ const fmtUsd = (n) => {
};
const fmtCompact = (n) => {
const v = Number(n);
- if (!Number.isFinite(v)) return '—';
- if (Math.abs(v) >= 1e9) return `${(v / 1e9).toFixed(2)}B`;
- if (Math.abs(v) >= 1e6) return `${(v / 1e6).toFixed(2)}M`;
- if (Math.abs(v) >= 1e3) return `${(v / 1e3).toFixed(1)}K`;
- return v.toLocaleString('en-US', { maximumFractionDigits: 2 });
+ if (!Number.isFinite(v)) return '0';
+ const a = Math.abs(v);
+ if (a >= 1e9) return `${(v / 1e9).toFixed(2)}B`;
+ if (a >= 1e6) return `${(v / 1e6).toFixed(2)}M`;
+ if (a >= 1e3) return `${(v / 1e3).toFixed(1)}K`;
+ return v.toLocaleString('en-US', { maximumFractionDigits: v < 1 && v > 0 ? 4 : 2 });
};
const atomicsToTokens = (atomics, decimals = 6) => {
try {
- return Number(BigInt(atomics)) / 10 ** decimals;
+ // Avoid Number overflow on huge atomics: split integer/fraction via BigInt.
+ const a = BigInt(atomics);
+ const d = 10n ** BigInt(decimals);
+ return Number(a / d) + Number(a % d) / Number(d);
} catch {
return 0;
}
@@ -54,287 +77,893 @@ async function getJSON(path, opts = {}) {
return r.json();
}
+// Animate a number element from 0 (or its current value) to `target`, easing the
+// rollup. Respects reduced-motion (sets the final value immediately). `format`
+// renders the running value. Cancels cleanly if re-invoked on the same element.
+function rollup(el, target, format = fmtCompact, ms = 900) {
+ if (!el) return;
+ const to = Number(target) || 0;
+ if (REDUCED_MOTION || ms <= 0) {
+ el.textContent = format(to);
+ return;
+ }
+ if (el._rollupRAF) cancelAnimationFrame(el._rollupRAF);
+ const from = Number(el._rollupValue) || 0;
+ let start = null;
+ const ease = (t) => 1 - Math.pow(1 - t, 3); // easeOutCubic
+ const step = (ts) => {
+ if (start === null) start = ts;
+ const p = Math.min(1, (ts - start) / ms);
+ const v = from + (to - from) * ease(p);
+ el.textContent = format(v);
+ if (p < 1) el._rollupRAF = requestAnimationFrame(step);
+ else {
+ el._rollupValue = to;
+ el.textContent = format(to);
+ }
+ };
+ el._rollupRAF = requestAnimationFrame(step);
+}
+
+// Reveal-on-scroll: fade/slide sections in as they enter the viewport. No-op under
+// reduced motion (everything is simply visible).
+function observeReveal(root) {
+ if (REDUCED_MOTION || typeof IntersectionObserver !== 'function') {
+ root.querySelectorAll('.ec-reveal').forEach((el) => el.classList.add('in'));
+ return;
+ }
+ const io = new IntersectionObserver(
+ (entries) => {
+ for (const e of entries) {
+ if (e.isIntersecting) {
+ e.target.classList.add('in');
+ io.unobserve(e.target);
+ }
+ }
+ },
+ { rootMargin: '0px 0px -10% 0px', threshold: 0.08 },
+ );
+ root.querySelectorAll('.ec-reveal').forEach((el) => io.observe(el));
+}
+
// ── styles ──────────────────────────────────────────────────────────────────
function injectStyles() {
const css = `
- :root { color-scheme: dark; }
- * { box-sizing: border-box; }
- body { margin:0; background:#0a0a0d; color:#f5f5f7; font-family:Inter,system-ui,-apple-system,Segoe UI,Roboto,sans-serif; -webkit-font-smoothing:antialiased; }
+ :root {
+ --bg:#08080b; --panel:#0e0e13; --panel-2:#0b0b0f; --line:#1a1a22; --line-2:#23232c;
+ --ink:#f6f6f8; --muted:#9a9aa4; --muted-2:#80808b;
+ --gold:#f5c451; --green:#6ee7a8; --blue:#7cc4ff; --violet:#c4a8ff;
+ --ease:cubic-bezier(.22,1,.36,1);
+ color-scheme: dark;
+ }
+ * { box-sizing:border-box; }
+ body { margin:0; background:var(--bg); color:var(--ink);
+ font-family:Inter,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;
+ -webkit-font-smoothing:antialiased; text-rendering:optimizeLegibility; }
+ body::before { /* ambient top glow */
+ content:''; position:fixed; inset:0; pointer-events:none; z-index:0;
+ background:radial-gradient(900px 500px at 50% -8%, rgba(110,231,168,.10), transparent 60%),
+ radial-gradient(700px 500px at 85% 0%, rgba(124,196,255,.06), transparent 55%); }
a { color:inherit; text-decoration:none; }
- .ec-wrap { max-width:1100px; margin:0 auto; padding:28px 18px 80px; }
- .ec-top { display:flex; align-items:center; justify-content:space-between; gap:12px; margin-bottom:28px; }
- .ec-back { color:#8a8a93; font-size:13px; border:1px solid #232329; border-radius:8px; padding:6px 12px; transition:border-color .15s,color .15s; }
- .ec-back:hover { color:#fff; border-color:#3a3a44; }
- .ec-hero { text-align:center; padding:18px 0 30px; }
- .ec-badge { display:inline-block; font-size:11px; letter-spacing:.08em; text-transform:uppercase; color:#7ee787; border:1px solid #1f3a24; background:#0e1a10; border-radius:999px; padding:4px 12px; margin-bottom:14px; }
- .ec-h1 { font-size:clamp(28px,5vw,44px); font-weight:850; letter-spacing:-0.03em; margin:0 0 12px; background:linear-gradient(180deg,#fff,#b8b8c2); -webkit-background-clip:text; background-clip:text; -webkit-text-fill-color:transparent; }
- .ec-lede { color:#9a9aa3; font-size:16px; max-width:640px; margin:0 auto; line-height:1.5; }
- .ec-cta { margin-top:20px; display:flex; gap:10px; justify-content:center; flex-wrap:wrap; }
- .ec-btn { font-size:14px; font-weight:600; padding:10px 18px; border-radius:10px; border:1px solid #232329; transition:transform .12s,border-color .15s,background .15s; cursor:pointer; }
- .ec-btn:hover { transform:translateY(-1px); }
- .ec-btn.primary { background:#fff; color:#000; border-color:#fff; }
- .ec-btn.primary:hover { background:#e8e8ee; }
- .ec-section { margin-top:44px; }
- .ec-section h2 { font-size:20px; font-weight:750; letter-spacing:-0.02em; margin:0 0 4px; }
- .ec-section p.ec-desc { color:#8a8a93; font-size:14px; margin:0 0 18px; }
- .ec-grid { display:grid; gap:12px; }
- .ec-stats { grid-template-columns:repeat(auto-fit,minmax(170px,1fr)); }
- .ec-stat { border:1px solid #1c1c22; border-radius:14px; padding:18px; background:linear-gradient(180deg,#101015,#0c0c10); }
- .ec-stat .v { font-size:26px; font-weight:800; letter-spacing:-0.02em; }
- .ec-stat .k { color:#8a8a93; font-size:12.5px; margin-top:4px; }
- .ec-tiers { grid-template-columns:repeat(auto-fit,minmax(180px,1fr)); }
- .ec-tier { border:1px solid #1c1c22; border-radius:14px; padding:18px; background:#0e0e12; position:relative; transition:border-color .15s,transform .12s; }
- .ec-tier:hover { transform:translateY(-2px); border-color:#3a3a44; }
- .ec-tier.is-current { border-color:#7ee787; box-shadow:0 0 0 1px #1f3a24; }
- .ec-tier .badge-you { position:absolute; top:-9px; right:12px; font-size:10px; font-weight:700; letter-spacing:.06em; text-transform:uppercase; color:#0a0a0d; background:#7ee787; border-radius:999px; padding:3px 9px; }
- .ec-tier .tname { font-size:16px; font-weight:750; }
- .ec-tier .tmin { color:#8a8a93; font-size:12.5px; margin:2px 0 12px; }
+ code { font-family:ui-monospace,Menlo,monospace; }
+ ::selection { background:rgba(110,231,168,.25); }
+ :focus-visible { outline:2px solid var(--green); outline-offset:3px; border-radius:6px; }
+
+ .ec-wrap { position:relative; z-index:1; max-width:1120px; margin:0 auto; padding:24px 20px 100px; }
+ .ec-top { display:flex; align-items:center; justify-content:space-between; gap:12px; }
+ .ec-pill { display:inline-flex; align-items:center; gap:7px; font-size:12.5px; color:var(--muted);
+ border:1px solid var(--line); border-radius:999px; padding:7px 13px; transition:.18s var(--ease); }
+ .ec-pill:hover { color:var(--ink); border-color:var(--line-2); transform:translateY(-1px); }
+ .ec-pill .dot { width:7px; height:7px; border-radius:50%; background:var(--green);
+ box-shadow:0 0 10px var(--green); animation:ec-pulse 2.4s infinite; }
+ @keyframes ec-pulse { 0%,100%{opacity:1} 50%{opacity:.35} }
+
+ /* Hero */
+ .ec-hero { padding:56px 0 8px; text-align:center; }
+ .ec-badge { display:inline-flex; gap:8px; align-items:center; font-size:11.5px; letter-spacing:.1em;
+ text-transform:uppercase; color:var(--green); border:1px solid rgba(110,231,168,.25);
+ background:rgba(110,231,168,.06); border-radius:999px; padding:6px 14px; margin-bottom:20px; }
+ .ec-h1 { font-size:clamp(34px,6.2vw,60px); line-height:1.02; font-weight:840; letter-spacing:-.035em;
+ margin:0 0 16px; background:linear-gradient(180deg,#fff 30%,#a9a9b4); -webkit-background-clip:text;
+ background-clip:text; -webkit-text-fill-color:transparent; }
+ .ec-lede { color:var(--muted); font-size:clamp(15px,2vw,18px); line-height:1.55; max-width:620px; margin:0 auto; }
+ .ec-hero-stat { margin:30px auto 4px; display:inline-flex; flex-direction:column; gap:4px;
+ border:1px solid rgba(110,231,168,.22); background:rgba(110,231,168,.05); border-radius:18px; padding:18px 30px; }
+ .ec-hero-stat .hs-num { font-size:clamp(30px,5vw,46px); font-weight:850; letter-spacing:-.03em; color:var(--green);
+ font-variant-numeric:tabular-nums; line-height:1; }
+ .ec-hero-stat .hs-num .hs-sym { font-size:16px; font-weight:600; color:var(--muted); }
+ .ec-hero-stat .hs-lbl { font-size:12.5px; color:var(--muted); }
+ .ec-cta { margin-top:26px; display:flex; gap:11px; justify-content:center; flex-wrap:wrap; }
+ .ec-btn { font-size:14px; font-weight:600; padding:11px 20px; border-radius:11px; border:1px solid var(--line-2);
+ background:var(--panel); transition:.16s var(--ease); cursor:pointer; color:var(--ink); }
+ .ec-btn:hover { transform:translateY(-1px); border-color:#34343f; }
+ .ec-btn.primary { background:var(--ink); color:#06060a; border-color:var(--ink); font-weight:700; }
+ .ec-btn.primary:hover { background:#fff; }
+
+ /* Sections */
+ .ec-section { margin-top:64px; }
+ .ec-reveal { opacity:0; transform:translateY(16px); transition:opacity .6s var(--ease), transform .6s var(--ease); }
+ .ec-reveal.in { opacity:1; transform:none; }
+ .ec-htitle { font-size:13px; text-transform:uppercase; letter-spacing:.12em; color:var(--green); margin:0 0 8px; font-weight:700; }
+ .ec-h2 { font-size:clamp(22px,3vw,30px); font-weight:780; letter-spacing:-.025em; margin:0 0 8px; }
+ .ec-desc { color:var(--muted); font-size:14.5px; line-height:1.55; max-width:660px; margin:0 0 22px; }
+
+ /* The Flow */
+ .ec-flow-shell { position:relative; border:1px solid var(--line); border-radius:20px; overflow:hidden;
+ background:linear-gradient(180deg,#0c0c11,#090a0d); }
+ .ec-flow-canvas { display:block; width:100%; height:340px; }
+ .ec-flow-legend { display:flex; flex-wrap:wrap; gap:14px 22px; padding:14px 18px; border-top:1px solid var(--line);
+ font-size:12.5px; color:var(--muted); background:rgba(0,0,0,.2); }
+ .ec-leg { display:inline-flex; align-items:center; gap:7px; }
+ .ec-leg .sw { width:9px; height:9px; border-radius:50%; }
+ .ec-flow-note { position:absolute; bottom:62px; left:18px; right:18px; font-size:12px; color:var(--muted-2);
+ pointer-events:none; }
+ .ec-flow-pause { position:absolute; top:14px; right:14px; z-index:2; display:inline-flex; align-items:center; gap:6px;
+ font-size:12px; color:var(--muted); background:rgba(0,0,0,.45); border:1px solid var(--line-2);
+ border-radius:999px; padding:6px 12px; cursor:pointer; transition:.15s var(--ease); backdrop-filter:blur(6px); }
+ .ec-flow-pause:hover { color:var(--ink); border-color:#3a3a44; }
+
+ /* Stat band */
+ .ec-stats { display:grid; gap:13px; grid-template-columns:repeat(auto-fit,minmax(180px,1fr)); }
+ .ec-stat { border:1px solid var(--line); border-radius:16px; padding:20px;
+ background:linear-gradient(180deg,var(--panel),var(--panel-2)); position:relative; overflow:hidden; }
+ .ec-stat::after { content:''; position:absolute; left:0; top:0; height:2px; width:100%;
+ background:linear-gradient(90deg,transparent,var(--accent,var(--green)),transparent); opacity:.5; }
+ .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; }
+
+ /* Verify wallets */
+ .ec-wallets { display:grid; gap:13px; grid-template-columns:repeat(auto-fit,minmax(260px,1fr)); }
+ .ec-wallet { display:block; border:1px solid var(--line); border-radius:16px; padding:20px;
+ background:linear-gradient(180deg,var(--panel),var(--panel-2)); transition:.16s var(--ease); }
+ a.ec-wallet:hover { transform:translateY(-2px); border-color:var(--accent); box-shadow:0 8px 30px -12px var(--accent-glow); }
+ .ec-wallet .wlabel { font-size:12.5px; color:var(--muted); display:flex; align-items:center; gap:8px; }
+ .ec-wallet .wlabel .sw { width:9px; height:9px; border-radius:50%; background:var(--accent); }
+ .ec-wallet .wbal { font-size:26px; font-weight:820; letter-spacing:-.02em; margin:8px 0 7px; font-variant-numeric:tabular-nums; }
+ .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 */
+ .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;
+ background:linear-gradient(180deg,var(--panel),var(--panel-2)); }
+ .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-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); }
+ .ec-tag.planned { background:rgba(139,139,150,.12); color:var(--muted); }
+ .ec-proj label { font-size:12.5px; color:var(--muted); display:block; margin-bottom:8px; }
+ .ec-proj input[type=range] { width:100%; accent-color:var(--green); }
+ .ec-proj-out { margin-top:14px; font-size:14px; line-height:1.6; }
+ .ec-proj-out b { color:var(--green); font-variant-numeric:tabular-nums; }
+
+ /* Tiers */
+ .ec-tiers { display:grid; gap:13px; grid-template-columns:repeat(auto-fit,minmax(190px,1fr)); }
+ .ec-tier { border:1px solid var(--line); border-radius:16px; padding:20px; background:var(--panel);
+ position:relative; transition:.16s var(--ease); }
+ .ec-tier:hover { transform:translateY(-3px); border-color:var(--line-2); }
+ .ec-tier.cur { border-color:var(--green); box-shadow:0 0 0 1px rgba(110,231,168,.3), 0 12px 40px -16px rgba(110,231,168,.4); }
+ .ec-tier .you { position:absolute; top:-10px; right:14px; font-size:10px; font-weight:800; letter-spacing:.07em;
+ text-transform:uppercase; color:#06060a; background:var(--green); border-radius:999px; padding:3px 10px; }
+ .ec-tier .tn { font-size:17px; font-weight:780; }
+ .ec-tier .tm { color:var(--muted); font-size:12.5px; margin:3px 0 14px; }
.ec-tier ul { list-style:none; margin:0; padding:0; }
- .ec-tier li { font-size:12.5px; color:#c2c2cc; padding:4px 0 4px 18px; position:relative; }
- .ec-tier li::before { content:'›'; position:absolute; left:2px; color:#7ee787; }
- .ec-cat { margin-bottom:22px; }
- .ec-cat h3 { font-size:13px; text-transform:uppercase; letter-spacing:.06em; color:#8a8a93; margin:0 0 10px; }
- .ec-items { display:grid; gap:8px; grid-template-columns:repeat(auto-fit,minmax(240px,1fr)); }
- .ec-item { display:flex; align-items:center; justify-content:space-between; gap:12px; border:1px solid #1a1a20; border-radius:11px; padding:12px 14px; background:#0d0d11; }
+ .ec-tier li { font-size:12.5px; color:#c9c9d2; padding:5px 0 5px 19px; position:relative; }
+ .ec-tier li::before { content:''; position:absolute; left:3px; top:11px; width:6px; height:6px; border-radius:50%;
+ background:var(--green); }
+ .ec-progress { margin:20px 0 0; }
+ .ec-progress .bar { height:8px; border-radius:999px; background:var(--line); overflow:hidden; }
+ .ec-progress .fill { height:100%; border-radius:999px; background:linear-gradient(90deg,var(--green),#a8f0c8);
+ width:0; transition:width 1s var(--ease); }
+ .ec-progress .lbl { display:flex; justify-content:space-between; font-size:12.5px; color:var(--muted); margin-top:9px; }
+
+ /* Pricing explorer */
+ .ec-px { display:grid; gap:16px; grid-template-columns:1fr 1fr; }
+ @media (max-width:760px){ .ec-px{ grid-template-columns:1fr; } }
+ .ec-px-list { border:1px solid var(--line); border-radius:16px; overflow:hidden; max-height:420px; overflow-y:auto; }
+ .ec-px-cat { font-size:11px; text-transform:uppercase; letter-spacing:.09em; color:var(--muted-2);
+ padding:12px 16px 6px; }
+ .ec-px-item { display:flex; align-items:center; justify-content:space-between; gap:12px; width:100%;
+ padding:12px 16px; background:none; border:none; border-top:1px solid var(--line); color:var(--ink);
+ font:inherit; text-align:left; cursor:pointer; transition:background .14s var(--ease); }
+ .ec-px-item:hover, .ec-px-item.sel { background:rgba(110,231,168,.06); }
+ .ec-px-item .pl { font-size:13.5px; }
+ .ec-px-item .pp { font-size:13px; font-weight:700; white-space:nowrap; font-variant-numeric:tabular-nums; }
+ .ec-px-item .pp.free { color:var(--green); }
+ .ec-px-item .pp.var { color:var(--muted); font-weight:500; }
+ .ec-px-detail { border:1px solid var(--line); border-radius:16px; padding:22px;
+ background:linear-gradient(180deg,var(--panel),var(--panel-2)); align-self:start; position:sticky; top:18px; }
+ .ec-px-detail .dt { font-size:16px; font-weight:740; }
+ .ec-px-row { display:flex; justify-content:space-between; padding:11px 0; border-bottom:1px solid var(--line); font-size:14px; }
+ .ec-px-row:last-child { border-bottom:none; }
+ .ec-px-row .val { font-weight:700; font-variant-numeric:tabular-nums; }
+ .ec-px-row .val.save { color:var(--green); }
+ .ec-px-three { font-size:13px; color:var(--muted); }
+
+ /* Name studio */
+ .ec-name { display:flex; gap:10px; max-width:520px; }
+ .ec-name input { flex:1; background:var(--panel); border:1px solid var(--line-2); border-radius:12px;
+ padding:14px 16px; color:var(--ink); font-size:16px; font-family:ui-monospace,Menlo,monospace; transition:.16s var(--ease); }
+ .ec-name input:focus { outline:none; border-color:var(--green); box-shadow:0 0 0 3px rgba(110,231,168,.12); }
+ .ec-name .suffix { align-self:center; color:var(--muted-2); font-family:ui-monospace,Menlo,monospace; font-size:13px; }
+ .ec-name-out { margin-top:18px; min-height:90px; }
+ .ec-rare-meter { height:8px; border-radius:999px; background:var(--line); overflow:hidden; margin:14px 0 12px; max-width:520px; }
+ .ec-rare-fill { height:100%; border-radius:999px; transition:width .5s var(--ease), background .3s; }
+ .ec-rare-head { display:flex; align-items:center; gap:12px; flex-wrap:wrap; }
+ .ec-rarity { font-size:11px; font-weight:800; text-transform:uppercase; letter-spacing:.06em; border-radius:999px; padding:4px 11px; }
+ .r-legendary{background:rgba(196,168,255,.14);color:#d6b8ff} .r-epic{background:rgba(124,196,255,.14);color:#9ed0ff}
+ .r-rare{background:rgba(110,231,168,.14);color:#8af0c0} .r-uncommon{background:rgba(245,196,81,.14);color:#f0d488}
+ .r-common{background:rgba(139,139,150,.12);color:#a7a7b2}
+
+ /* Catalog grid (compact, full list) */
+ .ec-cat { margin-bottom:24px; }
+ .ec-cat h3 { font-size:12px; text-transform:uppercase; letter-spacing:.09em; color:var(--muted); margin:0 0 11px; }
+ .ec-items { display:grid; gap:9px; grid-template-columns:repeat(auto-fit,minmax(240px,1fr)); }
+ .ec-item { display:flex; align-items:center; justify-content:space-between; gap:12px; border:1px solid var(--line);
+ border-radius:12px; padding:13px 15px; background:var(--panel); }
.ec-item .label { font-size:13.5px; }
- .ec-item .price { font-size:13.5px; font-weight:700; white-space:nowrap; }
- .ec-item .price.free { color:#7ee787; }
- .ec-item .price.var { color:#9a9aa3; font-weight:500; }
- .ec-name { display:flex; gap:8px; margin-top:6px; max-width:460px; }
- .ec-name input { flex:1; background:#0d0d11; border:1px solid #232329; border-radius:10px; padding:11px 14px; color:#fff; font-size:14px; font-family:ui-monospace,Menlo,monospace; }
- .ec-name input:focus { outline:none; border-color:#3a3a44; }
- .ec-name-out { margin-top:12px; min-height:22px; font-size:14px; }
- .ec-rarity { display:inline-block; font-size:11px; font-weight:700; text-transform:uppercase; letter-spacing:.05em; border-radius:999px; padding:3px 10px; margin-right:8px; }
- .r-legendary { background:#2a1a3a; color:#d6a8ff; } .r-epic { background:#1a2a3a; color:#8ec8ff; }
- .r-rare { background:#1a2a24; color:#7ee7b8; } .r-uncommon { background:#2a261a; color:#e7d68e; } .r-common { background:#1c1c22; color:#9a9aa3; }
- .ec-foot { margin-top:48px; padding-top:20px; border-top:1px solid #1a1a20; color:#6a6a73; font-size:12.5px; text-align:center; line-height:1.6; }
- .ec-skel { background:linear-gradient(90deg,#141419,#1c1c22,#141419); background-size:200% 100%; animation:ec-sh 1.2s infinite; border-radius:11px; }
+ .ec-item .price { font-size:13.5px; font-weight:700; white-space:nowrap; font-variant-numeric:tabular-nums; }
+ .ec-item .price.free { color:var(--green); } .ec-item .price.var { color:var(--muted); font-weight:500; }
+
+ /* States */
+ .ec-skel { background:linear-gradient(90deg,#101015,#191920,#101015); background-size:200% 100%;
+ animation:ec-sh 1.3s infinite; border-radius:14px; }
@keyframes ec-sh { 0%{background-position:200% 0} 100%{background-position:-200% 0} }
- .ec-err { border:1px solid #3a1f1f; background:#1a0e0e; color:#ff9b9b; border-radius:12px; padding:16px; font-size:13.5px; }
- .ec-muted { color:#8a8a93; }
- .ec-wallets { grid-template-columns:repeat(auto-fit,minmax(240px,1fr)); }
- .ec-wallet { display:block; border:1px solid #1c1c22; border-radius:14px; padding:18px; background:linear-gradient(180deg,#101015,#0c0c10); transition:border-color .15s,transform .12s; }
- a.ec-wallet:hover { border-color:#7ee787; transform:translateY(-2px); }
- .ec-wallet .wlabel { font-size:12.5px; color:#8a8a93; }
- .ec-wallet .wbal { font-size:24px; font-weight:800; letter-spacing:-0.02em; margin:4px 0 6px; }
- .ec-wallet .waddr { font-family:ui-monospace,Menlo,monospace; font-size:11.5px; color:#7ee787; }
- .ec-reflect-head { display:flex; flex-direction:column; gap:2px; }
- .ec-reflect-head .v { font-size:30px; font-weight:850; letter-spacing:-0.02em; color:#7ee787; }
- .ec-reflect-head .k { color:#8a8a93; font-size:13.5px; }
- .ec-reflect-list { margin-top:14px; border:1px solid #1a1a20; border-radius:12px; overflow:hidden; }
- .ec-reflect-row { display:flex; justify-content:space-between; gap:12px; padding:11px 14px; font-size:13px; border-bottom:1px solid #15151a; }
- .ec-reflect-row:last-child { border-bottom:none; }
- @media (prefers-reduced-motion: reduce){ .ec-skel{ animation:none } .ec-btn:hover,.ec-tier:hover{ transform:none } }
+ .ec-err { border:1px solid #3a1f1f; background:#160d0d; color:#ff9b9b; border-radius:14px; padding:16px; font-size:13.5px; }
+ .ec-muted { color:var(--muted); }
+ .ec-foot { margin-top:64px; padding-top:24px; border-top:1px solid var(--line); color:var(--muted-2);
+ font-size:12.5px; text-align:center; line-height:1.7; }
+ .ec-foot code { color:var(--muted); }
+
+ @media (prefers-reduced-motion: reduce){
+ .ec-skel{animation:none} .ec-pill .dot{animation:none}
+ .ec-btn:hover,.ec-tier:hover,a.ec-wallet:hover,.ec-pill:hover{transform:none}
+ }
`;
const el = document.createElement('style');
el.textContent = css;
document.head.appendChild(el);
}
-// ── sections ──────────────────────────────────────────────────────────────────
+// ── The Flow: live canvas economy visualization ───────────────────────────────
+//
+// Value enters from the left (a particle per "spend", colored by category), hits
+// the protocol splitter, and forks into three beneficiary lanes — treasury (gold),
+// holder rewards (green), creators (blue). Reward particles rain onto a row of
+// holder dots that pulse on contact. NOTHING is destroyed: there is no burn sink,
+// and the note under the canvas says so. Emission rate + lane weights are seeded
+// from real /api/three/stats so the picture reflects the actual economy. Pauses
+// when offscreen; under reduced-motion it renders a clean static diagram instead.
+class FlowViz {
+ constructor(canvas) {
+ this.canvas = canvas;
+ this.ctx = canvas.getContext('2d');
+ this.particles = [];
+ this.holders = [];
+ this.running = false;
+ this.userPaused = false; // WCAG 2.2.2 — explicit user pause overrides auto start/stop
+ this.lastEmit = 0;
+ this.emitInterval = 520; // ms between spends (tuned by activity)
+ this.weights = { treasury: 0.5, rewards: 0.4, seller: 0.1 };
+ this.categoryColors = ['#6ee7a8', '#7cc4ff', '#c4a8ff', '#f5c451'];
+ this._resize = this._resize.bind(this);
+ this._frame = this._frame.bind(this);
+ }
-function heroHTML() {
- return `
- <div class="ec-hero">
- <span class="ec-badge">$THREE · the only coin · no burns</span>
- <h1 class="ec-h1">The three.ws economy</h1>
- <p class="ec-lede">Everything that costs us compute is priced in $THREE. Hold $THREE for lower fees and bigger perks. Every spend flows to the treasury and reflects back to holders — supply is never burned.</p>
- <div class="ec-cta">
- <a class="ec-btn primary" href="/three-token">Get $THREE</a>
- <a class="ec-btn" href="#tiers">See holder tiers</a>
- </div>
- </div>`;
+ seed(stats) {
+ const r = stats?.by_role || {};
+ const t = Number(r.treasury || 0);
+ const rw = Number(r.rewards || 0);
+ const s = Number(r.seller || 0);
+ const sum = t + rw + s;
+ if (sum > 0) this.weights = { treasury: t / sum, rewards: rw / sum, seller: s / sum };
+ // Busier economies emit faster (bounded). payment_count drives tempo.
+ const pc = Number(stats?.payment_count || 0);
+ this.emitInterval = pc > 0 ? Math.max(220, 620 - Math.min(380, pc * 6)) : 760;
+ }
+
+ start() {
+ if (this.running || REDUCED_MOTION || this.userPaused) {
+ if (REDUCED_MOTION) this._renderStatic();
+ return;
+ }
+ this.running = true;
+ this._resize();
+ addEventListener('resize', this._resize, { passive: true });
+ this._initHolders();
+ this._raf = requestAnimationFrame(this._frame);
+ }
+
+ stop() {
+ this.running = false;
+ if (this._raf) cancelAnimationFrame(this._raf);
+ removeEventListener('resize', this._resize);
+ }
+
+ _resize() {
+ const dpr = Math.min(2, window.devicePixelRatio || 1);
+ const rect = this.canvas.getBoundingClientRect();
+ this.w = rect.width;
+ this.h = rect.height || 340;
+ this.canvas.width = Math.round(this.w * dpr);
+ this.canvas.height = Math.round(this.h * dpr);
+ this.ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
+ this.splitX = this.w * 0.42;
+ this.midY = this.h * 0.5;
+ this.lanes = {
+ treasury: this.h * 0.22,
+ rewards: this.h * 0.5,
+ seller: this.h * 0.78,
+ };
+ this._initHolders();
+ }
+
+ _initHolders() {
+ const n = Math.min(26, Math.max(10, Math.floor((this.w || 600) / 34)));
+ const x0 = this.w * 0.74;
+ const x1 = this.w - 26;
+ this.holders = Array.from({ length: n }, (_, i) => ({
+ x: x0 + ((x1 - x0) * (i % Math.ceil(n / 2))) / Math.max(1, Math.ceil(n / 2) - 1),
+ y: this.lanes.rewards + 34 + Math.floor(i / Math.ceil(n / 2)) * 22,
+ pulse: 0,
+ }));
+ }
+
+ _emit(now) {
+ // Pick a beneficiary lane by the real split weights.
+ const r = Math.random();
+ let role = 'treasury';
+ if (r < this.weights.rewards) role = 'rewards';
+ else if (r < this.weights.rewards + this.weights.seller) role = 'seller';
+ this.particles.push({
+ x: -8,
+ y: this.midY + (Math.random() - 0.5) * 30,
+ role,
+ phase: 'in', // in → split → out
+ t: 0,
+ cat: this.categoryColors[(Math.random() * this.categoryColors.length) | 0],
+ speed: 0.6 + Math.random() * 0.5,
+ targetHolder: role === 'rewards' ? (Math.random() * this.holders.length) | 0 : -1,
+ });
+ this.lastEmit = now;
+ }
+
+ _frame(now) {
+ if (!this.running) return;
+ const ctx = this.ctx;
+ ctx.clearRect(0, 0, this.w, this.h);
+
+ // Static scaffold: source, splitter, lanes.
+ this._drawScaffold(ctx);
+
+ if (now - this.lastEmit > this.emitInterval) this._emit(now);
+
+ const treasuryC = ROLE.treasury.color,
+ rewardsC = ROLE.rewards.color,
+ sellerC = ROLE.seller.color;
+ for (let i = this.particles.length - 1; i >= 0; i--) {
+ const p = this.particles[i];
+ p.t += 0.016 * p.speed;
+ let alive = true;
+ if (p.phase === 'in') {
+ p.x += (this.splitX - p.x) * 0.06 * p.speed;
+ p.y += (this.midY - p.y) * 0.06;
+ if (p.x >= this.splitX - 3) {
+ p.phase = 'out';
+ p.y = this.midY;
+ }
+ } else {
+ const laneY = this.lanes[p.role];
+ const endX = p.role === 'rewards' && p.targetHolder >= 0 && this.holders[p.targetHolder]
+ ? this.holders[p.targetHolder].x
+ : this.w + 10;
+ const endY = p.role === 'rewards' && p.targetHolder >= 0 && this.holders[p.targetHolder]
+ ? this.holders[p.targetHolder].y
+ : laneY;
+ p.x += (endX - p.x) * 0.05 * p.speed;
+ p.y += (endY - p.y) * 0.08;
+ if (Math.abs(p.x - endX) < 4) {
+ if (p.role === 'rewards' && this.holders[p.targetHolder]) this.holders[p.targetHolder].pulse = 1;
+ alive = false;
+ }
+ }
+ const color = p.phase === 'in' ? p.cat : p.role === 'treasury' ? treasuryC : p.role === 'rewards' ? rewardsC : sellerC;
+ ctx.beginPath();
+ ctx.arc(p.x, p.y, 2.6, 0, Math.PI * 2);
+ ctx.fillStyle = color;
+ ctx.shadowColor = color;
+ ctx.shadowBlur = 8;
+ ctx.fill();
+ ctx.shadowBlur = 0;
+ if (!alive) this.particles.splice(i, 1);
+ }
+
+ // Holder dots (rewards recipients) — pulse green on contact.
+ for (const hh of this.holders) {
+ hh.pulse *= 0.92;
+ const rad = 3 + hh.pulse * 4;
+ ctx.beginPath();
+ ctx.arc(hh.x, hh.y, rad, 0, Math.PI * 2);
+ ctx.fillStyle = `rgba(110,231,168,${0.35 + hh.pulse * 0.65})`;
+ if (hh.pulse > 0.05) {
+ ctx.shadowColor = ROLE.rewards.color;
+ ctx.shadowBlur = 10 * hh.pulse;
+ }
+ ctx.fill();
+ ctx.shadowBlur = 0;
+ }
+
+ // Cap particle count defensively.
+ if (this.particles.length > 240) this.particles.splice(0, this.particles.length - 240);
+ this._raf = requestAnimationFrame(this._frame);
+ }
+
+ _drawScaffold(ctx) {
+ // Source node (left).
+ ctx.fillStyle = 'rgba(255,255,255,.04)';
+ ctx.strokeStyle = 'rgba(255,255,255,.10)';
+ this._roundRect(ctx, 6, this.midY - 26, 64, 52, 10);
+ ctx.fill();
+ ctx.stroke();
+ ctx.fillStyle = '#8b8b96';
+ ctx.font = '600 10px Inter, sans-serif';
+ ctx.textAlign = 'center';
+ ctx.fillText('SPENDS', 38, this.midY + 3);
+
+ // Splitter node (center).
+ ctx.beginPath();
+ ctx.arc(this.splitX, this.midY, 16, 0, Math.PI * 2);
+ ctx.fillStyle = 'rgba(110,231,168,.10)';
+ ctx.strokeStyle = 'rgba(110,231,168,.5)';
+ ctx.lineWidth = 1.5;
+ ctx.fill();
+ ctx.stroke();
+ ctx.fillStyle = '#cfeede';
+ ctx.font = '700 9px Inter, sans-serif';
+ ctx.fillText('$THREE', this.splitX, this.midY + 3);
+
+ // Lane labels (right).
+ ctx.textAlign = 'left';
+ ctx.font = '600 11px Inter, sans-serif';
+ const labels = [
+ ['treasury', ROLE.treasury.color, 'Treasury'],
+ ['rewards', ROLE.rewards.color, 'Holders'],
+ ['seller', ROLE.seller.color, 'Creators'],
+ ];
+ for (const [k, c, txt] of labels) {
+ ctx.fillStyle = c;
+ ctx.globalAlpha = 0.8;
+ ctx.fillText(txt, this.w * 0.6, this.lanes[k] - 8);
+ ctx.globalAlpha = 1;
+ }
+ }
+
+ _roundRect(ctx, x, y, w, h, r) {
+ ctx.beginPath();
+ ctx.moveTo(x + r, y);
+ ctx.arcTo(x + w, y, x + w, y + h, r);
+ ctx.arcTo(x + w, y + h, x, y + h, r);
+ ctx.arcTo(x, y + h, x, y, r);
+ ctx.arcTo(x, y, x + w, y, r);
+ ctx.closePath();
+ }
+
+ // Reduced-motion: a calm, labeled static diagram (no animation).
+ _renderStatic() {
+ this._resize();
+ const ctx = this.ctx;
+ ctx.clearRect(0, 0, this.w, this.h);
+ this._drawScaffold(ctx);
+ ctx.strokeStyle = 'rgba(255,255,255,.12)';
+ ctx.lineWidth = 1.5;
+ for (const k of ['treasury', 'rewards', 'seller']) {
+ ctx.beginPath();
+ ctx.moveTo(this.splitX + 14, this.midY);
+ ctx.lineTo(this.w * 0.6, this.lanes[k]);
+ ctx.stroke();
+ }
+ }
}
-function statsHTML(stats) {
+// ── section renderers ─────────────────────────────────────────────────────────
+
+function statCards(stats) {
const dec = stats?.token?.decimals ?? 6;
- const sym = stats?.token?.symbol ?? '$THREE';
+ const reflected = atomicsToTokens(stats?.reflected?.total_atomics ?? '0', dec);
+ const treasuryLive = atomicsToTokens(stats?.onchain?.treasury?.balance_atomics ?? '0', dec);
const gross = atomicsToTokens(stats?.gross_atomics ?? '0', dec);
- const rewards = atomicsToTokens(stats?.by_role?.rewards ?? '0', dec);
- const treasury = atomicsToTokens(stats?.by_role?.treasury ?? '0', dec);
const toCreators = atomicsToTokens(stats?.by_role?.seller ?? '0', dec);
- const cards = [
- { v: fmtCompact(gross), k: `${sym} settled volume` },
- { v: fmtCompact(rewards), k: `${sym} reflected to holders` },
- { v: fmtCompact(treasury), k: `${sym} to treasury → buybacks` },
- { v: fmtCompact(toCreators), k: `${sym} earned by creators` },
- { v: (stats?.payment_count ?? 0).toLocaleString('en-US'), k: 'settled payments' },
+ return [
+ { key: 'gross', v: gross, accent: 'var(--green)', k: 'settled volume', sym: true },
+ { key: 'reflected', v: reflected, accent: 'var(--green)', k: 'reflected to holders', sym: true },
+ { key: 'treasury', v: treasuryLive, accent: 'var(--gold)', k: 'in treasury (live)', sym: true },
+ { key: 'creators', v: toCreators, accent: 'var(--blue)', k: 'earned by creators', sym: true },
+ { key: 'count', v: Number(stats?.payment_count || 0), accent: 'var(--violet)', k: 'settled payments', sym: false },
];
- return `<div class="ec-grid ec-stats">${cards
- .map((c) => `<div class="ec-stat"><div class="v">${esc(c.v)}</div><div class="k">${esc(c.k)}</div></div>`)
- .join('')}</div>`;
}
-// Verifiable on-chain panel — the wallets anyone can inspect. This is the answer
-// to "trust us, we burned some": here are the addresses, check them yourself.
function onchainHTML(stats) {
const dec = stats?.token?.decimals ?? 6;
- const sym = stats?.token?.symbol ?? '$THREE';
const oc = stats?.onchain || {};
- const wallet = (w, label) => {
+ const wallet = (w, role) => {
+ const r = ROLE[role === 'rewards' ? 'rewards' : 'treasury'];
if (!w?.address) {
- return `<div class="ec-wallet"><div class="wlabel">${esc(label)}</div><div class="wbal ec-muted">not configured</div></div>`;
+ return `<div class="ec-wallet" style="--accent:${r.color};--accent-glow:${r.glow}"><div class="wlabel"><span class="sw"></span>${esc(r.label)}</div><div class="wbal ec-muted" style="font-size:15px">not yet configured</div></div>`;
}
const bal = fmtCompact(atomicsToTokens(w.balance_atomics ?? '0', dec));
- return `<a class="ec-wallet" href="${esc(w.explorer)}" target="_blank" rel="noopener">
- <div class="wlabel">${esc(label)}</div>
- <div class="wbal">${esc(bal)} ${esc(sym)}</div>
+ const sub = role === 'rewards' ? 'distributed pro-rata to holders' : 'funds buybacks — never burned';
+ return `<a class="ec-wallet" style="--accent:${r.color};--accent-glow:${r.glow}" href="${esc(w.explorer)}" target="_blank" rel="noopener">
+ <div class="wlabel"><span class="sw"></span>${esc(r.label)} · ${esc(sub)}</div>
+ <div class="wbal">${esc(bal)}<span class="sym">$THREE</span></div>
<div class="waddr">${esc(shortAddr(w.address))} · verify on Solscan ↗</div>
</a>`;
};
- return `<div class="ec-grid ec-wallets">
- ${wallet(oc.treasury, 'Treasury → buybacks')}
- ${wallet(oc.rewards_pool, 'Holder rewards pool')}
- </div>`;
+ return `<div class="ec-wallets">${wallet(oc.treasury, 'treasury')}${wallet(oc.rewards_pool, 'rewards')}</div>`;
}
-// Reflected-to-holders panel — real $THREE returned to holders, with run history.
-// Beats a static "0.5% burned" counter: this is value RETURNED, not destroyed.
function reflectedHTML(stats) {
const dec = stats?.token?.decimals ?? 6;
- const sym = stats?.token?.symbol ?? '$THREE';
const r = stats?.reflected || { total_atomics: '0', run_count: 0, recent: [] };
const total = fmtCompact(atomicsToTokens(r.total_atomics ?? '0', dec));
- const head = `<div class="ec-reflect-head"><div class="v">${esc(total)} ${esc(sym)}</div><div class="k">returned to holders across ${r.run_count} distribution${r.run_count === 1 ? '' : 's'} — never burned</div></div>`;
+ let history;
if (!r.recent?.length) {
- return `${head}<p class="ec-muted" style="margin-top:12px">Distributions begin once the rewards pool funds. Every run will be listed here with an on-chain transaction you can verify.</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 with an on-chain transaction you can verify — value returned to holders, never destroyed.</p>`;
+ } else {
+ history = `<div class="ec-reflect-list">${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>`;
+ })
+ .join('')}</div>`;
}
- 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 status = d.status === 'completed' ? '✓ paid' : 'planned';
- return `<div class="ec-reflect-row"><span>${esc(when)}</span><span>${esc(amt)} ${esc(sym)} → ${d.holder_count} holders</span><span class="ec-muted">${esc(status)}</span></div>`;
- })
- .join('');
- return `${head}<div class="ec-reflect-list">${rows}</div>`;
+ 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>
+ ${history}
+ </div>
+ <div class="ec-card ec-proj">
+ <label for="ec-proj-range">If you held this much $THREE…</label>
+ <input id="ec-proj-range" type="range" min="0" max="6" step="0.1" value="3" aria-label="Amount of $THREE held" />
+ <div class="ec-proj-out" id="ec-proj-out"></div>
+ </div>`;
}
function tiersHTML(tierData) {
const ladder = tierData?.ladder || [];
- const currentLevel = tierData?.tier?.level ?? null;
- const sub =
- currentLevel != null
- ? `You're <strong>${esc(tierData.tier.label)}</strong> — holding ${fmtUsd(tierData.held_usd)} of $THREE.${
- tierData.next ? ` ${fmtUsd(tierData.next.usd_to_go)} more to reach ${esc(tierData.next.label)}.` : ' Top tier reached.'
- }`
- : 'Sign in and link a Solana wallet to see your tier.';
+ const cur = tierData?.tier?.level ?? null;
const cards = ladder
.map((t) => {
- const isCurrent = t.level === currentLevel;
- const perks = (t.perks || []).map((p) => `<li>${esc(p)}</li>`).join('');
- return `<div class="ec-tier${isCurrent ? ' is-current' : ''}">
- ${isCurrent ? '<span class="badge-you">You</span>' : ''}
- <div class="tname">${esc(t.label)}</div>
- <div class="tmin">${t.min_usd > 0 ? `Hold ${fmtUsd(t.min_usd)}+` : 'Free — everyone'}${
- t.discount_bps > 0 ? ` · ${(t.discount_bps / 100).toFixed(0)}% off compute` : ''
- }</div>
+ const is = t.level === cur;
+ const perks = (t.perks || []).slice(0, 4).map((p) => `<li>${esc(p)}</li>`).join('');
+ return `<div class="ec-tier${is ? ' cur' : ''}">
+ ${is ? '<span class="you">You</span>' : ''}
+ <div class="tn">${esc(t.label)}</div>
+ <div class="tm">${t.min_usd > 0 ? `Hold ${fmtUsd(t.min_usd)}+` : 'Free — everyone'}${t.discount_bps > 0 ? ` · ${(t.discount_bps / 100).toFixed(0)}% off` : ''}</div>
<ul>${perks}</ul>
</div>`;
})
.join('');
- return `<p class="ec-desc">${sub}</p><div class="ec-grid ec-tiers">${cards}</div>`;
+ let progress = '';
+ if (cur != null && tierData?.next) {
+ const next = tierData.next;
+ const held = Number(tierData.held_usd || 0);
+ const prevMin = ladder.find((t) => t.level === cur)?.min_usd || 0;
+ const pct = Math.max(0, Math.min(100, ((held - prevMin) / Math.max(1, next.min_usd - prevMin)) * 100));
+ progress = `<div class="ec-progress">
+ <div class="bar"><div class="fill" id="ec-tier-fill"></div></div>
+ <div class="lbl"><span>You hold ${fmtUsd(held)}</span><span>${fmtUsd(next.usd_to_go)} to ${esc(next.label)}</span></div>
+ </div>`;
+ setTimeout(() => {
+ const f = document.getElementById('ec-tier-fill');
+ if (f) f.style.width = `${pct}%`;
+ }, 80);
+ } else if (cur == null) {
+ progress = `<p class="ec-muted" style="margin-top:18px;font-size:13px">Sign in and link a Solana wallet to see your tier and track progress to the next one.</p>`;
+ }
+ return `<div class="ec-tiers">${cards}</div>${progress}`;
}
-function catalogHTML(actions) {
+function catalogGroups(actions) {
const byCat = {};
for (const a of actions) (byCat[a.category] ||= []).push(a);
- const order = ['generation', 'data', 'scarcity', 'marketplace'];
- return order
+ return ['generation', 'data', 'scarcity', 'marketplace']
.filter((c) => byCat[c]?.length)
- .map((cat) => {
- const items = byCat[cat]
- .map((a) => {
- let price;
- if (a.usd == null) price = `<span class="price var">priced per item</span>`;
- else if (a.usd === 0) price = `<span class="price free">Free</span>`;
- else price = `<span class="price">${fmtUsd(a.usd)}</span>`;
- return `<div class="ec-item"><span class="label">${esc(a.label)}</span>${price}</div>`;
- })
- .join('');
- return `<div class="ec-cat"><h3>${esc(CATEGORY_LABELS[cat] || cat)}</h3><div class="ec-items">${items}</div></div>`;
- })
+ .map((cat) => ({ cat, label: CATEGORY_LABELS[cat] || cat, items: byCat[cat] }));
+}
+
+// ── page ──────────────────────────────────────────────────────────────────────
+function shell() {
+ return `
+ <div class="ec-wrap">
+ <div class="ec-top">
+ <a class="ec-pill" href="/"><span class="dot"></span>three.ws</a>
+ <a class="ec-pill" href="/three-token">$THREE price ↗</a>
+ </div>
+
+ <header class="ec-hero ec-reveal">
+ <span class="ec-badge">◆ $THREE · the only coin · zero burns</span>
+ <h1 class="ec-h1">An economy you can<br/>watch and verify.</h1>
+ <p class="ec-lede">You pay in $THREE only for real compute. Hold it for lower fees and bigger perks. <strong style="color:var(--ink)">30% of every compute fee goes straight back to holders</strong> — funded by real usage, never minted, never burned.</p>
+ <div class="ec-hero-stat" id="ec-hero-stat" aria-live="polite">
+ <div class="hs-num"><span data-roll>0</span> <span class="hs-sym">$THREE</span></div>
+ <div class="hs-lbl">returned to holders &amp; counting · 0 burned</div>
+ </div>
+ <div class="ec-cta">
+ <a class="ec-btn primary" href="/three-token">Get $THREE</a>
+ <a class="ec-btn" href="#tiers">See holder tiers</a>
+ </div>
+ </header>
+
+ <section class="ec-section ec-reveal" id="flow">
+ <p class="ec-htitle">The Flow</p>
+ <h2 class="ec-h2">Where every $THREE goes</h2>
+ <p class="ec-desc">Live. Each particle is value entering the protocol — it splits to the treasury, to creators, and rains back onto holders. There is no burn lane: nothing is destroyed.</p>
+ <div class="ec-flow-shell">
+ <button class="ec-flow-pause" id="ec-flow-pause" type="button" aria-pressed="false" aria-label="Pause the animation">❚❚ Pause</button>
+ <canvas class="ec-flow-canvas" id="ec-flow" role="img" aria-label="Live visualization of $THREE flowing from spends to treasury, creators, and holders"></canvas>
+ <div class="ec-flow-note">Lane width reflects the real split of settled volume.</div>
+ <div class="ec-flow-legend">
+ <span class="ec-leg"><span class="sw" style="background:var(--gold)"></span>Treasury → buybacks</span>
+ <span class="ec-leg"><span class="sw" style="background:var(--green)"></span>Holder rewards</span>
+ <span class="ec-leg"><span class="sw" style="background:var(--blue)"></span>Creators</span>
+ <span class="ec-leg ec-muted">No burn lane — supply is never destroyed.</span>
+ </div>
+ </div>
+ </section>
+
+ <section class="ec-section ec-reveal" id="stats">
+ <p class="ec-htitle">Live economy</p>
+ <h2 class="ec-h2">The numbers, settled on-chain</h2>
+ <div id="ec-stats" class="ec-stats">${'<div class="ec-stat ec-skel" style="height:96px"></div>'.repeat(5)}</div>
+ <p class="ec-stamp" id="ec-stamp" aria-live="polite">Loading live figures…</p>
+ </section>
+
+ <section class="ec-section ec-reveal" id="verify">
+ <p class="ec-htitle">Don't trust — verify</p>
+ <h2 class="ec-h2">The real wallets, on Solscan</h2>
+ <p class="ec-desc">No anonymous "trust us." The treasury and the holder-rewards pool are real Solana accounts. Open them and check the balances against the numbers above.</p>
+ <div id="ec-onchain"><div class="ec-wallets">${'<div class="ec-wallet ec-skel" style="height:108px"></div>'.repeat(2)}</div></div>
+ </section>
+
+ <section class="ec-section ec-reveal" id="reflected">
+ <p class="ec-htitle">Real yield, not burns</p>
+ <h2 class="ec-h2">Value returned to holders</h2>
+ <p class="ec-desc">Other tokens burn supply and call it a number. We route real usage fees back to holders pro-rata — never minted, never a tax on your transfers — and record every distribution on-chain. Drag the slider to see what a bag would have earned from past distributions.</p>
+ <div id="ec-reflected" class="ec-reflect"><div class="ec-card ec-skel" style="height:200px"></div><div class="ec-card ec-skel" style="height:200px"></div></div>
+ </section>
+
+ <section class="ec-section ec-reveal" id="tiers">
+ <p class="ec-htitle">Hold to unlock</p>
+ <h2 class="ec-h2">Holder tiers</h2>
+ <p class="ec-desc">Holding $THREE — not spending it — lowers your fees and raises your limits. The more you hold, the more you keep.</p>
+ <div id="ec-tiers"><div class="ec-tiers">${'<div class="ec-tier ec-skel" style="height:170px"></div>'.repeat(5)}</div></div>
+ </section>
+
+ <section class="ec-section ec-reveal" id="pricing">
+ <p class="ec-htitle">What you pay for</p>
+ <h2 class="ec-h2">Pricing explorer</h2>
+ <p class="ec-desc">Only real compute and genuinely scarce things cost $THREE. Pick one to see its price — and what your tier discount would make it. Everything else (creating, discovering, embedding, chatting, basic worlds, draft generation) is free forever.</p>
+ <div class="ec-px">
+ <div id="ec-px-list" class="ec-px-list">${'<div class="ec-skel" style="height:46px;margin:8px;border-radius:10px"></div>'.repeat(6)}</div>
+ <div id="ec-px-detail" class="ec-px-detail"><p class="ec-muted">Select an action to see its price.</p></div>
+ </div>
+ </section>
+
+ <section class="ec-section ec-reveal" id="names">
+ <p class="ec-htitle">Scarcity</p>
+ <h2 class="ec-h2">Rare name studio</h2>
+ <p class="ec-desc">Common <code>*.threews.sol</code> names mint free. Short, dictionary, and reserved names are rare — priced in $THREE by how rare they are.</p>
+ <div class="ec-name">
+ <input id="ec-name-input" type="text" placeholder="yourname" autocomplete="off" spellcheck="false" maxlength="63" aria-label="Check a name's rarity and price" />
+ <span class="suffix">.threews.sol</span>
+ </div>
+ <div class="ec-name-out" id="ec-name-out"><span class="ec-muted">Type a name to see its rarity and price.</span></div>
+ </section>
+
+ <section class="ec-section ec-reveal" id="catalog">
+ <p class="ec-htitle">Full price list</p>
+ <h2 class="ec-h2">Everything priced in $THREE</h2>
+ <div id="ec-catalog">${'<div class="ec-skel" style="height:46px;margin-bottom:9px;border-radius:12px"></div>'.repeat(6)}</div>
+ </section>
+
+ <div class="ec-foot">$THREE is the only coin three.ws references. Contract <code>${MINT}</code>. Prices shown in USD settle in $THREE at the live market price. No burns — ever.</div>
+ </div>`;
+}
+
+// ── interactivity ───────────────────────────────────────────────────────────
+
+let LIVE_PRICE = 0; // $THREE/USD, fetched once for conversions
+let DISCOUNT_BPS = 0; // current holder's tier discount
+
+function discountedUsd(usd) {
+ if (!(usd > 0) || DISCOUNT_BPS <= 0) return usd;
+ return Math.max(0.01, Math.round(usd * (10000 - DISCOUNT_BPS)) / 10000);
+}
+const usdToThree = (usd) => (LIVE_PRICE > 0 && usd > 0 ? usd / LIVE_PRICE : null);
+
+function renderPriceDetail(action) {
+ const el = document.getElementById('ec-px-detail');
+ if (!el) return;
+ if (action.usd == null) {
+ el.innerHTML = `<div class="dt">${esc(action.label)}</div>
+ <p class="ec-muted" style="margin-top:12px">Priced per item — set by the seller (marketplace) or by rarity (scarcity). 90% goes to the creator on a sale; the rest splits to treasury and holder rewards.</p>`;
+ return;
+ }
+ if (action.usd === 0) {
+ el.innerHTML = `<div class="dt">${esc(action.label)}</div><p style="margin-top:12px;color:var(--green);font-weight:600">Free forever.</p>`;
+ return;
+ }
+ const full = action.usd;
+ const yours = discountedUsd(full);
+ const saved = full - yours;
+ const three = usdToThree(yours);
+ el.innerHTML = `<div class="dt">${esc(action.label)}</div>
+ <div class="ec-px-row"><span>List price</span><span class="val">${fmtUsd(full)}</span></div>
+ <div class="ec-px-row"><span>Your tier price${DISCOUNT_BPS > 0 ? ` <span class="ec-muted">(−${(DISCOUNT_BPS / 100).toFixed(0)}%)</span>` : ''}</span><span class="val${saved > 0 ? ' save' : ''}">${fmtUsd(yours)}</span></div>
+ ${saved > 0 ? `<div class="ec-px-row"><span>You save</span><span class="val save">${fmtUsd(saved)}</span></div>` : ''}
+ <div class="ec-px-row"><span>Settles in</span><span class="val ec-px-three">${three != null ? `≈ ${fmtCompact(three)} $THREE` : 'live $THREE'}</span></div>
+ <p class="ec-muted" style="margin-top:14px;font-size:12.5px">Splits 70% treasury / 30% holder rewards. ${DISCOUNT_BPS > 0 ? 'Your discount is applied automatically at checkout.' : 'Hold $THREE to unlock a tier discount on this.'}</p>`;
+}
+
+function wirePricing(actions) {
+ const list = document.getElementById('ec-px-list');
+ if (!list) return;
+ const groups = catalogGroups(actions);
+ list.innerHTML = groups
+ .map(
+ (g) =>
+ `<div class="ec-px-cat">${esc(g.label)}</div>` +
+ g.items
+ .map((a, i) => {
+ const price =
+ a.usd == null ? `<span class="pp var">per item</span>` : a.usd === 0 ? `<span class="pp free">Free</span>` : `<span class="pp">${fmtUsd(a.usd)}</span>`;
+ return `<button class="ec-px-item" data-id="${esc(a.id)}"><span class="pl">${esc(a.label)}</span>${price}</button>`;
+ })
+ .join(''),
+ )
.join('');
+ const byId = Object.fromEntries(actions.map((a) => [a.id, a]));
+ const buttons = [...list.querySelectorAll('.ec-px-item')];
+ const select = (btn) => {
+ buttons.forEach((b) => b.classList.toggle('sel', b === btn));
+ renderPriceDetail(byId[btn.dataset.id]);
+ };
+ buttons.forEach((b) => b.addEventListener('click', () => select(b)));
+ // Auto-select the first paid action so the detail panel isn't empty.
+ const firstPaid = buttons.find((b) => byId[b.dataset.id]?.usd > 0) || buttons[0];
+ if (firstPaid) select(firstPaid);
}
-// ── rare-name lookup ────────────────────────────────────────────────────────
-function wireNameLookup(root) {
+function wireProjector(stats) {
+ const range = document.getElementById('ec-proj-range');
+ const out = document.getElementById('ec-proj-out');
+ if (!range || !out) return;
+ const dec = stats?.token?.decimals ?? 6;
+ const reflectedTotal = atomicsToTokens(stats?.reflected?.total_atomics ?? '0', dec);
+ // Eligible supply from the most recent run (best estimate of the holder base).
+ const recent = stats?.reflected?.recent?.[0];
+ const eligibleSupply = recent ? atomicsToTokens(recent.eligible_supply_atomics ?? '0', dec) : 0;
+ // Map slider 0–6 to a $THREE bag on a log scale (1 → 1,000,000).
+ const update = () => {
+ const v = Number(range.value);
+ const bag = Math.round(Math.pow(10, v));
+ const bagUsd = LIVE_PRICE > 0 ? bag * LIVE_PRICE : null;
+ let earned = null;
+ 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>`);
+ };
+ range.addEventListener('input', update);
+ update();
+}
+
+function wireNameStudio(root) {
const input = root.querySelector('#ec-name-input');
const out = root.querySelector('#ec-name-out');
if (!input || !out) return;
+ const RANK = { common: 0.18, uncommon: 0.42, rare: 0.64, epic: 0.84, legendary: 1 };
let timer = null;
let seq = 0;
const run = async () => {
const name = input.value.trim();
if (!name) {
- out.innerHTML = '<span class="ec-muted">Type a name to check its rarity and price.</span>';
+ out.innerHTML = '<span class="ec-muted">Type a name to see its rarity and price.</span>';
return;
}
const mine = ++seq;
- out.innerHTML = '<span class="ec-muted">Checking…</span>';
try {
const q = await getJSON(`${API}/name-quote?name=${encodeURIComponent(name)}`);
- if (mine !== seq) return; // a newer keystroke superseded this
- const rarity = `<span class="ec-rarity r-${esc(q.rarity)}">${esc(q.rarity_label)}</span>`;
- if (q.free) {
- out.innerHTML = `${rarity}<strong>${esc(q.full_name)}</strong> — <span style="color:#7ee787">free to mint</span> <span class="ec-muted">(common name)</span>`;
- } else {
- const tokens = q.three ? `${fmtCompact(q.three.token_amount)} $THREE` : '';
- out.innerHTML = `${rarity}<strong>${esc(q.full_name)}</strong> — ${fmtUsd(q.usd)} <span class="ec-muted">≈ ${esc(tokens)} · ${esc(q.reasons.join(', '))}</span>`;
- }
+ if (mine !== seq) return;
+ const pct = (RANK[q.rarity] || 0.18) * 100;
+ const color = q.free ? 'var(--muted)' : `var(--${q.rarity === 'legendary' ? 'violet' : q.rarity === 'epic' ? 'blue' : q.rarity === 'rare' ? 'green' : 'gold'})`;
+ const priceLine = q.free
+ ? `<span style="color:var(--green);font-weight:700">Free to mint</span> <span class="ec-muted">— common name</span>`
+ : `<strong>${fmtUsd(q.usd)}</strong> <span class="ec-muted">${q.three ? `≈ ${fmtCompact(q.three.token_amount)} $THREE` : ''}</span>`;
+ out.innerHTML = `
+ <div class="ec-rare-head">
+ <span class="ec-rarity r-${esc(q.rarity)}">${esc(q.rarity_label)}</span>
+ <strong style="font-family:ui-monospace,Menlo,monospace">${esc(q.full_name)}</strong>
+ </div>
+ <div class="ec-rare-meter"><div class="ec-rare-fill" style="width:${pct}%;background:${color}"></div></div>
+ <div style="font-size:14px">${priceLine}</div>
+ <div class="ec-muted" style="font-size:12.5px;margin-top:6px">${esc((q.reasons || []).join(' · '))}</div>`;
} catch (e) {
if (mine !== seq) return;
out.innerHTML =
e.code === 'invalid_label'
- ? '<span class="ec-err" style="display:inline-block;padding:6px 10px">Use letters, digits, and hyphens only.</span>'
- : '<span class="ec-muted">Couldn\'t price that name — try again.</span>';
+ ? '<div class="ec-err">Use letters, digits, and hyphens only (no leading/trailing hyphen).</div>'
+ : '<span class="ec-muted">Couldn\'t price that name — try again in a moment.</span>';
}
};
input.addEventListener('input', () => {
clearTimeout(timer);
- timer = setTimeout(run, 280);
+ timer = setTimeout(run, 260);
});
}
-// ── render ──────────────────────────────────────────────────────────────────
-function shell() {
- return `
- <div class="ec-wrap">
- <div class="ec-top">
- <a class="ec-back" href="/">← three.ws</a>
- <a class="ec-back" href="/three-token">$THREE price ↗</a>
- </div>
- ${heroHTML()}
- <div class="ec-section" id="stats"><h2>Live economy</h2><p class="ec-desc">Settled on-chain through the $THREE rail. No burns — every spend reflects to holders or funds buybacks.</p><div id="ec-stats"><div class="ec-grid ec-stats">${'<div class="ec-stat ec-skel" style="height:84px"></div>'.repeat(5)}</div></div></div>
- <div class="ec-section" id="verify"><h2>Verify on-chain</h2><p class="ec-desc">No anonymous "trust us." The treasury and the holder-rewards pool are real Solana wallets — open them on Solscan and check the balances against the numbers above.</p><div id="ec-onchain"><div class="ec-grid ec-wallets">${'<div class="ec-wallet ec-skel" style="height:96px"></div>'.repeat(2)}</div></div></div>
- <div class="ec-section" id="reflected"><h2>Reflected to holders</h2><p class="ec-desc">We never burn supply. The rewards pool is distributed pro-rata back to $THREE holders — value returned, not destroyed. Every run is recorded here.</p><div id="ec-reflected"><div class="ec-skel" style="height:80px"></div></div></div>
- <div class="ec-section" id="tiers"><h2>Holder tiers</h2><div id="ec-tiers"><div class="ec-grid ec-tiers">${'<div class="ec-tier ec-skel" style="height:150px"></div>'.repeat(5)}</div></div></div>
- <div class="ec-section" id="names"><h2>Rare names</h2><p class="ec-desc">Common <code>*.threews.sol</code> names are free. Short, dictionary, and reserved names are rare — priced in $THREE.</p>
- <div class="ec-name"><input id="ec-name-input" type="text" placeholder="yourname" autocomplete="off" spellcheck="false" maxlength="63" aria-label="Check a name's rarity" /></div>
- <div class="ec-name-out" id="ec-name-out"><span class="ec-muted">Type a name to check its rarity and price.</span></div>
- </div>
- <div class="ec-section" id="pricing"><h2>What you pay for</h2><p class="ec-desc">Only things that cost real compute or are genuinely scarce. Everything else — creating, discovering, embedding, chatting, basic worlds, draft generation — is free forever.</p><div id="ec-catalog"><div class="ec-grid ec-items">${'<div class="ec-item ec-skel" style="height:46px"></div>'.repeat(8)}</div></div></div>
- <div class="ec-foot">$THREE is the only coin three.ws references. Contract <code>FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump</code>. Prices shown in USD settle in $THREE at the live market price.</div>
- </div>`;
-}
-
-async function load() {
+// ── load orchestration ─────────────────────────────────────────────────────────
+async function load(root) {
const setErr = (id, msg) => {
const el = document.getElementById(id);
if (el) el.innerHTML = `<div class="ec-err">${esc(msg)}</div>`;
};
- // Stats + catalog are public; tier needs auth (gracefully optional). One stats
- // fetch feeds three panels: the headline cards, the verifiable wallets, and the
- // reflected-to-holders history.
+ // Live $THREE price (for conversions) — best-effort, non-blocking.
+ getJSON('/api/token/price')
+ .then((p) => {
+ LIVE_PRICE = Number(p?.price_usd) || 0;
+ })
+ .catch(() => {});
+
+ // Stats drive the flow viz, the stat band, on-chain wallets, reflections + projector.
getJSON(`${API}/stats`)
.then((s) => {
- const stats = document.getElementById('ec-stats');
- if (stats) stats.innerHTML = statsHTML(s);
- const onchain = document.getElementById('ec-onchain');
- if (onchain) onchain.innerHTML = onchainHTML(s);
- const reflected = document.getElementById('ec-reflected');
- if (reflected) reflected.innerHTML = reflectedHTML(s);
+ const band = document.getElementById('ec-stats');
+ if (band) {
+ band.innerHTML = statCards(s)
+ .map(
+ (c) =>
+ `<div class="ec-stat" style="--accent:${c.accent}"><div class="v" style="--accent:${c.accent}"><span data-roll>0</span>${c.sym ? '<span class="sym">$THREE</span>' : ''}</div><div class="k">${esc(c.k)}</div></div>`,
+ )
+ .join('');
+ const cards = statCards(s);
+ band.querySelectorAll('[data-roll]').forEach((el, i) => {
+ rollup(el, cards[i].v, cards[i].sym ? fmtCompact : (n) => Math.round(n).toLocaleString('en-US'));
+ });
+ }
+ // Hero north-star metric: total $THREE returned to holders.
+ const heroEl = document.querySelector('#ec-hero-stat [data-roll]');
+ if (heroEl) {
+ const dec = s?.token?.decimals ?? 6;
+ rollup(heroEl, atomicsToTokens(s?.reflected?.total_atomics ?? '0', dec), fmtCompact, 1400);
+ }
+ const oc = document.getElementById('ec-onchain');
+ if (oc) oc.innerHTML = onchainHTML(s);
+ const rf = document.getElementById('ec-reflected');
+ if (rf) {
+ rf.innerHTML = reflectedHTML(s);
+ wireProjector(s);
+ }
+ // Trust stamp: when the data is from and where it comes from.
+ const stamp = document.getElementById('ec-stamp');
+ if (stamp) {
+ const when = new Date().toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
+ stamp.textContent = `Updated ${when} · source: Solana RPC + settle ledger`;
+ }
+ if (window._ecFlow) window._ecFlow.seed(s);
})
.catch(() => {
setErr('ec-stats', 'Economy stats are temporarily unavailable.');
@@ -344,47 +973,111 @@ async function load() {
getJSON(`${API}/catalog`)
.then((c) => {
- const el = document.getElementById('ec-catalog');
- if (el) el.innerHTML = catalogHTML(c.actions || []);
+ const actions = c.actions || [];
+ wirePricing(actions);
+ const cat = document.getElementById('ec-catalog');
+ if (cat) {
+ cat.innerHTML = catalogGroups(actions)
+ .map(
+ (g) =>
+ `<div class="ec-cat"><h3>${esc(g.label)}</h3><div class="ec-items">${g.items
+ .map((a) => {
+ const price = a.usd == null ? `<span class="price var">per item</span>` : a.usd === 0 ? `<span class="price free">Free</span>` : `<span class="price">${fmtUsd(a.usd)}</span>`;
+ return `<div class="ec-item"><span class="label">${esc(a.label)}</span>${price}</div>`;
+ })
+ .join('')}</div></div>`,
+ )
+ .join('');
+ }
})
- .catch(() => setErr('ec-catalog', 'Price catalog is temporarily unavailable.'));
+ .catch(() => {
+ setErr('ec-px-list', 'Price catalog is temporarily unavailable.');
+ setErr('ec-catalog', 'Price catalog is temporarily unavailable.');
+ });
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);
+ // Re-render the price detail now that the discount is known.
+ const sel = document.querySelector('.ec-px-item.sel');
+ if (sel) sel.click();
})
- .catch(async (e) => {
- // 401 isn't an error here — show the ladder without a "current" tier.
+ .catch((e) => {
if (e.status === 401 || e.status === 403) {
- try {
- const c = await getJSON(`${API}/catalog`); // cheap warm call already cached
- void c;
- } catch {
- /* ignore */
- }
- // Re-render the ladder from the public stats endpoint's perspective:
- // fetch tier ladder anonymously is not available, so render a sign-in prompt
- // plus the static ladder shape from a tier-pass-less call is impossible;
- // instead show the prompt — the ladder fills once signed in.
const el = document.getElementById('ec-tiers');
+ // Render the ladder without a "current" marker, plus a sign-in nudge.
if (el)
- el.innerHTML =
- '<p class="ec-desc">Sign in and link a Solana wallet to see your tier and unlock holder perks.</p>';
+ el.innerHTML = tiersHTML({
+ ladder: DEFAULT_LADDER,
+ tier: null,
+ next: null,
+ });
} else {
setErr('ec-tiers', 'Tier info is temporarily unavailable.');
}
});
+
+ wireNameStudio(root);
}
+// Static ladder shape so a signed-out visitor still sees the tiers (the live
+// endpoint returns the authoritative copy; this mirrors api/_lib/three-tier.js).
+const DEFAULT_LADDER = [
+ { level: 0, id: 'member', label: 'Member', min_usd: 0, discount_bps: 0, perks: ['Everything free-forever: create, discover, embed, social, basic worlds'] },
+ { level: 1, id: 'bronze', label: 'Bronze', min_usd: 25, discount_bps: 500, perks: ['5% off all $THREE compute', '2× free generation quota', 'Bronze profile badge'] },
+ { level: 2, id: 'silver', label: 'Silver', min_usd: 100, discount_bps: 1000, perks: ['10% off all $THREE compute', '3× free generation quota', 'Private worlds', 'Priority MCP routing'] },
+ { level: 3, id: 'gold', label: 'Gold', min_usd: 500, discount_bps: 2000, perks: ['20% off all $THREE compute', '5× free generation quota', 'Branded worlds', 'Early access to drops'] },
+ { level: 4, id: 'genesis', label: 'Genesis', min_usd: 2500, discount_bps: 3000, perks: ['30% off all $THREE compute', '10× free generation quota', 'First dibs on rare names', 'Genesis-only cosmetics'] },
+];
+
function init() {
injectStyles();
document.title = 'The $THREE economy · three.ws';
const root = document.createElement('main');
root.innerHTML = shell();
document.body.appendChild(root);
- wireNameLookup(root);
- load();
+
+ // The Flow: start it, and pause when offscreen to save battery/CPU.
+ const canvas = document.getElementById('ec-flow');
+ if (canvas) {
+ const flow = new FlowViz(canvas);
+ window._ecFlow = flow;
+ flow.start();
+ if (typeof IntersectionObserver === 'function' && !REDUCED_MOTION) {
+ new IntersectionObserver(
+ (entries) => {
+ for (const e of entries) {
+ if (e.isIntersecting) flow.start();
+ else flow.stop();
+ }
+ },
+ { threshold: 0.01 },
+ ).observe(canvas);
+ }
+ // WCAG 2.2.2 Pause/Stop/Hide — a control for the perpetual motion.
+ const pauseBtn = document.getElementById('ec-flow-pause');
+ if (pauseBtn) {
+ if (REDUCED_MOTION) pauseBtn.style.display = 'none'; // nothing animating to pause
+ pauseBtn.addEventListener('click', () => {
+ flow.userPaused = !flow.userPaused;
+ pauseBtn.setAttribute('aria-pressed', String(flow.userPaused));
+ if (flow.userPaused) {
+ flow.stop();
+ pauseBtn.innerHTML = '▶ Play';
+ pauseBtn.setAttribute('aria-label', 'Play the animation');
+ } else {
+ pauseBtn.innerHTML = '❚❚ Pause';
+ pauseBtn.setAttribute('aria-label', 'Pause the animation');
+ flow.start();
+ }
+ });
+ }
+ }
+
+ observeReveal(root);
+ load(root);
}
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init);
diff --git a/vercel.json b/vercel.json
index aa850b10a..001f628f7 100644
--- a/vercel.json
+++ b/vercel.json
@@ -708,6 +708,10 @@
"src": "/launchpad/?",
"dest": "/launchpad.html"
},
+ {
+ "src": "/launch/?",
+ "dest": "/launch.html"
+ },
{
"src": "/next/?",
"dest": "/next/index.html"
diff --git a/vite.config.js b/vite.config.js
index e02ebe94c..70feffdc9 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -285,6 +285,7 @@ const appConfig = {
'embed-demo': resolve(__dirname, 'pages/embed-demo.html'),
widget: resolve(__dirname, 'pages/widget.html'),
launchpad: resolve(__dirname, 'pages/launchpad.html'),
+ launch: resolve(__dirname, 'pages/launch.html'),
start: resolve(__dirname, 'pages/start.html'),
create: resolve(__dirname, 'pages/create.html'),
'create-agent': resolve(__dirname, 'pages/create-agent.html'),
@@ -733,6 +734,8 @@ support: resolve(__dirname, 'pages/support.html'),
'/launch-week/': resolve(root, 'pages/three-ws-launch-week.html'),
'/launchpad': resolve(root, 'pages/launchpad.html'),
'/launchpad/': resolve(root, 'pages/launchpad.html'),
+ '/launch': resolve(root, 'pages/launch.html'),
+ '/launch/': resolve(root, 'pages/launch.html'),
'/p': resolve(root, 'public/p/index.html'),
'/p/': resolve(root, 'public/p/index.html'),
'/eth-vanity': resolve(root, 'public/eth-vanity.html'),
diff --git a/workers/agent-sniper/intel/classify.js b/workers/agent-sniper/intel/classify.js
new file mode 100644
index 000000000..69c6ffcd9
--- /dev/null
+++ b/workers/agent-sniper/intel/classify.js
@@ -0,0 +1,145 @@
+// Coin Intelligence — classification. Answers "what kind of coin is this?"
+//
+// Category: meme | tech | ai | culture | community | political | news | animal |
+// celebrity | utility | unknown
+//
+// Two 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.
+
+import { llmComplete } from '../../../api/_lib/llm.js';
+
+const CATEGORIES = [
+ 'meme', 'tech', 'ai', 'culture', 'community',
+ 'political', 'news', 'animal', 'celebrity', 'utility', 'unknown',
+];
+
+// Ordered keyword tables — first strong hit wins for the heuristic seed. Lower
+// tables are weaker; AI is checked before tech (it's a tech subtype we surface
+// separately), animal before meme (animals are usually memes but worth tagging).
+const KEYWORDS = [
+ ['ai', /\b(ai|artificial intelligence|gpt|llm|agent|neural|machine learning|ml|model|inference|gpu|compute)\b/i],
+ ['animal', /\b(dog|doge|shib|inu|cat|kitty|frog|pepe|monkey|ape|bear|bull|penguin|hippo|capybara|wolf|fox|duck|goat|hamster)\b/i],
+ ['political', /\b(trump|biden|maga|election|president|senator|congress|vote|government|liberty|freedom|patriot|democrat|republican)\b/i],
+ ['celebrity', /\b(elon|musk|kanye|drake|taylor|swift|messi|ronaldo|kardashian|mrbeast|celebrity)\b/i],
+ ['tech', /\b(protocol|chain|defi|stake|staking|yield|swap|dex|node|validator|zk|rollup|layer|infra|sdk|oracle|bridge)\b/i],
+ ['utility', /\b(tool|utility|payment|pay|wallet|launchpad|scanner|tracker|bot|dashboard|api)\b/i],
+ ['culture', /\b(culture|art|music|fashion|sport|game|gaming|movie|anime|meme culture|lifestyle|vibe)\b/i],
+ ['community', /\b(community|dao|family|gang|army|holders|together|movement|cult|society|club)\b/i],
+];
+
+function tokenize(text) {
+ return (text || '')
+ .toLowerCase()
+ .replace(/[^a-z0-9\s]/g, ' ')
+ .split(/\s+/)
+ .filter((w) => w.length >= 3 && w.length <= 20);
+}
+
+/**
+ * Instant deterministic classification. Always returns a result.
+ * @returns {{ category: string, tags: string[], confidence: number, source: 'heuristic' }}
+ */
+export function heuristicClassify({ name, symbol, description } = {}) {
+ const haystack = `${name || ''} ${symbol || ''} ${description || ''}`;
+ for (const [cat, re] of KEYWORDS) {
+ const m = haystack.match(re);
+ if (m) {
+ return {
+ category: cat,
+ tags: [m[0].toLowerCase()].filter(Boolean),
+ confidence: 0.45,
+ source: 'heuristic',
+ };
+ }
+ }
+ // No keyword hit: short tickers with descriptions read as memes; otherwise unknown.
+ const words = tokenize(`${name} ${description}`);
+ return {
+ category: words.length ? 'meme' : 'unknown',
+ tags: [],
+ confidence: words.length ? 0.3 : 0.15,
+ source: 'heuristic',
+ };
+}
+
+const SYSTEM = `You are a pump.fun coin classifier. Given a coin's name, symbol, and description, classify it precisely. Be literal and grounded — do not hype. Output ONLY strict JSON, no prose.`;
+
+function buildUser({ name, symbol, description, twitter, telegram, website }) {
+ return `Classify this pump.fun coin.
+
+Name: ${name || '(none)'}
+Symbol: ${symbol || '(none)'}
+Description: ${description || '(none)'}
+Has socials: ${[twitter && 'twitter', telegram && 'telegram', website && 'website'].filter(Boolean).join(', ') || 'none'}
+
+Output strict JSON:
+{
+ "category": one of ${JSON.stringify(CATEGORIES)},
+ "is_news_meme": boolean, // true if it references a current/recent news story or trending event
+ "tags": ["3-6 short lowercase tags"],
+ "narrative": "one literal sentence: what this coin is about and why someone made it",
+ "confidence": 0.0-1.0
+}
+
+Rules: pick the single best category. "ai" for AI/agent themes, "tech" for protocol/defi/infra, "animal" for animal mascots, "meme" only when nothing more specific fits. Never invent facts not implied by the inputs.`;
+}
+
+function coerceCategory(c) {
+ const v = String(c || '').toLowerCase().trim();
+ return CATEGORIES.includes(v) ? v : 'unknown';
+}
+
+function parseJson(text) {
+ if (!text) return null;
+ // Tolerate code fences / leading prose.
+ const match = text.match(/\{[\s\S]*\}/);
+ if (!match) return null;
+ try { return JSON.parse(match[0]); } catch { return null; }
+}
+
+/**
+ * Full classification: heuristic seed, then LLM refinement when available.
+ * Always resolves to a usable record — never throws.
+ *
+ * @returns {Promise<{category, tags, narrative, is_news_meme, confidence, source}>}
+ */
+export async function classifyCoin(coin = {}, { timeoutMs = 12_000 } = {}) {
+ const seed = heuristicClassify(coin);
+
+ // Nothing to feed an LLM with — keep the heuristic.
+ if (!coin.name && !coin.symbol && !coin.description) {
+ return { ...seed, narrative: null, is_news_meme: false };
+ }
+
+ try {
+ const raw = await 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 };
+
+ 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);
+ return {
+ category: coerceCategory(parsed.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,
+ source: 'llm',
+ };
+ } catch {
+ // LLM unavailable / timed out — heuristic stands. Never block the pipeline.
+ return { ...seed, narrative: null, is_news_meme: false };
+ }
+}
+
+export const _internals = { CATEGORIES, KEYWORDS, tokenize };
diff --git a/workers/agent-sniper/intel/signals.js b/workers/agent-sniper/intel/signals.js
new file mode 100644
index 000000000..218b3c35a
--- /dev/null
+++ b/workers/agent-sniper/intel/signals.js
@@ -0,0 +1,334 @@
+// Coin Intelligence — signal computation. Pure, no I/O, fully deterministic.
+//
+// Given an `observation` of a pump.fun coin's first seconds of trading, derive
+// the signals that separate organic launches from bundles, sniper swarms, and
+// dev dumps. Every number traces to a real observed trade — nothing is invented.
+// Signals that need data we may not have (wallet age, funding source) return
+// `null` rather than a fabricated value (Rule 1).
+//
+// Observation shape (built by watcher.js):
+// {
+// mint, symbol, name, creator,
+// createdAtMs, // coin creation (best-effort, from feed)
+// firstSeenAtMs, // when we started observing
+// endedAtMs, // when the window closed
+// devBuyLamports, // creator's initial buy (lamports) | null
+// trades: [ { // every buy/sell observed, in arrival order
+// trader, isBuy, lamports, baseAmount, ts (ms), signature
+// } ],
+// walletMeta?: Map<wallet, { ageMs?, funder?, priorTxCount? }> // optional RPC enrichment
+// }
+//
+// Returns a structured signals object plus a 0..100 quality score and risk flags.
+
+const LAMPORTS_PER_SOL = 1_000_000_000;
+
+// Window (ms from first trade) we treat as the "launch burst" — bundles and
+// snipers pile in here. We measure from the first observed trade, not from
+// createdAtMs, because feed delivery jitter makes absolute creation time noisy;
+// relative arrival ordering is reliable.
+const BURST_MS = 3_000;
+const SNIPE_MS = 5_000;
+
+function lamportsToSol(l) {
+ const n = Number(l);
+ return Number.isFinite(n) ? n / LAMPORTS_PER_SOL : 0;
+}
+
+function sum(arr) {
+ let s = 0;
+ for (const x of arr) s += x;
+ return s;
+}
+
+function median(nums) {
+ if (!nums.length) return 0;
+ const s = [...nums].sort((a, b) => a - b);
+ const mid = s.length >> 1;
+ return s.length % 2 ? s[mid] : (s[mid - 1] + s[mid]) / 2;
+}
+
+function clamp01(x) {
+ if (!Number.isFinite(x)) return 0;
+ return x < 0 ? 0 : x > 1 ? 1 : x;
+}
+
+function round(x, places = 4) {
+ if (!Number.isFinite(x)) return null;
+ const f = 10 ** places;
+ return Math.round(x * f) / f;
+}
+
+// Shannon entropy of a distribution, normalized to 0..1 against log(n). High
+// entropy = evenly spread (organic); low = concentrated/clustered (coordinated).
+function normalizedEntropy(counts) {
+ const total = sum(counts);
+ if (total <= 0 || counts.length <= 1) return 0;
+ let h = 0;
+ for (const c of counts) {
+ if (c <= 0) continue;
+ const p = c / total;
+ h -= p * Math.log(p);
+ }
+ return clamp01(h / Math.log(counts.length));
+}
+
+/**
+ * Aggregate per-wallet activity from the trade list.
+ * @returns Map<wallet, { buyCount, sellCount, buyLamports, sellLamports, baseBought, baseSold, firstTs, lastTs }>
+ */
+export function aggregateWallets(trades) {
+ const m = new Map();
+ for (const t of trades) {
+ if (!t.trader) continue;
+ let w = m.get(t.trader);
+ if (!w) {
+ w = { buyCount: 0, sellCount: 0, buyLamports: 0, sellLamports: 0, baseBought: 0, baseSold: 0, firstTs: t.ts, lastTs: t.ts };
+ m.set(t.trader, w);
+ }
+ const lp = Number(t.lamports) || 0;
+ const base = Number(t.baseAmount) || 0;
+ if (t.isBuy) { w.buyCount++; w.buyLamports += lp; w.baseBought += base; }
+ else { w.sellCount++; w.sellLamports += lp; w.baseSold += base; }
+ if (t.ts < w.firstTs) w.firstTs = t.ts;
+ if (t.ts > w.lastTs) w.lastTs = t.ts;
+ }
+ return m;
+}
+
+/**
+ * Detect the launch-burst bundle signature: many distinct wallets buying within
+ * the first BURST_MS with tightly-clustered sizes. Returns 0..1.
+ *
+ * Three independent tells, blended:
+ * - burst density: share of all buys that hit in the opening burst
+ * - size clustering: largest near-identical-amount cluster among burst buys
+ * - wallet multiplicity: many distinct wallets in the burst (a real degen
+ * rush has them too, so this only amplifies the other two, never alone)
+ */
+export function bundleScore(trades) {
+ const buys = trades.filter((t) => t.isBuy);
+ if (buys.length < 4) return 0;
+ const t0 = Math.min(...buys.map((b) => b.ts));
+ const burst = buys.filter((b) => b.ts - t0 <= BURST_MS);
+ if (burst.length < 4) return 0;
+
+ const burstDensity = burst.length / buys.length;
+
+ // Size clustering: bucket burst buy sizes to 2 sig-figs of SOL and find the
+ // largest bucket. Bots fund identical amounts; humans don't.
+ const buckets = new Map();
+ for (const b of burst) {
+ const sol = lamportsToSol(b.lamports);
+ if (sol <= 0) continue;
+ // round to 2 significant figures
+ const mag = sol === 0 ? 0 : Math.floor(Math.log10(Math.abs(sol)));
+ const f = 10 ** (mag - 1);
+ const key = f > 0 ? Math.round(sol / f) * f : sol;
+ buckets.set(key, (buckets.get(key) || 0) + 1);
+ }
+ const largestBucket = buckets.size ? Math.max(...buckets.values()) : 0;
+ const clustering = burst.length ? largestBucket / burst.length : 0;
+
+ const distinctBurstWallets = new Set(burst.map((b) => b.trader)).size;
+ const walletMultiplier = distinctBurstWallets >= 5 ? 1 : distinctBurstWallets / 5;
+
+ // Blend: density and clustering are the real signal; wallet count amplifies.
+ const raw = (burstDensity * 0.5 + clustering * 0.5) * (0.6 + 0.4 * walletMultiplier);
+ return round(clamp01(raw));
+}
+
+/**
+ * Bubblemap connectivity: share of distinct buyer wallets funded from a common
+ * source. Requires walletMeta with `funder`. Returns null when unavailable —
+ * never a fabricated number.
+ */
+export function bubblemapConnectivity(walletAgg, walletMeta) {
+ if (!walletMeta || walletMeta.size === 0) return null;
+ const funders = new Map();
+ let known = 0;
+ for (const wallet of walletAgg.keys()) {
+ const meta = walletMeta.get(wallet);
+ const f = meta?.funder;
+ if (!f) continue;
+ known++;
+ funders.set(f, (funders.get(f) || 0) + 1);
+ }
+ if (known < 3) return null;
+ const biggestCluster = Math.max(...funders.values());
+ return round(clamp01(biggestCluster / known));
+}
+
+/**
+ * Fresh-wallet ratio: share of buyers whose wallet had ~no prior history.
+ * Requires walletMeta with priorTxCount. Null when unavailable.
+ */
+export function freshWalletRatio(walletAgg, walletMeta) {
+ if (!walletMeta || walletMeta.size === 0) return null;
+ let known = 0;
+ let fresh = 0;
+ for (const wallet of walletAgg.keys()) {
+ const meta = walletMeta.get(wallet);
+ if (meta?.priorTxCount == null) continue;
+ known++;
+ if (meta.priorTxCount <= 1) fresh++;
+ }
+ if (known < 3) return null;
+ return round(fresh / known);
+}
+
+/**
+ * The full signal computation. Returns a structured object.
+ */
+export function computeSignals(observation) {
+ const trades = Array.isArray(observation.trades) ? observation.trades : [];
+ const walletAgg = aggregateWallets(trades);
+
+ const buys = trades.filter((t) => t.isBuy);
+ const sells = trades.filter((t) => !t.isBuy);
+ const buyLamports = sum(buys.map((b) => Number(b.lamports) || 0));
+ const sellLamports = sum(sells.map((s) => Number(s.lamports) || 0));
+
+ const uniqueBuyers = new Set(buys.map((b) => b.trader).filter(Boolean)).size;
+ const uniqueSellers = new Set(sells.map((s) => s.trader).filter(Boolean)).size;
+ const uniqueTraders = walletAgg.size;
+
+ const buySols = buys.map((b) => lamportsToSol(b.lamports)).filter((x) => x > 0);
+ const largestBuyLamports = buys.length ? Math.max(...buys.map((b) => Number(b.lamports) || 0)) : 0;
+ const avgBuySol = buySols.length ? sum(buySols) / buySols.length : 0;
+ const medianBuySol = median(buySols);
+
+ // Snipe ratio: share of buy volume that landed in the first SNIPE_MS.
+ let snipeRatio = 0;
+ if (buys.length && buyLamports > 0) {
+ const t0 = Math.min(...buys.map((b) => b.ts));
+ const early = sum(buys.filter((b) => b.ts - t0 <= SNIPE_MS).map((b) => Number(b.lamports) || 0));
+ snipeRatio = clamp01(early / buyLamports);
+ }
+
+ // Concentration: per-wallet NET buy (buy − sell, floored at 0) share of total.
+ const netBuys = [];
+ for (const w of walletAgg.values()) {
+ const net = Math.max(0, w.buyLamports - w.sellLamports);
+ if (net > 0) netBuys.push(net);
+ }
+ netBuys.sort((a, b) => b - a);
+ const totalNet = sum(netBuys) || 0;
+ const shareOfTop = (k) => (totalNet > 0 ? clamp01(sum(netBuys.slice(0, k)) / totalNet) : 0);
+ const concentrationTop1 = shareOfTop(1);
+ const concentrationTop5 = shareOfTop(5);
+ const concentrationTop10 = shareOfTop(10);
+
+ // Arrival-time entropy across 1s buckets — organic flow is spread out.
+ let timingEntropy = 0;
+ if (buys.length > 2) {
+ const t0 = Math.min(...buys.map((b) => b.ts));
+ const span = Math.max(1, Math.max(...buys.map((b) => b.ts)) - t0);
+ const bucketCount = Math.min(30, Math.max(2, Math.ceil(span / 1000)));
+ const counts = new Array(bucketCount).fill(0);
+ for (const b of buys) {
+ const idx = Math.min(bucketCount - 1, Math.floor(((b.ts - t0) / span) * bucketCount));
+ counts[idx]++;
+ }
+ timingEntropy = normalizedEntropy(counts);
+ }
+
+ // Dev behavior.
+ const devBuyLamports = observation.devBuyLamports != null ? Number(observation.devBuyLamports) : null;
+ const creator = observation.creator;
+ const creatorAgg = creator ? walletAgg.get(creator) : null;
+ const devSellLamports = creatorAgg ? creatorAgg.sellLamports : 0;
+ const devSold = !!(creatorAgg && creatorAgg.sellCount > 0 && devSellLamports > 0);
+ const devBuySol = devBuyLamports != null ? lamportsToSol(devBuyLamports) : null;
+
+ // Optional wallet-graph enrichment.
+ const bubblemap = bubblemapConnectivity(walletAgg, observation.walletMeta);
+ const freshRatio = freshWalletRatio(walletAgg, observation.walletMeta);
+
+ const bundle = bundleScore(trades);
+
+ // Organic score: high buyer diversity, even arrival timing, low clustering,
+ // dev not dumping, no single whale. Blend of positives minus the bundle tell.
+ const diversity = uniqueBuyers >= 10 ? 1 : uniqueBuyers / 10;
+ const whalePenalty = concentrationTop1; // 1 wallet owning everything is bad
+ let organic = (
+ diversity * 0.30 +
+ timingEntropy * 0.25 +
+ (1 - bundle) * 0.25 +
+ (1 - clamp01(snipeRatio)) * 0.10 +
+ (1 - whalePenalty) * 0.10
+ );
+ if (devSold) organic *= 0.6; // dev dumping is a hard organic killer
+ if (freshRatio != null) organic *= (1 - 0.4 * freshRatio); // fresh-wallet swarm
+ organic = clamp01(organic);
+
+ const buySellRatio = sellLamports > 0 ? buyLamports / sellLamports : (buyLamports > 0 ? Infinity : 0);
+
+ const signals = {
+ window_seconds: observation.endedAtMs && observation.firstSeenAtMs
+ ? Math.round((observation.endedAtMs - observation.firstSeenAtMs) / 1000) : null,
+ trade_count: trades.length,
+ buy_count: buys.length,
+ sell_count: sells.length,
+ buy_volume_sol: round(lamportsToSol(buyLamports), 4),
+ sell_volume_sol: round(lamportsToSol(sellLamports), 4),
+ net_volume_sol: round(lamportsToSol(buyLamports - sellLamports), 4),
+ buy_sell_ratio: Number.isFinite(buySellRatio) ? round(buySellRatio, 2) : null,
+ unique_buyers: uniqueBuyers,
+ unique_sellers: uniqueSellers,
+ unique_traders: uniqueTraders,
+ largest_buy_sol: round(lamportsToSol(largestBuyLamports), 4),
+ avg_buy_sol: round(avgBuySol, 4),
+ median_buy_sol: round(medianBuySol, 4),
+
+ bundle_score: bundle,
+ snipe_ratio: round(snipeRatio),
+ organic_score: round(organic),
+ coordination_score: round(clamp01(bundle * 0.6 + (bubblemap ?? 0) * 0.4)),
+ timing_entropy: round(timingEntropy),
+
+ concentration_top1: round(concentrationTop1),
+ concentration_top5: round(concentrationTop5),
+ concentration_top10: round(concentrationTop10),
+
+ fresh_wallet_ratio: freshRatio,
+ bubblemap_connectivity: bubblemap,
+
+ dev_buy_sol: devBuySol != null ? round(devBuySol, 4) : null,
+ dev_sold: devSold,
+ dev_sell_sol: round(lamportsToSol(devSellLamports), 4),
+ };
+
+ const risk = summarizeRisk(signals);
+ return { signals, ...risk, walletAgg };
+}
+
+/**
+ * Reduce signals to a 0..100 quality score and a list of human-readable risk
+ * flags. The score is intentionally simple and transparent — the learned
+ * weights in learn.js refine ranking; this is the always-available baseline.
+ */
+export function summarizeRisk(signals) {
+ const flags = [];
+ if (signals.bundle_score >= 0.6) flags.push('bundle_launch');
+ if (signals.dev_sold) flags.push('dev_dumped');
+ if (signals.concentration_top1 >= 0.5) flags.push('single_whale');
+ if (signals.unique_buyers > 0 && signals.unique_buyers < 5) flags.push('low_diversity');
+ if (signals.fresh_wallet_ratio != null && signals.fresh_wallet_ratio >= 0.7) flags.push('fresh_wallet_swarm');
+ if (signals.buy_sell_ratio != null && signals.buy_sell_ratio < 1 && signals.sell_count >= 3) flags.push('sell_pressure');
+ if (signals.snipe_ratio >= 0.85 && signals.unique_buyers < 8) flags.push('sniped');
+
+ // Quality score: start from organic, penalize each risk dimension. Clamp 0..100.
+ let q = (signals.organic_score ?? 0) * 100;
+ q -= signals.bundle_score * 40;
+ q -= signals.concentration_top1 * 25;
+ if (signals.dev_sold) q -= 25;
+ if (signals.fresh_wallet_ratio != null) q -= signals.fresh_wallet_ratio * 20;
+ // Reward genuine breadth.
+ q += Math.min(15, (signals.unique_buyers || 0) * 0.5);
+ const quality = Math.max(0, Math.min(100, Math.round(q)));
+
+ return { quality_score: quality, risk_flags: flags };
+}
+
+export const _internals = { normalizedEntropy, median, BURST_MS, SNIPE_MS, LAMPORTS_PER_SOL };
diff --git a/workers/agent-sniper/intel/store.js b/workers/agent-sniper/intel/store.js
new file mode 100644
index 000000000..5eb2648d9
--- /dev/null
+++ b/workers/agent-sniper/intel/store.js
@@ -0,0 +1,201 @@
+// Coin Intelligence — persistence + hot-path cache.
+//
+// The sniper reads intel on the buy decision path, so reads must be instant:
+// an in-process Map serves the worker with zero I/O. Writes upsert into
+// pump_coin_intel + pump_coin_wallets (fire-and-forget — a DB hiccup never
+// blocks the feed). Cross-process consumers (the API, other workers) read from
+// Postgres. The DB import is lazy so dev/test without DATABASE_URL still loads.
+
+let _sqlPromise = null;
+async function getSql() {
+ if (_sqlPromise) return _sqlPromise;
+ _sqlPromise = import('../../../api/_lib/db.js')
+ .then((m) => m.sql)
+ .catch((err) => { console.warn('[coin-intel] db import failed:', err?.message); return null; });
+ return _sqlPromise;
+}
+
+// ── hot-path cache ───────────────────────────────────────────────────────────
+const CACHE_LIMIT = 5_000;
+const CACHE_TTL_MS = 30 * 60_000; // 30 min — coins are only interesting fresh
+const _cache = new Map(); // mint -> { record, at }
+
+export function cacheGet(mint) {
+ const hit = _cache.get(mint);
+ if (!hit) return null;
+ if (Date.now() - hit.at > CACHE_TTL_MS) { _cache.delete(mint); return null; }
+ return hit.record;
+}
+
+export function cacheSet(mint, record) {
+ _cache.set(mint, { record, at: Date.now() });
+ if (_cache.size > CACHE_LIMIT) {
+ const drop = Math.floor(CACHE_LIMIT / 4);
+ const it = _cache.keys();
+ for (let i = 0; i < drop; i++) _cache.delete(it.next().value);
+ }
+}
+
+/** Newest-first snapshot of cached intel — used as a feed fallback in dev. */
+export function cacheRecent(limit = 50) {
+ const out = [];
+ for (const { record } of _cache.values()) out.push(record);
+ out.sort((a, b) => (b.first_seen_at_ms || 0) - (a.first_seen_at_ms || 0));
+ return out.slice(0, limit);
+}
+
+const big = (v) => (v == null ? null : String(BigInt(Math.round(Number(v) || 0))));
+
+/**
+ * Persist a finished intel record + its per-wallet ledger. Idempotent upsert.
+ * @param {object} rec the record assembled by watcher.js
+ * @param {Map} walletAgg wallet -> aggregate (from computeSignals)
+ */
+export async function persistIntel(rec, walletAgg) {
+ cacheSet(rec.mint, rec);
+ const sql = await getSql();
+ if (!sql) return;
+
+ const s = rec.signals || {};
+ try {
+ await sql`
+ insert into pump_coin_intel (
+ mint, network, symbol, name, creator, bonding_curve, image_uri, description,
+ twitter, telegram, website, created_at, first_seen_at, observation_ended_at,
+ observation_seconds, dev_buy_lamports, dev_sold, dev_sell_lamports,
+ buy_count, sell_count, buy_volume_lamports, sell_volume_lamports,
+ 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
+ ) 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},
+ ${rec.twitter || null}, ${rec.telegram || null}, ${rec.website || null},
+ to_timestamp(${rec.created_at_sec || null}), now(), now(),
+ ${s.window_seconds ?? null}, ${big(rec.dev_buy_lamports)}, ${!!s.dev_sold}, ${big(rec.dev_sell_lamports)},
+ ${s.buy_count ?? 0}, ${s.sell_count ?? 0}, ${big(rec.buy_volume_lamports)}, ${big(rec.sell_volume_lamports)},
+ ${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},
+ ${rec.quality_score ?? null}, ${rec.risk_flags || []},
+ ${rec.category || null}, ${rec.tags || []}, ${rec.narrative || null},
+ ${rec.classify_confidence ?? null}, ${rec.classify_source || null}, now()
+ )
+ on conflict (mint) do update set
+ symbol = excluded.symbol, name = excluded.name,
+ observation_ended_at = excluded.observation_ended_at,
+ observation_seconds = excluded.observation_seconds,
+ dev_buy_lamports = excluded.dev_buy_lamports, dev_sold = excluded.dev_sold,
+ dev_sell_lamports = excluded.dev_sell_lamports,
+ buy_count = excluded.buy_count, sell_count = excluded.sell_count,
+ buy_volume_lamports = excluded.buy_volume_lamports,
+ sell_volume_lamports = excluded.sell_volume_lamports,
+ unique_buyers = excluded.unique_buyers, unique_sellers = excluded.unique_sellers,
+ largest_buy_lamports = excluded.largest_buy_lamports,
+ signals = excluded.signals, bundle_score = excluded.bundle_score,
+ organic_score = excluded.organic_score, snipe_ratio = excluded.snipe_ratio,
+ concentration_top10 = excluded.concentration_top10,
+ fresh_wallet_ratio = excluded.fresh_wallet_ratio,
+ bubblemap_connectivity = excluded.bubblemap_connectivity,
+ quality_score = excluded.quality_score, risk_flags = excluded.risk_flags,
+ category = excluded.category, tags = excluded.tags, narrative = excluded.narrative,
+ classify_confidence = excluded.classify_confidence,
+ classify_source = excluded.classify_source, updated_at = now()
+ `;
+ } catch (err) {
+ console.warn('[coin-intel] persist intel failed:', err?.message);
+ }
+
+ if (walletAgg && walletAgg.size) await persistWallets(sql, rec.mint, rec.creator, walletAgg);
+}
+
+async function persistWallets(sql, mint, creator, walletAgg) {
+ // Build a single multi-row upsert. Cap rows to keep statements bounded — the
+ // top traders by activity are what concentration/bubblemap care about.
+ const rows = [...walletAgg.entries()]
+ .sort((a, b) => (b[1].buyLamports + b[1].sellLamports) - (a[1].buyLamports + a[1].sellLamports))
+ .slice(0, 200);
+ try {
+ for (const [wallet, w] of rows) {
+ 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
+ ) 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}
+ )
+ on conflict (mint, wallet) do update set
+ buy_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
+ `;
+ }
+ } catch (err) {
+ console.warn('[coin-intel] persist wallets failed:', err?.message);
+ }
+}
+
+/** Read one coin's intel — cache first, then DB. */
+export async function readIntel(mint) {
+ const cached = cacheGet(mint);
+ if (cached) return cached;
+ const sql = await getSql();
+ if (!sql) return null;
+ try {
+ const [row] = await sql`select * from pump_coin_intel where mint = ${mint} limit 1`;
+ return row || null;
+ } catch (err) {
+ console.warn('[coin-intel] read intel failed:', err?.message);
+ return null;
+ }
+}
+
+/** Read the live radar feed (newest first), with optional filters. */
+export async function readRecent({ limit = 50, minQuality = null, category = null, network = 'mainnet' } = {}) {
+ const cap = Math.max(1, Math.min(200, limit | 0 || 50));
+ const sql = await getSql();
+ if (!sql) return cacheRecent(cap);
+ try {
+ const rows = await sql`
+ select * from pump_coin_intel
+ where network = ${network}
+ and (${minQuality}::int is null or quality_score >= ${minQuality})
+ and (${category}::text is null or category = ${category})
+ order by first_seen_at desc
+ limit ${cap}
+ `;
+ return rows;
+ } catch (err) {
+ console.warn('[coin-intel] read recent failed:', err?.message);
+ return cacheRecent(cap);
+ }
+}
+
+// ── learned weights (read by scorer; written by learn.js) ────────────────────
+let _weights = null;
+let _weightsAt = 0;
+const WEIGHTS_TTL_MS = 5 * 60_000;
+
+export async function getLearnedWeights(network = 'mainnet') {
+ if (_weights && Date.now() - _weightsAt < WEIGHTS_TTL_MS) return _weights;
+ const sql = await getSql();
+ if (!sql) return null;
+ try {
+ const [row] = await sql`
+ select weights, sample_size from pump_intel_weights
+ where network = ${network} order by trained_at desc limit 1
+ `;
+ _weights = row?.weights || null;
+ _weightsAt = Date.now();
+ return _weights;
+ } catch {
+ return null;
+ }
+}
diff --git a/workers/agent-sniper/intel/watcher.js b/workers/agent-sniper/intel/watcher.js
new file mode 100644
index 000000000..26beb3b9a
--- /dev/null
+++ b/workers/agent-sniper/intel/watcher.js
@@ -0,0 +1,249 @@
+// Coin Intelligence — the observation watcher.
+//
+// Holds its own PumpPortal connection so it can DYNAMICALLY subscribe to each
+// new mint's trade stream for an observation window, then unsubscribe. The
+// shared feed (api/_lib/pumpfun-ws-feed.js) subscribes once on open and can't
+// add keys later, so the watcher manages a lean connection of its own.
+//
+// Lifecycle per coin:
+// create event → start observation (record dev buy + metadata) → subscribe
+// to its trades → accumulate every buy/sell for windowMs → compute signals →
+// classify → persist → unsubscribe. The result is a complete intel record the
+// sniper and the /radar feed read instantly.
+
+import WebSocket from 'ws';
+import { computeSignals } from './signals.js';
+import { classifyCoin } from './classify.js';
+import { persistIntel } from './store.js';
+import { log } from '../log.js';
+
+const PUMPPORTAL_WS = 'wss://pumpportal.fun/api/data';
+const RECONNECT_DELAY_MS = 2_000;
+const LAMPORTS_PER_SOL = 1_000_000_000;
+const META_TIMEOUT_MS = 2_500;
+
+const _metaCache = new Map();
+async function fetchMeta(uri) {
+ if (!uri) return null;
+ if (_metaCache.has(uri)) return _metaCache.get(uri);
+ try {
+ const ctrl = new AbortController();
+ const tid = setTimeout(() => ctrl.abort(), META_TIMEOUT_MS);
+ const r = await fetch(uri, { signal: ctrl.signal });
+ clearTimeout(tid);
+ if (!r.ok) return null;
+ const d = await r.json();
+ const meta = {
+ description: d.description || null,
+ twitter: d.twitter || null,
+ telegram: d.telegram || null,
+ website: d.website || null,
+ image_uri: d.image || d.image_uri || null,
+ };
+ if (_metaCache.size > 500) _metaCache.clear();
+ _metaCache.set(uri, meta);
+ return meta;
+ } catch { return null; }
+}
+
+const solToLamports = (sol) => Math.round((Number(sol) || 0) * LAMPORTS_PER_SOL);
+
+/**
+ * Start the intel watcher.
+ * @param {object} opts
+ * @param {string} [opts.network='mainnet']
+ * @param {number} [opts.windowMs=90000] observation window per coin
+ * @param {number} [opts.maxConcurrent=400] cap on simultaneously-watched coins
+ * @param {AbortSignal} [opts.signal]
+ * @param {(rec: object) => void} [opts.onIntel] fired with each finished record
+ * @returns {() => void} stop
+ */
+export function startIntelWatcher({
+ network = 'mainnet',
+ windowMs = 90_000,
+ maxConcurrent = 400,
+ signal,
+ onIntel,
+} = {}) {
+ let active = true;
+ let ws = null;
+ let reconnectTimer = null;
+ let droppedSinceLog = 0;
+ const observations = new Map(); // mint -> { meta, trades, firstSeenAtMs, createdAtSec, devBuyLamports, timer }
+
+ function stop() {
+ active = false;
+ clearTimeout(reconnectTimer);
+ for (const obs of observations.values()) clearTimeout(obs.timer);
+ if (ws) try { ws.close(); } catch {}
+ }
+ signal?.addEventListener('abort', stop);
+
+ function send(obj) {
+ if (ws && ws.readyState === WebSocket.OPEN) {
+ try { ws.send(JSON.stringify(obj)); return true; } catch { return false; }
+ }
+ return false;
+ }
+
+ function startObservation(msg) {
+ const mint = msg.mint;
+ if (!mint || observations.has(mint)) return;
+ if (observations.size >= maxConcurrent) {
+ droppedSinceLog++;
+ return; // logged periodically below — never silently
+ }
+ const now = Date.now();
+ const obs = {
+ mint,
+ createdAtSec: Math.floor(now / 1000),
+ firstSeenAtMs: now,
+ creator: msg.traderPublicKey || null,
+ devBuyLamports: msg.solAmount != null ? solToLamports(msg.solAmount) : null,
+ mcSolFirstSeen: typeof msg.marketCapSol === 'number' ? msg.marketCapSol : null,
+ meta: {
+ name: msg.name || null,
+ symbol: msg.symbol || null,
+ bonding_curve: msg.bondingCurveKey || null,
+ image_uri: msg.uri || null,
+ uri: msg.uri || null,
+ description: null, twitter: null, telegram: null, website: null,
+ },
+ // The creator's initial buy is part of the launch tx — seed it as the
+ // first trade so dev sizing/concentration include it.
+ trades: msg.solAmount
+ ? [{ trader: msg.traderPublicKey || null, isBuy: true, lamports: solToLamports(msg.solAmount), baseAmount: Number(msg.tokenAmount) || 0, ts: now, signature: msg.signature }]
+ : [],
+ timer: null,
+ };
+ observations.set(mint, obs);
+ send({ method: 'subscribeTokenTrade', keys: [mint] });
+
+ // Enrich metadata off the hot path.
+ fetchMeta(obs.meta.uri).then((m) => {
+ if (m && observations.has(mint)) Object.assign(obs.meta, m);
+ }).catch(() => {});
+
+ obs.timer = setTimeout(() => finalize(mint), windowMs);
+ }
+
+ function recordTrade(msg) {
+ const obs = observations.get(msg.mint);
+ if (!obs) return;
+ obs.trades.push({
+ trader: msg.traderPublicKey || null,
+ isBuy: msg.txType === 'buy',
+ lamports: msg.solAmount != null ? solToLamports(msg.solAmount) : 0,
+ baseAmount: Number(msg.tokenAmount) || 0,
+ ts: Date.now(),
+ signature: msg.signature,
+ });
+ }
+
+ async function finalize(mint) {
+ const obs = observations.get(mint);
+ if (!obs) return;
+ observations.delete(mint);
+ clearTimeout(obs.timer);
+ send({ method: 'unsubscribeTokenTrade', keys: [mint] });
+
+ try {
+ const endedAtMs = Date.now();
+ const { signals, quality_score, risk_flags, walletAgg } = computeSignals({
+ mint,
+ creator: obs.creator,
+ createdAtMs: obs.firstSeenAtMs,
+ firstSeenAtMs: obs.firstSeenAtMs,
+ endedAtMs,
+ devBuyLamports: obs.devBuyLamports,
+ trades: obs.trades,
+ });
+ 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,
+ });
+
+ const record = {
+ mint,
+ network,
+ symbol: obs.meta.symbol,
+ name: obs.meta.name,
+ creator: obs.creator,
+ bonding_curve: obs.meta.bonding_curve,
+ image_uri: obs.meta.image_uri,
+ description: obs.meta.description,
+ twitter: obs.meta.twitter,
+ telegram: obs.meta.telegram,
+ website: obs.meta.website,
+ created_at_sec: obs.createdAtSec,
+ first_seen_at_ms: obs.firstSeenAtMs,
+ dev_buy_lamports: obs.devBuyLamports,
+ dev_sell_lamports: solToLamports(signals.dev_sell_sol || 0),
+ buy_volume_lamports: solToLamports(signals.buy_volume_sol || 0),
+ sell_volume_lamports: solToLamports(signals.sell_volume_sol || 0),
+ largest_buy_lamports: solToLamports(signals.largest_buy_sol || 0),
+ signals,
+ quality_score,
+ risk_flags,
+ category: cls.category,
+ tags: cls.tags,
+ narrative: cls.narrative,
+ classify_confidence: cls.confidence,
+ classify_source: cls.source,
+ };
+
+ await persistIntel(record, walletAgg);
+ if (active && onIntel) { try { onIntel(record); } catch {} }
+ } catch (err) {
+ log.error?.('intel finalize failed', { mint, err: err?.message });
+ }
+ }
+
+ function connect() {
+ if (!active) return;
+ ws = new WebSocket(PUMPPORTAL_WS);
+
+ ws.on('open', () => {
+ send({ method: 'subscribeNewToken' });
+ // Re-subscribe trades for anything still mid-observation after a reconnect.
+ const keys = [...observations.keys()];
+ if (keys.length) send({ method: 'subscribeTokenTrade', keys });
+ log.info?.('intel watcher connected', { network, watching: keys.length });
+ });
+
+ ws.on('message', (raw) => {
+ if (!active) return;
+ let msg;
+ try { msg = JSON.parse(raw.toString()); } catch { return; }
+ if (msg.message) return; // ack
+ if (msg.txType === 'create') startObservation(msg);
+ else if (msg.txType === 'buy' || msg.txType === 'sell') recordTrade(msg);
+ });
+
+ ws.on('error', (err) => log.warn?.('intel watcher ws error', { err: err?.message }));
+ ws.on('close', () => {
+ if (!active) return;
+ reconnectTimer = setTimeout(connect, RECONNECT_DELAY_MS);
+ });
+ }
+
+ // Periodic visibility into dropped observations (no silent caps — Rule).
+ const dropTimer = setInterval(() => {
+ if (droppedSinceLog > 0) {
+ log.warn?.('intel watcher at capacity — dropped observations', {
+ dropped: droppedSinceLog, watching: observations.size, cap: maxConcurrent,
+ });
+ droppedSinceLog = 0;
+ }
+ }, 60_000);
+ signal?.addEventListener('abort', () => clearInterval(dropTimer));
+
+ connect();
+ return () => { clearInterval(dropTimer); stop(); };
+}