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: $THREE holder leaderboard, snapshot cron, and OG image updates
nirholaseaadcef4cf9b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 080a7a2e0..6b2f9c446 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,10 @@Public history for [three.ws](https://three.ws), newest first. New pages come from `added` dates in data/pages.json; everything else is curated in data/changelog.json. Also available as [JSON](https://three.ws/changelog.json) and [RSS](https://three.ws/changelog.xml), live at [three.ws/changelog](https://three.ws/changelog).+## 2026-06-21++- **$THREE holder leaderboard loads faster from a shared snapshot** — The $THREE holder leaderboard, its share card, and the token stats panel used to rescan every holder on-chain on each page view. They now read from a holder snapshot that refreshes every few minutes, so the board and badges load faster and the same numbers stay consistent across all three surfaces. (`/leaderboard`) `[improvement, infra]`+## 2026-06-20- **Grind-Bounty Market** (`/vanity/bounties`) — A decentralized x402 bounty market for hard Solana vanity addresses — escrow a USDC bounty and a fleet of independent workers grinds it in parallel. The first verified match wins, but the found key is sealed to you so the worker never sees your wallet. Earn USDC by grinding open bounties.diff --git a/api/_lib/coin/three-holders.js b/api/_lib/coin/three-holders.jsnew file mode 100644index 000000000..68371d75c--- /dev/null+++ b/api/_lib/coin/three-holders.js@@ -0,0 +1,153 @@+// $THREE holder snapshot — the cached read/write layer behind the public holder+// leaderboard, its OG share card, and the token stats panel.+//+// Why this exists: those three public surfaces each used to call+// fetchHolderBalances({ mint: THREE_MINT }) directly — a full Helius DAS+// `getTokenAccounts` walk of EVERY $THREE holder — on every edge-cache miss. That+// recomputed a slowly-changing set on web/bot traffic, so DAS credit burn scaled+// with page views (and the OG card amplified it: every crawler/unfurl that missed+// cache triggered a full scan). This module flips that around: a single cron+// (api/cron/three-holders-snapshot.js) runs ONE scan every few minutes and writes+// the result to three_holder_snapshot; the public reads serve from that snapshot+// for the cost of a single DB query.+//+// threeHolderBalances() returns the exact same Map<wallet, bigint> shape that+// fetchHolderBalances() returns, so call sites swap their data source in one line+// and every downstream derivation (ranking, tiers, % of supply) is untouched.++import { sql } from '../db.js';+import { TOKEN_MINT as THREE_MINT } from '../token/config.js';+import { fetchHolderBalances } from './holders.js';++const UPSERT_CHUNK = 2000; // rows per batched upsert — mirrors persistHolderSnapshot+// A snapshot older than this is treated as missing: the reader falls back to a+// live scan so a stalled cron degrades to "slightly more expensive" rather than+// "serving hours-old holder data". The cron runs every 5m, so 30m tolerates a few+// missed ticks before falling back.+const MAX_SNAPSHOT_AGE_MS = 30 * 60_000;++let _ensured = null;+function ensureTables() {+ if (_ensured) return _ensured;+ _ensured = (async () => {+ await sql`+ create table if not exists three_holder_snapshot (+ wallet text primary key,+ balance bigint not null,+ updated_at timestamptz not null default now()+ )+ `;+ await sql`+ create index if not exists three_holder_snapshot_balance_idx+ on three_holder_snapshot (balance desc)+ `;+ await sql`+ create table if not exists three_holder_snapshot_meta (+ id smallint primary key default 1,+ snapshot_at timestamptz,+ holder_count integer not null default 0+ )+ `;+ await sql`+ insert into three_holder_snapshot_meta (id, snapshot_at, holder_count)+ values (1, null, 0)+ on conflict (id) do nothing+ `;+ return true;+ })().catch((err) => {+ console.error('[three-holders] ensureTables failed:', err?.message || err);+ _ensured = null; // allow a retry on the next call+ return false;+ });+ return _ensured;+}++/**+ * Run a full $THREE holder scan and atomically refresh the snapshot table.+ * Called by the cron only. Returns { holders, scannedAt } for logging.+ */+export async function refreshThreeHolderSnapshot() {+ if (!(await ensureTables())) throw new Error('three_holder_snapshot table unavailable');++ const balances = await fetchHolderBalances({ mint: THREE_MINT });+ const wallets = [...balances.keys()].filter((w) => balances.get(w) > 0n);+ const now = new Date();++ // Batched multi-row upsert via unnest — one round-trip per chunk instead of+ // one per holder (thousands of serial Neon HTTP calls otherwise).+ for (let i = 0; i < wallets.length; i += UPSERT_CHUNK) {+ const chunk = wallets.slice(i, i + UPSERT_CHUNK);+ const balanceStrs = chunk.map((w) => balances.get(w).toString());+ await sql`+ insert into three_holder_snapshot (wallet, balance, updated_at)+ select u.wallet, u.balance, ${now}+ from unnest(${chunk}::text[], ${balanceStrs}::bigint[]) as u(wallet, balance)+ on conflict (wallet) do update set+ balance = excluded.balance,+ updated_at = excluded.updated_at+ `;+ }++ // Hard-delete wallets that fully exited since the last snapshot — this is a+ // pure cache, so there's no accrual to preserve (unlike coin_holders). Neon's+ // HTTP client expands arrays into Postgres params, so use `<> all(...)`.+ if (wallets.length > 0) {+ await sql`+ delete from three_holder_snapshot+ where not (wallet = any(${wallets}))+ `;+ } else {+ // An empty scan almost certainly means Helius was unreachable, not that+ // $THREE has zero holders — never wipe a good snapshot on a bad scan.+ throw new Error('holder scan returned 0 holders — refusing to wipe snapshot');+ }++ await sql`+ update three_holder_snapshot_meta+ set snapshot_at = ${now}, holder_count = ${wallets.length}+ where id = 1+ `;++ return { holders: wallets.length, scannedAt: now.toISOString() };+}++/**+ * Read the cached snapshot as a Map<wallet, bigint>. Returns null when there is+ * no fresh snapshot (table missing, never populated, or older than+ * MAX_SNAPSHOT_AGE_MS) so the caller can fall back to a live scan.+ */+export async function readThreeHolderSnapshot() {+ let meta;+ try {+ [meta] = await sql`select snapshot_at, holder_count from three_holder_snapshot_meta where id = 1`;+ } catch {+ // Table not created yet (migration pending on a fresh deploy) — signal the+ // caller to live-scan rather than erroring the public read.+ return null;+ }+ if (!meta?.snapshot_at) return null;+ const ageMs = Date.now() - new Date(meta.snapshot_at).getTime();+ if (ageMs > MAX_SNAPSHOT_AGE_MS) return null;++ const rows = await sql`select wallet, balance from three_holder_snapshot`;+ const balances = new Map();+ for (const r of rows) {+ // Neon returns bigint columns as strings to preserve precision.+ balances.set(r.wallet, BigInt(r.balance));+ }+ return balances.size > 0 ? balances : null;+}++/**+ * The drop-in replacement for fetchHolderBalances({ mint: THREE_MINT }) on public+ * read paths: serve the cached snapshot, falling back to a single live scan only+ * on a cold start (snapshot missing/stale). Same Map<wallet, bigint> shape, so+ * callers' downstream ranking/tier/percentage logic is unchanged.+ */+export async function threeHolderBalances() {+ const snap = await readThreeHolderSnapshot();+ if (snap) return snap;+ // Cold start or stalled cron — one live scan keeps the page correct. This is+ // the rare path now, not the per-request default.+ return fetchHolderBalances({ mint: THREE_MINT });+}diff --git a/api/_lib/migrations/20260621120000_three_holder_snapshot.sql b/api/_lib/migrations/20260621120000_three_holder_snapshot.sqlnew file mode 100644index 000000000..62a1da507--- /dev/null+++ b/api/_lib/migrations/20260621120000_three_holder_snapshot.sql@@ -0,0 +1,39 @@+-- Migration: $THREE holder snapshot cache.+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/20260621120000_three_holder_snapshot.sql+-- Idempotent + re-runnable.+--+-- Public surfaces (the holder leaderboard, its OG share card, and the token+-- stats panel) previously each ran a full Helius DAS `getTokenAccounts` walk of+-- EVERY $THREE holder on every edge-cache miss — recomputing a slow-changing set+-- on web/bot traffic and burning DAS credits in proportion to page views. This+-- table is the shared, slowly-refreshed snapshot those reads now serve from: a+-- single background cron (api/cron/three-holders-snapshot.js) does ONE scan every+-- few minutes and writes the result here, so public reads cost a DB query, not a+-- Helius walk. The OG-card bot-amplification vector disappears entirely.+--+-- The table is a pure cache (no accrual/payout semantics — that lives in+-- coin_holders): a wallet that fully exits is hard-deleted on the next snapshot.++create table if not exists three_holder_snapshot (+ wallet text primary key,+ -- Atomic on-chain balance (token base units). $THREE max supply fits in bigint.+ balance bigint not null,+ updated_at timestamptz not null default now()+);++-- The leaderboard slices the top holders by descending balance; index it.+create index if not exists three_holder_snapshot_balance_idx+ on three_holder_snapshot (balance desc);++-- Single-row metadata: when the last full snapshot completed + its holder count,+-- so readers can cheaply judge staleness without scanning the table.+create table if not exists three_holder_snapshot_meta (+ id smallint primary key default 1,+ snapshot_at timestamptz,+ holder_count integer not null default 0,+ constraint three_holder_snapshot_meta_singleton check (id = 1)+);++insert into three_holder_snapshot_meta (id, snapshot_at, holder_count)+values (1, null, 0)+on conflict (id) do nothing;diff --git a/api/cron/three-holders-snapshot.js b/api/cron/three-holders-snapshot.jsnew file mode 100644index 000000000..5490e02d1--- /dev/null+++ b/api/cron/three-holders-snapshot.js@@ -0,0 +1,63 @@+// @ts-check+// GET /api/cron/three-holders-snapshot — refresh the cached $THREE holder set.+//+// The public holder leaderboard (api/leaderboard.js), its OG share card+// (api/og-leaderboard.js), and the token stats panel (api/three-token/[action].js)+// all need the full $THREE holder set to rank wallets and compute % of supply.+// Reading that live meant a full Helius DAS `getTokenAccounts` walk on every+// edge-cache miss — so DAS credit burn scaled with page/bot traffic, not with how+// often the data actually changes.+//+// This cron runs ONE scan every 5 minutes and writes the result to+// three_holder_snapshot; the public surfaces serve from that snapshot. Net effect:+// $THREE holder DAS calls drop from traffic-driven to a fixed ~12/hour, and the+// OG-card crawler-amplification vector is gone.+//+// Standalone (not [name].js) so the import graph stays minimal — just the snapshot+// module and its Helius/DB dependencies.++import { error, json, method, wrap } from '../_lib/http.js';+import { env } from '../_lib/env.js';+import { constantTimeEquals } from '../_lib/crypto.js';+import { refreshThreeHolderSnapshot } from '../_lib/coin/three-holders.js';++// Vercel cron invokes with `Authorization: Bearer <CRON_SECRET>`; manual probes+// may use `X-Cron-Secret: <CRON_SECRET>`. Accept either, constant-time.+function requireCron(req, res) {+ const secret = process.env.CRON_SECRET || env.CRON_SECRET;+ if (!secret) {+ error(res, 503, 'not_configured', 'CRON_SECRET unset');+ return false;+ }+ const auth = req.headers['authorization'] || '';+ const bearer = auth.startsWith('Bearer ') ? auth.slice(7) : '';+ const header = req.headers['x-cron-secret'] || '';+ if (constantTimeEquals(bearer, secret) || constantTimeEquals(header, secret)) return true;+ error(res, 401, 'unauthorized', 'invalid cron secret');+ return false;+}++export default wrap(async (req, res) => {+ if (!method(req, res, ['GET', 'POST'])) return;+ if (!requireCron(req, res)) return;++ if (!process.env.HELIUS_API_KEY) {+ // No key → the snapshot can't refresh; the public reads keep serving the+ // last good snapshot (or live-fall-back) and degrade gracefully.+ return json(res, 200, { ok: false, reason: 'HELIUS_API_KEY unset', refreshed: false });+ }++ const started = Date.now();+ try {+ const result = await refreshThreeHolderSnapshot();+ console.log(+ `[three-holders-snapshot] refreshed ${result.holders} holders in ${Date.now() - started}ms`,+ );+ return json(res, 200, { ok: true, refreshed: true, ...result, elapsed_ms: Date.now() - started });+ } catch (err) {+ // Never throw: a failed scan leaves the prior snapshot intact (the refresh+ // only deletes inside a successful scan), so public reads are unaffected.+ console.error('[three-holders-snapshot] refresh failed:', err?.message || err);+ return json(res, 200, { ok: false, refreshed: false, error: err?.message || String(err) });+ }+});diff --git a/api/leaderboard.js b/api/leaderboard.jsindex f9353cfb7..ac967c85e 100644--- a/api/leaderboard.js+++ b/api/leaderboard.js@@ -1,10 +1,11 @@// GET /api/leaderboard — public $THREE holder leaderboard (clean, paginated)// ---------------------------------------------------------------------------// The canonical holder board for /leaderboard's "$THREE Holders" view. It wraps-// the real Helius DAS holder scan (api/_lib/coin/holders.js) and the live market-// module (price / supply / holder count), then derives a holder TIER from each-// wallet's on-chain balance so the page can render badges and gate the 3D PFP-// generator without re-deriving thresholds client-side.+// The canonical holder board for /leaderboard's "$THREE Holders" view. It serves+// the cached $THREE holder snapshot (api/_lib/coin/three-holders.js, refreshed by+// the three-holders-snapshot cron — falling back to a live Helius DAS scan only on+// a cold cache) and the live market module (price / supply / holder count), then+// derives a holder TIER from each wallet's on-chain balance so the page can render+// badges and gate the 3D PFP generator without re-deriving thresholds client-side.//// Query params:// ?limit=<1..100> page size (default 50)@@ -29,7 +30,7 @@import { cors, json, method, wrap } from './_lib/http.js';import { TOKEN_MINT as THREE_MINT } from './_lib/token/config.js';import { fetchTokenMarketData } from './_lib/market/token-market.js';-import { fetchHolderBalances } from './_lib/coin/holders.js';+import { threeHolderBalances } from './_lib/coin/three-holders.js';const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;@@ -77,8 +78,10 @@ export default wrap(async (req, res) => {// Real holder set (every $THREE holder across both token programs) + live// market data for supply → % of supply and the header price strip. Both are// independently resilient: a market blip just nulls the percentages.+ // Holders come from the cached snapshot (refreshed by the+ // three-holders-snapshot cron); only a cold/stale cache live-scans Helius.const [balances, market] = await Promise.all([- fetchHolderBalances({ mint: THREE_MINT }),+ threeHolderBalances(),fetchTokenMarketData(THREE_MINT).catch(() => null),]);diff --git a/api/og-leaderboard.js b/api/og-leaderboard.jsindex 52eb980da..6cb66502e 100644--- a/api/og-leaderboard.js+++ b/api/og-leaderboard.js@@ -20,7 +20,7 @@import { ImageResponse } from '@vercel/og';import { TOKEN_MINT as THREE_MINT } from './_lib/token/config.js';import { fetchTokenMarketData } from './_lib/market/token-market.js';-import { fetchHolderBalances } from './_lib/coin/holders.js';+import { threeHolderBalances } from './_lib/coin/three-holders.js';const WIDTH = 1200;const HEIGHT = 630;@@ -65,7 +65,9 @@ function fmtUsd(n) {// Build the ranked holder list + market context once, shared by both card modes.async function loadBoard() {const [balances, market] = await Promise.all([- fetchHolderBalances({ mint: THREE_MINT }).catch(() => new Map()),+ // Cached snapshot (three-holders-snapshot cron) — no per-render Helius walk,+ // which also removes the crawler-amplified DAS burn on this OG card.+ threeHolderBalances().catch(() => new Map()),fetchTokenMarketData(THREE_MINT).catch(() => null),]);const decimals = Number(market?.decimals ?? 6);diff --git a/api/three-token/[action].js b/api/three-token/[action].jsindex f1c875d45..44b5b6af5 100644--- a/api/three-token/[action].js+++ b/api/three-token/[action].js@@ -20,7 +20,7 @@ import { getSessionUser } from '../_lib/auth.js';import { cors, error, json, method, wrap } from '../_lib/http.js';import { TOKEN_MINT as THREE_MINT } from '../_lib/token/config.js';import { fetchTokenMarketData } from '../_lib/market/token-market.js';-import { fetchHolderBalances } from '../_lib/coin/holders.js';+import { threeHolderBalances } from '../_lib/coin/three-holders.js';import { buybackStats } from '../_lib/token/buyback.js';// Truncate a base58 wallet for display: "FeMb…Jpump".@@ -211,11 +211,12 @@ export default wrap(async (req, res) => {const offset = Math.max(0, Number(url.searchParams.get('offset')) || 0);try {- // Real holder set from Helius (every $THREE holder, all token programs)- // plus market data for supply → % of supply. Both are independently- // resilient; a market-data blip just nulls the percentages.+ // Holder set from the cached snapshot (three-holders-snapshot cron) — the+ // full $THREE holder list across all token programs, without a per-request+ // Helius DAS walk. Market data gives supply → % of supply. Both are+ // independently resilient; a market-data blip just nulls the percentages.const [balances, market] = await Promise.all([- fetchHolderBalances({ mint: THREE_MINT }),+ threeHolderBalances(),fetchTokenMarketData(THREE_MINT).catch(() => null),]);diff --git a/data/changelog.json b/data/changelog.jsonindex b23ac5644..0bea0f072 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,16 @@{"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-06-21",+ "title": "$THREE holder leaderboard loads faster from a shared snapshot",+ "summary": "The $THREE holder leaderboard, its share card, and the token stats panel used to rescan every holder on-chain on each page view. They now read from a holder snapshot that refreshes every few minutes, so the board and badges load faster and the same numbers stay consistent across all three surfaces.",+ "tags": [+ "improvement",+ "infra"+ ],+ "link": "/leaderboard"+ },{"date": "2026-06-20","title": "Oracle “wins” and backtest now load instead of erroring",diff --git a/public/admin/index.html b/public/admin/index.htmlindex d4140017a..9e57d83c8 100644--- a/public/admin/index.html+++ b/public/admin/index.html@@ -96,6 +96,15 @@.bar-track { flex: 1; background: #1b1b1b; border-radius: 4px; height: 8px; }.bar-fill { height: 8px; border-radius: 4px; background: linear-gradient(90deg,var(--accent),var(--accent2)); }.bar-count { width: 40px; color: #aaa; flex-shrink: 0; }++ /* Column chart (time series) */+ .col-chart { display: flex; align-items: flex-end; gap: 3px; height: 120px; padding-top: 8px; }+ .col { flex: 1; min-width: 0; background: linear-gradient(180deg,var(--accent),var(--accent2)); border-radius: 3px 3px 0 0; min-height: 2px; opacity: .85; transition: opacity .15s; cursor: default; position: relative; }+ .col:hover { opacity: 1; }+ .col-axis { display: flex; justify-content: space-between; font-size: 10px; color: #444; padding-top: 6px; }++ /* Compact KPI row reused across analytics tabs */+ .kpi-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px,1fr)); gap: 12px; margin-bottom: 20px; }</style></head><body>@@ -104,6 +113,9 @@<span class="sidebar-brand">three.ws <span class="sidebar-badge">ADMIN</span></span><a class="nav-item active" data-tab="overview" onclick="switchTab('overview')">Overview</a><a class="nav-item" data-tab="users" onclick="switchTab('users')">Users</a>+ <a class="nav-item" data-tab="revenue" onclick="switchTab('revenue')">Revenue</a>+ <a class="nav-item" data-tab="llm" onclick="switchTab('llm')">LLM Spend</a>+ <a class="nav-item" data-tab="usage" onclick="switchTab('usage')">Usage</a><a class="nav-item" href="/admin/news">News</a><a class="nav-item" href="/admin/sdp">Solana Platform</a><a class="nav-item" href="/dashboard/">Dashboard</a>@@ -115,6 +127,9 @@</div><div id="tab-overview"></div><div id="tab-users" style="display:none"></div>+ <div id="tab-revenue" style="display:none"></div>+ <div id="tab-llm" style="display:none"></div>+ <div id="tab-usage" style="display:none"></div></main></div>@@ -189,14 +204,19 @@ async function boot() {// ── Tab routing ─────────────────────────────────────────────────────────────+const TAB_TITLES = { overview: 'Overview', users: 'Users', revenue: 'Revenue', llm: 'LLM Spend', usage: 'Usage' };function switchTab(tab) {state.tab = tab;document.querySelectorAll('.nav-item[data-tab]').forEach((el) => el.classList.toggle('active', el.dataset.tab === tab));- document.getElementById('tab-overview').style.display = tab === 'overview' ? '' : 'none';- document.getElementById('tab-users').style.display = tab === 'users' ? '' : 'none';- document.getElementById('page-title').textContent = tab === 'overview' ? 'Overview' : 'Users';+ ['overview', 'users', 'revenue', 'llm', 'usage'].forEach((t) => {+ document.getElementById('tab-' + t).style.display = t === tab ? '' : 'none';+ });+ document.getElementById('page-title').textContent = TAB_TITLES[tab] || 'Overview';if (tab === 'overview' && !state.statsData) loadOverview();if (tab === 'users') loadUsers();+ if (tab === 'revenue') loadRevenue();+ if (tab === 'llm') loadLlmSpend();+ if (tab === 'usage') loadFeatures();}// ── Overview tab ─────────────────────────────────────────────────────────────@@ -220,6 +240,10 @@ async function loadOverview() {${statCard('Total agents', c.total_agents)}${statCard('Active subs', c.active_subscriptions)}</div>+ <div class="section">+ <div class="section-head"><span class="section-title">New signups · last 30 days</span><span style="margin-left:auto;font-size:12px;color:#555" id="signups-total"></span></div>+ <div class="chart-wrap" id="signups-chart"></div>+ </div><div style="display:grid;grid-template-columns:1fr 1fr;gap:16px"><div class="section"><div class="section-head"><span class="section-title">Plan breakdown</span></div>@@ -232,6 +256,8 @@ async function loadOverview() {</div>`;+ renderSignups(data.recentSignups || []);+const maxPlan = Math.max(...data.planBreakdown.map((r) => r.users), 1);document.getElementById('plan-chart').innerHTML = data.planBreakdown.map((r) =>`<div class="bar-row">@@ -402,8 +428,153 @@ function confirmDelete(id) {function closeDrawer() { document.getElementById('drawer').classList.remove('open'); }+// ── Shared chart renderers ───────────────────────────────────────────────────++// Column chart from [{day, <valueKey>}] rows. Fills missing days as zero so the+// 30-day window is always continuous and comparable week-over-week.+function renderSignups(rows) {+ const wrap = document.getElementById('signups-chart');+ if (!wrap) return;+ const total = rows.reduce((s, r) => s + (r.users || 0), 0);+ const totalEl = document.getElementById('signups-total');+ if (totalEl) totalEl.textContent = `${total} total`;+ wrap.innerHTML = colChart(rows.map((r) => ({ day: r.day, value: r.users })));+}++// Generic column chart markup. Each item: {day, value}. Bars scale to the max.+function colChart(items, fmt = (v) => v) {+ if (!items.length) return '<div class="empty" style="padding:20px">No activity yet.</div>';+ const max = Math.max(...items.map((i) => i.value), 1);+ const cols = items.map((i) =>+ `<div class="col" style="height:${Math.max(2, Math.round(i.value / max * 100))}%" title="${esc(fmtDate(i.day))}: ${esc(fmt(i.value))}"></div>`+ ).join('');+ const first = items[0]?.day, last = items[items.length - 1]?.day;+ return `<div class="col-chart">${cols}</div><div class="col-axis"><span>${esc(fmtDate(first))}</span><span>${esc(fmtDate(last))}</span></div>`;+}++// Horizontal ranked bars from rows, picking label + value via accessors.+function rankBars(rows, labelOf, valueOf, fmt = (v) => v) {+ if (!rows.length) return '<div class="empty" style="padding:20px">No data.</div>';+ const max = Math.max(...rows.map(valueOf), 1);+ return rows.map((r) => {+ const v = valueOf(r);+ return `<div class="bar-row">+ <span class="bar-label" style="width:140px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title="${esc(labelOf(r))}">${esc(labelOf(r))}</span>+ <div class="bar-track"><div class="bar-fill" style="width:${Math.round(v / max * 100)}%"></div></div>+ <span class="bar-count" style="width:70px;text-align:right">${esc(fmt(v))}</span>+ </div>`;+ }).join('');+}++function kpi(label, value, sub) {+ return `<div class="stat-card"><div class="stat-label">${esc(label)}</div><div class="stat-value">${esc(value ?? '—')}</div>${sub ? `<div class="stat-sub">${esc(sub)}</div>` : ''}</div>`;+}++// ── Revenue tab (x402 payments) ───────────────────────────────────────────────++async function loadRevenue() {+ const el = document.getElementById('tab-revenue');+ el.innerHTML = '<div class="empty"><span class="spinner"></span></div>';+ const data = await api.get('/api/admin/x402');+ if (data.error) { el.innerHTML = `<div class="empty">Error: ${esc(data.error_description || data.error)}</div>`; return; }+ const t = data.totals || {};+ el.innerHTML = `+ <div class="kpi-grid">+ ${kpi('Settled (30d)', t.settled, 'successful payments')}+ ${kpi('Volume (30d)', fmtUsdc(t.volume_atomics), 'USDC')}+ ${kpi('Unique payers', t.unique_payers)}+ ${kpi('Failed', t.failed, 'payment attempts')}+ </div>+ <div class="section">+ <div class="section-head"><span class="section-title">Payments · last 30 days</span></div>+ <div class="chart-wrap" id="rev-day"></div>+ </div>+ <div class="section">+ <div class="section-head"><span class="section-title">Top routes by volume</span></div>+ <div class="chart-wrap" id="rev-route"></div>+ </div>+ `;+ document.getElementById('rev-day').innerHTML = colChart((data.byDay || []).map((r) => ({ day: r.day, value: r.payments })), (v) => v + ' payments');+ document.getElementById('rev-route').innerHTML = rankBars(data.byRoute || [], (r) => r.route, (r) => Number(r.volume_atomics) || 0, (v) => fmtUsdc(v));+}++// ── LLM Spend tab ─────────────────────────────────────────────────────────────++async function loadLlmSpend() {+ const el = document.getElementById('tab-llm');+ el.innerHTML = '<div class="empty"><span class="spinner"></span></div>';+ const data = await api.get('/api/admin/llm-spend');+ if (data.error) { el.innerHTML = `<div class="empty">Error: ${esc(data.error_description || data.error)}</div>`; return; }+ const t = data.totals || {};+ el.innerHTML = `+ <div class="kpi-grid">+ ${kpi('Spend (24h)', fmtUsd(t.cost_micro_usd_24h), `${t.calls_24h ?? 0} calls`)}+ ${kpi('Spend (7d)', fmtUsd(t.cost_micro_usd_7d), `${t.calls_7d ?? 0} calls`)}+ ${kpi('Spend (30d)', fmtUsd(t.cost_micro_usd_30d), `${t.total_calls ?? 0} calls`)}+ ${kpi('Paid calls', t.paid_calls, `of ${t.total_calls ?? 0}`)}+ ${kpi('Input tokens', fmtNum(t.input_tokens))}+ ${kpi('Output tokens', fmtNum(t.output_tokens))}+ </div>+ <div class="section">+ <div class="section-head"><span class="section-title">Spend · last 30 days</span></div>+ <div class="chart-wrap" id="llm-day"></div>+ </div>+ <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px">+ <div class="section">+ <div class="section-head"><span class="section-title">By provider</span></div>+ <div class="chart-wrap" id="llm-provider"></div>+ </div>+ <div class="section">+ <div class="section-head"><span class="section-title">Top models</span></div>+ <div class="chart-wrap" id="llm-model"></div>+ </div>+ </div>+ `;+ document.getElementById('llm-day').innerHTML = colChart((data.byDay || []).map((r) => ({ day: r.day, value: Number(r.cost_micro_usd) || 0 })), (v) => fmtUsd(v));+ document.getElementById('llm-provider').innerHTML = rankBars(data.byProvider || [], (r) => r.provider, (r) => Number(r.cost_micro_usd) || 0, (v) => fmtUsd(v));+ document.getElementById('llm-model').innerHTML = rankBars(data.byModel || [], (r) => r.model, (r) => Number(r.cost_micro_usd) || 0, (v) => fmtUsd(v));+}++// ── Usage tab (feature adoption) ──────────────────────────────────────────────++async function loadFeatures() {+ const el = document.getElementById('tab-usage');+ el.innerHTML = '<div class="empty"><span class="spinner"></span></div>';+ const data = await api.get('/api/admin/features');+ if (data.error) { el.innerHTML = `<div class="empty">Error: ${esc(data.error_description || data.error)}</div>`; return; }++ // Daily totals across all kinds for the trend column chart.+ const dayMap = {};+ for (const r of data.byDay || []) dayMap[r.day] = (dayMap[r.day] || 0) + (r.events || 0);+ const dayRows = Object.keys(dayMap).sort().map((day) => ({ day, value: dayMap[day] }));++ el.innerHTML = `+ <div class="section">+ <div class="section-head"><span class="section-title">Events · last 30 days</span></div>+ <div class="chart-wrap" id="feat-day"></div>+ </div>+ <div class="section">+ <div class="section-head"><span class="section-title">By event kind</span></div>+ <div class="section-body">+ <table><thead><tr><th>Kind</th><th>Events</th><th>Users</th><th>Agents</th></tr></thead><tbody>+ ${(data.byKind || []).map((r) => `<tr><td style="color:#ddd">${esc(r.kind)}</td><td>${fmtNum(r.events)}</td><td>${fmtNum(r.users)}</td><td>${fmtNum(r.agents)}</td></tr>`).join('') || '<tr><td colspan="4" class="empty">No events.</td></tr>'}+ </tbody></table>+ </div>+ </div>+ <div class="section">+ <div class="section-head"><span class="section-title">Top tools</span></div>+ <div class="chart-wrap" id="feat-tool"></div>+ </div>+ `;+ document.getElementById('feat-day').innerHTML = colChart(dayRows, (v) => v + ' events');+ document.getElementById('feat-tool').innerHTML = rankBars(data.byTool || [], (r) => r.tool, (r) => r.events, (v) => fmtNum(v));+}+// ── Utils ─────────────────────────────────────────────────────────────────────+function fmtUsd(micro) { const v = (Number(micro) || 0) / 1e6; return '$' + v.toLocaleString('en-US', { minimumFractionDigits: v < 100 ? 2 : 0, maximumFractionDigits: v < 1 ? 4 : 2 }); }+function fmtUsdc(atomics) { const v = (Number(atomics) || 0) / 1e6; return v.toLocaleString('en-US', { maximumFractionDigits: 2 }) + ' USDC'; }+function fmtNum(n) { return (Number(n) || 0).toLocaleString('en-US'); }function fmtDate(iso) { return iso ? new Date(iso).toLocaleDateString('en-US', { month:'short', day:'numeric', year:'numeric' }) : '—'; }function fmtBytes(b) { if (!b) return '0 B'; const u=['B','KB','MB','GB','TB']; let i=0; while(b>=1024&&i<4){b/=1024;i++;} return b.toFixed(i?1:0)+' '+u[i]; }function shortAddr(a, n=6) { return a ? `${a.slice(0,n)}…${a.slice(-4)}` : '—'; }diff --git a/public/changelog.json b/public/changelog.jsonindex 5db41d839..b14e11b29 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,11 +1,22 @@{- "generated_at": "2026-06-20T12:01:11.783Z",+ "generated_at": "2026-06-21T00:59:23.556Z","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-21",+ "type": "update",+ "title": "$THREE holder leaderboard loads faster from a shared snapshot",+ "summary": "The $THREE holder leaderboard, its share card, and the token stats panel used to rescan every holder on-chain on each page view. They now read from a holder snapshot that refreshes every few minutes, so the board and badges load faster and the same numbers stay consistent across all three surfaces.",+ "link": "/leaderboard",+ "tags": [+ "improvement",+ "infra"+ ]+ },{"date": "2026-06-20","type": "launch",diff --git a/public/changelog.xml b/public/changelog.xmlindex 785e5a525..ef477e4d7 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>$THREE holder leaderboard loads faster from a shared snapshot</title>+ <link>https://three.ws/leaderboard</link>+ <guid isPermaLink="false">2026-06-21:$THREE holder leaderboard loads faster from a shared snapshot</guid>+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>The $THREE holder leaderboard, its share card, and the token stats panel used to rescan every holder on-chain on each page view. They now read from a holder snapshot that refreshes every few minutes, so the board and badges load faster and the same numbers stay consistent across all three surfaces.</description>+ </item><item><title>Grind-Bounty Market</title><link>https://three.ws/vanity/bounties</link>diff --git a/tests/api/three-holders-snapshot.test.js b/tests/api/three-holders-snapshot.test.jsnew file mode 100644index 000000000..a167f198e--- /dev/null+++ b/tests/api/three-holders-snapshot.test.js@@ -0,0 +1,74 @@+// Unit tests for the $THREE holder snapshot cache (api/_lib/coin/three-holders.js).+// The DB (sql) and the live Helius scan (fetchHolderBalances) are mocked at the+// module boundary, so these exercise the staleness gate and the cold-cache+// fallback — the logic that decides whether a public read costs a DB query or a+// Helius DAS walk.++import { describe, it, expect, vi, beforeEach } from 'vitest';++const h = { sql: vi.fn() };+vi.mock('../../api/_lib/db.js', () => ({ sql: (...a) => h.sql(...a) }));+vi.mock('../../api/_lib/coin/holders.js', () => ({ fetchHolderBalances: vi.fn() }));+vi.mock('../../api/_lib/token/config.js', () => ({ TOKEN_MINT: 'THREEsynthetic1111111111111111111111111111' }));++import { readThreeHolderSnapshot, threeHolderBalances } from '../../api/_lib/coin/three-holders.js';+import { fetchHolderBalances } from '../../api/_lib/coin/holders.js';++beforeEach(() => {+ h.sql.mockReset();+ fetchHolderBalances.mockReset();+});++describe('readThreeHolderSnapshot', () => {+ it('returns null when the snapshot has never been populated', async () => {+ h.sql.mockResolvedValueOnce([{ snapshot_at: null, holder_count: 0 }]); // meta+ expect(await readThreeHolderSnapshot()).toBeNull();+ });++ it('returns null when the snapshot is older than the freshness window', async () => {+ const stale = new Date(Date.now() - 60 * 60_000).toISOString(); // 1h old > 30m max+ h.sql.mockResolvedValueOnce([{ snapshot_at: stale, holder_count: 5 }]); // meta+ expect(await readThreeHolderSnapshot()).toBeNull();+ });++ it('returns null (not an error) when the meta table is missing', async () => {+ h.sql.mockRejectedValueOnce(new Error('relation "three_holder_snapshot_meta" does not exist'));+ expect(await readThreeHolderSnapshot()).toBeNull();+ });++ it('returns a wallet→bigint Map for a fresh snapshot, coercing string balances', async () => {+ h.sql.mockResolvedValueOnce([{ snapshot_at: new Date().toISOString(), holder_count: 2 }]); // meta+ h.sql.mockResolvedValueOnce([+ { wallet: 'walletA', balance: '300' },+ { wallet: 'walletB', balance: '100' },+ ]); // rows+ const map = await readThreeHolderSnapshot();+ expect(map).toBeInstanceOf(Map);+ expect(map.get('walletA')).toBe(300n);+ expect(map.get('walletB')).toBe(100n);+ });++ it('returns null when a fresh snapshot row set is unexpectedly empty', async () => {+ h.sql.mockResolvedValueOnce([{ snapshot_at: new Date().toISOString(), holder_count: 0 }]); // meta+ h.sql.mockResolvedValueOnce([]); // rows+ expect(await readThreeHolderSnapshot()).toBeNull();+ });+});++describe('threeHolderBalances', () => {+ it('serves the cached snapshot without a live Helius scan', async () => {+ h.sql.mockResolvedValueOnce([{ snapshot_at: new Date().toISOString(), holder_count: 1 }]); // meta+ h.sql.mockResolvedValueOnce([{ wallet: 'walletA', balance: '42' }]); // rows+ const map = await threeHolderBalances();+ expect(map.get('walletA')).toBe(42n);+ expect(fetchHolderBalances).not.toHaveBeenCalled();+ });++ it('falls back to a single live scan when the snapshot is cold/stale', async () => {+ h.sql.mockResolvedValueOnce([{ snapshot_at: null, holder_count: 0 }]); // meta → null snapshot+ fetchHolderBalances.mockResolvedValueOnce(new Map([['walletLive', 7n]]));+ const map = await threeHolderBalances();+ expect(map.get('walletLive')).toBe(7n);+ expect(fetchHolderBalances).toHaveBeenCalledTimes(1);+ });+});diff --git a/tests/api/three-token-leaderboard.test.js b/tests/api/three-token-leaderboard.test.jsindex c448b7acc..347d63120 100644--- a/tests/api/three-token-leaderboard.test.js+++ b/tests/api/three-token-leaderboard.test.js@@ -1,10 +1,10 @@-// Handler tests for GET /api/three-token/leaderboard. Helius holder data and-// market data are mocked at the module boundary, so these exercise the ranking,-// pagination, percentage math, and the empty-board degrade — no real RPC.+// Handler tests for GET /api/three-token/leaderboard. The cached holder snapshot+// and market data are mocked at the module boundary, so these exercise the+// ranking, pagination, percentage math, and the empty-board degrade — no real RPC.import { describe, it, expect, vi, beforeEach } from 'vitest';-vi.mock('../../api/_lib/coin/holders.js', () => ({ fetchHolderBalances: vi.fn() }));+vi.mock('../../api/_lib/coin/three-holders.js', () => ({ threeHolderBalances: vi.fn() }));vi.mock('../../api/_lib/market/token-market.js', () => ({ fetchTokenMarketData: vi.fn() }));vi.mock('../../api/_lib/token/config.js', () => ({TOKEN_MINT: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',@@ -12,7 +12,7 @@ vi.mock('../../api/_lib/token/config.js', () => ({vi.mock('../../api/_lib/zauth.js', () => ({ instrument: () => {}, drain: async () => {} }));vi.mock('../../api/_lib/sentry.js', () => ({ captureException: () => {} }));-import { fetchHolderBalances } from '../../api/_lib/coin/holders.js';+import { threeHolderBalances } from '../../api/_lib/coin/three-holders.js';import { fetchTokenMarketData } from '../../api/_lib/market/token-market.js';import handler from '../../api/three-token/[action].js';@@ -40,7 +40,7 @@ describe('GET /api/three-token/leaderboard', () => {beforeEach(() => { vi.clearAllMocks(); });it('ranks holders descending with rank, short wallet, and % of supply', async () => {- fetchHolderBalances.mockResolvedValueOnce(new Map([+ threeHolderBalances.mockResolvedValueOnce(new Map([['walletA', 300n],['walletB', 100n],['walletC', 200n],@@ -60,7 +60,7 @@ describe('GET /api/three-token/leaderboard', () => {});it('paginates with limit + offset and keeps absolute ranks', async () => {- fetchHolderBalances.mockResolvedValueOnce(new Map([+ threeHolderBalances.mockResolvedValueOnce(new Map([['walletA', 300n],['walletB', 100n],['walletC', 200n],@@ -77,7 +77,7 @@ describe('GET /api/three-token/leaderboard', () => {});it('excludes zero-balance wallets', async () => {- fetchHolderBalances.mockResolvedValueOnce(new Map([+ threeHolderBalances.mockResolvedValueOnce(new Map([['walletA', 300n],['walletZero', 0n],]));@@ -90,7 +90,7 @@ describe('GET /api/three-token/leaderboard', () => {});it('nulls percentages when market supply is unavailable', async () => {- fetchHolderBalances.mockResolvedValueOnce(new Map([['walletA', 300n]]));+ threeHolderBalances.mockResolvedValueOnce(new Map([['walletA', 300n]]));fetchTokenMarketData.mockResolvedValueOnce(null);const res = makeRes();await handler(makeReq({ url: '/api/three-token/leaderboard' }), res);@@ -99,7 +99,7 @@ describe('GET /api/three-token/leaderboard', () => {});it('degrades to an empty board (200, not 500) when Helius fails', async () => {- fetchHolderBalances.mockRejectedValueOnce(new Error('helius unconfigured'));+ threeHolderBalances.mockRejectedValueOnce(new Error('helius unconfigured'));const res = makeRes();await handler(makeReq({ url: '/api/three-token/leaderboard' }), res);expect(res.statusCode).toBe(200);diff --git a/vercel.json b/vercel.jsonindex d5c339bf9..f89826e52 100644--- a/vercel.json+++ b/vercel.json@@ -51,6 +51,9 @@"includeFiles": "data/pages.json","maxDuration": 30},+ "api/cron/three-holders-snapshot.js": {+ "maxDuration": 120+ },"api/cron/quota-check.js": {"includeFiles": "data/pages.json","maxDuration": 30@@ -3815,6 +3818,10 @@"path": "/api/cron/pump-agent-stats","schedule": "*/10 * * * *"},+ {+ "path": "/api/cron/three-holders-snapshot",+ "schedule": "*/5 * * * *"+ },{"path": "/api/cron/pumpfun-monitor","schedule": "*/3 * * * *"