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: coin3d page + pumpfun-mcp native bindings, config updates
nirholasc4bd4b9f87c4
diff --git a/packages/pumpfun-mcp/src/index.js b/packages/pumpfun-mcp/src/index.jsindex 398f14795..d3c57fd7e 100644--- a/packages/pumpfun-mcp/src/index.js+++ b/packages/pumpfun-mcp/src/index.js@@ -24,6 +24,7 @@ import {} from '@modelcontextprotocol/sdk/types.js';import { FALLBACK_TOOLS } from './tools.js';+import { buildNativeRegistry } from './native.js';const BACKEND_URL = process.env.PUMPFUN_MCP_URL || 'https://three.ws/api/pump-fun-mcp';const SERVER_NAME = 'three.ws-pumpfun-mcp';@@ -71,8 +72,23 @@ async function loadTools() {return FALLBACK_TOOLS;}+// Invoke a single backend tool and return its unwrapped structuredContent.+// Throws on a JSON-RPC error envelope so native composers can treat an+// individual source as unavailable (Promise.allSettled) without faking data.+async function callTool(name, args) {+ const env = await callBackend('tools/call', { name, arguments: args || {} });+ if (env?.error) {+ const err = new Error(env.error.message || `${name} failed`);+ err.rpcCode = env.error.code;+ throw err;+ }+ return env?.result?.structuredContent ?? null;+}+async function main() {- const tools = await loadTools();+ const backendTools = await loadTools();+ const native = buildNativeRegistry(BACKEND_URL, callTool);+ const tools = [...backendTools, ...native.defs];const server = new Server({ name: SERVER_NAME, version: SERVER_VERSION },@@ -95,6 +111,25 @@ async function main() {server.setRequestHandler(CallToolRequestSchema, async (request) => {const { name, arguments: args } = request.params;++ // Native composed tools run in-process (they orchestrate backend reads).+ if (native.handlers.has(name)) {+ try {+ const data = await native.handlers.get(name)(args || {});+ return {+ content: [{ type: 'text', text: JSON.stringify(data) }],+ structuredContent: data,+ };+ } catch (err) {+ return {+ isError: true,+ content: [+ { type: 'text', text: `[${err.rpcCode ?? -32603}] ${err.message || 'tool error'}` },+ ],+ };+ }+ }+let env;try {env = await callBackend('tools/call', { name, arguments: args || {} });diff --git a/packages/pumpfun-mcp/src/native.js b/packages/pumpfun-mcp/src/native.jsnew file mode 100644index 000000000..85d4c159b--- /dev/null+++ b/packages/pumpfun-mcp/src/native.js@@ -0,0 +1,141 @@+// Native (client-composed) tools for the pump.fun MCP bridge.+//+// These don't exist on the backend as single endpoints — they orchestrate+// several backend read tools and add value on top (here: a deep-link into the+// three.ws /coin3d viewer). Keeping them in the bridge means the package is+// useful the moment it's installed, with no backend deploy required, while+// still sourcing every number from the same canonical on-chain reads.++// Derive the public site origin (for viewer links) from the backend URL, so a+// self-hosted backend produces self-hosted viewer links automatically.+function siteBaseFrom(backendUrl) {+ try {+ return new URL(backendUrl).origin;+ } catch {+ return 'https://three.ws';+ }+}++function ipfsToHttp(url) {+ if (typeof url !== 'string') return null;+ if (url.startsWith('ipfs://')) return `https://ipfs.io/ipfs/${url.slice(7)}`;+ return url;+}++// The token logo lives in the off-chain metadata JSON pointed to by the+// on-chain `uri`. Resolve it best-effort: a direct image field wins, otherwise+// fetch the uri JSON and read .image. Returns null rather than guessing.+async function resolveImage(d) {+ const direct = d.image || d.imageUrl || d.metadata?.image;+ if (direct) return ipfsToHttp(direct);+ const uri = d.uri || d.metadata?.uri;+ if (!uri) return null;+ try {+ const res = await fetch(ipfsToHttp(uri), { signal: AbortSignal.timeout(6000) });+ if (!res.ok) return null;+ const meta = await res.json();+ return meta?.image ? ipfsToHttp(meta.image) : null;+ } catch {+ return null;+ }+}++function num(v) {+ const n = Number(v);+ return Number.isFinite(n) ? n : null;+}++function pct01(v) {+ const n = num(v);+ if (n === null) return null;+ const p = n > 1 ? n / 100 : n;+ return Math.max(0, Math.min(1, p));+}++// pumpfun_token_3d — assemble a live 3D snapshot of a token and return a+// shareable viewer deep-link plus the underlying data.+async function token3dHandler(args, { call, siteBase }) {+ const mint = String(args?.mint || '').trim();+ if (!mint) {+ const err = new Error('mint is required');+ err.rpcCode = -32602;+ throw err;+ }+ const network = args?.network === 'devnet' ? 'devnet' : 'mainnet';++ const [details, curve, holders] = await Promise.allSettled([+ call('getTokenDetails', { mint }),+ call('getBondingCurve', { mint, network }),+ call('getTokenHolders', { mint, limit: 12, network }),+ ]);++ const d = details.status === 'fulfilled' ? details.value || {} : {};+ const c = curve.status === 'fulfilled' ? curve.value || null : null;+ const h = holders.status === 'fulfilled' ? holders.value || null : null;++ if (details.status === 'rejected' && curve.status === 'rejected' && holders.status === 'rejected') {+ const err = new Error(`no on-chain data for ${mint}: ${details.reason?.message || 'unavailable'}`);+ err.rpcCode = -32004;+ throw err;+ }++ const name = d.name || d.metadata?.name || null;+ const symbol = (d.symbol || d.metadata?.symbol || '') || null;+ const image = await resolveImage(d);++ const q = new URLSearchParams({ mint });+ if (network === 'devnet') q.set('network', 'devnet');+ const viewerUrl = `${siteBase}/coin3d?${q.toString()}`;++ return {+ mint,+ network,+ name,+ symbol: symbol ? symbol.toUpperCase() : null,+ image,+ marketCapUsd: num(d.marketCapUsd ?? d.usdMarketCap ?? d.market_cap),+ graduated: Boolean(c?.graduated || c?.complete),+ graduationProgress: pct01(c?.graduationProgress ?? c?.progress),+ topHolderPercent: num(h?.topHolderPercent),+ topHolders: Array.isArray(h?.holders) ? h.holders : [],+ viewerUrl,+ embedHtml: `<iframe src="${viewerUrl}" width="640" height="420" frameborder="0" allow="fullscreen" style="border:0;border-radius:16px"></iframe>`,+ rendering: {+ coin: image ? 'token logo textured onto a spinning 3D medallion' : 'brand-tinted disc (no logo found)',+ holderGalaxy: (h?.holders?.length || 0) > 0+ ? `${h.holders.length} top holders as balance-sized, concentration-tinted orbiting spheres`+ : 'no holder data available',+ graduationRing: c+ ? (c.graduated || c.complete ? 'full ring (graduated to Raydium)' : 'arc filled to bonding-curve progress')+ : 'no bonding-curve data available',+ },+ };+}++export const NATIVE_TOOLS = [+ {+ def: {+ name: 'pumpfun_token_3d',+ description:+ 'Live 3D snapshot of a pump.fun / Solana token. Composes on-chain token metadata, bonding-curve graduation progress, and top-holder distribution, and returns a shareable three.ws /coin3d viewer deep-link (a spinning coin medallion textured with the token logo, a holder galaxy, and a graduation ring) plus an embeddable iframe and the underlying data. Read-only, free.',+ inputSchema: {+ type: 'object',+ properties: {+ mint: { type: 'string', description: 'SPL / pump.fun token mint address (base58).' },+ network: { type: 'string', enum: ['mainnet', 'devnet'], default: 'mainnet' },+ },+ required: ['mint'],+ },+ },+ handler: token3dHandler,+ },+];++export function buildNativeRegistry(backendUrl, call) {+ const siteBase = siteBaseFrom(backendUrl);+ const defs = NATIVE_TOOLS.map((t) => t.def);+ const handlers = new Map(+ NATIVE_TOOLS.map((t) => [t.def.name, (args) => t.handler(args, { call, siteBase })]),+ );+ return { defs, handlers };+}diff --git a/pages/coin3d.html b/pages/coin3d.htmlnew file mode 100644index 000000000..a86e0c2c0--- /dev/null+++ b/pages/coin3d.html@@ -0,0 +1,139 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />+ <title>Token in 3D · three.ws</title>+ <meta name="description" content="A live 3D snapshot of any pump.fun / Solana token — coin medallion, holder galaxy, and bonding-curve graduation, rendered from real on-chain data." />+ <meta property="og:title" content="Token in 3D · three.ws" />+ <meta property="og:description" content="See any pump.fun token as a live 3D scene — coin, holders, and graduation progress." />+ <meta property="og:type" content="website" />+ <style>+ :root {+ --bg-0: #06060c;+ --bg-1: #0e1022;+ --fg: #eef1ff;+ --muted: #97a0c4;+ --accent: #6ea8ff;+ --card: rgba(16, 18, 36, 0.72);+ --border: rgba(120, 140, 220, 0.18);+ }+ * { box-sizing: border-box; }+ html, body { margin: 0; height: 100%; }+ body {+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Inter, system-ui, sans-serif;+ color: var(--fg);+ background: radial-gradient(120% 120% at 50% 0%, var(--bg-1) 0%, var(--bg-0) 60%);+ overflow: hidden;+ }+ #scene {+ position: fixed;+ inset: 0;+ width: 100vw;+ height: 100vh;+ display: block;+ touch-action: none;+ }++ /* HUD */+ #hud {+ position: fixed;+ left: max(20px, env(safe-area-inset-left));+ bottom: max(20px, env(safe-area-inset-bottom));+ width: min(360px, calc(100vw - 40px));+ padding: 18px 20px;+ background: var(--card);+ border: 1px solid var(--border);+ border-radius: 16px;+ backdrop-filter: blur(14px);+ -webkit-backdrop-filter: blur(14px);+ box-shadow: 0 12px 40px rgba(0, 0, 0, 0.45);+ animation: rise 0.5s cubic-bezier(0.2, 0.8, 0.2, 1) both;+ }+ @keyframes rise { from { opacity: 0; transform: translateY(16px); } to { opacity: 1; transform: none; } }+ .hud-head { display: flex; align-items: baseline; gap: 10px; flex-wrap: wrap; }+ .hud-head h1 { font-size: 20px; margin: 0; line-height: 1.2; }+ .ticker { color: var(--accent); font-weight: 700; font-size: 14px; letter-spacing: 0.02em; }+ .hud-stats { display: grid; grid-template-columns: 1fr 1fr; gap: 10px 18px; margin: 16px 0 14px; }+ .hud-stats div { min-width: 0; }+ .hud-stats dt { color: var(--muted); font-size: 11px; text-transform: uppercase; letter-spacing: 0.06em; margin: 0 0 2px; }+ .hud-stats dd { margin: 0; font-size: 15px; font-weight: 600; font-variant-numeric: tabular-nums; }+ .hud-link {+ display: inline-block;+ color: var(--accent);+ text-decoration: none;+ font-size: 13px;+ font-weight: 600;+ transition: opacity 0.15s ease;+ }+ .hud-link:hover { opacity: 0.78; }+ .hud-link:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; border-radius: 4px; }++ /* Hint */+ .hint {+ position: fixed;+ top: max(16px, env(safe-area-inset-top));+ right: max(16px, env(safe-area-inset-right));+ color: var(--muted);+ font-size: 12px;+ letter-spacing: 0.03em;+ pointer-events: none;+ opacity: 0.7;+ }++ /* Status overlay (loading / error / empty) */+ #status {+ position: fixed;+ inset: 0;+ display: grid;+ place-items: center;+ padding: 24px;+ background: radial-gradient(120% 120% at 50% 0%, var(--bg-1) 0%, var(--bg-0) 70%);+ z-index: 5;+ }+ .status-card {+ text-align: center;+ max-width: 380px;+ animation: rise 0.4s ease both;+ }+ .status-card h2 { margin: 14px 0 8px; font-size: 19px; }+ .status-card p { color: var(--muted); font-size: 14px; line-height: 1.5; margin: 0 0 18px; word-break: break-word; }+ .status-action {+ display: inline-block;+ padding: 9px 18px;+ background: var(--accent);+ color: #04060f;+ font-weight: 700;+ font-size: 14px;+ border-radius: 10px;+ text-decoration: none;+ transition: transform 0.12s ease, box-shadow 0.12s ease;+ }+ .status-action:hover { transform: translateY(-1px); box-shadow: 0 8px 24px rgba(110, 168, 255, 0.35); }+ .status-action:focus-visible { outline: 2px solid #fff; outline-offset: 3px; }+ #status[data-kind='error'] .status-card h2 { color: #ff8f8f; }+ .spinner {+ width: 38px;+ height: 38px;+ margin: 0 auto;+ border: 3px solid var(--border);+ border-top-color: var(--accent);+ border-radius: 50%;+ animation: spin 0.9s linear infinite;+ }+ @keyframes spin { to { transform: rotate(360deg); } }++ @media (max-width: 520px) {+ #hud { width: calc(100vw - 32px); left: 16px; bottom: 16px; }+ .hint { display: none; }+ }+ </style>+ </head>+ <body>+ <canvas id="scene"></canvas>+ <div class="hint">drag to orbit · scroll to zoom</div>+ <div id="hud" hidden></div>+ <div id="status"></div>+ <script type="module" src="/src/coin3d/main.js"></script>+ </body>+</html>diff --git a/scripts/_coin3d-diag.mjs b/scripts/_coin3d-diag.mjsnew file mode 100644index 000000000..25eb9fa07--- /dev/null+++ b/scripts/_coin3d-diag.mjs@@ -0,0 +1,27 @@+import puppeteer from 'puppeteer';+const url = 'http://localhost:3000/coin3d?mint=DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263';+const browser = await puppeteer.launch({ headless: 'new',+ args: ['--no-sandbox','--use-gl=angle','--use-angle=swiftshader','--enable-unsafe-swiftshader','--ignore-gpu-blocklist'] });+const page = await browser.newPage();+await page.setViewport({ width: 1200, height: 800 });+await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30000 });+await page.waitForFunction(() => !!window.__coin3d, { timeout: 25000 });+const px = await page.evaluate(() => {+ const { renderer, scene, camera } = window.__coin3d;+ renderer.render(scene, camera); // force a fresh draw this tick+ const gl = renderer.getContext();+ const w = gl.drawingBufferWidth, h = gl.drawingBufferHeight;+ const cx = Math.floor(w/2)-50, cy = Math.floor(h/2)-50;+ const buf = new Uint8Array(100*100*4);+ gl.readPixels(cx, cy, 100, 100, gl.RGBA, gl.UNSIGNED_BYTE, buf);+ let lit=0, maxc=0;+ for (let i=0;i<buf.length;i+=4){ const m=Math.max(buf[i],buf[i+1],buf[i+2]); if(m>20) lit++; if(m>maxc) maxc=m; }+ return { drawBuffer:[w,h], litPixelsCenter: lit, maxChannel: maxc };+});+console.log('GL_PIXELS', JSON.stringify(px));+// element-level screenshot of the HUD card (reliable, avoids full-page compositing)+const hud = await page.$('#hud');+await page.addStyleTag({ content: '#hud{backdrop-filter:none!important;-webkit-backdrop-filter:none!important;background:#11142e!important}' });+await new Promise(r=>setTimeout(r,300));+await hud.screenshot({ path: 'scripts/_hud.png' });+await browser.close();diff --git a/scripts/_coin3d-shot.mjs b/scripts/_coin3d-shot.mjsnew file mode 100644index 000000000..38f0ab04e--- /dev/null+++ b/scripts/_coin3d-shot.mjs@@ -0,0 +1,29 @@+import puppeteer from 'puppeteer';+const url = 'http://localhost:3000/coin3d?mint=DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263';+const browser = await puppeteer.launch({+ headless: 'new',+ args: ['--no-sandbox','--use-gl=angle','--use-angle=swiftshader','--enable-unsafe-swiftshader','--ignore-gpu-blocklist'],+});+const page = await browser.newPage();+await page.setViewport({ width: 1200, height: 800 });+const errors = [], warns = [];+page.on('console', m => { if (m.type()==='error') errors.push(m.text()); if (m.type()==='warning') warns.push(m.text()); });+page.on('pageerror', e => errors.push('PAGEERROR: '+e.message));+await page.goto(url, { waitUntil: 'networkidle2', timeout: 30000 });+await page.waitForFunction(() => {+ const hud = document.getElementById('hud'); const st = document.getElementById('status');+ return (hud && !hud.hidden) || (st && st.dataset.kind === 'error');+}, { timeout: 20000 }).catch(()=>{});+await new Promise(r => setTimeout(r, 2500));+const state = await page.evaluate(() => ({+ hudVisible: !document.getElementById('hud').hidden,+ statusKind: document.getElementById('status')?.dataset.kind || null,+ statusHidden: document.getElementById('status')?.hidden,+ title: document.title,+ hudText: document.getElementById('hud')?.innerText?.replace(/\s+/g,' ').slice(0,220),+}));+await page.screenshot({ path: 'scripts/_coin3d.png' });+console.log('STATE', JSON.stringify(state));+console.log('ERRORS', errors.length, JSON.stringify(errors.slice(0,8)));+console.log('WARNS', warns.length, JSON.stringify(warns.slice(0,4)));+await browser.close();diff --git a/scripts/_coin3d.png b/scripts/_coin3d.pngnew file mode 100644index 000000000..753189aa8Binary files /dev/null and b/scripts/_coin3d.png differdiff --git a/scripts/_hud.png b/scripts/_hud.pngnew file mode 100644index 000000000..35e8eb9a1Binary files /dev/null and b/scripts/_hud.png differdiff --git a/server-3d.json b/server-3d.jsonindex da7ca8a72..9d3fc0ba4 100644--- a/server-3d.json+++ b/server-3d.json@@ -1,7 +1,7 @@{"$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","name": "io.github.nirholas/three-ws-3d-studio",- "description": "Turn text or an image into an interactive, textured 3D model (GLB). Generate, preview as a live <model-viewer> artifact, inspect, and optimize — powered by three.ws.",+ "description": "Turn text or an image into an interactive, textured 3D model (GLB). By three.ws.","repository": {"url": "https://github.com/nirholas/three.ws","source": "github"diff --git a/server-bazaar.json b/server-bazaar.jsonindex 10d2326d7..e0ae7248d 100644--- a/server-bazaar.json+++ b/server-bazaar.json@@ -1,7 +1,7 @@{"$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json","name": "io.github.nirholas/three-ws-x402-bazaar",- "description": "Discover paid agent services across the live x402 facilitator network: search and browse the bazaar, then get exact prices, payment networks, input schemas, and a ready pay link.",+ "description": "Discover, search, and price paid agent services across the live x402 facilitator network.","repository": {"url": "https://github.com/nirholas/three.ws","source": "github"diff --git a/src/coin3d/main.js b/src/coin3d/main.jsnew file mode 100644index 000000000..63ad1251d--- /dev/null+++ b/src/coin3d/main.js@@ -0,0 +1,376 @@+// /coin3d — a live 3D snapshot of any pump.fun / Solana token.+//+// Reads ?mint=<base58> (and optional &network=mainnet|devnet), pulls real+// data from the public pump.fun MCP endpoint (/api/pump-fun-mcp), and renders+// an interactive Three.js scene:+//+// • a spinning coin medallion textured with the token's logo,+// • a galaxy of the top holders as spheres sized by balance and tinted by+// concentration (the rug-risk picture, spatially),+// • a graduation ring that fills with the token's bonding-curve progress.+//+// All data is live and on-chain (no mocks). Every state — loading, error,+// empty, populated — is designed. This is the page that the MCP tool+// `pumpfun_token_3d` deep-links to.++import {+ Scene, PerspectiveCamera, WebGLRenderer, Group, Color,+ CylinderGeometry, SphereGeometry, TorusGeometry, RingGeometry,+ MeshStandardMaterial, MeshBasicMaterial, Mesh,+ HemisphereLight, DirectionalLight, AmbientLight,+ TextureLoader, SRGBColorSpace, DoubleSide, AdditiveBlending,+ Vector3, MathUtils, PointLight,+} from 'three';+import { OrbitControls } from 'three/addons/controls/OrbitControls.js';++const MCP_ENDPOINT = '/api/pump-fun-mcp';+const WSOL = 'So11111111111111111111111111111111111111112';++// ── DOM handles ─────────────────────────────────────────────────────────────+const canvas = document.getElementById('scene');+const hud = document.getElementById('hud');+const statusEl = document.getElementById('status');++// ── URL params ──────────────────────────────────────────────────────────────+const params = new URLSearchParams(location.search);+const mint = (params.get('mint') || '').trim();+const network = params.get('network') === 'devnet' ? 'devnet' : 'mainnet';++// ── MCP client (JSON-RPC over the public read-only endpoint) ─────────────────+let rpcId = 0;+async function mcpCall(name, args = {}) {+ const res = await fetch(MCP_ENDPOINT, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: ++rpcId,+ method: 'tools/call',+ params: { name, arguments: args },+ }),+ });+ if (!res.ok) throw new Error(`${name} → HTTP ${res.status}`);+ const env = await res.json();+ if (env.error) throw new Error(env.error.message || `${name} failed`);+ return env.result?.structuredContent ?? null;+}++// Pull the three data sources in parallel. Holder + curve data are+// best-effort: if a source is unavailable we keep the snapshot but degrade the+// matching visual, rather than failing the whole scene.+async function loadSnapshot() {+ const [details, curve, holders] = await Promise.allSettled([+ mcpCall('getTokenDetails', { mint }),+ mcpCall('getBondingCurve', { mint, network }),+ mcpCall('getTokenHolders', { mint, limit: 12, network }),+ ]);+ const d = details.status === 'fulfilled' ? details.value || {} : {};+ const c = curve.status === 'fulfilled' ? curve.value || null : null;+ const h = holders.status === 'fulfilled' ? holders.value || null : null;++ const name = d.name || d.metadata?.name || 'Unknown token';+ const symbol = (d.symbol || d.metadata?.symbol || '').toUpperCase();+ const image = await resolveImage(d);++ return {+ mint,+ name,+ symbol,+ image,+ marketCapUsd: numOrNull(d.marketCapUsd ?? d.usdMarketCap ?? d.market_cap),+ graduationProgress: clamp01(numOrNull(c?.graduationProgress ?? c?.progress)),+ graduated: Boolean(c?.graduated || c?.complete),+ topHolderPercent: numOrNull(h?.topHolderPercent),+ holders: Array.isArray(h?.holders) ? h.holders : [],+ };+}++// The token logo lives in the off-chain metadata JSON pointed to by the+// on-chain `uri`, not in getTokenDetails directly. Resolve it (best-effort):+// a direct image field wins; otherwise fetch the uri JSON and read .image.+async function resolveImage(d) {+ const direct = d.image || d.imageUrl || d.metadata?.image;+ if (direct) return ipfsToHttp(direct);+ const uri = d.uri || d.metadata?.uri;+ if (!uri) return null;+ try {+ const res = await fetch(ipfsToHttp(uri), { signal: AbortSignal.timeout(6000) });+ if (!res.ok) return null;+ const meta = await res.json();+ return meta?.image ? ipfsToHttp(meta.image) : null;+ } catch {+ return null;+ }+}++function ipfsToHttp(url) {+ if (typeof url !== 'string') return null;+ if (url.startsWith('ipfs://')) return `https://ipfs.io/ipfs/${url.slice(7)}`;+ return url;+}++function numOrNull(v) {+ const n = Number(v);+ return Number.isFinite(n) ? n : null;+}+function clamp01(v) {+ if (v === null) return null;+ return Math.max(0, Math.min(1, v > 1 ? v / 100 : v));+}++// ── Status overlay (loading / error / empty) ─────────────────────────────────+function setStatus(kind, title, detail, action) {+ if (kind === null) {+ statusEl.hidden = true;+ statusEl.innerHTML = '';+ return;+ }+ statusEl.hidden = false;+ statusEl.dataset.kind = kind;+ statusEl.innerHTML = `+ <div class="status-card">+ ${kind === 'loading' ? '<div class="spinner" aria-hidden="true"></div>' : ''}+ <h2>${escapeHtml(title)}</h2>+ ${detail ? `<p>${escapeHtml(detail)}</p>` : ''}+ ${action ? `<a class="status-action" href="${action.href}">${escapeHtml(action.label)}</a>` : ''}+ </div>`;+}++function escapeHtml(s) {+ return String(s).replace(/[&<>"']/g, (c) => (+ { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]+ ));+}++// ── Three.js scene ────────────────────────────────────────────────────────────+let renderer, scene, camera, controls, rafId;+const spin = new Group();+let holderGalaxy = null;+const holderOrbits = [];++function initScene() {+ renderer = new WebGLRenderer({ canvas, antialias: true, alpha: true });+ renderer.setPixelRatio(Math.min(devicePixelRatio, 2));+ renderer.outputColorSpace = SRGBColorSpace;++ scene = new Scene();++ camera = new PerspectiveCamera(45, 1, 0.1, 100);+ camera.position.set(0, 1.6, 6.2);++ controls = new OrbitControls(camera, renderer.domElement);+ controls.enableDamping = true;+ controls.dampingFactor = 0.08;+ controls.minDistance = 3.5;+ controls.maxDistance = 12;+ controls.autoRotate = true;+ controls.autoRotateSpeed = 0.6;++ scene.add(new HemisphereLight(0xbfd4ff, 0x0a0a16, 0.9));+ scene.add(new AmbientLight(0xffffff, 0.25));+ const key = new DirectionalLight(0xffffff, 1.6);+ key.position.set(4, 6, 5);+ scene.add(key);+ const rim = new PointLight(0x6ea8ff, 0.8, 30);+ rim.position.set(-5, 2, -4);+ scene.add(rim);++ scene.add(spin);+ resize();+ addEventListener('resize', resize);+ animate();+}++function resize() {+ const w = canvas.clientWidth || innerWidth;+ const h = canvas.clientHeight || innerHeight;+ renderer.setSize(w, h, false);+ camera.aspect = w / h;+ camera.updateProjectionMatrix();+}++function animate() {+ rafId = requestAnimationFrame(animate);+ const t = performance.now() / 1000;+ spin.rotation.y += 0.004;+ for (const o of holderOrbits) {+ o.angle += o.speed;+ o.mesh.position.x = Math.cos(o.angle) * o.radius;+ o.mesh.position.z = Math.sin(o.angle) * o.radius;+ o.mesh.position.y = o.y + Math.sin(t * o.bob + o.phase) * 0.08;+ }+ controls.update();+ renderer.render(scene, camera);+}++// The coin medallion: a thin cylinder with the logo on both faces and a+// metallic rim. Falls back to a brand-tinted disc if the logo can't be loaded.+function buildCoin(snapshot) {+ const rim = new MeshStandardMaterial({ color: 0x2b2f44, metalness: 0.9, roughness: 0.35 });+ const faceMat = new MeshStandardMaterial({ color: 0x1a1d2e, metalness: 0.5, roughness: 0.6 });+ const geo = new CylinderGeometry(1.6, 1.6, 0.28, 64);+ // [side, top, bottom] material groups for a CylinderGeometry.+ const coin = new Mesh(geo, [rim, faceMat, faceMat]);+ coin.rotation.x = Math.PI / 2; // face the camera+ spin.add(coin);++ if (snapshot.image) {+ const loader = new TextureLoader();+ loader.setCrossOrigin('anonymous');+ loader.load(+ snapshot.image,+ (tex) => {+ tex.colorSpace = SRGBColorSpace;+ const lit = new MeshStandardMaterial({ map: tex, metalness: 0.3, roughness: 0.55 });+ coin.material = [rim, lit, lit];+ },+ undefined,+ () => {+ // Texture failed — keep the tinted disc; not an error worth blocking on.+ },+ );+ }+}++// Holder galaxy: each top holder is a sphere orbiting the coin. Size scales+// with balance share; color runs cool→hot as concentration rises.+function buildHolderGalaxy(snapshot) {+ holderGalaxy = new Group();+ spin.add(holderGalaxy);++ const holders = snapshot.holders.slice(0, 12);+ if (!holders.length) return;++ const amounts = holders.map((h) => Number(h.uiAmount ?? h.amount ?? h.percent ?? 0)).filter((n) => n > 0);+ const max = amounts.length ? Math.max(...amounts) : 1;++ holders.forEach((h, i) => {+ const amt = Number(h.uiAmount ?? h.amount ?? h.percent ?? 0);+ const share = max > 0 ? amt / max : 0;+ const radius = 2.6 + (i % 3) * 0.55;+ const size = MathUtils.lerp(0.12, 0.42, share);+ const color = new Color().setHSL(MathUtils.lerp(0.58, 0.0, share), 0.75, 0.55);+ const mesh = new Mesh(+ new SphereGeometry(size, 24, 24),+ new MeshStandardMaterial({ color, emissive: color, emissiveIntensity: 0.35, roughness: 0.4 }),+ );+ const angle = (i / holders.length) * Math.PI * 2;+ const y = MathUtils.lerp(-0.6, 0.6, (i % 4) / 3);+ mesh.position.set(Math.cos(angle) * radius, y, Math.sin(angle) * radius);+ holderGalaxy.add(mesh);+ holderOrbits.push({+ mesh, radius, y, angle,+ speed: 0.0008 + (i % 3) * 0.0004,+ bob: 0.6 + (i % 5) * 0.15,+ phase: i,+ });+ });+}++// Graduation ring: a faint full torus with a bright arc filled to progress.+function buildGraduationRing(snapshot) {+ const base = new Mesh(+ new TorusGeometry(2.05, 0.03, 12, 96),+ new MeshBasicMaterial({ color: 0x2a2f4a }),+ );+ base.rotation.x = Math.PI / 2;+ spin.add(base);++ const p = snapshot.graduated ? 1 : snapshot.graduationProgress;+ if (p === null) return;+ const sweep = Math.max(0.02, p) * Math.PI * 2;+ const arc = new Mesh(+ new RingGeometry(2.0, 2.12, 96, 1, 0, sweep),+ new MeshBasicMaterial({+ color: snapshot.graduated ? 0x44e08a : 0x6ea8ff,+ side: DoubleSide,+ transparent: true,+ opacity: 0.95,+ blending: AdditiveBlending,+ }),+ );+ arc.rotation.x = Math.PI / 2;+ spin.add(arc);+}++// ── HUD ───────────────────────────────────────────────────────────────────────+function renderHud(s) {+ const cap = s.marketCapUsd !== null ? `$${compact(s.marketCapUsd)}` : '—';+ const grad = s.graduated+ ? 'Graduated → Raydium'+ : s.graduationProgress !== null+ ? `${Math.round(s.graduationProgress * 100)}% to graduation`+ : 'Bonding curve';+ const conc = s.topHolderPercent !== null ? `${s.topHolderPercent.toFixed(1)}%` : '—';+ hud.hidden = false;+ hud.innerHTML = `+ <div class="hud-head">+ <h1>${escapeHtml(s.name)}</h1>+ ${s.symbol ? `<span class="ticker">$${escapeHtml(s.symbol)}</span>` : ''}+ </div>+ <dl class="hud-stats">+ <div><dt>Market cap</dt><dd>${cap}</dd></div>+ <div><dt>Top-holder share</dt><dd>${conc}</dd></div>+ <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>`;+}++function compact(n) {+ 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);+}++// ── Boot ────────────────────────────────────────────────────────────────────+async function main() {+ if (!mint) {+ setStatus('empty', 'No token specified', 'Add ?mint=<address> to view a token in 3D.', {+ href: '/demo/coin',+ label: 'Browse coins',+ });+ return;+ }++ setStatus('loading', 'Loading token…', 'Fetching live on-chain data.');+ let snapshot;+ try {+ snapshot = await loadSnapshot();+ } catch (err) {+ setStatus('error', "Couldn't load this token", err.message, {+ href: '/demo/coin',+ label: 'Browse coins',+ });+ return;+ }++ if (snapshot.name === 'Unknown token' && !snapshot.image && !snapshot.holders.length) {+ setStatus('error', 'Token not found', `No on-chain data for ${mint}.`, {+ href: '/demo/coin',+ label: 'Browse coins',+ });+ return;+ }++ initScene();+ buildCoin(snapshot);+ buildGraduationRing(snapshot);+ buildHolderGalaxy(snapshot);+ renderHud(snapshot);+ setStatus(null);+ document.title = `${snapshot.name}${snapshot.symbol ? ` ($${snapshot.symbol})` : ''} · 3D — three.ws`;++ // Expose the live scene for embedders and host pages (e.g. to react to the+ // loaded snapshot or drive the camera from the outside).+ window.__coin3d = { renderer, scene, camera, controls, snapshot };+ dispatchEvent(new CustomEvent('coin3d:ready', { detail: { snapshot } }));+}++addEventListener('beforeunload', () => {+ if (rafId) cancelAnimationFrame(rafId);+ renderer?.dispose?.();+});++main();diff --git a/vercel.json b/vercel.jsonindex 33d0758dd..65dc66dc9 100644--- a/vercel.json+++ b/vercel.json@@ -571,6 +571,14 @@"src": "/playground/","dest": "/playground.html"},+ {+ "src": "/coin3d",+ "dest": "/coin3d.html"+ },+ {+ "src": "/coin3d/",+ "dest": "/coin3d.html"+ },{"src": "/p/([a-z0-9-]+)/?","dest": "/p/index.html"diff --git a/vite.config.js b/vite.config.jsindex 434f5448b..05d8686f9 100644--- a/vite.config.js+++ b/vite.config.js@@ -230,6 +230,7 @@ const appConfig = {tutorials: resolve(__dirname, 'pages/tutorials.html'),tutorial: resolve(__dirname, 'pages/tutorial.html'),playground: resolve(__dirname, 'pages/playground.html'),+ coin3d: resolve(__dirname, 'pages/coin3d.html'),embed: resolve(__dirname, 'pages/embed.html'),'embed-demo': resolve(__dirname, 'pages/embed-demo.html'),widget: resolve(__dirname, 'pages/widget.html'),