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
<!DOCTYPE html>
<html lang="en">
<head>
<script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
<meta charset="UTF-8" />
<link rel="icon" href="/favicon.ico" sizes="any" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<link rel="manifest" href="/manifest.webmanifest" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title data-i18n="three_live.meta_title">$THREE Live · Protocol Pulse — three.ws</title>
<meta name="description" content="The $THREE protocol as a living 3D organism. Watch real on-chain trades pulse through it in real time — every transaction emits a burst, whales send shockwaves, with a live trade feed and protocol stats." data-i18n-attr="content:three_live.meta_description"/>
<link rel="canonical" href="https://three.ws/three-live" />
<link rel="stylesheet" href="/style.css" />
<link rel="stylesheet" href="/nav.css" />
<link rel="stylesheet" href="/mobile.css" />
<style>
:root {
--pl-bg: #050505;
--pl-panel: rgba(9, 11, 18, 0.82);
--pl-border: rgba(255, 255, 255, 0.10);
--pl-text: #eaecf5;
--pl-muted: #8b92ad;
--pl-faint: #5a6178;
--pl-green: #34e0a8;
--pl-red: #ff5d73;
--pl-accent: #8b7bff;
--pl-mono: var(--font-mono, 'JetBrains Mono', ui-monospace, monospace);
--pl-disp: var(--font-display, 'Space Grotesk', system-ui, sans-serif);
}
html, body { background: var(--pl-bg); color: var(--pl-text); overflow: hidden; height: 100%; }
body { margin: 0; }
.site-header { position: relative; z-index: 20; background: rgba(0,0,0,0.85); backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px); }
#pl-stage { position: fixed; inset: 0; z-index: 0; }
#pl-canvas-host { position: absolute; inset: 0; }
#pl-canvas-host canvas { display: block; width: 100% !important; height: 100% !important; cursor: grab; }
#pl-canvas-host canvas:active { cursor: grabbing; }
.pl-overlay { position: absolute; pointer-events: none; z-index: 10; }
.pl-overlay > * { pointer-events: auto; }
/* Wide layout keeps the hero and the trade feed in opposite corners, so the
wrapper contributes no box at all and each child anchors to #pl-stage
exactly as it did before. The narrow rules below turn it into the single
stacked column that lets the feed survive on a phone. */
#pl-hud-top { display: contents; }
.pl-sr {
position: absolute; width: 1px; height: 1px; margin: -1px;
padding: 0; border: 0; overflow: hidden; white-space: nowrap;
clip: rect(0 0 0 0); clip-path: inset(50%);
}
/* ── Hero readout (top-left): price + sentiment ── */
.pl-hero {
top: calc(var(--header-h, 3.5rem) + 16px);
left: 18px;
background: var(--pl-panel);
border: 1px solid var(--pl-border);
border-radius: 14px;
padding: 16px 18px;
backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px);
min-width: 232px;
}
.pl-hero .sym { font-family: var(--pl-mono); font-size: 11px; font-weight: 400; line-height: 1.4; margin: 0; letter-spacing: 0.16em; color: var(--pl-muted); text-transform: uppercase; display: flex; align-items: center; gap: 8px; }
.pl-hero .sym .dot { width: 8px; height: 8px; border-radius: 50%; background: #555; }
.pl-hero[data-state="connecting"] .dot { background: #f5a623; animation: plPulse 1.2s ease-in-out infinite; }
.pl-hero[data-state="live"] .dot { background: var(--pl-green); box-shadow: 0 0 10px rgba(52,224,168,0.8); animation: plPulse 1.6s ease-in-out infinite; }
.pl-hero[data-state="quiet"] .dot { background: var(--pl-accent); box-shadow: 0 0 8px rgba(139,123,255,0.6); }
.pl-hero[data-state="error"] .dot { background: var(--pl-red); }
.pl-hero .price { font-family: var(--pl-disp); font-size: 34px; font-weight: 600; line-height: 1.1; margin: 8px 0 2px; font-variant-numeric: tabular-nums; }
.pl-hero .chg { font-family: var(--pl-mono); font-size: 14px; font-weight: 600; }
.pl-hero .chg.up { color: var(--pl-green); }
.pl-hero .chg.down { color: var(--pl-red); }
.pl-hero .chg.flat { color: var(--pl-muted); }
.pl-activity {
margin-top: 12px; display: flex; align-items: center; gap: 10px;
font-family: var(--pl-mono); font-size: 11px; letter-spacing: 0.04em; color: var(--pl-muted);
}
.pl-activity .bar { flex: 1; height: 6px; border-radius: 3px; background: rgba(255,255,255,0.08); overflow: hidden; position: relative; }
.pl-activity .bar .fill { position: absolute; top: 0; bottom: 0; left: 0; width: 0; background: linear-gradient(90deg, var(--pl-accent), var(--pl-green)); transition: width var(--duration-slow) var(--ease-standard); border-radius: 3px; }
.pl-activity .reading { font-weight: 600; color: var(--pl-text); min-width: 64px; text-align: right; }
/* Failure notice: stays up for as long as the feed is actually down. */
.pl-fault {
display: flex; align-items: center; gap: 10px; flex-wrap: wrap;
margin: 12px 0 0; padding: 9px 11px;
background: rgba(255, 93, 115, 0.09);
border: 1px solid rgba(255, 93, 115, 0.32); border-radius: 10px;
font-family: var(--pl-mono); font-size: 11.5px; line-height: 1.5; color: #ffb8c2;
}
.pl-fault[hidden] { display: none; }
.pl-retry {
flex: none; margin-left: auto; cursor: pointer;
font-family: var(--pl-mono); font-size: 11px; letter-spacing: 0.05em;
color: var(--pl-text); background: rgba(255, 255, 255, 0.07);
border: 1px solid var(--pl-border); border-radius: 7px; padding: 5px 10px;
transition: background var(--duration-fast) var(--ease-standard), border-color var(--duration-fast) var(--ease-standard), transform var(--duration-fast) var(--ease-standard);
}
.pl-retry:hover { background: rgba(255, 255, 255, 0.14); border-color: rgba(255, 255, 255, 0.28); }
.pl-retry:active { transform: translateY(1px); }
.pl-retry:focus-visible { outline: 2px solid var(--pl-accent); outline-offset: 2px; }
.pl-retry[disabled] { opacity: 0.55; cursor: progress; }
/* ── Stat grid (bottom-left) ── */
.pl-stats {
bottom: 18px; left: 18px;
display: grid; grid-template-columns: repeat(2, minmax(108px, 1fr)); gap: 1px;
background: var(--pl-border);
border: 1px solid var(--pl-border); border-radius: 12px; overflow: hidden;
backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px);
max-width: 340px;
}
.pl-stats .cell { background: var(--pl-panel); padding: 11px 14px; }
.pl-stats .label { font-family: var(--pl-mono); font-size: 9.5px; letter-spacing: 0.1em; text-transform: uppercase; color: var(--pl-faint); }
.pl-stats .value { font-family: var(--pl-mono); font-size: 15px; color: var(--pl-text); margin-top: 3px; font-variant-numeric: tabular-nums; }
.pl-stats .value.g { color: var(--pl-green); }
.pl-stats .value.r { color: var(--pl-red); }
/* ── Live trade ticker (right) ── */
.pl-ticker {
top: calc(var(--header-h, 3.5rem) + 16px);
right: 18px;
width: 264px;
background: var(--pl-panel);
border: 1px solid var(--pl-border);
border-radius: 14px;
backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px);
overflow: hidden;
}
.pl-ticker .head {
display: flex; align-items: center; gap: 8px;
padding: 11px 14px; border-bottom: 1px solid var(--pl-border);
font-family: var(--pl-mono); font-size: 10px; letter-spacing: 0.12em; text-transform: uppercase; color: var(--pl-muted);
}
.pl-ticker .head .live { display: inline-flex; align-items: center; gap: 5px; margin-left: auto; color: var(--pl-green); }
.pl-ticker .head .live::before { content: ''; width: 6px; height: 6px; border-radius: 50%; background: var(--pl-green); animation: plPulse 1.4s ease-in-out infinite; }
.pl-ticker ol { list-style: none; margin: 0; padding: 6px; max-height: 280px; overflow: hidden; }
.pl-ticker li {
display: flex; align-items: center; gap: 8px; padding: 6px 8px; border-radius: 8px;
font-family: var(--pl-mono); font-size: 12px; animation: plRise 0.35s ease both;
}
.pl-ticker li .side { font-weight: 700; width: 34px; font-size: 10px; letter-spacing: 0.05em; }
.pl-ticker li.buy .side { color: var(--pl-green); }
.pl-ticker li.sell .side { color: var(--pl-red); }
.pl-ticker li .amt { color: var(--pl-text); font-variant-numeric: tabular-nums; }
.pl-ticker li.buy { background: linear-gradient(90deg, rgba(52,224,168,0.10), transparent); }
.pl-ticker li.sell { background: linear-gradient(90deg, rgba(255,93,115,0.10), transparent); }
.pl-ticker li .who { color: var(--pl-faint); margin-left: auto; }
.pl-ticker .empty { padding: 22px 14px; text-align: center; color: var(--pl-faint); font-family: var(--pl-mono); font-size: 11.5px; line-height: 1.6; }
@keyframes plRise { from { opacity: 0; transform: translateY(-6px); } to { opacity: 1; transform: none; } }
@keyframes plPulse { 0%,100% { opacity: 0.4; } 50% { opacity: 1; } }
/* ── Flow counters (bottom-center) ── */
.pl-flow {
bottom: 18px; left: 50%; transform: translateX(-50%);
display: flex; gap: 1px; background: var(--pl-border);
border: 1px solid var(--pl-border); border-radius: 12px; overflow: hidden;
backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px);
font-family: var(--pl-mono);
}
.pl-flow .seg { background: var(--pl-panel); padding: 9px 18px; text-align: center; }
.pl-flow .label { font-size: 9px; letter-spacing: 0.1em; text-transform: uppercase; color: var(--pl-faint); }
.pl-flow .num { font-size: 17px; margin-top: 2px; font-variant-numeric: tabular-nums; }
.pl-flow .seg.buys .num { color: var(--pl-green); }
.pl-flow .seg.sells .num { color: var(--pl-red); }
.pl-flow .seg.win .label { font-size: 9px; }
/* ── Hint + intro + error ── */
.pl-hint {
bottom: 18px; right: 18px;
font-family: var(--pl-mono); font-size: 10.5px; color: var(--pl-faint);
background: var(--pl-panel); border: 1px solid var(--pl-border); border-radius: 10px;
padding: 7px 11px; line-height: 1.6;
}
.pl-hint b { color: var(--pl-muted); }
.pl-intro {
position: absolute; inset: 0; z-index: 12; display: flex; flex-direction: column;
align-items: center; justify-content: center; pointer-events: none;
background: radial-gradient(ellipse at center, rgba(139,123,255,0.10) 0%, var(--pl-bg) 72%);
opacity: 1; transition: opacity var(--duration-slow) var(--ease-standard) var(--duration-fast);
}
.pl-intro.is-hidden { opacity: 0; }
.pl-intro .ring { width: 54px; height: 54px; border-radius: 50%; border: 2px solid rgba(255,255,255,0.15); border-top-color: var(--pl-accent); animation: plSpin 1s linear infinite; }
.pl-intro .label { margin-top: 18px; font-family: var(--pl-mono); font-size: 12px; letter-spacing: 0.2em; color: var(--pl-muted); text-transform: uppercase; }
@keyframes plSpin { to { transform: rotate(360deg); } }
.pl-toast {
position: absolute; top: calc(var(--header-h, 3.5rem) + 16px); left: 50%; transform: translateX(-50%) translateY(-8px);
background: rgba(40, 12, 18, 0.92); border: 1px solid rgba(255,93,115,0.4); color: #ffb8c2;
border-radius: 10px; padding: 8px 14px; font-family: var(--pl-mono); font-size: 12px;
opacity: 0; transition: opacity var(--duration-base), transform var(--duration-base); pointer-events: none;
}
.pl-toast.is-visible { opacity: 1; transform: translateX(-50%) translateY(0); }
@media (max-width: 820px) {
.pl-hint { display: none; }
/* One column from the header down to the bottom HUD band. --pl-dock-h is
measured from the live band height, so the feed grows into whatever
room is left instead of being deleted from the small screen. */
#pl-hud-top {
display: flex; flex-direction: column; gap: 10px;
position: absolute; z-index: 10; pointer-events: none;
top: calc(var(--header-h, 3.5rem) + 16px);
left: 12px; right: 12px;
bottom: calc(var(--pl-dock-h, 210px) + 10px);
}
#pl-hud-top > * { position: static; pointer-events: none; }
.pl-hero { min-width: 0; padding: 12px 14px; flex: 0 0 auto; }
.pl-hero .price { font-size: 28px; }
.pl-ticker { display: flex; flex-direction: column; width: auto; flex: 1 1 auto; min-height: 0; }
.pl-ticker ol { max-height: none; flex: 1 1 auto; overflow-y: auto; }
/* Under roughly two rows of trades the feed reads as a scrap of a panel
rather than a feed, so the short-viewport case drops it and leaves the
hero and the bottom band whole. */
#pl-hud-top.is-cramped .pl-ticker { display: none; }
/* --pl-band-base clears the flow row AND the shared corner stack, which
spans the full width down here and would otherwise sit on the grid. */
.pl-stats {
left: 12px; right: 12px; bottom: calc(var(--pl-band-base, 80px) + 10px);
grid-template-columns: repeat(2, 1fr); max-width: none;
}
.pl-flow { bottom: 12px; left: 12px; right: 12px; transform: none; }
.pl-flow .seg { flex: 1; padding: 8px 10px; }
.pl-flow .label { font-size: 8.5px; white-space: nowrap; }
.pl-flow .num { font-size: 16px; }
}
</style>
<meta property="og:type" content="website">
<meta property="og:site_name" content="three.ws">
<meta property="og:title" content="$THREE Live · Protocol Pulse · three.ws" data-i18n-attr="content:three_live.meta_og_title">
<meta property="og:description" content="The $THREE protocol as a living 3D organism. Real on-chain trades pulse through it in real time — each transaction emits a particle burst, whales send shockwaves, with a live trade feed and a HUD of price, market cap, holders, and volume." data-i18n-attr="content:three_live.meta_og_description">
<meta property="og:url" content="https://three.ws/three-live">
<meta property="og:image" content="https://three.ws/api/page-og?s=crypto&t=%24THREE+Live+%C2%B7+Protocol+Pulse&d=The+%24THREE+protocol+as+a+living+3D+organism.+Real+on-chain+trades+pulse+through+it+in+real+time%3A+each+transaction+emits+a+particle+burst%2C+whales+send&p=%2Fthree-live">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="$THREE Live · Protocol Pulse · three.ws" data-i18n-attr="content:three_live.meta_twitter_title">
<meta name="twitter:description" content="The $THREE protocol as a living 3D organism. Real on-chain trades pulse through it in real time — each transaction emits a particle burst, whales send shockwaves, with a live trade feed and a HUD of price, market cap, holders, and volume." data-i18n-attr="content:three_live.meta_twitter_description">
<meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&t=%24THREE+Live+%C2%B7+Protocol+Pulse&d=The+%24THREE+protocol+as+a+living+3D+organism.+Real+on-chain+trades+pulse+through+it+in+real+time%3A+each+transaction+emits+a+particle+burst%2C+whales+send&p=%2Fthree-live">
<script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"$THREE Live · Protocol Pulse","description":"The $THREE protocol as a living 3D organism. Real on-chain trades pulse through it in real time — each transaction emits a particle burst, whales send shockwaves, with a live trade feed and a HUD of price, market cap, holders, and volume.","url":"https://three.ws/three-live","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>
<meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">
<meta property="og:locale" content="en_US">
<meta property="og:image:alt" content="$THREE Live · Protocol Pulse — three.ws">
<meta name="twitter:site" content="@trythreews">
</head>
<body>
<header><div id="nav-container"></div></header>
<script src="/nav.js"></script>
<!-- data-corner-ignore: this page declares its own corner-stack clearance from
measured HUD geometry (syncDock below). Without it the stack's automatic
probe adds a second, overlapping lift on top of that reservation. -->
<div id="pl-stage" data-corner-ignore>
<div id="pl-canvas-host"></div>
<!-- Hero: price + sentiment gauge -->
<div id="pl-hud-top">
<section class="pl-overlay pl-hero" id="pl-hero" data-state="connecting" aria-live="polite">
<h1 class="sym"><span class="dot" aria-hidden="true"></span> <span id="pl-status-text" data-i18n="three_live.three_connecting">$THREE · connecting…</span><span class="pl-sr">: Protocol Pulse, live on-chain $THREE activity rendered in 3D</span></h1>
<div class="price" id="pl-price">$—</div>
<div class="chg flat" id="pl-change">—</div>
<div class="pl-activity" title="On-chain trade throughput in the last 60s. Activity, not a buy/sell signal.">
<span data-i18n="three_live.quiet">QUIET</span>
<span class="bar"><span class="fill" id="pl-activity-fill"></span></span>
<span data-i18n="three_live.busy">BUSY</span>
<span class="reading" id="pl-activity-reading">—</span>
</div>
<div class="pl-links" style="display:flex;gap:14px;margin-top:12px;flex-wrap:wrap;font-family:var(--pl-mono);font-size:11.5px">
<a href="/three-token" style="color:var(--pl-faint);text-decoration:none" data-i18n="three_live.price_trades">▸ Price & trades</a>
<a href="/dashboard/holders" style="color:var(--pl-faint);text-decoration:none" data-i18n="three_live.holder_leaderboard">▸ Holder leaderboard</a>
<a href="https://pump.fun/coin/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump" target="_blank" rel="noopener" style="color:var(--pl-faint);text-decoration:none" data-i18n="three_live.buy_three">▸ Buy $THREE ↗</a>
</div>
<!-- Persistent, actionable failure notice. A toast alone disappears after a
few seconds and leaves a HUD full of dashes with no explanation. -->
<p class="pl-fault" id="pl-fault" role="alert" hidden>
<span id="pl-fault-text"></span>
<button type="button" id="pl-fault-retry" class="pl-retry">Retry now</button>
</p>
</section>
<!-- Live trade ticker -->
<aside class="pl-overlay pl-ticker" id="pl-ticker">
<div class="head">Live trades <span class="live" data-i18n="three_live.live">live</span></div>
<ol id="pl-ticker-list" role="list">
<!-- The script swaps this for the shared state-kit empty state, so it is
marked script-owned: the i18n catalog pass would otherwise reset it
to a bare text node and wipe that markup. -->
<li class="empty" id="pl-ticker-empty" data-i18n-owned="1">Live trades will appear here.</li>
</ol>
</aside>
</div>
<!-- Stat grid -->
<section class="pl-overlay pl-stats" id="pl-stats">
<div class="cell"><div class="label">Market cap</div><div class="value g" id="pl-mcap">—</div></div>
<div class="cell"><div class="label">24h volume</div><div class="value" id="pl-vol">—</div></div>
<div class="cell"><div class="label">Holders</div><div class="value" id="pl-holders">—</div></div>
<div class="cell"><div class="label">Liquidity</div><div class="value" id="pl-liq">—</div></div>
<div class="cell"><div class="label">Agents deployed</div><div class="value" id="pl-agents">—</div></div>
<div class="cell"><div class="label">$THREE bought back</div><div class="value" id="pl-bought">-</div></div>
</section>
<!-- Flow counters -->
<section class="pl-overlay pl-flow" id="pl-flow">
<div class="seg buys"><div class="label">Buys / 60s</div><div class="num" id="pl-buys">0</div></div>
<div class="seg win"><div class="label">Vol / 60s</div><div class="num" id="pl-vol60">$0</div></div>
<div class="seg sells"><div class="label">Sells / 60s</div><div class="num" id="pl-sells">0</div></div>
</section>
<div class="pl-overlay pl-hint"><b data-i18n="three_live.drag">Drag</b> to orbit · <b data-i18n="three_live.scroll">Scroll</b> to zoom · each particle is a real trade</div>
<div class="pl-intro" id="pl-intro"><div class="ring"></div><div class="label">Reading the chain</div></div>
<div class="pl-toast" id="pl-toast"></div>
</div>
<script type="module">
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';
import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';
import { emptyStateHTML } from '/src/shared/state-kit.js';
// ── Config / live data sources ───────────────────────────────────────
const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
const STATS_API = '/api/three-token/stats';
const TRADES_SSE = `/api/agents/pumpfun-feed?kind=trades&mint=${THREE_MINT}`;
const STATS_INTERVAL_MS = 8_000;
let _solUsd = 0; // refreshed from Jupiter on boot
const FLOW_WINDOW_MS = 60_000;
const WHALE_USD = 2_000; // a trade this big sends a shockwave
const PARTICLE_POOL = 1400; // hard cap on live particles
const TICKER_MAX = 14;
const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
// ── DOM ──────────────────────────────────────────────────────────────
const host = document.getElementById('pl-canvas-host');
const heroEl = document.getElementById('pl-hero');
const statusText = document.getElementById('pl-status-text');
const priceEl = document.getElementById('pl-price');
const changeEl = document.getElementById('pl-change');
const activityFill = document.getElementById('pl-activity-fill');
const activityReading = document.getElementById('pl-activity-reading');
const tickerList = document.getElementById('pl-ticker-list');
const tickerEmpty = document.getElementById('pl-ticker-empty');
// Upgrade the static placeholder to a guided empty state. Plain headline copy
// with the on-chain technical detail tucked behind an info tooltip (C06).
if (tickerEmpty) {
tickerEmpty.style.cssText = 'padding:0;display:block;';
tickerEmpty.innerHTML = emptyStateHTML({
compact: true,
icon: '',
live: true,
title: 'No trades yet',
body: 'Live trades will appear here.',
tip: 'Streaming live from the $THREE bonding curve on-chain. Each trade shows up the moment it settles.',
});
}
const introEl = document.getElementById('pl-intro');
const toastEl = document.getElementById('pl-toast');
const hudTop = document.getElementById('pl-hud-top');
const statsPanel = document.getElementById('pl-stats');
const flowPanel = document.getElementById('pl-flow');
const hintPanel = document.querySelector('.pl-hint');
const faultEl = document.getElementById('pl-fault');
const faultText = document.getElementById('pl-fault-text');
const faultRetry = document.getElementById('pl-fault-retry');
const el = (id) => document.getElementById(id);
// Null-tolerant writers. Privacy/anti-popup browser extensions strip
// fixed-position overlays (our HUD is a set of `.pl-overlay` nodes), which
// would otherwise make a per-frame `el(id).textContent = …` throw on a null
// node and kill the entire render loop — re-firing every animation frame and
// flooding error telemetry. These no-op when the node is gone; the WebGL
// scene keeps rendering regardless of what the page chrome looks like.
const setText = (node, value) => { if (node) node.textContent = value; };
const setTextById = (id, value) => { const n = el(id); if (n) n.textContent = value; };
// ── Scene ──────────────────────────────────────────────────────────────
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x04050a);
scene.fog = new THREE.FogExp2(0x04050a, 0.0125);
const camera = new THREE.PerspectiveCamera(52, 1, 0.1, 600);
camera.position.set(0, 6, 64);
const renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: 'high-performance' });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.1;
host.appendChild(renderer.domElement);
const composer = new EffectComposer(renderer);
composer.addPass(new RenderPass(scene, camera));
const bloom = new UnrealBloomPass(new THREE.Vector2(1, 1), 1.05, 0.6, 0.12);
composer.addPass(bloom);
composer.addPass(new OutputPass());
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.06;
controls.rotateSpeed = 0.55;
controls.zoomSpeed = 0.7;
controls.minDistance = 26;
controls.maxDistance = 140;
controls.enablePan = false;
controls.autoRotate = !reduceMotion;
controls.autoRotateSpeed = 0.5;
scene.add(new THREE.AmbientLight(0xffffff, 0.5));
const keyLight = new THREE.DirectionalLight(0xc9b8ff, 1.0); keyLight.position.set(30, 40, 40); scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x5b8cff, 0.5); rimLight.position.set(-40, -10, -30); scene.add(rimLight);
// ── Starfield ──────────────────────────────────────────────────────────
(function stars() {
const n = 2200;
const pos = new Float32Array(n * 3);
for (let i = 0; i < n; i++) {
const r = 140 + Math.random() * 220;
const t = Math.random() * Math.PI * 2;
const p = Math.acos(2 * Math.random() - 1);
pos[i*3] = r * Math.sin(p) * Math.cos(t);
pos[i*3+1] = r * Math.sin(p) * Math.sin(t);
pos[i*3+2] = r * Math.cos(p);
}
const g = new THREE.BufferGeometry();
g.setAttribute('position', new THREE.BufferAttribute(pos, 3));
scene.add(new THREE.Points(g, new THREE.PointsMaterial({ size: 0.5, color: 0x9fb0ff, transparent: true, opacity: 0.55, sizeAttenuation: true })));
})();
// ── The Core — a living organism whose surface displaces with a heartbeat
// and whose colour reflects live buy/sell sentiment. ───────────────────
const coreUniforms = {
uTime: { value: 0 },
uPulse: { value: 0 }, // momentary kick on each trade (decays)
uHeart: { value: 0 }, // activity level (trade frequency) — NOT directional
uColorCalm: { value: new THREE.Color(0xe8e8e8) }, // neutral white at rest
uColorHot: { value: new THREE.Color(0x46e0d0) }, // teal when busy
};
const coreMat = new THREE.ShaderMaterial({
uniforms: coreUniforms,
vertexShader: `
uniform float uTime; uniform float uPulse; uniform float uHeart;
varying vec3 vNormal; varying float vDisp;
// layered trig displacement — organic, dependency-free, always compiles
float wob(vec3 p, float t) {
return sin(p.x * 2.1 + t) * sin(p.y * 2.4 + t * 1.3) * sin(p.z * 2.0 + t * 0.7)
+ 0.5 * sin(p.x * 4.3 - t * 1.7) * sin(p.z * 3.7 + t);
}
void main() {
vNormal = normalize(normalMatrix * normal);
float heartbeat = (0.06 + uHeart * 0.10) * sin(uTime * 2.4);
float d = wob(position, uTime * 0.6) * (0.16 + uHeart * 0.08) + heartbeat + uPulse * 0.42;
vDisp = d;
vec3 displaced = position + normal * d;
gl_Position = projectionMatrix * modelViewMatrix * vec4(displaced, 1.0);
}
`,
fragmentShader: `
uniform float uHeart; uniform float uPulse;
uniform vec3 uColorCalm; uniform vec3 uColorHot;
varying vec3 vNormal; varying float vDisp;
void main() {
vec3 viewDir = vec3(0.0, 0.0, 1.0);
float fres = pow(1.0 - max(dot(normalize(vNormal), viewDir), 0.0), 2.2);
// Colour reflects ACTIVITY (how busy the curve is), never buy/sell direction.
float activity = clamp(uHeart + uPulse * 0.5, 0.0, 1.0);
vec3 tone = mix(uColorCalm, uColorHot, activity);
vec3 base = tone * (0.35 + vDisp * 1.6 + uPulse * 0.8);
vec3 col = base + fres * tone * 1.4;
gl_FragColor = vec4(col, 1.0);
}
`,
});
const core = new THREE.Mesh(new THREE.IcosahedronGeometry(9, 24), coreMat);
scene.add(core);
// Wireframe shell + soft glow halo around the core
const shell = new THREE.Mesh(
new THREE.IcosahedronGeometry(10.4, 3),
new THREE.MeshBasicMaterial({ color: 0x8b7bff, wireframe: true, transparent: true, opacity: 0.10 })
);
scene.add(shell);
const halo = new THREE.Mesh(
new THREE.SphereGeometry(13.5, 32, 32),
new THREE.MeshBasicMaterial({ color: 0x8b7bff, transparent: true, opacity: 0.05, side: THREE.BackSide })
);
scene.add(halo);
// ── Trade particles — pooled. Each live trade emits a burst that flies
// outward (buys up/green, sells down/red), then fades and recycles. ────
const pPos = new Float32Array(PARTICLE_POOL * 3);
const pCol = new Float32Array(PARTICLE_POOL * 3);
const pVel = new Float32Array(PARTICLE_POOL * 3);
const pLife = new Float32Array(PARTICLE_POOL); // remaining life (s); 0 = free
const pMaxLife = new Float32Array(PARTICLE_POOL);
const pSize = new Float32Array(PARTICLE_POOL);
let pCursor = 0;
for (let i = 0; i < PARTICLE_POOL; i++) { pPos[i*3+1] = 9999; }
const pGeo = new THREE.BufferGeometry();
pGeo.setAttribute('position', new THREE.BufferAttribute(pPos, 3));
pGeo.setAttribute('color', new THREE.BufferAttribute(pCol, 3));
pGeo.setAttribute('psize', new THREE.BufferAttribute(pSize, 1));
const pMat = new THREE.ShaderMaterial({
uniforms: { uScale: { value: renderer.getPixelRatio() * 220 } },
transparent: true, depthWrite: false, blending: THREE.AdditiveBlending,
vertexShader: `
attribute float psize; attribute vec3 color; uniform float uScale;
varying vec3 vColor;
void main() {
vColor = color;
vec4 mv = modelViewMatrix * vec4(position, 1.0);
gl_PointSize = psize * uScale / max(-mv.z, 1.0);
gl_Position = projectionMatrix * mv;
}
`,
fragmentShader: `
varying vec3 vColor;
void main() {
float d = length(gl_PointCoord - vec2(0.5));
if (d > 0.5) discard;
float a = smoothstep(0.5, 0.0, d);
gl_FragColor = vec4(vColor, a);
}
`,
});
const particles = new THREE.Points(pGeo, pMat);
particles.frustumCulled = false;
scene.add(particles);
// Shockwave rings (whales). Small pool of expanding rings.
const shockwaves = [];
function spawnShockwave(color) {
const geo = new THREE.RingGeometry(9.2, 9.8, 64);
const mat = new THREE.MeshBasicMaterial({ color, transparent: true, opacity: 0.8, side: THREE.DoubleSide, depthWrite: false, blending: THREE.AdditiveBlending });
const ring = new THREE.Mesh(geo, mat);
ring.lookAt(camera.position);
ring.userData = { life: 1.2, max: 1.2 };
scene.add(ring);
shockwaves.push(ring);
if (shockwaves.length > 12) { const old = shockwaves.shift(); scene.remove(old); old.geometry.dispose(); old.material.dispose(); }
}
const BULL = new THREE.Color(0x34e0a8);
const BEAR = new THREE.Color(0xff5d73);
function emitTrade(isBuy, usd) {
const value = Math.max(1, usd || 1);
const mag = Math.min(1, Math.log10(value + 1) / Math.log10(50_000)); // 0..1
const count = Math.round(4 + mag * 36);
const baseColor = isBuy ? BULL : BEAR;
const dirY = isBuy ? 1 : -1;
const speed = 8 + mag * 26;
const size = 1.4 + mag * 5.5;
const life = 1.4 + mag * 1.6;
for (let k = 0; k < count; k++) {
const i = pCursor; pCursor = (pCursor + 1) % PARTICLE_POOL;
// emit from a point on the core surface
const theta = Math.random() * Math.PI * 2;
const phi = Math.acos(2 * Math.random() - 1);
const nx = Math.sin(phi) * Math.cos(theta);
const ny = Math.sin(phi) * Math.sin(theta);
const nz = Math.cos(phi);
pPos[i*3] = nx * 9.5; pPos[i*3+1] = ny * 9.5; pPos[i*3+2] = nz * 9.5;
// velocity: radial out + biased vertically by side
const sp = speed * (0.6 + Math.random() * 0.7);
pVel[i*3] = nx * sp * 0.7;
pVel[i*3+1] = ny * sp * 0.5 + dirY * (sp * 0.6);
pVel[i*3+2] = nz * sp * 0.7;
const tint = 0.75 + Math.random() * 0.25;
pCol[i*3] = baseColor.r * tint; pCol[i*3+1] = baseColor.g * tint; pCol[i*3+2] = baseColor.b * tint;
pSize[i] = size * (0.7 + Math.random() * 0.6);
pMaxLife[i] = life; pLife[i] = life;
}
// momentary core kick + heartbeat feed
coreUniforms.uPulse.value = Math.min(1.2, coreUniforms.uPulse.value + 0.25 + mag * 0.6);
pGeo.attributes.color.needsUpdate = true;
if (value >= WHALE_USD) spawnShockwave(baseColor);
}
// ── Live sentiment / flow bookkeeping ───────────────────────────────────
const recentTrades = []; // { t, isBuy, usd } — for activity level + factual counts
let lastTradeAt = 0;
// Roll up the last 60s of activity: factual buy/sell counts + total volume, plus
// a non-directional "busyness" reading. We deliberately do NOT synthesize a
// buy/sell verdict or net-flow signal — the scene shows what happened on-chain,
// it does not make a call. Each transaction is still labelled buy/sell (factual).
function updateFlowCounters(now) {
while (recentTrades.length && now - recentTrades[0].t > FLOW_WINDOW_MS) recentTrades.shift();
let buys = 0, sells = 0, vol = 0;
for (const r of recentTrades) { if (r.isBuy) buys++; else sells++; vol += r.usd; }
setTextById('pl-buys', String(buys));
setTextById('pl-sells', String(sells));
setTextById('pl-vol60', vol > 0 ? fmtUsd(vol) : '$0');
const trades = buys + sells;
const busy = Math.min(1, trades / 30); // 30 trades/min ≈ "busy"
if (activityFill) activityFill.style.width = Math.round(busy * 100) + '%';
setText(activityReading, trades === 0 ? 'Quiet' : trades >= 24 ? 'Very busy' : trades >= 8 ? 'Active' : 'Steady');
}
// ── HUD updates ─────────────────────────────────────────────────────────
function fmtUsd(n) {
n = Number(n);
if (!Number.isFinite(n) || n === 0) return '—';
const a = Math.abs(n);
if (a >= 1e9) return '$' + (n/1e9).toFixed(2) + 'B';
if (a >= 1e6) return '$' + (n/1e6).toFixed(2) + 'M';
if (a >= 1e3) return '$' + (n/1e3).toFixed(1) + 'K';
if (a >= 1) return '$' + n.toFixed(2);
return '$' + n.toPrecision(3);
}
function fmtNum(n) {
n = Number(n);
if (!Number.isFinite(n)) return '—';
if (n >= 1e6) return (n/1e6).toFixed(1) + 'M';
if (n >= 1e3) return (n/1e3).toFixed(1) + 'K';
return String(Math.round(n));
}
// ── Status resolution ───────────────────────────────────────────────────
// The stream and the stats poll fail independently, so they each keep their
// own health flag and one resolver decides what the badge says. The old code
// let whichever handler fired last win, which is how a stats outage could be
// erased by the next SSE retry and leave a HUD of dashes with no explanation.
let streamState = 'connecting'; // connecting | live | quiet | reconnecting
let statsOk = null; // null = not answered yet, true/false = last poll
const STREAM_LABEL = {
connecting: '$THREE · connecting…',
live: '$THREE · live',
quiet: '$THREE · market quiet',
reconnecting: '$THREE · reconnecting…',
};
function setHero(state, text) {
if (heroEl) heroEl.dataset.state = state;
if (text != null && statusText) {
// Claim the node from the i18n catalog pass. It lands after an async
// locale fetch and would otherwise revert a live badge to "connecting…"
// for the rest of the session.
statusText.setAttribute('data-i18n-owned', '1');
statusText.textContent = text;
}
}
function setStream(state) { streamState = state; renderStatus(); }
function renderStatus() {
const streamDown = streamState === 'connecting' || streamState === 'reconnecting';
// Until something has actually happened the markup already says
// "connecting…", and it says it in the visitor's language. Leave that
// first paint to the i18n catalog and only claim the node once the
// script has a status of its own to report.
const untouched = streamState === 'connecting' && statsOk !== false;
if (statsOk === false && streamDown) {
setHero('error', '$THREE · live data unavailable');
} else {
setHero(streamState === 'reconnecting' ? 'connecting' : streamState, untouched ? null : STREAM_LABEL[streamState]);
}
renderFault();
}
// One persistent line naming exactly what is down and offering the recovery.
function renderFault() {
if (!faultEl) return;
const streamDown = streamState === 'reconnecting';
let msg = '';
if (statsOk === false && streamDown) msg = 'Price, stats and the trade stream are all unreachable. Retrying automatically.';
else if (statsOk === false) msg = 'Price and protocol stats are unreachable. The trade stream is still running.';
else if (streamDown) msg = 'The live trade stream dropped. Reconnecting automatically.';
if (!msg) { faultEl.hidden = true; return; }
setText(faultText, msg);
faultEl.hidden = false;
}
function pushTicker(isBuy, usd, who) {
if (!tickerList) return;
if (tickerEmpty) tickerEmpty.remove();
const li = document.createElement('li');
li.className = isBuy ? 'buy' : 'sell';
const side = document.createElement('span'); side.className = 'side'; side.textContent = isBuy ? 'BUY' : 'SELL';
const amt = document.createElement('span'); amt.className = 'amt'; amt.textContent = fmtUsd(usd);
const w = document.createElement('span'); w.className = 'who'; w.textContent = who ? who.slice(0, 4) + '…' + who.slice(-4) : '';
li.append(side, amt, w);
tickerList.prepend(li);
while (tickerList.children.length > TICKER_MAX) tickerList.lastChild.remove();
}
// ── Stats polling ───────────────────────────────────────────────────────
let statsTimer = null, statsFailures = 0;
async function pollStats() {
try {
const r = await fetch(STATS_API, { cache: 'no-store' });
if (!r.ok) throw new Error('stats ' + r.status);
const d = await r.json();
const tk = d.token || {}; const pr = d.protocol || {};
statsFailures = 0;
statsOk = true;
renderStatus();
if (tk.price_usd != null) setText(priceEl, fmtUsd(tk.price_usd));
const chg = Number(tk.price_change_24h);
if (Number.isFinite(chg) && changeEl) {
changeEl.textContent = (chg >= 0 ? '+' : '') + chg.toFixed(2) + '% · 24h';
changeEl.className = 'chg ' + (chg > 0.01 ? 'up' : chg < -0.01 ? 'down' : 'flat');
}
setTextById('pl-mcap', fmtUsd(tk.market_cap));
setTextById('pl-vol', fmtUsd(tk.volume_24h));
setTextById('pl-holders', tk.holders != null ? fmtNum(tk.holders) : '—');
setTextById('pl-liq', fmtUsd(tk.liquidity));
setTextById('pl-agents', pr.total_agents != null ? fmtNum(pr.total_agents) : '—');
const bb = d.buyback || {};
setTextById('pl-bought', bb.three_bought != null ? fmtNum(bb.three_bought) : '-');
// market cap gently scales the core
if (tk.market_cap) {
const mc = Math.min(1, Math.log10(Number(tk.market_cap) + 1) / Math.log10(50_000_000));
targetCoreScale = 0.85 + mc * 0.4;
}
} catch (err) {
statsFailures++;
// Badge the error on the FIRST failure for fast feedback, then keep
// retrying on the poll interval. The persistent notice in the hero is
// what the visitor reads; the toast is only the arrival cue.
statsOk = false;
renderStatus();
if (statsFailures === 1) showToast('Live stats unavailable. Retrying.');
}
}
// ── Trades SSE ──────────────────────────────────────────────────────────
let es = null, sseRetry = 0, sseRetryTimer = null;
function connectTrades() {
try { es = new EventSource(TRADES_SSE); } catch { scheduleReconnect(); return; }
es.addEventListener('open', () => { /* server "open" event */ });
es.onopen = () => { sseRetry = 0; setStream('live'); };
es.addEventListener('trade', (ev) => {
let d; try { d = JSON.parse(ev.data); } catch { return; }
const isBuy = d.is_buy === true || d.txType === 'buy' || d.tx_type === 'buy';
const usd = Number(d.sol_value_usd) || (Number(d.sol_amount ?? d.solAmount) || 0) * _solUsd;
const now = performance.now();
lastTradeAt = now;
recentTrades.push({ t: now, isBuy, usd });
emitTrade(isBuy, usd);
pushTicker(isBuy, usd, d.trader || d.traderPublicKey);
setStream('live');
});
es.onerror = () => { setStream('reconnecting'); scheduleReconnect(); };
}
function scheduleReconnect() {
if (sseRetryTimer) return;
if (es) { try { es.close(); } catch {} es = null; }
const delay = Math.min(15_000, 1_000 * 2 ** sseRetry++);
sseRetryTimer = setTimeout(() => { sseRetryTimer = null; connectTrades(); }, delay);
}
let toastTimer = null;
function showToast(msg) {
if (!toastEl) return;
toastEl.textContent = msg; toastEl.classList.add('is-visible');
clearTimeout(toastTimer); toastTimer = setTimeout(() => toastEl.classList.remove('is-visible'), 3200);
}
// ── Animation loop ───────────────────────────────────────────────────────
let targetCoreScale = 1, coreScale = 1;
let raf = null, prev = performance.now(), running = true;
const heartEMA = { v: 0 };
function tick(now) {
raf = requestAnimationFrame(tick);
const dt = Math.min(0.05, (now - prev) / 1000); prev = now;
const t = now / 1000;
// core shader
coreUniforms.uTime.value = t;
coreUniforms.uPulse.value *= Math.pow(0.02, dt); // fast decay
// heartbeat amplitude tracks trade frequency (trades in last 8s)
const recent8 = recentTrades.filter((r) => now - r.t < 8_000).length;
heartEMA.v += (Math.min(1, recent8 / 12) - heartEMA.v) * 0.05;
coreUniforms.uHeart.value = heartEMA.v;
coreScale += (targetCoreScale - coreScale) * 0.04;
core.scale.setScalar(coreScale);
shell.scale.setScalar(coreScale);
shell.rotation.y += dt * 0.06; shell.rotation.x += dt * 0.02;
halo.scale.setScalar(coreScale * (1 + coreUniforms.uPulse.value * 0.04));
// particles integrate
let anyAlive = false;
for (let i = 0; i < PARTICLE_POOL; i++) {
if (pLife[i] <= 0) continue;
anyAlive = true;
pLife[i] -= dt;
const f = Math.max(0, pLife[i] / pMaxLife[i]);
pVel[i*3] *= 0.96; pVel[i*3+1] *= 0.96; pVel[i*3+2] *= 0.96;
pPos[i*3] += pVel[i*3] * dt; pPos[i*3+1] += pVel[i*3+1] * dt; pPos[i*3+2] += pVel[i*3+2] * dt;
if (pLife[i] <= 0) { pPos[i*3+1] = 9999; pSize[i] = 0; continue; }
// fade by shrinking size (additive material has no per-vertex alpha)
const baseSz = pSize[i];
pGeo.attributes.psize.array[i] = baseSz * (0.3 + f * 0.7);
}
if (anyAlive) {
pGeo.attributes.position.needsUpdate = true;
pGeo.attributes.psize.needsUpdate = true;
}
// shockwaves
for (let i = shockwaves.length - 1; i >= 0; i--) {
const r = shockwaves[i]; r.userData.life -= dt;
if (r.userData.life <= 0) { scene.remove(r); r.geometry.dispose(); r.material.dispose(); shockwaves.splice(i, 1); continue; }
const k = 1 - r.userData.life / r.userData.max;
r.scale.setScalar(1 + k * 3.2); r.material.opacity = 0.8 * (1 - k); r.lookAt(camera.position);
}
// idle/quiet state
if (lastTradeAt && now - lastTradeAt > 25_000 && streamState === 'live') setStream('quiet');
updateFlowCounters(now);
controls.update();
composer.render();
}
// ── Recovery control ────────────────────────────────────────────────────
// The poll already retries on its own interval; this is the visitor's way to
// stop waiting for it. Both feeds are re-armed, because the notice can name
// either one.
if (faultRetry) {
faultRetry.addEventListener('click', async () => {
faultRetry.disabled = true;
faultRetry.textContent = 'Retrying…';
if (streamState === 'reconnecting') {
if (sseRetryTimer) { clearTimeout(sseRetryTimer); sseRetryTimer = null; }
sseRetry = 0;
if (es) { try { es.close(); } catch { /* already closed */ } es = null; }
connectTrades();
}
await pollStats();
faultRetry.disabled = false;
faultRetry.textContent = 'Retry now';
});
}
// ── Bottom-band measurement ─────────────────────────────────────────────
// Two consumers, one measure pass. The narrow layout needs to know how tall
// the bottom HUD band is so the trade feed can fill exactly the gap above it,
// and the shared corner stack (language control, Getting started) needs the
// same clearance so it stops landing on top of the page's own controls. The
// stack's own probe cannot see these: it walks up to the nearest fixed
// ancestor, which here is the full-viewport #pl-stage, and gives up.
const CORNER_KEY = 'three-live-hud';
const narrowLayout = window.matchMedia('(max-width: 820px)');
function clearanceOf(node) {
if (!node || getComputedStyle(node).display === 'none') return 0;
const r = node.getBoundingClientRect();
return r.height > 0 ? Math.max(0, window.innerHeight - r.top) : 0;
}
let stackRo = null, stackWatched = false;
function syncDock() {
const root = document.documentElement;
const stackEl = document.getElementById('tws-corner-stack');
// Wide layout parks the stack in the corner it shares with the orbit hint
// and nothing else. Narrow layout turns it into a full-width bar, where the
// bottom-most thing the page owns is the flow row. Reserving only that keeps
// the lift small; the stat grid then steps over the stack itself, so the
// whole bottom band stacks flow, stack, stats without ever double-counting.
const need = narrowLayout.matches ? clearanceOf(flowPanel) : clearanceOf(hintPanel);
const stack = window.twsCornerStack;
if (stack) {
if (need > 0) stack.reserve(CORNER_KEY, { height: Math.round(need) });
else stack.release(CORNER_KEY);
}
// observe() fires the callback immediately, so this attaches exactly once:
// re-observing on every pass would spin the observer against itself.
if (stackEl && stackRo && !stackWatched) { stackWatched = true; stackRo.observe(stackEl); }
// Narrow layout turns the stack into a full-width bar sitting right where
// the stat grid does, so the grid steps over whatever is actually parked
// there (the stack alone, or the stack lifted by the walk companion).
// Clamped at 40% of the viewport for two reasons: the stack's position is
// partly a function of the reservation written just above, so an unbounded
// read could walk the band a little further up on every pass, and a HUD
// that climbs off the top is worse than one a helper pill overlaps.
let base = clearanceOf(flowPanel);
if (narrowLayout.matches && stackEl) {
const r = stackEl.getBoundingClientRect();
if (r.height > 0) {
base = Math.max(base, Math.round(window.innerHeight - r.top) + 10);
base = Math.min(base, Math.round(window.innerHeight * 0.4));
}
}
root.style.setProperty('--pl-band-base', Math.round(base) + 'px');
const band = Math.max(clearanceOf(statsPanel), clearanceOf(flowPanel));
if (band > 0) root.style.setProperty('--pl-dock-h', Math.round(band) + 'px');
// Measured from the column and the hero, never from the feed itself: the
// feed's own height goes to zero the moment this class hides it, which
// would latch the page into the cramped layout for good.
if (hudTop && heroEl) {
const room = hudTop.getBoundingClientRect().height - heroEl.getBoundingClientRect().height - 10;
hudTop.classList.toggle('is-cramped', narrowLayout.matches && room < 112);
}
}
// The stack grows when its Getting started checklist opens, which moves the
// floor the stat grid sits on. Watched separately because the element is
// mounted by another module and may not exist on the first pass.
stackRo = new ResizeObserver(syncDock);
const dockRo = new ResizeObserver(syncDock);
if (statsPanel) dockRo.observe(statsPanel);
if (flowPanel) dockRo.observe(flowPanel);
if (heroEl) dockRo.observe(heroEl);
window.addEventListener('resize', syncDock);
window.addEventListener('tws-corner-stack:ready', syncDock);
narrowLayout.addEventListener('change', syncDock);
syncDock();
// ── Resize / lifecycle ───────────────────────────────────────────────────
function resize() {
const w = host.clientWidth, h = host.clientHeight;
renderer.setSize(w, h); composer.setSize(w, h);
bloom.setSize(w, h);
camera.aspect = w / h; camera.updateProjectionMatrix();
pMat.uniforms.uScale.value = renderer.getPixelRatio() * 220;
}
new ResizeObserver(resize).observe(host);
resize();
document.addEventListener('visibilitychange', () => {
if (document.hidden) { if (raf) cancelAnimationFrame(raf); raf = null; }
else if (!raf) { prev = performance.now(); raf = requestAnimationFrame(tick); }
});
window.addEventListener('beforeunload', () => { if (es) es.close(); if (statsTimer) clearInterval(statsTimer); });
// ── Boot ──────────────────────────────────────────────────────────────────
renderStatus();
// Seed the SOL price used for trades that only supply sol_amount.
// Same-origin call to the free /api/crypto/token snapshot (wrapped-SOL mint)
// — Jupiter's browser fetch is CORS-blocked, this reuses the platform's
// cached multi-provider SOL/USD read instead.
fetch('/api/crypto/token?address=So11111111111111111111111111111111111111112', { signal: AbortSignal.timeout(9000) })
.then((r) => r.ok ? r.json() : null)
.then((d) => { const p = Number(d?.priceUsd); if (p > 0) _solUsd = p; })
.catch(() => {});
pollStats().finally(() => { setTimeout(() => introEl.classList.add('is-hidden'), 350); });
statsTimer = setInterval(pollStats, STATS_INTERVAL_MS);
connectTrades();
raf = requestAnimationFrame(tick);
</script>
<script src="/brand.js" defer></script>
<!-- Runtime i18n: detects locale, swaps annotated copy, mounts <lang-switcher>. -->
<script type="module" src="/i18n.js"></script>
</body>
</html>