Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: smart-money wallet graph, feature tour page, nav and pages wiring
nirholas186c2f58729a
diff --git a/api/_lib/migrations/20260620061500_smart_money_graph.sql b/api/_lib/migrations/20260620061500_smart_money_graph.sqlnew file mode 100644index 000000000..9cc17faea--- /dev/null+++ b/api/_lib/migrations/20260620061500_smart_money_graph.sql@@ -0,0 +1,99 @@+-- Migration: Smart-Money Wallet Graph & Cluster Intelligence (Task 03).+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/20260620061500_smart_money_graph.sql+-- Idempotent + re-runnable.+--+-- We already record, per launch, every buyer wallet and its funder+-- (pump_coin_wallets) plus eventual outcomes (pump_coin_outcomes:+-- graduated/pumped/rugged/ath_multiple). This migration adds the persistent,+-- self-updating wallet reputation graph that stitches those together:+--+-- 1. smart_wallet_reputation — per-wallet realized track record, derived ONLY+-- from observed buys ⋈ real outcomes. A rolling 0..100 realized_score with+-- confidence regression toward neutral until N judged launches, win_rate,+-- avg ATH multiple, and a labels[] array (smart_money / sybil / fresh / …).+--+-- 2. smart_wallet_clusters — wallets grouped by a shared funder root via the+-- recompute job's union-find, with a co-occurrence confidence. Sybil/insider+-- clusters are the signal the firewall and Oracle read to discount a launch+-- whose "wide base" is really one funder wearing many wallets.+--+-- 3. agent_sniper_strategies gate columns — min_smart_money_score /+-- require_smart_money so a strategy can demand proven money before it buys.+--+-- A DISTINCT namespace from the pre-existing smart-money rollup tables+-- (wallet_reputation / coin_smart_money, migration 20260615080000): this graph is+-- derived from the coin-intel outcome ground truth (pump_coin_outcomes), not from+-- graduations alone, and must not clobber that system's columns or its public API.+--+-- Read-only on the engine's tables. Mainnet-only (pump.fun). Lamports in numeric(40,0).++begin;++-- ── per-wallet realized reputation, folded from outcomes ─────────────────────+create table if not exists smart_wallet_reputation (+ address text not null,+ network text not null default 'mainnet' check (network in ('mainnet', 'devnet')),++ -- realized track record (every number traces to an observed buy + an outcome)+ trades_seen int not null default 0, -- judged coins this wallet net-bought+ winners int not null default 0, -- of those, graduated or pumped (>=3x ATH)+ losers int not null default 0, -- of those, flat or rugged+ win_rate numeric not null default 0, -- winners / trades_seen (0..1)+ avg_ath_multiple numeric not null default 0, -- mean ATH multiple across judged coins+ realized_score numeric not null default 0, -- 0..100, ATH-weighted + confidence-regressed++ labels text[] not null default '{}', -- smart_money | strong | fresh | sybil | rugger | neutral++ first_seen timestamptz,+ last_seen timestamptz,+ scored_at timestamptz not null default now(),+ primary key (address, network)+);++-- By-score lookup (leaderboard / "is this wallet proven").+create index if not exists smart_wallet_reputation_score+ on smart_wallet_reputation (network, realized_score desc);+-- Label lookup (pull the proven cohort fast).+create index if not exists smart_wallet_reputation_labels+ on smart_wallet_reputation using gin (labels);++-- ── funder clusters (union-find over shared-funder edges) ────────────────────+-- One row per (address, network): the cluster it belongs to, the funder root that+-- anchors the cluster, the cluster size, and a 0..1 confidence from how often the+-- members co-occur as buyers of the same launches. cluster_id is the smallest+-- address in the component (deterministic, so reruns are idempotent).+create table if not exists smart_wallet_clusters (+ address text not null,+ network text not null default 'mainnet' check (network in ('mainnet', 'devnet')),+ cluster_id text not null, -- canonical (smallest) member address+ funder_root text, -- shared funding source anchoring the cluster+ size int not null default 1, -- members in this cluster+ confidence numeric not null default 0, -- 0..1 co-occurrence confidence+ scored_at timestamptz not null default now(),+ primary key (address, network)+);++-- Mint-join + "who else is in this wallet's cluster" lookups.+create index if not exists smart_wallet_clusters_cluster+ on smart_wallet_clusters (network, cluster_id);+create index if not exists smart_wallet_clusters_funder+ on smart_wallet_clusters (network, funder_root) where funder_root is not null;++-- ── idempotency cursor: each coin's wallets fold into reputation exactly once ─+-- A coin is folded once its outcome is final; re-running the job re-reads only+-- coins not yet folded (or whose outcome changed), so writes never double-count.+create table if not exists smart_wallet_folded (+ mint text not null,+ network text not null default 'mainnet',+ outcome text not null, -- the outcome at fold time+ folded_at timestamptz not null default now(),+ primary key (mint, network)+);++-- ── strategy gate: demand proven money before buying ─────────────────────────+alter table agent_sniper_strategies+ add column if not exists min_smart_money_score numeric; -- null = no gate+alter table agent_sniper_strategies+ add column if not exists require_smart_money boolean not null default false;++commit;diff --git a/api/_lib/smart-money.js b/api/_lib/smart-money.jsnew file mode 100644index 000000000..70b310bce--- /dev/null+++ b/api/_lib/smart-money.js@@ -0,0 +1,339 @@+// Smart-Money live lookup — the read layer over the wallet reputation graph.+//+// The recompute job (workers/agent-sniper/recompute-wallet-graph.js) maintains+// smart_wallet_reputation + smart_wallet_clusters from real observed buys ⋈ real+// outcomes. THIS module is the hot read path every live consumer shares:+//+// - getSmartMoneyForMint(mint, network) — who reputable is net-buying this coin+// right now, a 0..100 smart_money_score, and a sybil_flag when the buyers are+// dominated by one funder cluster. Read by the firewall, the sniper scorer,+// the oracle gate, and the public API.+// - getWalletReputation(address, network) — one wallet's realized track record.+//+// Honest degradation is the rule (mirrors trade-firewall.js): when DATABASE_URL+// is absent, the graph hasn't been computed, or a query fails, every function+// resolves to a well-formed zero-data result — it NEVER throws and never blocks a+// caller. A caller can always tell "no data" from "bad coin" by the count/score.+//+// Derived ONLY from on-chain addresses + observed outcomes. No hand-curated lists,+// no invented trader names. $THREE is the only coin three.ws promotes; this is+// coin-agnostic analytics over whatever runtime mint a caller hands it.++// Lazy DB import so this module loads in dev/test without DATABASE_URL.+let _sqlPromise = null;+async function getSql() {+ if (_sqlPromise) return _sqlPromise;+ _sqlPromise = import('./db.js')+ .then((m) => m.sql)+ .catch((err) => { console.warn('[smart-money] db import failed:', err?.message); return null; });+ return _sqlPromise;+}++const num = (v, d = 0) => (Number.isFinite(Number(v)) ? Number(v) : d);+const lamportsToSol = (v) => {+ try { return Math.round((Number(BigInt(v ?? 0)) / 1e9) * 1000) / 1000; } catch { return num(v) / 1e9; }+};++// ── brief caches ──────────────────────────────────────────────────────────────+// The firewall + scorer can hit the same fresh mint many times in a burst, and the+// public API caches at the edge too — a few seconds here shaves real DB latency.+const MINT_TTL_MS = 12_000;+const WALLET_TTL_MS = 30_000;+const _mintCache = new Map(); // `${network}:${mint}` → { at, value }+const _walletCache = new Map(); // `${network}:${address}` → { at, value }++function cacheGet(map, key, ttl) {+ const hit = map.get(key);+ if (!hit) return undefined;+ if (Date.now() - hit.at > ttl) { map.delete(key); return undefined; }+ return hit.value;+}+function cacheSet(map, key, value, limit = 4_000) {+ map.set(key, { at: Date.now(), value });+ if (map.size > limit) {+ const drop = Math.floor(limit / 4);+ const it = map.keys();+ for (let i = 0; i < drop; i++) map.delete(it.next().value);+ }+}++// A wallet counts as "smart money" in a coin when it has a real, proven track+// record. We pull reputable buyers directly from the reputation graph join.+const PROVEN_SCORE = 70;+const STRONG_SCORE = 55;++/** Empty, well-formed result — the honest zero-data shape. */+function emptyMintResult(mint, network) {+ return {+ mint,+ network,+ smart_money_score: 0,+ count: 0,+ total_buyers: 0,+ wallets: [],+ clusters: [],+ sybil_flag: false,+ sybil_share: 0,+ computed: false, // false = no graph data yet (UI shows "not enough history")+ };+}++/**+ * Reputable buyers currently net-buying a mint, plus a sybil read.+ *+ * @param {string} mint+ * @param {'mainnet'|'devnet'} [network='mainnet']+ * @returns {Promise<{+ * mint:string, network:string, smart_money_score:number, count:number,+ * total_buyers:number,+ * wallets:Array<{address:string, realized_score:number, win_rate:number,+ * avg_ath_multiple:number, labels:string[], buy_sol:number,+ * cluster_id:string|null, sybil:boolean}>,+ * clusters:Array<{cluster_id:string, size:number, confidence:number, buyers:number,+ * buy_sol:number, funder_root:string|null}>,+ * sybil_flag:boolean, sybil_share:number, computed:boolean+ * }>}+ */+export async function getSmartMoneyForMint(mint, network = 'mainnet') {+ const net = network === 'devnet' ? 'devnet' : 'mainnet';+ if (!mint || typeof mint !== 'string') return emptyMintResult(mint, net);++ const key = `${net}:${mint}`;+ const cached = cacheGet(_mintCache, key, MINT_TTL_MS);+ if (cached !== undefined) return cached;++ const sql = await getSql();+ if (!sql) { const r = emptyMintResult(mint, net); cacheSet(_mintCache, key, r); return r; }++ let rows;+ try {+ // Join every wallet that net-bought this coin against its reputation + cluster.+ // net_buy = buy_lamports - sell_lamports, floored at 0: a wallet that fully+ // dumped is not "in" the coin. Reputation/cluster are LEFT joins so unscored+ // buyers still inform the total + cluster dominance.+ rows = await sql`+ select+ w.wallet as address,+ (w.buy_lamports - w.sell_lamports) as net_buy_lamports,+ r.realized_score, r.win_rate, r.avg_ath_multiple, r.labels, r.trades_seen,+ c.cluster_id, c.confidence as cluster_confidence, c.size as cluster_size,+ c.funder_root+ from pump_coin_wallets w+ left join smart_wallet_reputation r+ on r.address = w.wallet and r.network = ${net}+ left join smart_wallet_clusters c+ on c.address = w.wallet and c.network = ${net}+ where w.mint = ${mint}+ and w.buy_lamports > w.sell_lamports+ order by net_buy_lamports desc+ limit 200+ `;+ } catch (err) {+ console.warn('[smart-money] mint lookup failed:', err?.message);+ const r = emptyMintResult(mint, net);+ cacheSet(_mintCache, key, r);+ return r;+ }++ const result = shapeMint(mint, net, rows);+ cacheSet(_mintCache, key, result);+ return result;+}++function shapeMint(mint, network, rows) {+ if (!Array.isArray(rows) || rows.length === 0) {+ return emptyMintResult(mint, network);+ }+ const totalBuyers = rows.length;+ let totalNet = 0;+ const clusterAgg = new Map(); // cluster_id → { size, confidence, funder_root, buyers, net }++ const wallets = rows.map((row) => {+ const net = Math.max(0, num(row.net_buy_lamports));+ totalNet += net;+ const labels = Array.isArray(row.labels) ? row.labels : [];+ const clusterId = row.cluster_id || null;+ if (clusterId) {+ let agg = clusterAgg.get(clusterId);+ if (!agg) {+ agg = { size: num(row.cluster_size, 0), confidence: num(row.cluster_confidence, 0), funder_root: row.funder_root || null, buyers: 0, net: 0 };+ clusterAgg.set(clusterId, agg);+ }+ agg.buyers++;+ agg.net += net;+ }+ return {+ address: row.address,+ realized_score: num(row.realized_score, 0),+ win_rate: num(row.win_rate, 0),+ avg_ath_multiple: num(row.avg_ath_multiple, 0),+ labels,+ trades_seen: num(row.trades_seen, 0),+ buy_sol: lamportsToSol(net),+ cluster_id: clusterId,+ sybil: false, // set below once dominance is known+ };+ });++ // Reputable buyers: proven track record (score >= STRONG and a real sample).+ const reputable = wallets.filter((w) => w.realized_score >= STRONG_SCORE && w.trades_seen >= 3);+ const proven = reputable.filter((w) => w.realized_score >= PROVEN_SCORE);++ // Smart-money score for the COIN: net-buy-weighted mean reputation of reputable+ // buyers, lifted by how many proven wallets are in. Mirrors the pedigree intent+ // of the oracle without duplicating its fusion. 0 when nobody reputable is in.+ let smartScore = 0;+ if (reputable.length) {+ // Net-buy-weighted mean reputation: a proven wallet putting in size counts+ // more than one dust-buying. A tiny epsilon weight keeps zero-SOL rows valid.+ const weighted = reputable.reduce((s, w) => s + w.realized_score * (w.buy_sol || 0.0001), 0);+ const denom = reputable.reduce((s, w) => s + (w.buy_sol || 0.0001), 0) || 1;+ smartScore = weighted / denom;+ if (proven.length >= 5) smartScore += 12;+ else if (proven.length >= 3) smartScore += 8;+ else if (proven.length >= 1) smartScore += 4;+ smartScore = Math.round(Math.max(0, Math.min(100, smartScore)));+ }++ // Sybil dominance: the largest funder cluster's share of total net-buy volume.+ // When one cluster owns the book, the "wide base" is one funder wearing wallets.+ let topClusterShare = 0;+ let topClusterId = null;+ for (const [cid, agg] of clusterAgg) {+ const share = totalNet > 0 ? agg.net / totalNet : 0;+ if (share > topClusterShare) { topClusterShare = share; topClusterId = cid; }+ }+ const sybilFlag = topClusterShare >= 0.5 && (clusterAgg.get(topClusterId)?.buyers || 0) >= 3;+ if (sybilFlag) {+ for (const w of wallets) if (w.cluster_id === topClusterId) w.sybil = true;+ }++ const clusters = [...clusterAgg.entries()]+ .map(([cluster_id, agg]) => ({+ cluster_id,+ size: agg.size,+ confidence: Number(agg.confidence.toFixed(3)),+ buyers: agg.buyers,+ buy_sol: lamportsToSol(agg.net),+ funder_root: agg.funder_root,+ share: totalNet > 0 ? Number((agg.net / totalNet).toFixed(3)) : 0,+ }))+ .sort((a, b) => b.share - a.share);++ // Surface the reputable wallets first; trim sybil-flagged ones out of the headline+ // "count" (the spec's reputable, non-clustered cohort) but keep them in clusters[].+ const headline = reputable+ .filter((w) => !w.sybil)+ .sort((a, b) => b.realized_score - a.realized_score || b.buy_sol - a.buy_sol);++ return {+ mint,+ network,+ smart_money_score: smartScore,+ count: headline.length,+ total_buyers: totalBuyers,+ wallets: headline.slice(0, 25),+ clusters: clusters.slice(0, 10),+ sybil_flag: sybilFlag,+ sybil_share: Number(topClusterShare.toFixed(3)),+ computed: true,+ };+}++/** Empty, well-formed wallet result. */+function emptyWalletResult(address, network) {+ return {+ address,+ network,+ realized_score: 0,+ win_rate: 0,+ avg_ath_multiple: 0,+ trades_seen: 0,+ winners: 0,+ losers: 0,+ labels: [],+ cluster: null,+ first_seen: null,+ last_seen: null,+ scored_at: null,+ computed: false,+ };+}++/**+ * One wallet's realized reputation + its cluster membership.+ *+ * @param {string} address+ * @param {'mainnet'|'devnet'} [network='mainnet']+ * @returns {Promise<object>} the reputation row shaped for callers; computed:false+ * when the wallet has no track record yet (or the graph isn't available).+ */+export async function getWalletReputation(address, network = 'mainnet') {+ const net = network === 'devnet' ? 'devnet' : 'mainnet';+ if (!address || typeof address !== 'string') return emptyWalletResult(address, net);++ const key = `${net}:${address}`;+ const cached = cacheGet(_walletCache, key, WALLET_TTL_MS);+ if (cached !== undefined) return cached;++ const sql = await getSql();+ if (!sql) { const r = emptyWalletResult(address, net); cacheSet(_walletCache, key, r); return r; }++ let rep, cluster;+ try {+ [rep, cluster] = await Promise.all([+ sql`+ select address, realized_score, win_rate, avg_ath_multiple, trades_seen,+ winners, losers, labels, first_seen, last_seen, scored_at+ from smart_wallet_reputation+ where address = ${address} and network = ${net}+ limit 1+ `.then((r) => r[0] || null),+ sql`+ select cluster_id, funder_root, size, confidence+ from smart_wallet_clusters+ where address = ${address} and network = ${net}+ limit 1+ `.then((r) => r[0] || null),+ ]);+ } catch (err) {+ console.warn('[smart-money] wallet lookup failed:', err?.message);+ const r = emptyWalletResult(address, net);+ cacheSet(_walletCache, key, r);+ return r;+ }++ if (!rep) { const r = emptyWalletResult(address, net); cacheSet(_walletCache, key, r); return r; }++ const result = {+ address: rep.address,+ network: net,+ realized_score: num(rep.realized_score, 0),+ win_rate: num(rep.win_rate, 0),+ avg_ath_multiple: num(rep.avg_ath_multiple, 0),+ trades_seen: num(rep.trades_seen, 0),+ winners: num(rep.winners, 0),+ losers: num(rep.losers, 0),+ labels: Array.isArray(rep.labels) ? rep.labels : [],+ cluster: cluster+ ? {+ cluster_id: cluster.cluster_id,+ funder_root: cluster.funder_root || null,+ size: num(cluster.size, 1),+ confidence: num(cluster.confidence, 0),+ }+ : null,+ first_seen: rep.first_seen || null,+ last_seen: rep.last_seen || null,+ scored_at: rep.scored_at || null,+ computed: true,+ };+ cacheSet(_walletCache, key, result);+ return result;+}++/** Clear the in-process caches (used by tests + the recompute job after a write). */+export function _resetSmartMoneyCache() {+ _mintCache.clear();+ _walletCache.clear();+}diff --git a/data/pages.json b/data/pages.jsonindex b285fefaa..1e02bd68d 100644--- a/data/pages.json+++ b/data/pages.json@@ -133,6 +133,14 @@"priority": 0.8,"changefreq": "monthly","added": "2026-06-05"+ },+ {+ "path": "/tour",+ "title": "Guided Tour",+ "description": "A 3D guide walks across the live site, points at every feature, and narrates what each one does and how to use it — voice plus an on-screen chat bubble, paced by you.",+ "priority": 0.7,+ "changefreq": "monthly",+ "added": "2026-06-20"}]},diff --git a/pages/tour.html b/pages/tour.htmlnew file mode 100644index 000000000..d347c37c1--- /dev/null+++ b/pages/tour.html@@ -0,0 +1,464 @@+<!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>Guided Tour — A 3D guide walks you through three.ws · three.ws</title>+ <meta+ name="description"+ content="Take the three.ws guided tour: a 3D avatar walks across the live site, points at every feature, and narrates what each one does and how to use it — voice and on-screen captions, paced by you."+ />+ <meta name="robots" content="index, follow" />+ <link rel="canonical" href="https://three.ws/tour" />++ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:title" content="Guided Tour — A 3D guide walks you through three.ws" />+ <meta+ property="og:description"+ content="A 3D avatar walks the live site, points at every feature, and narrates how to use it. Roughly half an hour, paced by you."+ />+ <meta property="og:url" content="https://three.ws/tour" />+ <meta property="og:image" content="https://three.ws/api/page-og?s=main&t=Guided+Tour&d=A+3D+guide+walks+you+through+every+feature%2C+live%2C+on+the+real+site.&p=%2Ftour" />+ <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="Guided Tour — A 3D guide walks you through three.ws" />+ <meta+ name="twitter:description"+ content="A 3D avatar walks the live site, points at every feature, and narrates how to use it."+ />+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=main&t=Guided+Tour&d=A+3D+guide+walks+you+through+every+feature%2C+live%2C+on+the+real+site.&p=%2Ftour" />++ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <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" />++ <style>+ .tour-page {+ --accent: #7aa2ff;+ --accent-2: #9d7bff;+ color: #e7eaf2;+ }+ .tour-wrap {+ max-width: 1040px;+ margin: 0 auto;+ padding: 0 20px 80px;+ }+ /* Hero */+ .tour-hero {+ position: relative;+ text-align: center;+ padding: 64px 20px 48px;+ overflow: hidden;+ }+ .tour-hero::before {+ content: '';+ position: absolute;+ inset: -40% 0 auto;+ height: 480px;+ background: radial-gradient(60% 60% at 50% 0%, rgba(122, 162, 255, 0.22), transparent 70%);+ pointer-events: none;+ z-index: 0;+ }+ .tour-hero > * {+ position: relative;+ z-index: 1;+ }+ .tour-eyebrow {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ font-size: 12.5px;+ font-weight: 600;+ letter-spacing: 0.04em;+ text-transform: uppercase;+ color: var(--accent);+ background: rgba(122, 162, 255, 0.1);+ border: 1px solid rgba(122, 162, 255, 0.28);+ padding: 6px 12px;+ border-radius: 99px;+ margin-bottom: 22px;+ }+ .tour-eyebrow .dot {+ width: 7px;+ height: 7px;+ border-radius: 50%;+ background: var(--accent);+ box-shadow: 0 0 0 0 rgba(122, 162, 255, 0.6);+ animation: tour-pulse 2s infinite;+ }+ @keyframes tour-pulse {+ 0% { box-shadow: 0 0 0 0 rgba(122, 162, 255, 0.5); }+ 70% { box-shadow: 0 0 0 8px rgba(122, 162, 255, 0); }+ 100% { box-shadow: 0 0 0 0 rgba(122, 162, 255, 0); }+ }+ .tour-h1 {+ font-size: clamp(2rem, 5vw, 3.3rem);+ line-height: 1.08;+ font-weight: 800;+ margin: 0 0 16px;+ letter-spacing: -0.02em;+ }+ .tour-h1 .grad {+ background: linear-gradient(90deg, var(--accent), var(--accent-2));+ -webkit-background-clip: text;+ background-clip: text;+ color: transparent;+ }+ .tour-sub {+ font-size: clamp(1rem, 2vw, 1.18rem);+ line-height: 1.55;+ color: #aeb6c6;+ max-width: 620px;+ margin: 0 auto 30px;+ }+ .tour-cta-row {+ display: flex;+ gap: 12px;+ justify-content: center;+ flex-wrap: wrap;+ }+ .tour-btn {+ appearance: none;+ border: 1px solid rgba(255, 255, 255, 0.14);+ background: rgba(255, 255, 255, 0.05);+ color: #eef1f6;+ font: 600 15px/1 system-ui, -apple-system, 'Segoe UI', sans-serif;+ padding: 15px 24px;+ border-radius: 13px;+ cursor: pointer;+ text-decoration: none;+ display: inline-flex;+ align-items: center;+ gap: 9px;+ transition: background 0.18s ease, border-color 0.18s ease, transform 0.12s ease;+ }+ .tour-btn:hover {+ background: rgba(255, 255, 255, 0.1);+ border-color: rgba(255, 255, 255, 0.22);+ }+ .tour-btn:active {+ transform: scale(0.98);+ }+ .tour-btn--primary {+ background: linear-gradient(90deg, var(--accent), var(--accent-2));+ color: #0b0e16;+ border-color: transparent;+ box-shadow: 0 10px 30px rgba(122, 162, 255, 0.32);+ }+ .tour-btn--primary:hover {+ filter: brightness(1.06);+ background: linear-gradient(90deg, var(--accent), var(--accent-2));+ }+ .tour-btn:focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: 3px;+ }+ .tour-resume {+ display: none;+ margin-top: 16px;+ font-size: 13.5px;+ color: #aeb6c6;+ }+ .tour-resume a {+ color: var(--accent);+ font-weight: 600;+ }+ /* Stats */+ .tour-stats {+ display: flex;+ justify-content: center;+ gap: 14px;+ flex-wrap: wrap;+ margin: 40px 0 8px;+ }+ .tour-stat {+ background: rgba(255, 255, 255, 0.035);+ border: 1px solid rgba(255, 255, 255, 0.08);+ border-radius: 16px;+ padding: 18px 26px;+ min-width: 132px;+ text-align: center;+ }+ .tour-stat__n {+ font-size: 1.8rem;+ font-weight: 800;+ background: linear-gradient(90deg, var(--accent), var(--accent-2));+ -webkit-background-clip: text;+ background-clip: text;+ color: transparent;+ font-variant-numeric: tabular-nums;+ }+ .tour-stat__l {+ font-size: 12.5px;+ color: #8b93a7;+ margin-top: 4px;+ }+ /* Sections */+ .tour-section {+ margin-top: 64px;+ }+ .tour-section__title {+ font-size: 1.5rem;+ font-weight: 700;+ margin: 0 0 8px;+ text-align: center;+ }+ .tour-section__lead {+ color: #8b93a7;+ text-align: center;+ margin: 0 auto 28px;+ max-width: 560px;+ font-size: 15px;+ }+ .tour-how {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));+ gap: 16px;+ }+ .tour-how__card {+ background: rgba(255, 255, 255, 0.035);+ border: 1px solid rgba(255, 255, 255, 0.08);+ border-radius: 16px;+ padding: 22px;+ }+ .tour-how__icon {+ width: 42px;+ height: 42px;+ border-radius: 11px;+ display: grid;+ place-items: center;+ font-size: 20px;+ background: rgba(122, 162, 255, 0.12);+ border: 1px solid rgba(122, 162, 255, 0.22);+ margin-bottom: 14px;+ }+ .tour-how__h {+ font-weight: 700;+ margin: 0 0 6px;+ font-size: 16px;+ }+ .tour-how__p {+ color: #9aa3b6;+ font-size: 14px;+ line-height: 1.5;+ margin: 0;+ }+ /* Chapters */+ .tour-chapters {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));+ gap: 14px;+ }+ .tour-chapter {+ display: flex;+ align-items: center;+ gap: 16px;+ background: rgba(255, 255, 255, 0.035);+ border: 1px solid rgba(255, 255, 255, 0.08);+ border-radius: 14px;+ padding: 18px;+ transition: border-color 0.18s ease, background 0.18s ease;+ }+ .tour-chapter:hover {+ border-color: rgba(122, 162, 255, 0.3);+ background: rgba(122, 162, 255, 0.05);+ }+ .tour-chapter__num {+ flex: 0 0 auto;+ width: 38px;+ height: 38px;+ border-radius: 10px;+ display: grid;+ place-items: center;+ font-weight: 800;+ color: #0b0e16;+ background: linear-gradient(135deg, var(--accent), var(--accent-2));+ }+ .tour-chapter__body h3 {+ margin: 0 0 3px;+ font-size: 15.5px;+ }+ .tour-chapter__body p {+ margin: 0;+ font-size: 13px;+ color: #8b93a7;+ }+ .tour-final {+ text-align: center;+ margin-top: 68px;+ padding: 40px 24px;+ background: radial-gradient(120% 100% at 50% 0%, rgba(122, 162, 255, 0.1), transparent 70%);+ border: 1px solid rgba(255, 255, 255, 0.08);+ border-radius: 22px;+ }+ .tour-final h2 {+ font-size: 1.5rem;+ margin: 0 0 10px;+ }+ .tour-final p {+ color: #9aa3b6;+ margin: 0 0 22px;+ }+ </style>+ </head>+ <body class="tour-page">+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main class="tour-wrap">+ <section class="tour-hero">+ <span class="tour-eyebrow"><span class="dot"></span> Guided Tour</span>+ <h1 class="tour-h1">Let a 3D guide <span class="grad">walk you through</span> three.ws</h1>+ <p class="tour-sub">+ Press play and a 3D avatar steps onto the page, walks over to each feature,+ points right at it, and tells you what it does and how to use it — speaking+ out loud with a chat bubble over its head. It covers the whole platform, on+ the real live site, and you set the pace.+ </p>+ <div class="tour-cta-row">+ <button class="tour-btn tour-btn--primary" id="tour-start">▶ Start the guided tour</button>+ <a class="tour-btn" href="#how">How it works</a>+ </div>+ <p class="tour-resume" id="tour-resume">+ You have a tour in progress — <a href="#" id="tour-resume-link">pick it back up →</a>+ </p>+ </section>++ <div class="tour-stats" id="tour-stats">+ <div class="tour-stat"><div class="tour-stat__n" id="stat-features">—</div><div class="tour-stat__l">features visited</div></div>+ <div class="tour-stat"><div class="tour-stat__n" id="stat-minutes">~30</div><div class="tour-stat__l">minutes, paced by you</div></div>+ <div class="tour-stat"><div class="tour-stat__n" id="stat-chapters">6</div><div class="tour-stat__l">chapters</div></div>+ </div>++ <section class="tour-section" id="how">+ <h2 class="tour-section__title">How it works</h2>+ <p class="tour-section__lead">No video, no slides — the guide drives the actual site, so everything it points at is the real thing you'll use.</p>+ <div class="tour-how">+ <div class="tour-how__card">+ <div class="tour-how__icon">🚶</div>+ <h3 class="tour-how__h">It walks and points</h3>+ <p class="tour-how__p">The avatar moves across the page to stand beside each feature, faces it, and gestures — with a beam connecting the guide to exactly what it's talking about.</p>+ </div>+ <div class="tour-how__card">+ <div class="tour-how__icon">🗣️</div>+ <h3 class="tour-how__h">It speaks and captions</h3>+ <p class="tour-how__p">Every stop is narrated out loud and shown in a chat bubble above the guide's head, so you can listen, read, or mute the voice and just read along.</p>+ </div>+ <div class="tour-how__card">+ <div class="tour-how__icon">🎛️</div>+ <h3 class="tour-how__h">You're in control</h3>+ <p class="tour-how__p">Pause, skip ahead, step back, or scrub the progress bar anytime. Wander off to explore and the guide waits — press play and it takes you back to where you were.</p>+ </div>+ </div>+ </section>++ <section class="tour-section">+ <h2 class="tour-section__title">What you'll see</h2>+ <p class="tour-section__lead">The tour runs as chapters — from building your first agent to taking it on-chain.</p>+ <div class="tour-chapters" id="tour-chapters"></div>+ </section>++ <section class="tour-final">+ <h2>Ready when you are</h2>+ <p>Bring your curiosity — the guide handles the rest.</p>+ <button class="tour-btn tour-btn--primary" id="tour-start-2">▶ Start the guided tour</button>+ </section>+ </main>++ <script>+ // Friendly one-line summaries for each chapter, keyed by curriculum+ // section id. The curriculum (built from data/pages.json) supplies the+ // authoritative titles and per-chapter stop counts at runtime.+ const CHAPTER_BLURB = {+ main: 'Get your bearings — the front door, discovery, and the marketplace.',+ build: 'Give your AI a body: avatars, a brain, a voice, and the studios.',+ crypto: 'Wallets, payments, token launches, and live market intelligence.',+ labs: 'The showcases — living demos that push the platform to full power.',+ 'agent-tools': 'Talk to your agents, manage them, and check their reputation.',+ learn: 'Docs, guides, and tutorials for going deeper on your own.',+ };++ const STATE_KEY = 'tws:tour:state';++ function startTour() {+ // The engine boots on the first stop's page via ?tour=start.+ fetch('/tour/curriculum.json', { cache: 'force-cache' })+ .then((r) => r.json())+ .then((c) => {+ const first = (c.stops && c.stops[0] && c.stops[0].path) || '/';+ location.href = first + '?tour=start';+ })+ .catch(() => {+ location.href = '/?tour=start';+ });+ }++ document.getElementById('tour-start').addEventListener('click', startTour);+ document.getElementById('tour-start-2').addEventListener('click', startTour);++ // Resume affordance when a tour is already in progress this session.+ try {+ const raw = sessionStorage.getItem(STATE_KEY);+ const st = raw ? JSON.parse(raw) : null;+ if (st && st.active) {+ const resume = document.getElementById('tour-resume');+ resume.style.display = 'block';+ document.getElementById('tour-resume-link').addEventListener('click', (e) => {+ e.preventDefault();+ fetch('/tour/curriculum.json', { cache: 'force-cache' })+ .then((r) => r.json())+ .then((c) => {+ const stop = (c.stops && c.stops[st.index || 0]) || c.stops[0];+ location.href = (stop ? stop.path : '/') + '?tour=1';+ })+ .catch(() => (location.href = '/?tour=1'));+ });+ }+ } catch (_) {}++ // Populate stats + chapter cards from the live curriculum.+ fetch('/tour/curriculum.json', { cache: 'force-cache' })+ .then((r) => r.json())+ .then((c) => {+ document.getElementById('stat-features').textContent = c.stopCount || (c.stops || []).length;+ document.getElementById('stat-minutes').textContent = '~' + (c.estimatedMinutes || 30);+ document.getElementById('stat-chapters').textContent = (c.sections || []).length || 6;++ const counts = {};+ (c.stops || []).forEach((s) => (counts[s.section] = (counts[s.section] || 0) + 1));+ const host = document.getElementById('tour-chapters');+ host.innerHTML = '';+ (c.sections || []).forEach((section, i) => {+ const n = counts[section.id] || 0;+ const card = document.createElement('div');+ card.className = 'tour-chapter';+ card.innerHTML =+ '<div class="tour-chapter__num">' + (i + 1) + '</div>' ++ '<div class="tour-chapter__body"><h3>' + escapeHtml(section.title) ++ ' <span style="color:#7f8aa0;font-weight:500;font-size:12px">· ' + n + ' stops</span></h3>' ++ '<p>' + escapeHtml(CHAPTER_BLURB[section.id] || '') + '</p></div>';+ host.appendChild(card);+ });+ })+ .catch(() => {+ /* curriculum not built yet — the static fallback stats still read well */+ });++ function escapeHtml(s) {+ return String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({+ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''',+ })[c]);+ }+ </script>++ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ </body>+</html>diff --git a/public/nav-data.js b/public/nav-data.jsindex 9e1629456..cb2149ba6 100644--- a/public/nav-data.js+++ b/public/nav-data.js@@ -82,6 +82,12 @@ export const NAV_GROUPS = [href: '/what-is',desc: 'Plain-English intro + real use-cases — start here',},+ {+ title: 'Take the guided tour',+ href: '/tour',+ badge: 'New',+ desc: 'A 3D guide walks you through every feature, live',+ },{title: '$THREE Token',href: '/three-token',diff --git a/public/nav.js b/public/nav.jsindex c2fbf4c4d..b7b61f08f 100644--- a/public/nav.js+++ b/public/nav.js@@ -102,7 +102,31 @@ function loadThemeSwitcher() {document.head.appendChild(s);}+// Load the site-wide Guided Tour engine (src/feature-tour.js → /feature-tour.js)+// only when a tour is starting (?tour=) or already in progress (sessionStorage).+// Runs before the nav-container short-circuit below so it also boots on the+// full-screen 3D pages the tour visits (e.g. /forge, /club) which have no nav.+// The module is self-bootstrapping + idempotent; a page that never tours pays+// nothing for it.+function loadFeatureTour() {+ if (window.top !== window.self) return; // never inside an embed/iframe+ let active = false;+ try {+ const raw = sessionStorage.getItem('tws:tour:state');+ active = !!raw && JSON.parse(raw).active === true;+ } catch (_) {}+ const param = new URLSearchParams(location.search).get('tour');+ const wanted = param === 'start' || param === '1' || (param !== '0' && active);+ if (!wanted) return;+ if (document.querySelector('script[src="/feature-tour.js"]')) return;+ const s = document.createElement('script');+ s.type = 'module';+ s.src = '/feature-tour.js';+ document.head.appendChild(s);+}+function boot() {+ loadFeatureTour();loadCornerStack();loadGlossary();loadSearch();diff --git a/public/tour/curriculum.json b/public/tour/curriculum.jsonindex f12e868fa..2f43d2995 100644--- a/public/tour/curriculum.json+++ b/public/tour/curriculum.json@@ -1,6 +1,6 @@{"version": 1,- "generatedAt": "2026-06-20T05:20:15.130Z",+ "generatedAt": "2026-06-20T05:33:35.841Z","generatedBy": "scripts/build-tour.mjs from data/pages.json","title": "The three.ws Guided Tour","tagline": "A 3D guide walks you through every feature, live, on the real site.",diff --git a/scripts/build-tour.mjs b/scripts/build-tour.mjsindex b14d0b6f1..b17a8d045 100644--- a/scripts/build-tour.mjs+++ b/scripts/build-tour.mjs@@ -46,6 +46,8 @@ const SECTION_INTROS = {// preferred over its /features/* landing-page twin.const DENY = new Set(['/login', '/register', '/forgot-password', '/sitemap',+ // The tour's own landing page is the entry point, not a stop on the route.+ '/tour',// /features/* are marketing landings for product pages already in the tour.'/features/ar', '/features/forge', '/features/scan', '/features/play','/features/walk', '/features/studio', '/features/marketplace',diff --git a/scripts/extension-screenshots.mjs b/scripts/extension-screenshots.mjsindex b9c832eec..ea3a90a3a 100644--- a/scripts/extension-screenshots.mjs+++ b/scripts/extension-screenshots.mjs@@ -8,16 +8,22 @@// marquee-1280x800.png — marquee promotional image// screenshot-1..5.png — 1280×800 screenshots of the real product//-// The five screenshots are taken from a real Chromium (Playwright) driving the-// real extension surfaces — the avatar walking on real content pages, the popup-// avatar picker, the settings page, and the avatar narrating with its speech-// bubble. Avatars render from the live /walk-embed (WALK_EMBED_BASE, default-// http://localhost:3000 so the screenshots use the current source build); the-// popup/options grids list real public three.ws avatars and the real voice-// catalog. Nothing is mocked.+// Everything is captured from the real product with a real Chromium (Playwright):+// • The popup and settings pages are the real extension pages, listing real+// public three.ws avatars and the real voice catalog.+// • The avatar is the real /walk-embed 3D render (WALK_EMBED_BASE, default+// http://localhost:3000 so shots use the current source build).+// • The host pages (article / social) are real, live websites.//-// Prereqs: `npm run build:extension` (so dist/extension exists) and a running-// source server at WALK_EMBED_BASE (`npm run dev`).+// The avatar-on-a-site shots composite the real transparent avatar render over a+// real site screenshot. They are layered rather than captured in one frame only+// because headless software-GL Chromium cannot render WebGL inside a cross-origin+// iframe on a heavy host page without crashing — the pixels in both layers are+// the genuine product. In a real browser the extension renders the same avatar+// in-page directly.+//+// Prereqs: `npm run build:extension` (dist/extension) and a running source server+// at WALK_EMBED_BASE (`npm run dev`).//// node scripts/extension-screenshots.mjs//@@ -34,12 +40,11 @@ const root = join(__dirname, '..');const EXT_DIST = join(root, 'dist', 'extension');const OUT = join(root, 'extensions', 'walk-avatar', 'store-assets');const BASE = (process.env.WALK_EMBED_BASE || 'http://localhost:3000').replace(/\/$/, '');-const BASE_ORIGIN = new URL(BASE).origin;const THREEWS = 'https://three.ws';const W = 1280;const H = 800;-const AVATAR_LOAD_MS = 26000; // software-GL avatar bring-up budget+const GL_ARGS = ['--no-sandbox', '--enable-unsafe-swiftshader', '--disable-dev-shm-usage', '--disable-gpu-process-crash-limit'];mkdirSync(OUT, { recursive: true });@@ -48,18 +53,31 @@ if (!existsSync(join(EXT_DIST, 'popup.html'))) {process.exit(1);}-// ── Real public-avatar catalog (used for the popup/options grids) ─────────────-// Pulled once from the live, no-auth endpoint so the grids show real models.+// Software GL can SEGV the GPU process; retry the whole browser session.+async function withBrowser(fn, { attempts = 4, args = GL_ARGS } = {}) {+ let lastErr;+ for (let i = 0; i < attempts; i++) {+ const browser = await chromium.launch({ args });+ try {+ const out = await fn(browser);+ await browser.close();+ return out;+ } catch (err) {+ lastErr = err;+ await browser.close().catch(() => {});+ console.warn(` retry ${i + 1}/${attempts}: ${String(err.message || err).split('\n')[0]}`);+ }+ }+ throw lastErr;+}++// ── Real public-avatar catalog (popup/options grids) ──────────────────────────async function fetchPublicAvatars(limit = 48) {- const res = await fetch(`${THREEWS}/api/avatars/public?limit=${limit}`, {- headers: { Accept: 'application/json' },- });+ const res = await fetch(`${THREEWS}/api/avatars/public?limit=${limit}`, { headers: { Accept: 'application/json' } });if (!res.ok) throw new Error(`/api/avatars/public ${res.status}`);const body = await res.json();- const avatars = (body.avatars || []).filter((a) => a && a.id);- // Thumbnailed avatars first so the grids read well, then the rest. Normalize- // into the shape both popup.js and options.js consume.- return avatars+ return (body.avatars || [])+ .filter((a) => a && a.id).map((a) => ({id: a.id,name: a.name,@@ -72,34 +90,102 @@ async function fetchPublicAvatars(limit = 48) {.sort((a, b) => Number(b.has_thumbnail) - Number(a.has_thumbnail));}-// ── Tiny static server for the built extension pages ──────────────────────────-const MIME = {- '.html': 'text/html; charset=utf-8',- '.js': 'text/javascript; charset=utf-8',- '.css': 'text/css; charset=utf-8',- '.png': 'image/png',- '.svg': 'image/svg+xml',- '.json': 'application/json',-};+// ── Real avatar render, transparent + trimmed ─────────────────────────────────+async function captureAvatar({ narrate = null } = {}) {+ const buf = await withBrowser(async (browser) => {+ const ctx = await browser.newContext({ viewport: { width: 460, height: 680 }, deviceScaleFactor: 2 });+ const page = await ctx.newPage();+ await page.goto(`${BASE}/walk-embed?controls=none&autoplay=true&ground=false&orbit=false&bg=transparent`, {+ waitUntil: 'domcontentloaded',+ timeout: 30000,+ });+ // Wait until the embed reports the avatar is up (status leaves "loading…").+ let ready = false;+ for (let i = 0; i < 16; i++) {+ await page.waitForTimeout(2000);+ const s = await page.evaluate(() => document.getElementById('walk-status')?.textContent || '');+ if (s && !/loading/i.test(s)) { ready = true; break; }+ }+ if (!ready) throw new Error('avatar did not finish loading');+ if (narrate) {+ await page.evaluate((text) => {+ window.postMessage({ type: 'walk:setMotion', motion: 'idle' }, '*');+ window.postMessage({ type: 'walk:narrate', text }, '*');+ }, narrate);+ await page.waitForTimeout(2500);+ } else {+ await page.waitForTimeout(800);+ }+ return page.screenshot({ omitBackground: true });+ });+ return sharp(buf).trim().png().toBuffer();+}++// ── Real site screenshot (no WebGL in the host page → stable) ──────────────────+async function dismissConsent(page) {+ for (const label of ['Accept all', 'Accept', 'I agree', 'Agree', 'Got it', 'Allow all']) {+ const btn = page.getByRole('button', { name: new RegExp(`^\\s*${label}\\s*$`, 'i') }).first();+ if (await btn.count().catch(() => 0)) {+ await btn.click({ timeout: 1500 }).catch(() => {});+ await page.waitForTimeout(300);+ break;+ }+ }+}+async function removeClutter(page) {+ await page.evaluate(() => {+ const sel = [+ '#siteNotice', '.mw-dismissable-notice', '#centralNotice', '.frb', '[class*="frbanner"]',+ '[id*="cookie"]', '[class*="cookie"]', '[id*="consent"]', '[class*="consent"]',+ '[class*="gdpr"]', '[aria-label*="cookie" i]',+ ];+ for (const s of sel) document.querySelectorAll(s).forEach((el) => el.remove());+ }).catch(() => {});+}+async function captureSite(candidates) {+ return withBrowser(async (browser) => {+ const ctx = await browser.newContext({ viewport: { width: W, height: H }, deviceScaleFactor: 1, ignoreHTTPSErrors: true });+ const page = await ctx.newPage();+ let loaded = false;+ for (const url of candidates) {+ try {+ await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30000 });+ loaded = true;+ break;+ } catch { /* next */ }+ }+ if (!loaded) throw new Error(`no candidate loaded: ${candidates.join(', ')}`);+ await dismissConsent(page);+ await removeClutter(page);+ await page.waitForTimeout(1000);+ await removeClutter(page);+ return page.screenshot();+ });+}++// ── Composite the real avatar over the real site ──────────────────────────────+async function compositeAvatar(siteBuf, avatarBuf, { heightPx = 380, margin = 26, position = 'bottom-right' } = {}) {+ const av = await sharp(avatarBuf).resize({ height: heightPx }).png().toBuffer();+ const m = await sharp(av).metadata();+ const left = position.includes('left') ? margin : W - (m.width || 240) - margin;+ const top = H - (m.height || heightPx) - margin + 8;+ return sharp(siteBuf).composite([{ input: av, left: Math.round(left), top: Math.round(top) }]).png().toBuffer();+}++// ── Extension pages: static server + chrome.* shim + real API routing ─────────+const MIME = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.png': 'image/png', '.svg': 'image/svg+xml', '.json': 'application/json' };function serveExtension() {return new Promise((resolve) => {const server = http.createServer((req, res) => {const path = decodeURIComponent((req.url || '/').split('?')[0]);const file = join(EXT_DIST, path === '/' ? 'popup.html' : path);- if (!file.startsWith(EXT_DIST) || !existsSync(file)) {- res.writeHead(404).end('not found');- return;- }+ if (!file.startsWith(EXT_DIST) || !existsSync(file)) { res.writeHead(404).end('not found'); return; }res.writeHead(200, { 'content-type': MIME[extname(file)] || 'application/octet-stream' });res.end(readFileSync(file));});server.listen(0, '127.0.0.1', () => resolve(server));});}--// chrome.* runtime shim so the real popup.js / options.js run outside the-// extension host. Storage is in-memory; messages get sensible replies; the-// avatar/voice data still comes over the real network (routed below).function chromeShim(cfg) {return `(${((c) => {const store = { sync: { ...c.sync }, local: { ...c.local }, session: {} };@@ -118,373 +204,158 @@ function chromeShim(cfg) {});const replies = {'get-state': { session: c.session, settings: store.sync },- 'check-site': { allowed: true },- 'toggle-tab': { ok: true },- 'update-settings': { ok: true },- 'set-avatar': { ok: true },- 'clear-session': { ok: true },+ 'check-site': { allowed: true }, 'toggle-tab': { ok: true }, 'update-settings': { ok: true },+ 'set-avatar': { ok: true }, 'clear-session': { ok: true },};window.chrome = {runtime: {sendMessage: (m) => Promise.resolve(replies[m && m.type] ?? {}),onMessage: { addListener() {}, removeListener() {} },- openOptionsPage() {},- getManifest: () => ({ version: c.version }),- getURL: (p) => p,- lastError: null,+ openOptionsPage() {}, getManifest: () => ({ version: c.version }), getURL: (p) => p, lastError: null,},storage: { sync: area('sync'), local: area('local'), session: area('session') },tabs: {query: () => Promise.resolve([{ id: 1, url: c.currentUrl, title: 'Example' }]),get: () => Promise.resolve({ id: 1, url: c.currentUrl }),- create() {},- remove() {},- sendMessage() {},- onUpdated: { addListener() {} },+ create() {}, remove() {}, sendMessage() {}, onUpdated: { addListener() {} },},};}).toString()})(${JSON.stringify(cfg)})`;}--// Route the extension's three.ws API calls to real data. Avatar grids → live-// public catalog; voices → the genuine repo catalog; identity → minimal ok.async function routeApi(context, avatars) {await context.route('**/three.ws/api/**', async (route) => {const url = route.request().url();- const reply = (obj) =>- route.fulfill({- status: 200,- contentType: 'application/json',- headers: { 'access-control-allow-origin': '*' },- body: JSON.stringify(obj),- });- if (/\/api\/avatars\/(mine|featured)\b/.test(url) || /\/api\/avatars\?/.test(url)) {- return reply({ avatars });- }- if (/\/api\/tts\/voices\b/.test(url)) {- return reply({ enabled: true, default: DEFAULT_VOICE, voices: TTS_VOICES, providers: { nvidia: true, openai: true } });- }- if (/\/api\/(me|threews\/me)\b/.test(url)) {- return reply({ user: { handle: '@you', username: 'you' } });- }+ const reply = (obj) => route.fulfill({ status: 200, contentType: 'application/json', headers: { 'access-control-allow-origin': '*' }, body: JSON.stringify(obj) });+ if (/\/api\/avatars\/(mine|featured)\b/.test(url) || /\/api\/avatars\?/.test(url)) return reply({ avatars });+ if (/\/api\/tts\/voices\b/.test(url)) return reply({ enabled: true, default: DEFAULT_VOICE, voices: TTS_VOICES, providers: { nvidia: true, openai: true } });+ if (/\/api\/(me|threews\/me)\b/.test(url)) return reply({ user: { handle: '@you', username: 'you' } });return route.continue();});}-// ── Avatar-on-page mount (faithful to extensions/walk-avatar/content.js) ───────-async function mountAvatarOnPage(page, { position = 'bottom-right', size = { w: 200, h: 290 } } = {}) {- await page.evaluate(- ({ base, origin, position, size }) => {- window.__walkTicks = 0;- window.addEventListener('message', (e) => {- if (e.origin !== origin) return;- const s = JSON.stringify(e.data || '');- if (s.includes('position') || s.includes('walk:ready')) window.__walkTicks++;- });- const c = document.createElement('div');- c.id = '__threews_walk_container__';- c.style.cssText = `position:fixed;width:${size.w}px;height:${size.h}px;z-index:2147483647;background:transparent;border-radius:14px;filter:drop-shadow(0 10px 28px rgba(0,0,0,0.32));`;- const m = '20px';- Object.assign(c.style, position === 'bottom-left'- ? { bottom: m, left: m }- : position === 'top-right'- ? { top: m, right: m }- : { bottom: m, right: m });- const f = document.createElement('iframe');- f.id = '__threews_walk_iframe__';- f.src = `${base}/walk-embed?controls=none&autoplay=true&ground=false&orbit=false&bg=transparent`;- f.allow = 'accelerometer; gyroscope; autoplay';- f.setAttribute('scrolling', 'no');- f.style.cssText = 'width:100%;height:100%;border:0;background:transparent;display:block;border-radius:14px;';- c.appendChild(f);- (document.body || document.documentElement).appendChild(c);- },- { base: BASE, origin: BASE_ORIGIN, position, size },- );- // Wait until the embed's render loop is emitting position ticks (avatar mesh- // loaded + animating), with a generous software-GL fallback.- await page- .waitForFunction(() => window.__walkTicks > 8, { timeout: AVATAR_LOAD_MS })- .catch(() => {});- await page.waitForTimeout(1500);-}--async function postToEmbed(page, message) {- await page.evaluate(- ({ message, origin }) => {- document.getElementById('__threews_walk_iframe__')?.contentWindow?.postMessage(message, origin);- },- { message, origin: BASE_ORIGIN },- );-}--// Dismiss the most common cookie/consent overlays so they don't pollute shots.-async function dismissConsent(page) {- const labels = ['Accept all', 'Accept', 'I agree', 'Got it', 'Allow all', 'Agree'];- for (const label of labels) {- const btn = page.getByRole('button', { name: new RegExp(`^\\s*${label}\\s*$`, 'i') }).first();- if (await btn.count().catch(() => 0)) {- await btn.click({ timeout: 1500 }).catch(() => {});- await page.waitForTimeout(300);- break;- }- }-}--// Strip fundraising/cookie/consent overlays that pollute a clean shot.-async function removeClutter(page) {- await page.evaluate(() => {- const sel = [- '#siteNotice', '.mw-dismissable-notice', '#centralNotice', '.frb', '[class*="frbanner"]',- '[id*="cookie"]', '[class*="cookie"]', '[id*="consent"]', '[class*="consent"]',- '[class*="gdpr"]', '[aria-label*="cookie" i]', '[class*="banner--cookie"]',- ];- for (const s of sel) document.querySelectorAll(s).forEach((el) => el.remove());- }).catch(() => {});+// Compose a small extension surface onto a branded 1280×800 frame.+async function composeSurface(shotBuf, outName, caption) {+ const bg = await sharp(tileSvg(W, H, { title: '', sub: '' })).png().toBuffer();+ const meta = await sharp(shotBuf).metadata();+ const sw = meta.width, sh = meta.height;+ const mask = Buffer.from(`<svg xmlns="http://www.w3.org/2000/svg" width="${sw}" height="${sh}"><rect width="${sw}" height="${sh}" rx="16" ry="16"/></svg>`);+ const rounded = await sharp(shotBuf).composite([{ input: mask, blend: 'dest-in' }]).png().toBuffer();+ const left = Math.round((W - sw) / 2);+ const top = Math.round((H - sh) / 2) - 20;+ const shadow = Buffer.from(`<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}"><rect x="${left - 6}" y="${top + 12}" width="${sw + 12}" height="${sh + 12}" rx="22" fill="#000" opacity="0.5"/></svg>`);+ const cap = caption ? [{ input: Buffer.from(`<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="80"><text x="${W / 2}" y="46" text-anchor="middle" font-family="'Inter',system-ui,sans-serif" font-size="24" font-weight="600" fill="#fafafa">${caption}</text></svg>`), left: 0, top: H - 96 }] : [];+ await sharp(bg).composite([{ input: await sharp(shadow).blur(14).png().toBuffer(), left: 0, top: 0 }, { input: rounded, left, top }, ...cap]).png().toFile(join(OUT, outName));+ console.log(`✓ ${outName}`);}-async function gotoContent(page, candidates) {- for (const url of candidates) {- try {- await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30000 });- await dismissConsent(page);- await removeClutter(page);- await page.waitForTimeout(1000);- await removeClutter(page);- return url;- } catch {- /* try next */- }- }- throw new Error(`none of the candidate pages loaded: ${candidates.join(', ')}`);+async function snapExtensionPage(extBase, avatars, { file, viewport, shim, tabName, thumbSel, then }) {+ return withBrowser(async (browser) => {+ const ctx = await browser.newContext({ viewport, deviceScaleFactor: 2 });+ await routeApi(ctx, avatars);+ const page = await ctx.newPage();+ await page.addInitScript(shim);+ await page.goto(`${extBase}/${file}`, { waitUntil: 'domcontentloaded' });+ if (tabName) await page.getByRole('tab', { name: tabName }).click().catch(() => {});+ if (thumbSel) await page.waitForSelector(thumbSel, { timeout: 15000 }).catch(() => {});+ await page.waitForTimeout(2500);+ return then(page);+ }, { args: ['--no-sandbox', '--disable-dev-shm-usage'] });}-// ── Store-listing graphics (icon, promo tile, marquee) ────────────────────────+// ── Listing graphics ──────────────────────────────────────────────────────────const ICON_SVG = readFileSync(join(root, 'public', 'pwa-icon.svg'));-function tileSvg(w, h, { title, sub, big = 40, small = 19 }) {return Buffer.from(`<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}"><defs>- <linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">- <stop offset="0" stop-color="#0a0e16"/>- <stop offset="0.55" stop-color="#0d1422"/>- <stop offset="1" stop-color="#0a0a0a"/>- </linearGradient>- <radialGradient id="glow" cx="78%" cy="28%" r="60%">- <stop offset="0" stop-color="#7dd3fc" stop-opacity="0.22"/>- <stop offset="1" stop-color="#7dd3fc" stop-opacity="0"/>- </radialGradient>+ <linearGradient id="bg" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#0a0e16"/><stop offset="0.55" stop-color="#0d1422"/><stop offset="1" stop-color="#0a0a0a"/></linearGradient>+ <radialGradient id="glow" cx="78%" cy="28%" r="60%"><stop offset="0" stop-color="#7dd3fc" stop-opacity="0.22"/><stop offset="1" stop-color="#7dd3fc" stop-opacity="0"/></radialGradient></defs><rect width="${w}" height="${h}" fill="url(#bg)"/><rect width="${w}" height="${h}" fill="url(#glow)"/><text x="50" y="${h / 2 - 8}" font-family="'Space Grotesk','Inter',system-ui,sans-serif" font-size="${big}" font-weight="700" fill="#fafafa">${title}</text><text x="52" y="${h / 2 + 26}" font-family="'Inter',system-ui,sans-serif" font-size="${small}" fill="#a1a1aa">${sub}</text>- <text x="50" y="${h / 2 - 8}" font-family="'Space Grotesk','Inter',system-ui,sans-serif" font-size="${big}" font-weight="700" fill="#7dd3fc" opacity="0">${title}</text></svg>`);}-async function buildIcon() {await sharp(ICON_SVG).resize(128, 128).png().toFile(join(OUT, 'icon-128.png'));console.log('✓ icon-128.png');}-async function buildPromoTile() {- const w = 440, h = 280;- const iconSize = 132;+ const w = 440, h = 280, iconSize = 132;const bg = await sharp(tileSvg(w, h, { title: 'Walk Avatar', sub: 'Your 3D companion, on every site', big: 34, small: 15 })).png().toBuffer();const icon = await sharp(ICON_SVG).resize(iconSize, iconSize).png().toBuffer();- await sharp(bg)- .composite([{ input: icon, left: w - iconSize - 28, top: (h - iconSize) / 2 }])- .png()- .toFile(join(OUT, 'promo-tile-440x280.png'));+ await sharp(bg).composite([{ input: icon, left: w - iconSize - 28, top: (h - iconSize) / 2 }]).png().toFile(join(OUT, 'promo-tile-440x280.png'));console.log('✓ promo-tile-440x280.png');}--async function buildMarquee(walkShot) {+async function buildMarquee(avatarBuf) {const w = 1280, h = 800;const bg = await sharp(tileSvg(w, h, { title: 'three.ws · Walk Avatar', sub: 'Walk your 3D avatar on any website — and have it read pages aloud.', big: 58, small: 24 })).png().toBuffer();const icon = await sharp(ICON_SVG).resize(180, 180).png().toBuffer();const composites = [{ input: icon, left: 50, top: 70 }];- // Cut out the avatar from a real on-page shot and feature it on the marquee.- if (walkShot && existsSync(walkShot)) {- const fig = await sharp(walkShot)- .extract({ left: 980, top: 360, width: 300, height: 440 })- .resize({ height: 560 })- .png()- .toBuffer();- const meta = await sharp(fig).metadata();- composites.push({ input: fig, left: w - (meta.width || 300) - 40, top: h - 560 });+ if (avatarBuf) {+ const fig = await sharp(avatarBuf).resize({ height: 620 }).png().toBuffer();+ const m = await sharp(fig).metadata();+ composites.push({ input: fig, left: w - (m.width || 360) - 70, top: h - (m.height || 620) - 20 });}await sharp(bg).composite(composites).png().toFile(join(OUT, 'marquee-1280x800.png'));console.log('✓ marquee-1280x800.png');}-// Compose a small extension surface (popup) onto a branded 1280×800 canvas with-// rounded corners + shadow so the listing screenshot fills the required frame.-async function composeSurface(shotBuf, outName, caption) {- const bg = await sharp(tileSvg(W, H, { title: '', sub: '' })).png().toBuffer();- const meta = await sharp(shotBuf).metadata();- const sw = meta.width, sh = meta.height;- const radius = 16;- const mask = Buffer.from(`<svg xmlns="http://www.w3.org/2000/svg" width="${sw}" height="${sh}"><rect width="${sw}" height="${sh}" rx="${radius}" ry="${radius}"/></svg>`);- const rounded = await sharp(shotBuf)- .composite([{ input: mask, blend: 'dest-in' }])- .png()- .toBuffer();- const left = Math.round((W - sw) / 2);- const top = Math.round((H - sh) / 2) - 20;- const shadow = Buffer.from(`<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}"><rect x="${left - 6}" y="${top + 10}" width="${sw + 12}" height="${sh + 12}" rx="22" fill="#000" opacity="0.45"/></svg>`);- const cap = caption- ? [{ input: Buffer.from(`<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="80"><text x="${W / 2}" y="46" text-anchor="middle" font-family="'Inter',system-ui,sans-serif" font-size="24" font-weight="600" fill="#fafafa">${caption}</text></svg>`), left: 0, top: H - 96 }]- : [];- await sharp(bg)- .composite([- { input: await sharp(shadow).blur(14).png().toBuffer(), left: 0, top: 0 },- { input: rounded, left, top },- ...cap,- ])- .png()- .toFile(join(OUT, outName));- console.log(`✓ ${outName}`);-}-// ── Main ──────────────────────────────────────────────────────────────────────const avatars = await fetchPublicAvatars(48);console.log(`Loaded ${avatars.length} real public avatars for the grids.`);const extServer = await serveExtension();-const extPort = extServer.address().port;-const extBase = `http://127.0.0.1:${extPort}`;--// Software-GL Chromium in Codespaces can SEGV the GPU process on heavy pages, and-// a crashed GPU process poisons the whole browser. So each capture runs in its-// own short-lived browser — a crash is contained to one shot and we retry it.-const LAUNCH_ARGS = [- '--no-sandbox',- '--enable-unsafe-swiftshader',- '--disable-dev-shm-usage', // Codespaces /dev/shm is tiny — avoids "Target crashed"- '--disable-gpu-process-crash-limit',- // In production the avatar iframe is https://three.ws/walk-embed inside an- // https host page — no mixed content. For local capture the embed is served- // over http, so allow the otherwise-blocked insecure iframe.- '--allow-running-insecure-content',- `--unsafely-treat-insecure-origin-as-secure=${BASE_ORIGIN}`,-];--async function withPage(fn, { attempts = 2 } = {}) {- let lastErr;- for (let i = 0; i < attempts; i++) {- const browser = await chromium.launch({ args: LAUNCH_ARGS });- try {- // bypassCSP lets us inject the avatar iframe onto pages whose own CSP- // would otherwise forbid framing a third-party origin.- const context = await browser.newContext({- viewport: { width: W, height: H },- deviceScaleFactor: 1,- bypassCSP: true,- ignoreHTTPSErrors: true,- });- await routeApi(context, avatars);- const page = await context.newPage();- const out = await fn(page);- await browser.close();- return out;- } catch (err) {- lastErr = err;- await browser.close().catch(() => {});- console.warn(` retry (${i + 1}/${attempts}): ${String(err.message || err).split('\n')[0]}`);- }- }- throw lastErr;-}+const extBase = `http://127.0.0.1:${extServer.address().port}`;try {- // ── Screenshot 1: avatar walking on a real content/article page ──────────────- await withPage(async (page) => {- await gotoContent(page, [- 'https://en.wikipedia.org/wiki/Web_browser',- 'https://en.wikipedia.org/wiki/World_Wide_Web',- ]);- await mountAvatarOnPage(page, { position: 'bottom-right' });- await page.screenshot({ path: join(OUT, 'screenshot-1.png') });- });+ // Real avatar renders (reused across the on-site shots + marquee).+ console.log('Rendering avatar (walking)…');+ const avatarWalk = await captureAvatar();+ console.log('Rendering avatar (narrating)…');+ const avatarTalk = await captureAvatar({ narrate: 'Let me read this story to you while you keep browsing — tap me to mute any time.' });++ // 1: avatar on a real content/article page+ const site1 = await captureSite(['https://en.wikipedia.org/wiki/Web_browser', 'https://en.wikipedia.org/wiki/World_Wide_Web']);+ await sharp(await compositeAvatar(site1, avatarWalk, { heightPx: 400 })).toFile(join(OUT, 'screenshot-1.png'));console.log('✓ screenshot-1.png (avatar on an article page)');- // ── Screenshot 4: avatar narrating with its speech bubble ────────────────────- // text.npr.org is a real, deliberately lightweight news site — ideal for the- // narration shot and gentle on software GL.- await withPage(async (page) => {- await gotoContent(page, [- 'https://text.npr.org',- 'https://en.wikipedia.org/wiki/Three.js',- ]);- await mountAvatarOnPage(page, { position: 'bottom-right' });- await postToEmbed(page, { type: 'walk:setMotion', motion: 'idle' });- await postToEmbed(page, {- type: 'walk:narrate',- text: 'Let me read this story to you while you keep browsing — tap me to mute any time.',- });- await page.waitForTimeout(2500);- await page.screenshot({ path: join(OUT, 'screenshot-4.png') });- });+ // 4: avatar narrating with its speech bubble, on a real news page+ const site4 = await captureSite(['https://text.npr.org', 'https://en.wikipedia.org/wiki/Three.js']);+ await sharp(await compositeAvatar(site4, avatarTalk, { heightPx: 440 })).toFile(join(OUT, 'screenshot-4.png'));console.log('✓ screenshot-4.png (avatar narrating)');- // ── Screenshot 5: avatar on a real social page ───────────────────────────────- await withPage(async (page) => {- await gotoContent(page, [- 'https://mastodon.social/public/local',- 'https://mastodon.social/explore',- 'https://en.wikipedia.org/wiki/Social_media',- ]);- await mountAvatarOnPage(page, { position: 'bottom-right' });- await page.screenshot({ path: join(OUT, 'screenshot-5.png') });- });+ // 5: avatar on a real social page+ const site5 = await captureSite(['https://mastodon.social/public/local', 'https://mastodon.social/explore', 'https://en.wikipedia.org/wiki/Social_media']);+ await sharp(await compositeAvatar(site5, avatarWalk, { heightPx: 400, position: 'bottom-right' })).toFile(join(OUT, 'screenshot-5.png'));console.log('✓ screenshot-5.png (avatar on a social page)');- // ── Screenshot 2: popup with the avatar selection grid ───────────────────────- await withPage(async (page) => {- await page.addInitScript(- chromeShim({- version: '1.0.0',- currentUrl: 'https://en.wikipedia.org/wiki/Web_browser',- session: null,- sync: { walkSpeed: 1.2, position: 'bottom-right', sizePreset: 'medium', narrationEnabled: true, voice: DEFAULT_VOICE },- local: {},- }),- );- await page.setViewportSize({ width: 360, height: 600 });- await page.goto(`${extBase}/popup.html`, { waitUntil: 'domcontentloaded' });- // Move to the Featured grid (real public avatars, no sign-in needed).- await page.getByRole('tab', { name: /featured/i }).click().catch(() => {});- await page.waitForSelector('.avatar-thumb:not(.skeleton)', { timeout: 15000 }).catch(() => {});- await page.waitForTimeout(2500);- const popupShot = await page.screenshot();- await composeSurface(popupShot, 'screenshot-2.png', 'Pick any avatar — your own or a featured 3D character');+ // 2: popup with the avatar selection grid (real public avatars)+ const popupShot = await snapExtensionPage(extBase, avatars, {+ file: 'popup.html',+ viewport: { width: 360, height: 600 },+ shim: chromeShim({ version: '1.0.0', currentUrl: 'https://en.wikipedia.org/wiki/Web_browser', session: null, sync: { walkSpeed: 1.2, position: 'bottom-right', sizePreset: 'medium', narrationEnabled: true, voice: DEFAULT_VOICE }, local: {} }),+ tabName: /featured/i,+ thumbSel: '.avatar-thumb:not(.skeleton)',+ then: (page) => page.screenshot(),});+ await composeSurface(popupShot, 'screenshot-2.png', 'Pick any avatar — your own or a featured 3D character');- // ── Screenshot 3: settings page ──────────────────────────────────────────────- await withPage(async (page) => {- await page.addInitScript(- chromeShim({- version: '1.0.0',- currentUrl: 'https://three.ws',- session: 'demo-session',- sync: { walkSpeed: 1.2, position: 'bottom-right', sizePreset: 'medium', narrationEnabled: true, voice: DEFAULT_VOICE },- local: {},- }),- );- await page.goto(`${extBase}/options.html`, { waitUntil: 'domcontentloaded' });- await page.getByRole('tab', { name: /featured/i }).click().catch(() => {});- await page.waitForSelector('.av-thumb:not(.skeleton)', { timeout: 15000 }).catch(() => {});- await page.waitForTimeout(2000);- await page.screenshot({ path: join(OUT, 'screenshot-3.png') });+ // 3: settings page+ const optsShot = await snapExtensionPage(extBase, avatars, {+ file: 'options.html',+ viewport: { width: 940, height: 720 },+ shim: chromeShim({ version: '1.0.0', currentUrl: 'https://three.ws', session: 'demo-session', sync: { walkSpeed: 1.2, position: 'bottom-right', sizePreset: 'medium', narrationEnabled: true, voice: DEFAULT_VOICE }, local: {} }),+ tabName: /featured/i,+ thumbSel: '.av-thumb:not(.skeleton)',+ then: (page) => page.screenshot(),});- console.log('✓ screenshot-3.png (settings page)');+ await composeSurface(optsShot, 'screenshot-3.png', 'Set defaults, narration voice, and per-site rules');- // ── Listing graphics ─────────────────────────────────────────────────────────+ // Listing graphicsawait buildIcon();await buildPromoTile();- await buildMarquee(join(OUT, 'screenshot-1.png'));+ await buildMarquee(avatarWalk);} finally {extServer.close();}diff --git a/vercel.json b/vercel.jsonindex ab2e112ad..67514736f 100644--- a/vercel.json+++ b/vercel.json@@ -3431,6 +3431,14 @@"src": "/what-is/","dest": "/what-is.html"},+ {+ "src": "/tour",+ "dest": "/tour.html"+ },+ {+ "src": "/tour/",+ "dest": "/tour.html"+ },{"src": "/features","dest": "/features.html"diff --git a/vite.config.js b/vite.config.jsindex 5de60899c..37240fbd5 100644--- a/vite.config.js+++ b/vite.config.js@@ -281,6 +281,7 @@ const appConfig = {'app-next': resolve(__dirname, 'pages/app-next.html'),home: resolve(__dirname, 'pages/home.html'),'what-is': resolve(__dirname, 'pages/what-is.html'),+ tour: resolve(__dirname, 'pages/tour.html'),features: resolve(__dirname, 'pages/features.html'),'features-ar': resolve(__dirname, 'pages/features/ar.html'),'features-forge': resolve(__dirname, 'pages/features/forge.html'),diff --git a/workers/agent-sniper/intel/wallet-graph.js b/workers/agent-sniper/intel/wallet-graph.jsnew file mode 100644index 000000000..48759cae6--- /dev/null+++ b/workers/agent-sniper/intel/wallet-graph.js@@ -0,0 +1,234 @@+// Smart-Money Wallet Graph — pure scoring + clustering math (no I/O).+//+// The recompute job (recompute-wallet-graph.js) joins pump_coin_wallets ⋈+// pump_coin_outcomes and feeds the rows through here. Everything below is+// deterministic over plain arrays so it pins to fixtures and the live API and the+// worker can never disagree on what a wallet's reputation is.+//+// Honesty (Rule 1): a wallet's realized_score is derived ONLY from real observed+// buys and real outcomes. New wallets are regressed toward neutral until they have+// enough judged launches — we never fabricate confidence. No hand-curated lists,+// no invented "famous trader" names: a wallet is just an on-chain address.++// A coin is a "winner" for a wallet that net-bought it if it graduated or pumped.+// ATH multiple weights HOW good a win was (a 50x graduate beats a 3x pump).+const WINNING_OUTCOMES = new Set(['graduated', 'pumped']);++// Confidence regression — mirrors trader-stats.js. A wallet with few judged+// launches regresses toward NEUTRAL_SCORE so a 1-for-1 fluke can't read as elite.+const CONFIDENCE_FULL_AT = 8; // judged launches for full statistical confidence+const NEUTRAL_SCORE = 38; // unproven wallets regress toward this (below mid)++// ATH normalization: a mean ATH multiple of ~ATH_TANH_X across wins maps to a+// strongly positive sub-score. tanh keeps a single moonshot from saturating.+const ATH_TANH_X = 8;++// Label thresholds (applied AFTER confidence regression, so they require a record).+const PROVEN_SCORE = 70; // smart_money label floor+const STRONG_SCORE = 55; // strong label floor+const MIN_JUDGED_FOR_LABEL = 3; // need this many judged launches to earn a quality label++const clamp = (x, lo, hi) => Math.min(hi, Math.max(lo, x));+const clamp01 = (x) => clamp(Number.isFinite(x) ? x : 0, 0, 1);+const num = (v, d = 0) => (Number.isFinite(Number(v)) ? Number(v) : d);+const tanh = (x) => Math.tanh(x);++/**+ * Score one wallet from its judged launches.+ *+ * @param {Array<{outcome:string, ath_multiple:number|null, net_buy_lamports:number,+ * first_seen:number|null, last_seen:number|null, is_fresh?:boolean}>} judged+ * one entry per coin this wallet net-bought that now has a final outcome.+ * @returns {{+ * trades_seen:number, winners:number, losers:number, win_rate:number,+ * avg_ath_multiple:number, realized_score:number, confidence:number,+ * labels:string[], first_seen:number|null, last_seen:number|null+ * }}+ */+export function scoreWallet(judged) {+ const rows = Array.isArray(judged) ? judged : [];+ const tradesSeen = rows.length;++ let winners = 0;+ let losers = 0;+ let athSum = 0;+ let athCount = 0;+ let firstSeen = null;+ let lastSeen = null;+ let freshObserved = 0;++ for (const r of rows) {+ const outcome = String(r.outcome || '');+ if (WINNING_OUTCOMES.has(outcome)) winners++;+ else losers++;++ const ath = num(r.ath_multiple, NaN);+ if (Number.isFinite(ath) && ath > 0) { athSum += ath; athCount++; }++ const fs = num(r.first_seen, NaN);+ const ls = num(r.last_seen, NaN);+ if (Number.isFinite(fs)) firstSeen = firstSeen == null ? fs : Math.min(firstSeen, fs);+ if (Number.isFinite(ls)) lastSeen = lastSeen == null ? ls : Math.max(lastSeen, ls);+ if (r.is_fresh) freshObserved++;+ }++ const winRate = tradesSeen ? winners / tradesSeen : 0;+ const avgAth = athCount ? athSum / athCount : 0;++ // Raw quality (0..1): win-rate is the backbone; ATH magnitude lifts wallets+ // that don't just clip 3x pumps but ride graduations to multiples.+ const winComponent = clamp01(winRate); // 0..1+ const athComponent = 0.5 + 0.5 * tanh((avgAth - 1) / ATH_TANH_X); // 0.5..1 for avgAth>=1+ let raw = winComponent * 0.7 + athComponent * 0.3;++ // Confidence regression toward neutral until the wallet has a real sample.+ const confidence = clamp(tradesSeen / CONFIDENCE_FULL_AT, 0, 1);+ const effective = raw * confidence + (NEUTRAL_SCORE / 100) * (1 - confidence);+ const realizedScore = Math.round(clamp(effective * 100, 0, 100));++ const labels = [];+ if (tradesSeen >= MIN_JUDGED_FOR_LABEL) {+ if (realizedScore >= PROVEN_SCORE) labels.push('smart_money');+ else if (realizedScore >= STRONG_SCORE) labels.push('strong');+ if (winRate <= 0.15 && winners === 0) labels.push('rugger');+ else if (realizedScore < NEUTRAL_SCORE) labels.push('weak');+ } else {+ labels.push('fresh');+ }+ // A wallet observed mostly via brand-new (no-history) accounts is flagged fresh+ // even with some sample — it behaves like a throwaway, not a tracked trader.+ if (tradesSeen > 0 && freshObserved / tradesSeen >= 0.8 && !labels.includes('fresh')) labels.push('fresh');++ return {+ trades_seen: tradesSeen,+ winners,+ losers,+ win_rate: Number(winRate.toFixed(4)),+ avg_ath_multiple: Number(avgAth.toFixed(3)),+ realized_score: realizedScore,+ confidence: Number(confidence.toFixed(3)),+ labels,+ first_seen: firstSeen,+ last_seen: lastSeen,+ };+}++// ── Union-Find over shared-funder edges ──────────────────────────────────────+// Two wallets are linked when they share the same on-chain funder. The connected+// components are the sybil/insider clusters: many "different" wallets fed by one+// source. cluster_id is the lexicographically smallest member (deterministic →+// idempotent reruns).++class UnionFind {+ constructor() { this.parent = new Map(); }+ find(x) {+ if (!this.parent.has(x)) { this.parent.set(x, x); return x; }+ let root = x;+ while (this.parent.get(root) !== root) root = this.parent.get(root);+ // Path compression.+ let cur = x;+ while (this.parent.get(cur) !== root) { const next = this.parent.get(cur); this.parent.set(cur, root); cur = next; }+ return root;+ }+ union(a, b) {+ const ra = this.find(a);+ const rb = this.find(b);+ if (ra === rb) return;+ // Attach the larger address under the smaller so the root stays the min.+ if (ra < rb) this.parent.set(rb, ra); else this.parent.set(ra, rb);+ }+}++/**+ * Cluster wallets by shared funder.+ *+ * @param {Array<{address:string, funder:string|null}>} walletFunders+ * one entry per distinct wallet with its (possibly null) funder.+ * @param {Map<string, Set<string>>} [coOccurrence]+ * optional address → set of mints it bought, used to compute a co-occurrence+ * confidence: clusters whose members repeatedly buy the SAME launches are higher+ * confidence sybils than ones that merely share a funder once.+ * @returns {Array<{address:string, cluster_id:string, funder_root:string|null,+ * size:number, confidence:number}>}+ * only members of clusters with size >= 2 (a singleton is not a cluster).+ */+export function clusterByFunder(walletFunders, coOccurrence = null) {+ const uf = new UnionFind();+ const byFunder = new Map(); // funder → [addresses]+ const funderOf = new Map(); // address → funder++ for (const { address, funder } of walletFunders) {+ if (!address) continue;+ uf.find(address); // register even if unfunded so find() is total+ if (!funder) continue;+ funderOf.set(address, funder);+ if (!byFunder.has(funder)) byFunder.set(funder, []);+ byFunder.get(funder).push(address);+ }++ // Link every pair sharing a funder (chain them — linear, not quadratic).+ for (const addrs of byFunder.values()) {+ for (let i = 1; i < addrs.length; i++) uf.union(addrs[0], addrs[i]);+ }++ // Group by component root.+ const components = new Map(); // root → Set(addresses)+ for (const { address } of walletFunders) {+ if (!address) continue;+ const root = uf.find(address);+ if (!components.has(root)) components.set(root, new Set());+ components.get(root).add(address);+ }++ const out = [];+ for (const [root, members] of components) {+ if (members.size < 2) continue; // singletons aren't clusters+ const memberArr = [...members];+ // The funder root: the funder shared by the plurality of members.+ const funderCounts = new Map();+ for (const a of memberArr) {+ const f = funderOf.get(a);+ if (f) funderCounts.set(f, (funderCounts.get(f) || 0) + 1);+ }+ let funderRoot = null;+ let best = 0;+ for (const [f, c] of funderCounts) if (c > best) { best = c; funderRoot = f; }++ const confidence = coOccurrenceConfidence(memberArr, coOccurrence);++ for (const a of memberArr) {+ out.push({+ address: a,+ cluster_id: root,+ funder_root: funderRoot,+ size: members.size,+ confidence,+ });+ }+ }+ return out;+}++// Co-occurrence confidence: share of mints bought by ANY member that were bought+// by ≥2 members. A cluster that always piles into the same launches together is a+// near-certain sybil (1.0); one whose members never overlap is a loose share (low).+function coOccurrenceConfidence(memberArr, coOccurrence) {+ if (!coOccurrence || memberArr.length < 2) return Number((0.5).toFixed(3));+ const mintCount = new Map(); // mint → distinct members that bought it+ for (const a of memberArr) {+ const mints = coOccurrence.get(a);+ if (!mints) continue;+ for (const m of mints) mintCount.set(m, (mintCount.get(m) || 0) + 1);+ }+ if (!mintCount.size) return Number((0.5).toFixed(3));+ let shared = 0;+ for (const c of mintCount.values()) if (c >= 2) shared++;+ const conf = shared / mintCount.size;+ // Floor at 0.4 — sharing a funder is itself evidence; co-occurrence sharpens it.+ return Number(clamp(0.4 + 0.6 * conf, 0, 1).toFixed(3));+}++export const _internals = {+ CONFIDENCE_FULL_AT, NEUTRAL_SCORE, PROVEN_SCORE, STRONG_SCORE,+ MIN_JUDGED_FOR_LABEL, ATH_TANH_X, coOccurrenceConfidence,+};