Skip to content

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

pump dot fun improvements and 3D AI Agent on-chain agents

nirholasd0bfddf7182d
diff --git a/agent-protocol-sdk/src/idl.ts b/agent-protocol-sdk/src/idl.ts
index b167c560a..f4feda591 100644
--- a/agent-protocol-sdk/src/idl.ts
+++ b/agent-protocol-sdk/src/idl.ts
@@ -2,12 +2,13 @@
// contracts/agent-invocation/src/lib.rs. Anchor 0.30+ IDL format (carries its
// own `address` + `metadata` and per-instruction discriminators).
//
-// The `address` below is the program's declared id. Until the program is
-// deployed to a cluster you target, override it with `invokeSkill({ programId })`.
+// The `address` below is the program's live id, deployed to both Solana mainnet
+// and devnet (same program id on both clusters). Override it with
+// `invokeSkill({ programId })` only to target a different deployment.
import type { Idl } from '@coral-xyz/anchor';
-export const AGENT_INVOCATION_PROGRAM_ID = 'Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS';
+export const AGENT_INVOCATION_PROGRAM_ID = 'CcdC7xDhQ9r2PoafbsfWVewcbuAYozECHJEXWe4ELnqR';
export const IDL = {
address: AGENT_INVOCATION_PROGRAM_ID,
diff --git a/api/pump/trending.js b/api/pump/trending.js
index 63a8c8f4b..58782883a 100644
--- a/api/pump/trending.js
+++ b/api/pump/trending.js
@@ -20,6 +20,9 @@ const PUMP_FRONTEND_BASE = 'https://frontend-api-v3.pump.fun';
// Process-local cache. Trending shifts slowly; many tabs polling on nav into the
// dashboard would otherwise hammer the upstreams. Warm-starts share this map.
let _cache = { value: null, expiresAt: 0, limit: 0 };
+// Separate cache slot for the rich (full-coin) payload — it carries far more per
+// token than the thin projection, so it must not collide with `_cache`.
+let _richCache = { value: null, expiresAt: 0, limit: 0 };
const TTL_MS = 30_000;
// Primary: Birdeye trending feed. Returns null (not throws) on any failure so the
@@ -88,6 +91,45 @@ async function fetchPumpFun(limit) {
return data.length ? data : null;
}
+// Rich variant: the full pump.fun coin objects (market cap, image, ATH, replies,
+// age, socials, live flag) the 3D visualizer renders — sphere size, textures, and
+// the detail panel all key off these fields, none of which survive the thin
+// projection above. Images are repaired onto a working gateway, exactly like the
+// other live-market surfaces. Birdeye is skipped here: it doesn't expose market
+// cap, which is the whole point of the visualizer. Opt-in via `?rich=1` so the
+// thin contract every other consumer relies on stays byte-for-byte unchanged.
+function repairCoinImages(coins) {
+ for (const c of coins) {
+ if (!c || typeof c !== 'object') continue;
+ if (c.image_uri) c.image_uri = normalizeGatewayURL(c.image_uri);
+ if (c.image) c.image = normalizeGatewayURL(c.image);
+ }
+ return coins;
+}
+
+async function fetchPumpFunRich(limit) {
+ const url = new URL('/coins', PUMP_FRONTEND_BASE);
+ url.searchParams.set('offset', '0');
+ url.searchParams.set('limit', String(limit));
+ url.searchParams.set('sort', 'market_cap');
+ url.searchParams.set('order', 'DESC');
+ url.searchParams.set('includeNsfw', 'false');
+ let upstream;
+ try {
+ upstream = await fetch(url, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(8000) });
+ } catch {
+ return null;
+ }
+ if (!upstream.ok) return null;
+ const body = await upstream.json().catch(() => null);
+ const coins = Array.isArray(body) ? body : Array.isArray(body?.coins) ? body.coins : null;
+ if (!Array.isArray(coins)) return null;
+ const data = repairCoinImages(
+ coins.filter((c) => c && typeof c.mint === 'string' && c.mint.length >= 32),
+ );
+ return data.length ? data : null;
+}
+
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
if (!method(req, res, ['GET'])) return;
@@ -95,10 +137,27 @@ export default wrap(async (req, res) => {
const rl = await limits.publicIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl);
- const raw = Number(new URL(req.url, 'http://x').searchParams.get('limit') || '25');
+ const params = new URL(req.url, 'http://x').searchParams;
+ const raw = Number(params.get('limit') || '25');
const limit = Math.min(50, Math.max(1, Number.isFinite(raw) ? Math.floor(raw) : 25));
+ const rich = params.get('rich') === '1' || params.get('rich') === 'true';
const now = Date.now();
+
+ if (rich) {
+ if (_richCache.value && _richCache.limit >= limit && _richCache.expiresAt > now) {
+ return json(res, 200, { data: _richCache.value.slice(0, limit) }, {
+ 'cache-control': 'public, max-age=15, s-maxage=30',
+ });
+ }
+ const richData = await fetchPumpFunRich(limit);
+ if (!richData) {
+ return error(res, 502, 'upstream_error', 'Trending market data is temporarily unavailable');
+ }
+ _richCache = { value: richData, expiresAt: now + TTL_MS, limit };
+ return json(res, 200, { data: richData }, { 'cache-control': 'public, max-age=15, s-maxage=30' });
+ }
+
if (_cache.value && _cache.limit >= limit && _cache.expiresAt > now) {
return json(res, 200, { data: _cache.value.slice(0, limit) }, {
'cache-control': 'public, max-age=15, s-maxage=30',
diff --git a/contracts/agent-invocation/src/lib.rs b/contracts/agent-invocation/src/lib.rs
index 0bd8cf21d..4e403621c 100644
--- a/contracts/agent-invocation/src/lib.rs
+++ b/contracts/agent-invocation/src/lib.rs
@@ -1,6 +1,6 @@
use anchor_lang::prelude::*;
-declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");
+declare_id!("CcdC7xDhQ9r2PoafbsfWVewcbuAYozECHJEXWe4ELnqR");
/// Max accepted length (bytes) for `skill_name`, bounding the size of the
/// emitted event and the compute spent formatting it.
diff --git a/contracts/script/DeployValidationMainnet.s.sol b/contracts/script/DeployValidationMainnet.s.sol
index 9fc7f693e..77083808d 100644
--- a/contracts/script/DeployValidationMainnet.s.sol
+++ b/contracts/script/DeployValidationMainnet.s.sol
@@ -27,8 +27,9 @@ contract DeployValidationMainnet is Script {
// Canonical IdentityRegistry address (same on all 15 mainnet chains)
address constant IDENTITY_REGISTRY = 0x8004A169FB4a3325136EB29fA0ceB6D2e539a432;
- // Nick's deterministic CREATE2 factory — present on every EVM chain
- address constant CREATE2_FACTORY = 0x4e59b44847b379578588920cA78FbF26c0B4956C;
+ // Nick's deterministic CREATE2 factory (Arachnid proxy) — present on every EVM chain.
+ // Named ARACHNID_FACTORY to avoid colliding with forge-std Base.CREATE2_FACTORY.
+ address constant ARACHNID_FACTORY = 0x4e59b44847b379578588920cA78FbF26c0B4956C;
// Salt chosen to produce the 0x8004... vanity prefix on mainnet
bytes32 constant SALT = keccak256(abi.encodePacked("ValidationRegistry", uint256(1)));
@@ -52,7 +53,7 @@ contract DeployValidationMainnet is Script {
vm.stopBroadcast();
- require(address(validation) == predictedAddr, "Address mismatch — wrong deployer or factory?");
+ require(address(validation) == predictedAddr, "Address mismatch - wrong deployer or factory?");
console.log("Deployed ValidationRegistry:", address(validation));
}
diff --git a/pages/coin3d.html b/pages/coin3d.html
index 873a4ffec..a64e3a7cc 100644
--- a/pages/coin3d.html
+++ b/pages/coin3d.html
@@ -129,6 +129,12 @@
font-weight: 600;
font-variant-numeric: tabular-nums;
}
+ .hud-links {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px 16px;
+ align-items: center;
+ }
.hud-link {
display: inline-block;
color: var(--accent);
diff --git a/pages/launches.html b/pages/launches.html
index 6f6d02f7d..a862575bc 100644
--- a/pages/launches.html
+++ b/pages/launches.html
@@ -118,6 +118,12 @@
<span id="lx-count" class="lx-count" aria-live="polite"></span>
</section>
+ <nav class="lx-explore" aria-label="Explore the launchpad">
+ <a class="lx-explore-link" href="/pump-live">Live stream →</a>
+ <a class="lx-explore-link" href="/pump-visualizer">3D Visualizer →</a>
+ <a class="lx-explore-link" href="/launchpad">Launchpad Studio →</a>
+ </nav>
+
<section id="lx-feed" class="lx-grid" aria-label="Launched coins" aria-busy="true"></section>
<div id="lx-footer-state" class="lx-footer-state"></div>
diff --git a/pages/pump-live.html b/pages/pump-live.html
index 826ccdfa5..d193c9b7b 100644
--- a/pages/pump-live.html
+++ b/pages/pump-live.html
@@ -10,7 +10,6 @@
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<link rel="manifest" href="/site.webmanifest" />
-<text y='.9em' font-size='90'>�</text></svg>">
<title>3D-Agent · PumpFun Live</title>
<meta name="description" content="Real-time stream of new PumpFun token launches on Solana, presented by a 3D Agent.">
<link rel="canonical" href="https://three.ws/pump-live">
@@ -87,6 +86,45 @@
}
#header .status.connected { color: var(--green); }
#header .status.error { color: #ff4141; }
+ #header .header-links {
+ margin-left: auto;
+ display: flex;
+ gap: 18px;
+ font-size: 13px;
+ }
+ #header .header-links a { color: var(--green); }
+ #header .header-links a:hover { text-decoration: underline; }
+
+ /* ── Stats bar ───────────────────────────────────── */
+ #stats-bar {
+ display: flex;
+ gap: 0;
+ background: #0d0d0d;
+ border-bottom: 1px solid var(--dark-grey);
+ }
+ .stat {
+ flex: 1;
+ padding: 10px 16px;
+ border-right: 1px solid var(--dark-grey);
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ }
+ .stat:last-child { border-right: none; }
+ .stat-label {
+ font-size: 10px;
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+ color: #666;
+ }
+ .stat-value {
+ font-size: 18px;
+ font-weight: bold;
+ color: var(--green);
+ font-variant-numeric: tabular-nums;
+ transition: color 0.3s;
+ }
+ .stat-value.flash { color: #fff; }
/* ── Feed ────────────────────────────────────────── */
#feed-header {
@@ -120,10 +158,17 @@
border-radius: 50%;
border: 1px solid var(--light-grey);
}
- .token-info { flex: 1; }
- .token-name { font-size: 16px; font-weight: bold; }
+ .token-info { flex: 1; min-width: 0; }
+ .token-name {
+ font-size: 16px;
+ font-weight: bold;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
.token-symbol { color: #888; font-size: 12px; }
.token-mcap { margin-top: 4px; font-size: 14px; color: var(--green); }
+ .token-meta { margin-top: 2px; font-size: 11px; color: #777; }
.token-links { margin-top: 8px; font-size: 11px; display: flex; gap: 10px; }
@keyframes fadeIn {
@@ -131,6 +176,68 @@
to { opacity: 1; transform: translateY(0); }
}
+ /* ── Skeleton (empty / waiting state) ──────────────── */
+ .skeleton-card {
+ background: var(--dark-grey);
+ border: 1px solid var(--medium-grey);
+ border-radius: 8px;
+ margin-bottom: 8px;
+ padding: 12px;
+ display: flex;
+ gap: 12px;
+ }
+ .skeleton-card .sk-avatar {
+ width: 50px; height: 50px; border-radius: 50%;
+ flex-shrink: 0;
+ }
+ .skeleton-card .sk-lines { flex: 1; display: flex; flex-direction: column; gap: 8px; }
+ .sk-line { height: 12px; border-radius: 4px; }
+ .sk-line.w70 { width: 70%; }
+ .sk-line.w40 { width: 40%; }
+ .sk-line.w55 { width: 55%; }
+ .sk-avatar, .sk-line {
+ background: linear-gradient(90deg, #1a1a1a 25%, #242424 50%, #1a1a1a 75%);
+ background-size: 200% 100%;
+ animation: shimmer 1.4s ease-in-out infinite;
+ }
+ @keyframes shimmer {
+ 0% { background-position: 200% 0; }
+ 100% { background-position: -200% 0; }
+ }
+ .feed-empty-hint {
+ text-align: center;
+ color: #666;
+ font-size: 12px;
+ padding: 4px 0 12px;
+ }
+
+ /* ── Error state ───────────────────────────────────── */
+ .feed-error {
+ margin: 12px 8px;
+ padding: 20px 16px;
+ border: 1px solid #5a2222;
+ background: rgba(255, 65, 65, 0.06);
+ border-radius: 8px;
+ text-align: center;
+ }
+ .feed-error h3 { color: #ff6b6b; font-size: 14px; margin-bottom: 6px; }
+ .feed-error p { color: #999; font-size: 12px; margin-bottom: 14px; line-height: 1.5; }
+ .feed-error button {
+ background: var(--green);
+ color: #0a0a0a;
+ border: none;
+ border-radius: 6px;
+ padding: 9px 18px;
+ font-family: inherit;
+ font-size: 13px;
+ font-weight: bold;
+ cursor: pointer;
+ transition: transform 0.15s, box-shadow 0.15s, filter 0.15s;
+ }
+ .feed-error button:hover { filter: brightness(1.1); box-shadow: 0 0 12px var(--glow-color); }
+ .feed-error button:active { transform: translateY(1px); }
+ .feed-error button:focus-visible { outline: 2px solid var(--green); outline-offset: 2px; }
+
/* ── Scrollbar ─────────────────────────────────────── */
::-webkit-scrollbar { width: 8px; }
::-webkit-scrollbar-track { background: #0f0f0f; }
@@ -171,11 +278,29 @@
<div id="header">
<h1>🚀 3D Agent Live Feed</h1>
<div class="status" id="status">● Connecting...</div>
+ <nav class="header-links" aria-label="Explore the launchpad">
+ <a href="/launches">All launches →</a>
+ <a href="/pump-visualizer">Visualizer →</a>
+ </nav>
</div>
<div id="main-container">
<div id="viewer-container"></div>
<div id="feed-container">
+ <div id="stats-bar" role="group" aria-label="Live launch statistics">
+ <div class="stat">
+ <span class="stat-label">Tokens launched</span>
+ <span class="stat-value" id="stat-launched" aria-live="polite">0</span>
+ </div>
+ <div class="stat">
+ <span class="stat-label">Initial-buy volume</span>
+ <span class="stat-value" id="stat-volume" aria-live="polite">$0</span>
+ </div>
+ <div class="stat">
+ <span class="stat-label">Last launch</span>
+ <span class="stat-value" id="stat-age" aria-live="polite">—</span>
+ </div>
+ </div>
<div id="feed-header">
<h2>New Tokens on Pump.fun</h2>
</div>
@@ -188,24 +313,34 @@
import { Viewer } from '/src/viewer.js';
// ════════════════════════════════════════════════════════════════════
- // 3D Agent Setup
+ // 3D Agent Setup — the avatar reacts to each new launch. If the GLB or
+ // WebGL context fails to load we degrade gracefully: the feed must still
+ // connect and render, so the whole viewer init is isolated in try/catch.
// ════════════════════════════════════════════════════════════════════
- const viewerEl = document.getElementById('viewer-container');
- const viewer = new Viewer(viewerEl, { kiosk: true });
- window.viewer = viewer;
+ let viewer = null;
+
+ try {
+ const viewerEl = document.getElementById('viewer-container');
+ viewer = new Viewer(viewerEl, { kiosk: true });
+ window.viewer = viewer;
- await viewer.load('/animations/robotexpressive.glb', '', new Map());
+ await viewer.load('/animations/robotexpressive.glb', '', new Map());
- const idleClip =
- viewer.clips.find((c) => /^idle$/i.test(c.name)) || viewer.clips[0];
- if (idleClip && viewer.mixer) {
- viewer.mixer.clipAction(idleClip).play();
+ const idleClip =
+ viewer.clips.find((c) => /^idle$/i.test(c.name)) || viewer.clips[0];
+ if (idleClip && viewer.mixer) {
+ viewer.mixer.clipAction(idleClip).play();
+ }
+ } catch (err) {
+ console.warn('[pump-live] 3D viewer unavailable, continuing with feed only:', err?.message || err);
+ viewer = null;
}
function playAnimation(animationName, { loop = false } = {}) {
+ if (!viewer || !viewer.mixer) return;
const clip = viewer.clips.find((c) => c.name === animationName);
- if (!clip || !viewer.mixer) return;
+ if (!clip) return;
const action = viewer.mixer.clipAction(clip);
action.reset();
action.setLoop(loop ? LoopRepeat : LoopOnce, loop ? Infinity : 1);
@@ -214,78 +349,283 @@
}
// ════════════════════════════════════════════════════════════════════
- // PumpFun Live Token Feed Logic (adapted from original script)
+ // SOL price — drives real USD market caps. Sourced from the same-origin
+ // /api/pump/helius-stats endpoint (CoinGecko-backed, cached server-side).
+ // Refreshed every 60s; never blocks rendering. No hardcoded price.
+ // ════════════════════════════════════════════════════════════════════
+
+ let solPrice = 0;
+
+ async function refreshSolPrice() {
+ try {
+ const r = await fetch('/api/pump/helius-stats', { headers: { accept: 'application/json' } });
+ if (!r.ok) return;
+ const d = await r.json();
+ if (typeof d.sol_price === 'number' && d.sol_price > 0) solPrice = d.sol_price;
+ } catch { /* keep last known price; cards fall back to SOL-denominated MC */ }
+ }
+
+ // ════════════════════════════════════════════════════════════════════
+ // PumpFun Live Token Feed
+ //
+ // PumpPortal `subscribeNewToken` envelope (verified against the live feed):
+ // { txType:'create', mint, name, symbol, uri, marketCapSol, solAmount,
+ // traderPublicKey, signature, bondingCurveKey, ... }
+ // - `uri` is a metadata JSON URL; the real image lives at its `.image`.
+ // - there is NO `imageUri` field (the old renderer read a phantom field).
// ════════════════════════════════════════════════════════════════════
const RPC_ENDPOINT = 'wss://pumpportal.fun/api/data';
const MAX_FEED_ITEMS = 100;
+ const META_FETCH_TIMEOUT_MS = 4000;
+
+ // Reconnect backoff: 2s → 4s → 8s → 16s → 32s → cap 60s, reset on open.
+ // After MAX_RECONNECT_ATTEMPTS consecutive failures we stop auto-retrying
+ // and surface a manual Retry button (permanent-outage error state).
+ const BASE_BACKOFF_MS = 2000;
+ const MAX_BACKOFF_MS = 60000;
+ const MAX_RECONNECT_ATTEMPTS = 8;
const $log = document.getElementById('feed');
const $status = document.getElementById('status');
+ const $statLaunched = document.getElementById('stat-launched');
+ const $statVolume = document.getElementById('stat-volume');
+ const $statAge = document.getElementById('stat-age');
+
+ let ws = null;
+ let reconnectTimer = null;
+ let reconnectAttempts = 0;
+ let hasRenderedToken = false;
+ const seenMints = new Set();
+
+ // Live stats — accumulated only from real create events. Volume is kept in
+ // SOL and converted with the current SOL price at render time so a price
+ // refresh retroactively corrects the USD figure without double-counting.
+ let launchedCount = 0;
+ let volumeSol = 0;
+ let lastLaunchAt = 0;
+
+ const usd = (n) => '$' + n.toLocaleString(undefined, { maximumFractionDigits: n < 1000 ? 2 : 0 });
+ const isHttpUrl = (u) => typeof u === 'string' && /^https?:\/\//i.test(u);
+
+ function showSkeleton() {
+ $log.innerHTML = '';
+ for (let i = 0; i < 4; i++) {
+ const sk = document.createElement('div');
+ sk.className = 'skeleton-card';
+ sk.setAttribute('aria-hidden', 'true');
+ sk.innerHTML =
+ '<div class="sk-avatar"></div>' +
+ '<div class="sk-lines">' +
+ '<div class="sk-line w70"></div>' +
+ '<div class="sk-line w40"></div>' +
+ '<div class="sk-line w55"></div>' +
+ '</div>';
+ $log.appendChild(sk);
+ }
+ const hint = document.createElement('div');
+ hint.className = 'feed-empty-hint';
+ hint.id = 'feed-empty-hint';
+ hint.textContent = 'Waiting for new launches…';
+ $log.appendChild(hint);
+ }
+
+ function clearSkeleton() {
+ $log.querySelectorAll('.skeleton-card, #feed-empty-hint, .feed-error').forEach((el) => el.remove());
+ }
- let ws;
- let reconnectTimer;
+ function showError() {
+ $log.innerHTML = '';
+ const box = document.createElement('div');
+ box.className = 'feed-error';
+ box.setAttribute('role', 'alert');
+
+ const h = document.createElement('h3');
+ h.textContent = 'Live feed unavailable';
+ const p = document.createElement('p');
+ p.textContent = 'Could not reach the pump.fun launch stream after several attempts. PumpPortal may be temporarily down.';
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.textContent = 'Retry connection';
+ btn.addEventListener('click', () => {
+ reconnectAttempts = 0;
+ showSkeleton();
+ connect();
+ });
+
+ box.append(h, p, btn);
+ $log.appendChild(box);
+ }
+
+ function flash(el) {
+ el.classList.add('flash');
+ setTimeout(() => el.classList.remove('flash'), 320);
+ }
+
+ function renderStats() {
+ $statLaunched.textContent = launchedCount.toLocaleString();
+ $statVolume.textContent = solPrice > 0
+ ? usd(volumeSol * solPrice)
+ : volumeSol.toFixed(2) + ' SOL';
+ }
+
+ function formatAgo(ts) {
+ if (!ts) return '—';
+ const s = Math.max(0, Math.floor((Date.now() - ts) / 1000));
+ if (s < 60) return s + 's ago';
+ const m = Math.floor(s / 60);
+ if (m < 60) return m + 'm ago';
+ return Math.floor(m / 60) + 'h ago';
+ }
+
+ // The "Last launch" stat re-formats a real timestamp once a second — it is a
+ // relative-time label over actual event data, not a fabricated ticker.
+ setInterval(() => {
+ $statAge.textContent = formatAgo(lastLaunchAt);
+ }, 1000);
function connect() {
- if (reconnectTimer) clearTimeout(reconnectTimer);
+ if (reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null; }
+
+ setStatus('● Connecting…', '');
+ if (!hasRenderedToken) showSkeleton();
- setStatus('Connecting...', '');
ws = new WebSocket(RPC_ENDPOINT);
ws.onopen = () => {
+ reconnectAttempts = 0;
setStatus('● Live', 'connected');
ws.send(JSON.stringify({ method: 'subscribeNewToken' }));
};
ws.onmessage = (event) => {
+ let token;
try {
- const tokenData = JSON.parse(event.data);
- if (tokenData && tokenData.mint) {
- renderToken(tokenData);
- }
+ token = JSON.parse(event.data);
} catch (error) {
- console.error('Error parsing token data:', error);
+ console.error('[pump-live] bad frame:', error);
+ return;
}
+ // Subscription acks ("Successfully subscribed…") have no mint — ignore.
+ if (!token || !token.mint || token.txType !== 'create') return;
+ if (seenMints.has(token.mint)) return;
+ seenMints.add(token.mint);
+ renderToken(token);
};
ws.onclose = () => {
- setStatus('● Disconnected', 'error');
- reconnectTimer = setTimeout(connect, 5000); // Reconnect after 5s
+ if (reconnectAttempts >= MAX_RECONNECT_ATTEMPTS) {
+ setStatus('● Offline', 'error');
+ showError();
+ return;
+ }
+ const delay = Math.min(BASE_BACKOFF_MS * 2 ** reconnectAttempts, MAX_BACKOFF_MS);
+ reconnectAttempts++;
+ setStatus(`● Reconnecting in ${Math.round(delay / 1000)}s…`, 'error');
+ reconnectTimer = setTimeout(connect, delay);
};
ws.onerror = (error) => {
- console.error('WebSocket Error:', error);
- ws.close();
+ console.error('[pump-live] WebSocket error:', error?.message || error);
+ try { ws.close(); } catch { /* onclose drives reconnect */ }
};
}
function renderToken(token) {
- const card = document.createElement('div');
+ if (!hasRenderedToken) {
+ hasRenderedToken = true;
+ clearSkeleton();
+ }
+
+ // Update live stats from the real event.
+ launchedCount++;
+ if (typeof token.solAmount === 'number' && token.solAmount > 0) volumeSol += token.solAmount;
+ lastLaunchAt = Date.now();
+ renderStats();
+ flash($statLaunched);
+ $statAge.textContent = formatAgo(lastLaunchAt);
+
+ const name = (token.name && String(token.name).trim()) || 'Unnamed Token';
+ const symbol = token.symbol ? '$' + String(token.symbol).trim() : '';
+ const mcSol = typeof token.marketCapSol === 'number' ? token.marketCapSol : null;
+ const mcapText = mcSol == null
+ ? 'Market Cap: —'
+ : solPrice > 0
+ ? 'Market Cap: ' + usd(mcSol * solPrice)
+ : 'Market Cap: ' + mcSol.toFixed(2) + ' SOL';
+
+ const card = document.createElement('article');
card.className = 'token-card';
- const imageUrl = token.imageUri || `https://ui-avatars.com/api/?name=${token.symbol || 'T'}&background=random`;
- const mcap = token.marketCapSol ? `$${(token.marketCapSol * 150).toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}` : 'N/A';
-
- card.innerHTML = `
- <img src="${imageUrl}" alt="${token.name || 'Token'}">
- <div class="token-info">
- <div class="token-name">${token.name || 'Unnamed Token'}</div>
- <div class="token-symbol">${token.symbol ? '$' + token.symbol : ''}</div>
- <div class="token-mcap">Market Cap: ${mcap}</div>
- <div class="token-links">
- <a href="https://pump.fun/${token.mint}" target="_blank" rel="noopener noreferrer">Pump.fun</a>
- <a href="https://solscan.io/token/${token.mint}" target="_blank" rel="noopener noreferrer">Solscan</a>
- </div>
- </div>
- `;
+ // Placeholder avatar first (deterministic, no external call); the real
+ // image is fetched from the metadata URI and swapped in if it resolves.
+ const img = document.createElement('img');
+ img.loading = 'lazy';
+ img.alt = name;
+ img.src = `https://ui-avatars.com/api/?name=${encodeURIComponent(token.symbol || token.name || 'T')}&background=1a1a1a&color=00ff41&bold=true`;
+ img.addEventListener('error', () => {
+ img.src = `https://ui-avatars.com/api/?name=T&background=1a1a1a&color=00ff41`;
+ }, { once: true });
+
+ const info = document.createElement('div');
+ info.className = 'token-info';
+
+ const nameEl = document.createElement('div');
+ nameEl.className = 'token-name';
+ nameEl.textContent = name; // textContent → no HTML injection
+ nameEl.title = name;
+
+ const symEl = document.createElement('div');
+ symEl.className = 'token-symbol';
+ symEl.textContent = symbol;
+
+ const mcapEl = document.createElement('div');
+ mcapEl.className = 'token-mcap';
+ mcapEl.textContent = mcapText;
+
+ const links = document.createElement('div');
+ links.className = 'token-links';
+ const pumpLink = document.createElement('a');
+ pumpLink.href = 'https://pump.fun/' + encodeURIComponent(token.mint);
+ pumpLink.target = '_blank';
+ pumpLink.rel = 'noopener noreferrer';
+ pumpLink.textContent = 'Pump.fun';
+ const solscanLink = document.createElement('a');
+ solscanLink.href = 'https://solscan.io/token/' + encodeURIComponent(token.mint);
+ solscanLink.target = '_blank';
+ solscanLink.rel = 'noopener noreferrer';
+ solscanLink.textContent = 'Solscan';
+ links.append(pumpLink, solscanLink);
+
+ info.append(nameEl, symEl, mcapEl, links);
+ card.append(img, info);
$log.prepend(card);
- if ($log.children.length > MAX_FEED_ITEMS) {
- $log.removeChild($log.lastChild);
- }
-
- // Trigger agent animation for new token
+ while ($log.children.length > MAX_FEED_ITEMS) $log.removeChild($log.lastChild);
+
+ // Agent reacts to the new launch.
playAnimation('Wave', { loop: false });
+
+ // Resolve the real token image from its metadata JSON, then swap it in.
+ hydrateImage(token.uri, img);
+ }
+
+ async function hydrateImage(metaUri, img) {
+ if (!isHttpUrl(metaUri)) return;
+ try {
+ const ctrl = new AbortController();
+ const tid = setTimeout(() => ctrl.abort(), META_FETCH_TIMEOUT_MS);
+ const r = await fetch(metaUri, { signal: ctrl.signal });
+ clearTimeout(tid);
+ if (!r.ok) return;
+ const meta = await r.json();
+ const src = meta && meta.image;
+ if (!isHttpUrl(src)) return;
+ // Preload before swapping so we never flash a broken image.
+ const probe = new Image();
+ probe.onload = () => { img.src = src; };
+ probe.src = src;
+ } catch { /* keep the placeholder avatar */ }
}
function setStatus(text, className) {
@@ -293,7 +633,11 @@
$status.className = `status ${className}`;
}
- // Initial connection
+ // Fetch the SOL price up front (so the first cards show USD), then poll it,
+ // and open the live feed.
+ await refreshSolPrice();
+ setInterval(refreshSolPrice, 60000);
+ renderStats();
connect();
</script>
diff --git a/pages/pump-visualizer.html b/pages/pump-visualizer.html
index 4b743575e..4a6926ba2 100644
--- a/pages/pump-visualizer.html
+++ b/pages/pump-visualizer.html
@@ -111,6 +111,9 @@
display: flex;
gap: 8px;
align-items: center;
+ flex-wrap: wrap;
+ justify-content: center;
+ max-width: calc(100vw - 32px);
background: var(--vz-panel);
border: 1px solid var(--vz-border);
border-radius: 10px;
@@ -250,6 +253,31 @@
color: var(--vz-text);
}
+ /* ── Cross-links to sibling launchpad surfaces ──── */
+ .vz-links {
+ display: flex;
+ gap: 12px;
+ align-items: center;
+ border-left: 1px solid rgba(255, 255, 255, 0.08);
+ padding-left: 8px;
+ margin-left: 2px;
+ }
+ .vz-links a {
+ color: var(--vz-muted);
+ text-decoration: none;
+ font-size: 10px;
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+ white-space: nowrap;
+ transition: color 0.15s;
+ }
+ .vz-links a:hover { color: var(--vz-text); }
+ .vz-links a:focus-visible {
+ outline: 1px solid var(--vz-accent);
+ outline-offset: 2px;
+ border-radius: 4px;
+ }
+
/* ── Help / hint ──────────────────────────────── */
.vz-hint {
top: calc(var(--header-h, 3.5rem) + 12px);
@@ -645,10 +673,14 @@
<button type="button" data-sort="replies">Replies</button>
<button type="button" data-sort="recent">New</button>
</div>
+ <nav class="vz-links" aria-label="Explore the launchpad">
+ <a href="/pump-live">Feed →</a>
+ <a href="/launches">All launches →</a>
+ </nav>
</div>
<div class="vz-overlay vz-hint" id="vz-hint" aria-hidden="true">
- <b>Drag</b> to rotate · <b>Scroll</b> to zoom · <b>Click</b> a sphere · <b>/</b> to search
+ <b>Drag</b> to rotate · <b>Scroll</b> to zoom · <b>Click</b> for details · <b>Double-click</b> to open · <b>/</b> to search
<button type="button" class="dismiss" id="vz-hint-dismiss" aria-label="Dismiss">×</button>
</div>
@@ -703,7 +735,7 @@
import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';
import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';
- const TRENDING_API = '/api/pump/trending?limit=50';
+ const TRENDING_API = '/api/pump/trending?limit=50&rich=1';
const LIVE_FEED_API = '/api/agents/pumpfun-feed?kind=mint';
const MIGRATIONS_FEED_API = '/api/agents/pumpfun-feed?kind=graduation';
const MIGRATIONS_BACKFILL_API = '/api/pump/recent-graduations?limit=20';
@@ -1158,6 +1190,15 @@
selectToken(data);
}
+ // Double-click drills straight into the full 3D coin page (same tab).
+ renderer.domElement.addEventListener('dblclick', () => {
+ raycaster.setFromCamera(pointer, camera);
+ const hits = raycaster.intersectObjects(visibleMeshes(), false);
+ if (!hits.length) return;
+ const mint = hits[0].object.userData.token?.mint;
+ if (mint) window.location.href = `/coin3d?mint=${encodeURIComponent(mint)}`;
+ });
+
function setHovered(entry) {
if (hovered === entry) return;
if (hovered && hovered !== selected) {
@@ -1259,7 +1300,9 @@
const linksEl = document.getElementById('vz-detail-links');
linksEl.innerHTML = '';
if (token.mint) {
- linksEl.appendChild(linkNode(`https://pump.fun/coin/${token.mint}`, 'Pump.fun ↗', true));
+ // Primary action keeps the user inside three.ws — the full 3D coin page.
+ linksEl.appendChild(linkNode(`/coin3d?mint=${encodeURIComponent(token.mint)}`, 'Open in 3D →', { primary: true, internal: true }));
+ linksEl.appendChild(linkNode(`https://pump.fun/coin/${token.mint}`, 'Pump.fun ↗'));
linksEl.appendChild(linkNode(`https://solscan.io/token/${token.mint}`, 'Solscan ↗'));
}
if (token.twitter) linksEl.appendChild(linkNode(token.twitter, 'Twitter ↗'));
@@ -1270,11 +1313,14 @@
detailEl.setAttribute('aria-hidden', 'false');
}
- function linkNode(href, label, primary) {
+ function linkNode(href, label, opts = {}) {
+ const { primary = false, internal = false } = opts;
const a = document.createElement('a');
a.href = href;
- a.target = '_blank';
- a.rel = 'noopener noreferrer';
+ if (!internal) {
+ a.target = '_blank';
+ a.rel = 'noopener noreferrer';
+ }
a.textContent = label;
if (primary) a.className = 'primary';
return a;
@@ -2090,8 +2136,13 @@
try {
const resp = await fetch(TRENDING_API, { headers: { accept: 'application/json' } });
if (!resp.ok) throw new Error(`API returned ${resp.status}`);
- const data = await resp.json();
- if (!Array.isArray(data) || !data.length) throw new Error('No trending tokens returned');
+ const payload = await resp.json();
+ // Rich trending is wrapped as { data: [...] }; tolerate a bare array
+ // too so the viewer survives any future shape change upstream.
+ const data = Array.isArray(payload) ? payload
+ : Array.isArray(payload?.data) ? payload.data
+ : [];
+ if (!data.length) throw new Error('No trending tokens returned');
state.all = data;
const sorted = sortTokens(state.all, state.sortMode);
diff --git a/public/nav-data.js b/public/nav-data.js
index 4ea0e61df..0095d385b 100644
--- a/public/nav-data.js
+++ b/public/nav-data.js
@@ -147,6 +147,39 @@ export const NAV_GROUPS = [
},
],
},
+ {
+ label: 'Launch',
+ items: [
+ {
+ title: 'Launch a Coin',
+ href: '/launchpad',
+ desc: 'Create a token for your agent',
+ },
+ {
+ title: 'All Launches',
+ href: '/launches',
+ badge: 'New',
+ desc: 'Public feed of every agent coin',
+ },
+ {
+ title: 'Live Stream',
+ href: '/pump-live',
+ badge: 'Live',
+ badgeTone: 'live',
+ desc: 'Real-time new launches',
+ },
+ {
+ title: '3D Visualizer',
+ href: '/pump-visualizer',
+ desc: 'Trending tokens in 3D',
+ },
+ {
+ title: 'Token in 3D',
+ href: '/coin3d',
+ desc: 'View any token as a 3D scene',
+ },
+ ],
+ },
{
label: 'Embed',
items: [
diff --git a/scripts/verify-onchain-parity.mjs b/scripts/verify-onchain-parity.mjs
new file mode 100644
index 000000000..052d19bad
--- /dev/null
+++ b/scripts/verify-onchain-parity.mjs
@@ -0,0 +1,302 @@
+#!/usr/bin/env node
+/**
+ * ERC-8004 registry address-parity + on-chain provenance guard.
+ *
+ * The same registry addresses are hand-duplicated across three sources that can
+ * silently drift apart:
+ *
+ * 1. src/erc8004/abi.js — REGISTRY_DEPLOYMENTS (browser/client)
+ * 2. sdk/src/erc8004/abi.js — REGISTRY_DEPLOYMENTS (published SDK)
+ * 3. api/_lib/erc8004-chains.js — CHAINS[].registry (serverless crawler;
+ * carries the IdentityRegistry address only)
+ *
+ * A drift here is never benign: a stale address sends registrations, reputation,
+ * or validation writes to the wrong (or zero) contract. This guard asserts the
+ * three agree and that the addresses actually host bytecode on-chain.
+ *
+ * Two failure classes, two severities:
+ * - Address mismatch / drift trap — ALWAYS a real config bug → hard fail (exit 1).
+ * - Live bytecode — empty code at a declared address is a hard fail, but a
+ * network error reaching the RPC degrades to a warning so CI without egress
+ * (or a flaky public RPC) never blocks a deploy on transport noise.
+ *
+ * Runs standalone (`npm run verify:onchain`), in scripts/build-vercel.mjs phase 1
+ * alongside audit-deploy-artifacts.mjs, and via tests/onchain-parity.test.js.
+ *
+ * Live-bytecode chain subset is configurable:
+ * VERIFY_ONCHAIN_CHAINS=8453,84532 (default — Base mainnet + Base Sepolia)
+ * VERIFY_ONCHAIN_CHAINS=all (sweep every known chain)
+ * VERIFY_ONCHAIN_CHAINS=none (skip the live check entirely)
+ */
+import { dirname, resolve } from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+
+const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+
+const KINDS = ['identityRegistry', 'reputationRegistry', 'validationRegistry'];
+const ADDR_RE = /^0x[0-9a-fA-F]{40}$/;
+
+/** A value counts as a real address only if it is a well-formed 0x40-hex string. */
+function normalizeAddr(value) {
+ if (typeof value !== 'string') return null;
+ const trimmed = value.trim();
+ return ADDR_RE.test(trimmed) ? trimmed : null;
+}
+
+// ---------------------------------------------------------------------------
+// Load the three sources
+// ---------------------------------------------------------------------------
+
+/**
+ * Imports REGISTRY_DEPLOYMENTS from src/ and sdk/, and derives an equivalent
+ * per-chain map from the api/ CHAINS array (which carries the IdentityRegistry
+ * address only). Returns { sources, chains } where sources is keyed by label.
+ */
+export async function loadSources({ root = ROOT } = {}) {
+ const imp = async (rel) => import(pathToFileURL(resolve(root, rel)).href);
+
+ const [srcMod, sdkMod, apiMod] = await Promise.all([
+ imp('src/erc8004/abi.js'),
+ imp('sdk/src/erc8004/abi.js'),
+ imp('api/_lib/erc8004-chains.js'),
+ ]);
+
+ const apiDeployments = {};
+ for (const c of apiMod.CHAINS) {
+ // The api source only knows the IdentityRegistry per chain. Leaving the
+ // other kinds absent (not null-equal) means the parity check compares
+ // them across src/sdk only and never treats api silence as a drift.
+ apiDeployments[c.id] = { identityRegistry: c.registry };
+ }
+
+ const sources = {
+ 'src/erc8004/abi.js': srcMod.REGISTRY_DEPLOYMENTS,
+ 'sdk/src/erc8004/abi.js': sdkMod.REGISTRY_DEPLOYMENTS,
+ 'api/_lib/erc8004-chains.js': apiDeployments,
+ };
+
+ // CHAINS also feeds the live-bytecode check its RPC endpoints.
+ return { sources, chains: apiMod.CHAINS };
+}
+
+// ---------------------------------------------------------------------------
+// Parity check (deterministic — always runs, always hard-fails on mismatch)
+// ---------------------------------------------------------------------------
+
+/**
+ * Cross-checks the three sources. Returns { problems, merged } where problems is
+ * an array of precise mismatch descriptors and merged is the canonical
+ * { chainId: { kind: address } } map (real addresses only) for the live check.
+ *
+ * Three problem classes, all hard failures:
+ * - chain-set : a chainId present in one source is missing from another.
+ * - mismatch : two sources declare different real addresses for a slot.
+ * - drift-trap : one source has a real address, another has it null/empty
+ * for the SAME (chain, kind) — the ValidationRegistry trap.
+ */
+export function checkParity(sources) {
+ const labels = Object.keys(sources);
+ const problems = [];
+
+ // --- chain-set parity --------------------------------------------------
+ const chainSets = labels.map((l) => new Set(Object.keys(sources[l]).map(Number)));
+ const allChains = new Set(chainSets.flatMap((s) => [...s]));
+ for (const chainId of [...allChains].sort((a, b) => a - b)) {
+ const missingIn = labels.filter((l, i) => !chainSets[i].has(chainId));
+ if (missingIn.length) {
+ problems.push({
+ type: 'chain-set',
+ chainId,
+ detail: `chain ${chainId} present in [${labels
+ .filter((l, i) => chainSets[i].has(chainId))
+ .join(', ')}] but missing in [${missingIn.join(', ')}]`,
+ });
+ }
+ }
+
+ // --- per-(chain, kind) address parity ---------------------------------
+ const merged = {};
+ for (const chainId of [...allChains].sort((a, b) => a - b)) {
+ merged[chainId] = {};
+ for (const kind of KINDS) {
+ // Collect what each source says for this slot. A source that omits the
+ // kind entirely (the api source for reputation/validation) is recorded
+ // as `undefined` and excluded from the comparison — silence is not drift.
+ const declared = [];
+ for (const label of labels) {
+ const entry = sources[label][chainId];
+ if (!entry || !(kind in entry)) continue; // kind not carried by this source
+ declared.push({ label, raw: entry[kind], addr: normalizeAddr(entry[kind]) });
+ }
+ if (!declared.length) continue;
+
+ const real = declared.filter((d) => d.addr);
+ const absent = declared.filter((d) => !d.addr);
+
+ // drift trap: some sources have a real address, others null/empty.
+ if (real.length && absent.length) {
+ problems.push({
+ type: 'drift-trap',
+ chainId,
+ kind,
+ detail: `${kind} on chain ${chainId}: ${real
+ .map((d) => `${d.label}=${d.addr}`)
+ .join(', ')} vs absent in ${absent.map((d) => `${d.label}=${JSON.stringify(d.raw)}`).join(', ')}`,
+ });
+ }
+
+ // mismatch: real addresses that disagree (case-insensitive — checksum
+ // casing differences are not drift, a different address is).
+ const distinct = [...new Set(real.map((d) => d.addr.toLowerCase()))];
+ if (distinct.length > 1) {
+ problems.push({
+ type: 'mismatch',
+ chainId,
+ kind,
+ detail: `${kind} on chain ${chainId}: ${real.map((d) => `${d.label}=${d.addr}`).join(', ')}`,
+ });
+ }
+
+ if (real.length) merged[chainId][kind] = real[0].addr;
+ }
+ }
+
+ return { problems, merged };
+}
+
+// ---------------------------------------------------------------------------
+// Live bytecode check (best-effort — warns on transport error, fails on
+// confirmed-empty code at a declared address)
+// ---------------------------------------------------------------------------
+
+async function ethGetCode(rpcUrls, address) {
+ let lastError;
+ for (const url of rpcUrls) {
+ try {
+ const res = await fetch(url, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'eth_getCode',
+ params: [address, 'latest'],
+ }),
+ signal: AbortSignal.timeout(12_000),
+ });
+ if (!res.ok) {
+ lastError = new Error(`HTTP ${res.status}`);
+ continue;
+ }
+ const json = await res.json();
+ if (json.error) {
+ lastError = new Error(json.error.message || 'rpc error');
+ continue;
+ }
+ // Success: a definitive on-chain answer. "0x" / "0x0" means no code.
+ const code = typeof json.result === 'string' ? json.result : '0x';
+ return { ok: true, hasCode: code !== '0x' && code !== '0x0' && code.length > 2 };
+ } catch (err) {
+ lastError = err;
+ }
+ }
+ return { ok: false, error: lastError?.message || 'all RPCs unreachable' };
+}
+
+/** Parse VERIFY_ONCHAIN_CHAINS into the set of chainIds to probe. */
+export function resolveLiveChains(env, allChainIds) {
+ const raw = (env.VERIFY_ONCHAIN_CHAINS || '8453,84532').trim().toLowerCase();
+ if (raw === 'none') return [];
+ if (raw === 'all') return [...allChainIds];
+ return raw
+ .split(',')
+ .map((s) => Number(s.trim()))
+ .filter((n) => Number.isFinite(n));
+}
+
+/**
+ * For the configured chain subset, eth_getCode every declared (non-null) address
+ * and classify each as live / empty / unreachable. Empty is a hard failure;
+ * unreachable is a warning.
+ */
+export async function checkLiveBytecode({ merged, chains, chainIds }) {
+ const rpcByChain = Object.fromEntries(chains.map((c) => [c.id, c.rpcUrls]));
+ const nameByChain = Object.fromEntries(chains.map((c) => [c.id, c.name]));
+ const empty = [];
+ const unreachable = [];
+ const live = [];
+
+ for (const chainId of chainIds) {
+ const slots = merged[chainId];
+ const rpcUrls = rpcByChain[chainId];
+ if (!slots || !rpcUrls) continue;
+ for (const kind of KINDS) {
+ const addr = slots[kind];
+ if (!addr) continue;
+ const result = await ethGetCode(rpcUrls, addr);
+ const ctx = { chainId, name: nameByChain[chainId], kind, address: addr };
+ if (!result.ok) unreachable.push({ ...ctx, error: result.error });
+ else if (!result.hasCode) empty.push(ctx);
+ else live.push(ctx);
+ }
+ }
+ return { empty, unreachable, live };
+}
+
+// ---------------------------------------------------------------------------
+// CLI
+// ---------------------------------------------------------------------------
+
+const isMain = process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url);
+if (isMain) {
+ const start = Date.now();
+ const sweep = process.argv.includes('--sweep'); // print full live matrix
+ if (sweep) process.env.VERIFY_ONCHAIN_CHAINS = 'all';
+
+ const { sources, chains } = await loadSources();
+ const { problems, merged } = checkParity(sources);
+
+ let failed = false;
+
+ if (problems.length) {
+ failed = true;
+ console.error(`[verify:onchain] FAIL — ${problems.length} address-parity problem(s):`);
+ for (const p of problems) console.error(` [${p.type}] ${p.detail}`);
+ } else {
+ const slotCount = Object.values(merged).reduce((n, s) => n + Object.keys(s).length, 0);
+ console.log(
+ `[verify:onchain] parity OK — 3 sources agree across ${Object.keys(merged).length} chains / ${slotCount} address slots`,
+ );
+ }
+
+ const allChainIds = chains.map((c) => c.id);
+ const liveChainIds = resolveLiveChains(process.env, allChainIds);
+ if (liveChainIds.length) {
+ const { empty, unreachable, live } = await checkLiveBytecode({ merged, chains, chainIds: liveChainIds });
+
+ for (const e of live) {
+ console.log(`[verify:onchain] live ${e.name} (${e.chainId}) ${e.kind} ${e.address}`);
+ }
+ if (unreachable.length) {
+ console.warn(`[verify:onchain] WARN — ${unreachable.length} address(es) unreachable (network — not failing the build):`);
+ for (const u of unreachable) console.warn(` ${u.name} (${u.chainId}) ${u.kind} ${u.address} — ${u.error}`);
+ }
+ if (empty.length) {
+ failed = true;
+ console.error(`[verify:onchain] FAIL — ${empty.length} declared address(es) have NO bytecode on-chain:`);
+ for (const e of empty) console.error(` ${e.name} (${e.chainId}) ${e.kind} ${e.address} — eth_getCode returned 0x`);
+ }
+ console.log(
+ `[verify:onchain] live check — ${live.length} live, ${empty.length} empty, ${unreachable.length} unreachable across ${liveChainIds.length} chain(s)`,
+ );
+ } else {
+ console.log('[verify:onchain] live bytecode check skipped (VERIFY_ONCHAIN_CHAINS=none)');
+ }
+
+ const elapsed = ((Date.now() - start) / 1000).toFixed(1);
+ if (failed) {
+ console.error(`\n[verify:onchain] failed in ${elapsed}s`);
+ process.exit(1);
+ }
+ console.log(`[verify:onchain] clean in ${elapsed}s`);
+}
diff --git a/src/coin3d/main.js b/src/coin3d/main.js
index bf526edfd..63dacd80f 100644
--- a/src/coin3d/main.js
+++ b/src/coin3d/main.js
@@ -338,7 +338,11 @@ function renderHud(s) {
<div><dt>Status</dt><dd>${escapeHtml(grad)}</dd></div>
<div><dt>Top holders shown</dt><dd>${s.holders.length || 0}</dd></div>
</dl>
- <a class="hud-link" href="https://pump.fun/coin/${encodeURIComponent(s.mint)}" target="_blank" rel="noopener">View on pump.fun ↗</a>`;
+ <div class="hud-links">
+ <a class="hud-link" href="https://pump.fun/coin/${encodeURIComponent(s.mint)}" target="_blank" rel="noopener">View on pump.fun ↗</a>
+ <a class="hud-link" href="/launches">All launches →</a>
+ ${s.mint ? `<a class="hud-link" href="/communities/${encodeURIComponent(s.mint)}">3D world →</a>` : ''}
+ </div>`;
}
function compact(n) {
diff --git a/src/editor/launchpad-studio.js b/src/editor/launchpad-studio.js
index 95f149057..ce7c66b7e 100644
--- a/src/editor/launchpad-studio.js
+++ b/src/editor/launchpad-studio.js
@@ -652,6 +652,7 @@ export function mountLaunchpadStudio(root, options = {}) {
<span class="pill" data-mode-pill>Template-driven</span>
</div>
<div class="actions">
+ <a class="btn ghost" href="/launches" title="Public feed of every coin launched by a three.ws agent">See all launched coins →</a>
<a class="btn ghost" href="/embed" title="The original place-and-scale embed editor">Open classic editor</a>
<button class="btn" data-action="open-recent">My launchpads ▾</button>
<button class="btn" data-action="new-draft" title="Start a new draft (current draft cleared)">New</button>
diff --git a/src/launches.css b/src/launches.css
index 827f91fe8..4890111cc 100644
--- a/src/launches.css
+++ b/src/launches.css
@@ -360,6 +360,39 @@ body {
backdrop-filter: blur(var(--blur-md));
}
+.lx-explore {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: var(--space-xs) var(--space-md);
+ margin: calc(-1 * var(--space-sm)) 0 var(--space-lg);
+}
+
+.lx-explore-link {
+ color: var(--ink-dim);
+ font-size: var(--text-sm);
+ font-weight: var(--weight-medium);
+ font-family: var(--font-body);
+ text-decoration: none;
+ letter-spacing: 0.01em;
+ padding: var(--space-3xs) 0;
+ border-bottom: 1px solid transparent;
+ transition:
+ color var(--duration-fast) var(--ease-standard),
+ border-color var(--duration-fast) var(--ease-standard);
+}
+
+.lx-explore-link:hover {
+ color: var(--ink-bright);
+ border-bottom-color: var(--accent);
+}
+
+.lx-explore-link:focus-visible {
+ outline: var(--focus-ring-width) solid var(--focus-ring-color);
+ outline-offset: var(--focus-ring-offset);
+ border-radius: var(--radius-sm);
+}
+
.lx-net-toggle {
display: inline-flex;
padding: var(--space-3xs);
@@ -784,12 +817,15 @@ body {
.lx-card-actions {
display: flex;
+ flex-wrap: wrap;
gap: var(--space-xs);
margin-top: auto;
}
.lx-action {
- flex: 1;
+ flex: 1 1 auto;
+ min-width: 0;
+ white-space: nowrap;
display: inline-flex;
align-items: center;
justify-content: center;
diff --git a/src/launches.js b/src/launches.js
index 5c040c34b..24ab31b46 100644
--- a/src/launches.js
+++ b/src/launches.js
@@ -18,6 +18,8 @@
* · 60s live refresh that prepends genuinely new launches in place
*/
+import { mountCoinStatus } from './pump/coin-status-card.js';
+
const PAGE_SIZE = 24;
const ENRICH_CONCURRENCY = 4;
const LIVE_REFRESH_MS = 60_000;
@@ -317,56 +319,22 @@ function reveal(card, index) {
}
// ── market enrichment (mainnet only) ─────────────────────────────────────────
-// Small worker pool over /api/pump/coin so a long feed page doesn't fire 100
-// concurrent requests; each result patches its card in place.
-
-const enrichQueue = [];
-let enrichActive = 0;
-
-function queueEnrich(mint, card) {
- enrichQueue.push({ mint, card });
- pumpEnrichQueue();
-}
-
-function pumpEnrichQueue() {
- while (enrichActive < ENRICH_CONCURRENCY && enrichQueue.length) {
- const job = enrichQueue.shift();
- enrichActive++;
- enrichCard(job.mint, job.card).finally(() => {
- enrichActive--;
- pumpEnrichQueue();
- });
- }
-}
-
-async function enrichCard(mint, card) {
- let coin;
- try {
- const r = await fetch(`/api/pump/coin?mint=${encodeURIComponent(mint)}`);
- if (!r.ok) return;
- coin = await r.json();
- } catch {
- return; // registry data already on screen; market data is best-effort
- }
- if (!coin || !card.isConnected) return;
-
- const img = card.querySelector('.lx-coin-img');
- const imgSrc = coin.image_uri || coin.image;
- if (img && imgSrc) {
- img.addEventListener('load', () => img.classList.add('lx-img-in'), { once: true });
- img.src = imgSrc;
- }
-
- const mcap = card.querySelector('.lx-mcap-value');
- const cap = Number(coin.usd_market_cap);
- if (mcap && Number.isFinite(cap)) mcap.textContent = usdCompact(cap);
-
- if (coin.complete) {
- const badges = card.querySelector('.lx-badges');
- if (badges && !badges.querySelector('.lx-badge-grad')) {
- badges.prepend(el('span', { class: 'lx-badge lx-badge-grad', text: 'Graduated' }));
+// Live price / market cap / graduation now stream in through the shared
+// coin-status widget (src/pump/coin-status-card.js) — one fetch to
+// /api/pump/coin per card, field-mapped and formatted in one place. Each card
+// keeps a handle so its refresh timer is torn down when the feed is rebuilt.
+
+const cardStatusHandles = new Set();
+
+function teardownStatusHandles() {
+ for (const h of cardStatusHandles) {
+ try {
+ h.destroy();
+ } catch {
+ /* ignore */
}
}
+ cardStatusHandles.clear();
}
// ── card rendering ───────────────────────────────────────────────────────────
@@ -424,6 +392,16 @@ function launchCard(launch, index, { featured = false } = {}) {
}),
];
if (!isDevnet) {
+ actions.push(
+ el('a', {
+ class: 'lx-action',
+ href: `/coin3d?mint=${encodeURIComponent(launch.mint)}`,
+ target: '_blank',
+ rel: 'noopener noreferrer',
+ text: '3D view',
+ 'aria-label': `View ${launch.symbol || launch.name || 'coin'} in 3D`,
+ }),
+ );
actions.push(
el('a', {
class: 'lx-action',
diff --git a/src/pump/coin-status-card.js b/src/pump/coin-status-card.js
new file mode 100644
index 000000000..6e2740a3e
--- /dev/null
+++ b/src/pump/coin-status-card.js
@@ -0,0 +1,430 @@
+/**
+ * Shared live coin-status widget.
+ * ================================
+ *
+ * One module, three surfaces. Live coin status (symbol, price, market cap,
+ * graduation %, 24h volume, buy link) was independently implemented in
+ * agent-detail.js, agent-home-pumpfun.js and launches.js — each fetching
+ * `/api/pump/coin`, formatting numbers, and handling loading/error states on
+ * its own. This unifies all of that: map the response shape once here, and
+ * every consumer benefits when a field name or format changes.
+ *
+ * Data source: GET /api/pump/coin?mint=<mint> (pump.fun coin object, proxied).
+ * The raw shape is normalized exactly once in `mapCoin()`, so renaming an
+ * upstream field (e.g. `usd_market_cap` → `mcap`) is a one-line change that
+ * propagates to all three variants without touching any caller.
+ *
+ * Variants:
+ * · chip (default) — compact inline chip: symbol · price · mcap · grad %.
+ * · row — table-row layout: symbol, mint, volume, time.
+ * · card — full card: name, price, mcap, graduation ring, volume,
+ * buy link, time-since-launch.
+ *
+ * States: loading skeleton → populated → error (with Retry). The module owns
+ * its own refresh timer; callers just hand it a container and call destroy().
+ */
+
+const COIN_ENDPOINT = '/api/pump/coin';
+const DEFAULT_REFRESH_MS = 30_000;
+// pump.fun bonding curves complete (graduate) around a ~$69k USD market cap;
+// the same constant the agent token widget uses for its graduation gauge.
+const GRADUATION_CAP_USD = 69_000;
+const SVG_NS = 'http://www.w3.org/2000/svg';
+
+// ── formatting ───────────────────────────────────────────────────────────────
+// Copied from the existing implementations (launches.usdCompact /
+// agent-detail.launchUsdCompact / agent-detail.fmtPct) so the three surfaces
+// keep formatting identical after the refactor.
+
+/** Compact USD market cap: `$1.2M`, `$340.0K`, `$420`. */
+export function formatMcap(n) {
+ if (!Number.isFinite(n)) return '—';
+ if (n >= 1e9) return `$${(n / 1e9).toFixed(2)}B`;
+ if (n >= 1e6) return `$${(n / 1e6).toFixed(2)}M`;
+ if (n >= 1e3) return `$${(n / 1e3).toFixed(1)}K`;
+ return `$${n.toFixed(0)}`;
+}
+
+/** Per-token USD price: `$0.00012`, `$1.20`, `$1.2e-8`. */
+export function formatPrice(n) {
+ if (!Number.isFinite(n) || n <= 0) return '—';
+ if (n < 1e-6) return `$${n.toExponential(2)}`;
+ if (n < 1) return `$${n.toPrecision(2)}`;
+ if (n < 1000) return `$${n.toFixed(2)}`;
+ return `$${Math.round(n).toLocaleString('en-US')}`;
+}
+
+/** Percentage (0–100 in, clamped): `0%`, `34%`, `7.5%`. */
+export function formatPct(n) {
+ if (!Number.isFinite(n)) return '—';
+ const v = Math.max(0, Math.min(100, n));
+ return `${v >= 10 || v === 0 ? v.toFixed(0) : v.toFixed(1)}%`;
+}
+
+function timeSince(ms) {
+ const t = Number(ms);
+ if (!Number.isFinite(t) || t <= 0) return '';
+ const s = Math.max(0, (Date.now() - t) / 1000);
+ if (s < 60) return 'just now';
+ if (s < 3600) return `${Math.floor(s / 60)}m ago`;
+ if (s < 86400) return `${Math.floor(s / 3600)}h ago`;
+ if (s < 86400 * 30) return `${Math.floor(s / 86400)}d ago`;
+ return new Date(t).toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
+}
+
+function shortMint(s, head = 4, tail = 4) {
+ const str = String(s || '');
+ if (str.length <= head + tail + 1) return str;
+ return `${str.slice(0, head)}…${str.slice(-tail)}`;
+}
+
+// Plain-language values for screen readers — "1.2 million dollars" etc.
+function spokenUsd(n) {
+ if (!Number.isFinite(n)) return 'unavailable';
+ if (n >= 1e9) return `${(n / 1e9).toFixed(2)} billion dollars`;
+ if (n >= 1e6) return `${(n / 1e6).toFixed(2)} million dollars`;
+ if (n >= 1e3) return `${(n / 1e3).toFixed(1)} thousand dollars`;
+ return `${n.toFixed(2)} dollars`;
+}
+
+// ── field mapping (the single source of truth for the API shape) ─────────────
+
+/**
+ * Normalize the raw `/api/pump/coin` response into the shape every variant
+ * reads from. This is the ONLY place that knows the upstream field names — a
+ * rename here propagates to chip, row, and card at once.
+ */
+function mapCoin(raw, mint) {
+ const mcap = Number(raw?.usd_market_cap);
+ const supplyAtomic = Number(raw?.total_supply);
+ // pump.fun tokens carry 6 decimals; human supply = atomic / 1e6.
+ const supply = Number.isFinite(supplyAtomic) && supplyAtomic > 0 ? supplyAtomic / 1e6 : null;
+ const price = supply && Number.isFinite(mcap) ? mcap / supply : null;
+ const graduated = raw?.complete === true;
+ const graduationPct = graduated
+ ? 100
+ : Number.isFinite(mcap)
+ ? Math.max(0, Math.min(100, (mcap / GRADUATION_CAP_USD) * 100))
+ : null;
+ const volume24h = Number(raw?.volume_24h ?? raw?.volume24h);
+
+ return {
+ mint: raw?.mint || mint,
+ symbol: raw?.symbol || '',
+ name: raw?.name || '',
+ image: raw?.image_uri || raw?.image || '',
+ mcap: Number.isFinite(mcap) ? mcap : null,
+ price: Number.isFinite(price) ? price : null,
+ graduationPct,
+ graduated,
+ volume24h: Number.isFinite(volume24h) ? volume24h : null,
+ createdAt: Number(raw?.created_timestamp) || null,
+ };
+}
+
+// ── tiny DOM helper ──────────────────────────────────────────────────────────
+
+function el(tag, props = {}, children = []) {
+ const node = document.createElement(tag);
+ for (const [k, v] of Object.entries(props)) {
+ if (v == null || v === false) continue;
+ if (k === 'class') node.className = v;
+ else if (k === 'text') node.textContent = v;
+ else if (k.startsWith('on')) node.addEventListener(k.slice(2), v);
+ else node.setAttribute(k, v);
+ }
+ for (const c of [].concat(children || [])) {
+ if (c == null) continue;
+ node.appendChild(typeof c === 'string' ? document.createTextNode(c) : c);
+ }
+ return node;
+}
+
+// ── graduation ring (SVG arc via stroke-dasharray) ───────────────────────────
+
+function graduationRing(pct) {
+ const value = Math.max(0, Math.min(100, Number(pct) || 0));
+ const r = 13;
+ const circumference = 2 * Math.PI * r;
+ const dash = (value / 100) * circumference;
+
+ const svg = document.createElementNS(SVG_NS, 'svg');
+ svg.setAttribute('viewBox', '0 0 32 32');
+ svg.setAttribute('class', 'csc-ring');
+ svg.setAttribute('role', 'img');
+ svg.setAttribute('aria-label', `${formatPct(value)} to graduation`);
+
+ const track = document.createElementNS(SVG_NS, 'circle');
+ track.setAttribute('cx', '16');
+ track.setAttribute('cy', '16');
+ track.setAttribute('r', String(r));
+ track.setAttribute('class', 'csc-ring-track');
+
+ const arc = document.createElementNS(SVG_NS, 'circle');
+ arc.setAttribute('cx', '16');
+ arc.setAttribute('cy', '16');
+ arc.setAttribute('r', String(r));
+ arc.setAttribute('class', 'csc-ring-arc');
+ arc.setAttribute('stroke-dasharray', `${dash.toFixed(2)} ${(circumference - dash).toFixed(2)}`);
+ arc.setAttribute('transform', 'rotate(-90 16 16)');
+
+ const label = document.createElementNS(SVG_NS, 'text');
+ label.setAttribute('x', '16');
+ label.setAttribute('y', '16');
+ label.setAttribute('class', 'csc-ring-label');
+ label.textContent = `${Math.round(value)}`;
+
+ svg.append(track, arc, label);
+ return svg;
+}
+
+// ── variant renderers ────────────────────────────────────────────────────────
+
+function renderChip(coin, opts) {
+ const nodes = [el('span', { class: 'csc-sym', text: coin.symbol ? `$${coin.symbol}` : shortMint(coin.mint) })];
+ if (coin.price != null) {
+ nodes.push(el('span', { class: 'csc-price', text: formatPrice(coin.price), 'aria-label': `Price: ${formatPrice(coin.price)} per token` }));
+ }
+ if (coin.mcap != null) {
+ nodes.push(el('span', { class: 'csc-mcap', text: formatMcap(coin.mcap), 'aria-label': `Market cap: ${spokenUsd(coin.mcap)}` }));
+ }
+ if (coin.graduationPct != null) {
+ nodes.push(
+ el('span', {
+ class: `csc-grad${coin.graduated ? ' csc-grad-done' : ''}`,
+ text: coin.graduated ? 'Graduated' : `${formatPct(coin.graduationPct)} to grad`,
+ }),
+ );
+ }
+ if (opts.showBuy) nodes.push(buyLink(coin.mint));
+ return el('div', { class: 'csc csc-chip' }, nodes);
+}
+
+function renderRow(coin, opts) {
+ const nodes = [
+ el('span', { class: 'csc-sym', text: coin.symbol ? `$${coin.symbol}` : coin.name || '—' }),
+ el('span', { class: 'csc-mono csc-mint', text: shortMint(coin.mint) }),
+ el('span', {
+ class: 'csc-mcap',
+ text: coin.mcap != null ? formatMcap(coin.mcap) : '—',
+ 'aria-label': `Market cap: ${spokenUsd(coin.mcap)}`,
+ }),
+ ];
+ if (coin.volume24h != null) {
+ nodes.push(el('span', { class: 'csc-vol', text: `Vol ${formatMcap(coin.volume24h)}` }));
+ }
+ if (coin.createdAt) nodes.push(el('span', { class: 'csc-time', text: timeSince(coin.createdAt) }));
+ if (opts.showBuy) nodes.push(buyLink(coin.mint));
+ return el('div', { class: 'csc csc-row' }, nodes);
+}
+
+function renderCard(coin, opts) {
+ const head = el('div', { class: 'csc-card-head' }, [
+ coin.image ? el('img', { class: 'csc-card-img', src: coin.image, alt: '', loading: 'lazy' }) : null,
+ el('div', { class: 'csc-card-id' }, [
+ el('span', { class: 'csc-card-name', text: coin.name || coin.symbol || 'Coin' }),
+ el('span', { class: 'csc-sym', text: coin.symbol ? `$${coin.symbol}` : shortMint(coin.mint) }),
+ ]),
+ coin.graduationPct != null ? graduationRing(coin.graduationPct) : null,
+ ]);
+
+ const stats = el('div', { class: 'csc-card-stats' }, [
+ el('div', { class: 'csc-stat' }, [
+ el('span', { class: 'csc-stat-label', text: 'Price' }),
+ el('span', {
+ class: 'csc-stat-value',
+ text: coin.price != null ? formatPrice(coin.price) : '—',
+ 'aria-label': coin.price != null ? `Price: ${formatPrice(coin.price)} per token` : null,
+ }),
+ ]),
+ el('div', { class: 'csc-stat' }, [
+ el('span', { class: 'csc-stat-label', text: 'Market cap' }),
+ el('span', {
+ class: 'csc-stat-value',
+ text: coin.mcap != null ? formatMcap(coin.mcap) : '—',
+ 'aria-label': `Market cap: ${spokenUsd(coin.mcap)}`,
+ }),
+ ]),
+ ]);
+ if (coin.volume24h != null) {
+ stats.appendChild(
+ el('div', { class: 'csc-stat' }, [
+ el('span', { class: 'csc-stat-label', text: '24h volume' }),
+ el('span', { class: 'csc-stat-value', text: formatMcap(coin.volume24h) }),
+ ]),
+ );
+ }
+
+ // Market-cap progress bar mirrors the graduation ring as a wider readout.
+ const bar = el('div', { class: 'csc-bar', role: 'progressbar', 'aria-valuemin': '0', 'aria-valuemax': '100', 'aria-valuenow': String(Math.round(coin.graduationPct || 0)) }, [
+ el('div', { class: 'csc-bar-fill', style: `width:${Math.min(100, coin.graduationPct || 0).toFixed(1)}%` }),
+ ]);
+
+ const foot = el('div', { class: 'csc-card-foot' }, [
+ coin.createdAt ? el('span', { class: 'csc-time', text: `Launched ${timeSince(coin.createdAt)}` }) : null,
+ opts.showBuy ? buyLink(coin.mint) : null,
+ ]);
+
+ return el('div', { class: 'csc csc-card' }, [head, stats, coin.graduationPct != null ? bar : null, foot]);
+}
+
+function buyLink(mint) {
+ return el('a', {
+ class: 'csc-buy',
+ href: `https://pump.fun/${mint}`,
+ target: '_blank',
+ rel: 'noopener noreferrer',
+ text: 'Buy →',
+ });
+}
+
+const RENDERERS = { chip: renderChip, row: renderRow, card: renderCard };
+
+// ── loading / error states ───────────────────────────────────────────────────
+
+function skeleton(variant) {
+ const bars = variant === 'card' ? 4 : variant === 'row' ? 3 : 2;
+ return el(
+ 'div',
+ { class: `csc csc-${variant} csc-skeleton` },
+ Array.from({ length: bars }, () => el('span', { class: 'csc-skel-bar' })),
+ );
+}
+
+function errorState(variant, retry) {
+ return el('div', { class: `csc csc-${variant} csc-error`, role: 'alert' }, [
+ el('span', { class: 'csc-error-msg', text: 'Coin data unavailable.' }),
+ el('button', { class: 'csc-retry', type: 'button', text: 'Retry', onclick: retry }),
+ ]);
+}
+
+// ── styles (injected once) ───────────────────────────────────────────────────
+
+let stylesInjected = false;
+const STYLES = `
+.csc { color: var(--ink-bright, #e8e8e8); font-size: 13px; box-sizing: border-box; }
+.csc-chip, .csc-row { display: inline-flex; align-items: center; gap: 8px; flex-wrap: wrap; }
+.csc-row { display: flex; width: 100%; }
+.csc-sym { font-weight: 600; }
+.csc-mono { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
+.csc-mint, .csc-time, .csc-vol { color: var(--ink-dim, rgba(255,255,255,0.55)); font-size: 12px; }
+.csc-time { margin-left: auto; }
+.csc-price { color: var(--ink-dim, rgba(255,255,255,0.7)); }
+.csc-mcap { font-weight: 600; }
+.csc-grad { font-size: 11px; padding: 1px 7px; border-radius: 999px; background: rgba(120,140,255,0.14); color: rgba(190,200,255,0.95); }
+.csc-grad-done { background: rgba(120,200,140,0.16); color: rgba(170,235,190,0.95); }
+.csc-buy { color: var(--accent, #7c83ff); text-decoration: none; font-weight: 600; transition: opacity .15s; }
+.csc-buy:hover { opacity: .8; }
+.csc-buy:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; border-radius: 4px; }
+
+.csc-card { display: flex; flex-direction: column; gap: 12px; padding: 14px; border-radius: 14px;
+ background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.07); }
+.csc-card-head { display: flex; align-items: center; gap: 10px; }
+.csc-card-img { width: 40px; height: 40px; border-radius: 9px; object-fit: cover; flex: 0 0 auto; background: rgba(255,255,255,0.05); }
+.csc-card-id { display: flex; flex-direction: column; min-width: 0; gap: 1px; }
+.csc-card-name { font-weight: 600; font-size: 15px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.csc-ring { width: 36px; height: 36px; margin-left: auto; flex: 0 0 auto; }
+.csc-ring-track { fill: none; stroke: rgba(255,255,255,0.1); stroke-width: 3; }
+.csc-ring-arc { fill: none; stroke: var(--accent, #7c83ff); stroke-width: 3; stroke-linecap: round; transition: stroke-dasharray .5s ease; }
+.csc-ring-label { fill: var(--ink-bright, #e8e8e8); font-size: 11px; font-weight: 600; text-anchor: middle; dominant-baseline: central; }
+.csc-card-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(80px, 1fr)); gap: 10px; }
+.csc-stat { display: flex; flex-direction: column; gap: 2px; }
+.csc-stat-label { font-size: 11px; text-transform: uppercase; letter-spacing: .04em; color: var(--ink-dim, rgba(255,255,255,0.5)); }
+.csc-stat-value { font-size: 15px; font-weight: 600; }
+.csc-bar { height: 5px; border-radius: 999px; background: rgba(255,255,255,0.08); overflow: hidden; }
+.csc-bar-fill { height: 100%; background: var(--accent, #7c83ff); border-radius: 999px; transition: width .5s ease; }
+.csc-card-foot { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
+.csc-card-foot:empty { display: none; }
+
+.csc-skeleton { gap: 8px; }
+.csc-skel-bar { display: inline-block; height: 12px; min-width: 48px; flex: 1 1 48px; border-radius: 6px;
+ background: linear-gradient(90deg, rgba(255,255,255,0.06) 25%, rgba(255,255,255,0.12) 37%, rgba(255,255,255,0.06) 63%);
+ background-size: 400% 100%; animation: csc-shimmer 1.4s ease infinite; }
+.csc-card.csc-skeleton { min-height: 120px; }
+@keyframes csc-shimmer { 0% { background-position: 100% 50%; } 100% { background-position: 0 50%; } }
+@media (prefers-reduced-motion: reduce) { .csc-skel-bar { animation: none; } }
+
+.csc-error { display: flex; align-items: center; gap: 10px; color: var(--ink-dim, rgba(255,255,255,0.6)); font-size: 12px; }
+.csc-error-msg { flex: 1 1 auto; }
+.csc-retry { background: rgba(255,255,255,0.08); border: 1px solid rgba(255,255,255,0.12); color: inherit;
+ border-radius: 7px; padding: 3px 10px; font-size: 12px; cursor: pointer; transition: background .15s; }
+.csc-retry:hover { background: rgba(255,255,255,0.14); }
+.csc-retry:focus-visible { outline: 2px solid var(--accent, #7c83ff); outline-offset: 1px; }
+`;
+
+function injectStyles() {
+ if (stylesInjected || typeof document === 'undefined') return;
+ const tag = document.createElement('style');
+ tag.dataset.cscStyles = '1';
+ tag.textContent = STYLES;
+ document.head.appendChild(tag);
+ stylesInjected = true;
+}
+
+// ── mount ────────────────────────────────────────────────────────────────────
+
+/**
+ * Mounts a live coin-status display into `container`.
+ *
+ * @param {HTMLElement} container — where to render
+ * @param {string} mint — Solana mint address (base58)
+ * @param {object} [opts]
+ * @param {string} [opts.variant] — 'chip' | 'row' | 'card' (default: 'chip')
+ * @param {number} [opts.refreshMs] — live-refresh interval (default: 30000, 0 disables)
+ * @param {boolean} [opts.showBuy] — show "Buy" link (default: false)
+ * @returns {{ destroy: () => void }} — cleanup handle
+ */
+export function mountCoinStatus(container, mint, opts = {}) {
+ const variant = RENDERERS[opts.variant] ? opts.variant : 'chip';
+ const refreshMs = opts.refreshMs == null ? DEFAULT_REFRESH_MS : Number(opts.refreshMs);
+ const showBuy = !!opts.showBuy;
+ const render = RENDERERS[variant];
+
+ injectStyles();
+
+ let timer = null;
+ let abort = null;
+ let destroyed = false;
+ let lastCoin = null;
+
+ const paint = (node) => {
+ if (destroyed || !container) return;
+ container.replaceChildren(node);
+ };
+
+ async function load({ silent = false } = {}) {
+ if (destroyed) return;
+ if (abort) abort.abort();
+ abort = new AbortController();
+ container.setAttribute('aria-busy', 'true');
+ if (!silent && !lastCoin) paint(skeleton(variant));
+
+ try {
+ const r = await fetch(`${COIN_ENDPOINT}?mint=${encodeURIComponent(mint)}`, { signal: abort.signal });
+ if (!r.ok) throw new Error(`coin api ${r.status}`);
+ const raw = await r.json();
+ lastCoin = mapCoin(raw, mint);
+ paint(render(lastCoin, { showBuy }));
+ } catch (err) {
+ if (err?.name === 'AbortError' || destroyed) return;
+ // A refresh blip keeps the last good render; only a cold failure with
+ // nothing on screen shows the error state.
+ if (!lastCoin) paint(errorState(variant, () => load()));
+ } finally {
+ if (!destroyed) container.setAttribute('aria-busy', 'false');
+ }
+ }
+
+ load();
+ if (refreshMs > 0) {
+ timer = setInterval(() => load({ silent: true }), refreshMs);
+ }
+
+ return {
+ destroy() {
+ destroyed = true;
+ if (timer) clearInterval(timer);
+ if (abort) abort.abort();
+ },
+ };
+}
diff --git a/src/pump/coin-status-card.test.js b/src/pump/coin-status-card.test.js
new file mode 100644
index 000000000..b0ba0933a
--- /dev/null
+++ b/src/pump/coin-status-card.test.js
@@ -0,0 +1,61 @@
+// Unit tests for the shared coin-status formatters. These are the formatting
+// primitives copied from the three pre-refactor implementations; locking them
+// down here keeps all three surfaces rendering identically.
+
+import { describe, it, expect } from 'vitest';
+import { formatMcap, formatPrice, formatPct } from './coin-status-card.js';
+
+describe('formatMcap', () => {
+ it('renders billions, millions, and thousands compactly', () => {
+ expect(formatMcap(2_400_000_000)).toBe('$2.40B');
+ expect(formatMcap(1_200_000)).toBe('$1.20M');
+ expect(formatMcap(340_000)).toBe('$340.0K');
+ });
+
+ it('renders sub-thousand values as whole dollars', () => {
+ expect(formatMcap(420)).toBe('$420');
+ expect(formatMcap(0)).toBe('$0');
+ });
+
+ it('returns an em dash for non-finite input', () => {
+ expect(formatMcap(NaN)).toBe('—');
+ expect(formatMcap(Infinity)).toBe('—');
+ expect(formatMcap(undefined)).toBe('—');
+ });
+});
+
+describe('formatPct', () => {
+ it('rounds to whole numbers at or above 10%', () => {
+ expect(formatPct(34)).toBe('34%');
+ expect(formatPct(100)).toBe('100%');
+ });
+
+ it('keeps one decimal below 10% (but not at zero)', () => {
+ expect(formatPct(7.5)).toBe('7.5%');
+ expect(formatPct(0)).toBe('0%');
+ });
+
+ it('clamps out-of-range input to 0–100', () => {
+ expect(formatPct(-5)).toBe('0%');
+ expect(formatPct(140)).toBe('100%');
+ });
+
+ it('returns an em dash for non-finite input', () => {
+ expect(formatPct(NaN)).toBe('—');
+ });
+});
+
+describe('formatPrice', () => {
+ it('shows small per-token prices with two significant figures', () => {
+ expect(formatPrice(0.00012)).toBe('$0.00012');
+ });
+
+ it('formats whole-dollar prices to cents', () => {
+ expect(formatPrice(1.2)).toBe('$1.20');
+ });
+
+ it('rejects zero and non-finite input', () => {
+ expect(formatPrice(0)).toBe('—');
+ expect(formatPrice(NaN)).toBe('—');
+ });
+});
diff --git a/src/pump/launch-token-modal.css b/src/pump/launch-token-modal.css
index 83ba704b7..946e76727 100644
--- a/src/pump/launch-token-modal.css
+++ b/src/pump/launch-token-modal.css
@@ -354,18 +354,21 @@
box-sizing: border-box;
text-align: left;
}
-.ltm-pumpfun-link {
- display: inline-block;
- padding: 0.55rem 1.4rem;
- border-radius: 8px;
- background: rgba(120, 200, 140, 0.16);
- border: 1px solid rgba(120, 200, 140, 0.35);
- color: #d8f5e2;
+.ltm-cta-row {
+ display: flex;
+ gap: 8px;
+ flex-wrap: wrap;
+ justify-content: center;
+ margin-top: 16px;
+ width: 100%;
+}
+.ltm-cta-row .ltm-btn { flex: 1; min-width: 130px; }
+.ltm-cta-row a.ltm-btn {
text-decoration: none;
- font-size: 0.82rem;
- transition: background 0.15s;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
}
-.ltm-pumpfun-link:hover { background: rgba(120, 200, 140, 0.26); }
/* Status spinner (reuse mp-spinner pattern) */
@keyframes ltm-spin { to { transform: rotate(360deg); } }
diff --git a/src/pump/launch-token-modal.js b/src/pump/launch-token-modal.js
index 59bb269b8..89b07e657 100644
--- a/src/pump/launch-token-modal.js
+++ b/src/pump/launch-token-modal.js
@@ -789,7 +789,7 @@ export class LaunchTokenModal {
const mint = confirmed.agent?.token?.mint || prep.mint;
const pumpUrl =
prep.cluster === 'mainnet' ? `https://pump.fun/coin/${mint}` : null;
- this._renderStep4(mint, pumpUrl);
+ this._renderStep4(mint, pumpUrl, this.agentId);
} catch {
this._msg('Connection error, please try again', true);
reset();
@@ -798,8 +798,20 @@ export class LaunchTokenModal {
// ── Step 4 — Success ──────────────────────────────────────────────────────
- _renderStep4(mint, pumpUrl) {
+ _renderStep4(mint, pumpUrl, agentId) {
this._step = 4;
+ const isMainnet = this._d.cluster !== 'devnet';
+ const coin3dUrl = `/coin3d?mint=${encodeURIComponent(mint)}`;
+ const dashboardUrl = agentId
+ ? `/pump-dashboard?agent=${encodeURIComponent(agentId)}`
+ : '/pump-dashboard';
+ const ctaRow = isMainnet
+ ? `<div class="ltm-cta-row">
+ <a class="ltm-btn ltm-btn-primary" id="ltm-view-3d" href="${_esc(coin3dUrl)}" target="_blank" rel="noopener noreferrer">View in 3D</a>
+ <button class="ltm-btn" id="ltm-manage">Manage on Dashboard</button>
+ ${pumpUrl ? `<a class="ltm-btn" id="ltm-pumpfun" href="${_esc(pumpUrl)}" target="_blank" rel="noopener noreferrer">View on pump.fun ↗</a>` : ''}
+ </div>`
+ : '';
this._paint(
this._shell(
'Token Launched!',
@@ -813,10 +825,10 @@ export class LaunchTokenModal {
<button class="ltm-btn" id="ltm-download">Download card</button>
<button class="ltm-btn ltm-btn-primary" id="ltm-share-x">Share on X</button>
</div>
- ${pumpUrl ? `<a class="ltm-pumpfun-link" href="${_esc(pumpUrl)}" target="_blank" rel="noopener noreferrer">View on pump.fun →</a>` : ''}
+ ${ctaRow}
</div>`,
`<div></div>
- <button class="ltm-btn ltm-btn-primary btn btn--primary" id="ltm-done">Done</button>`,
+ <button class="ltm-btn ltm-btn-primary btn btn--primary" id="ltm-done">Close</button>`,
),
);
@@ -850,9 +862,13 @@ export class LaunchTokenModal {
window.open(intent, '_blank', 'noopener,noreferrer');
});
+ ov.querySelector('#ltm-manage')?.addEventListener('click', () => {
+ this._close();
+ window.location.href = dashboardUrl;
+ });
+
ov.querySelector('#ltm-done').addEventListener('click', () => {
this._close();
- location.reload();
});
window.dispatchEvent(