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.

feat: SSRF hardening, multiplayer tokens, and live x402 game surfaces

nirholas6caf90095788
diff --git a/api/_lib/fetch-model.js b/api/_lib/fetch-model.js
index 78a8150b6..3a3abcfef 100644
--- a/api/_lib/fetch-model.js
+++ b/api/_lib/fetch-model.js
@@ -13,13 +13,12 @@
import { lookup } from 'node:dns/promises';
import { Agent } from 'undici';
-import { env } from './env.js';
const DEFAULT_MAX_BYTES = 50 * 1024 * 1024; // 50 MB
const DEFAULT_TIMEOUT_MS = 20_000;
const MAX_REDIRECTS = 3;
-const IS_DEV = env.NODE_ENV !== 'production';
+const IS_DEV = process.env.NODE_ENV !== 'production';
export class FetchModelError extends Error {
constructor(message, code = 'fetch_failed') {
diff --git a/api/_lib/presence-store.js b/api/_lib/presence-store.js
index a7c10011f..c43d732db 100644
--- a/api/_lib/presence-store.js
+++ b/api/_lib/presence-store.js
@@ -14,7 +14,7 @@
import { Redis } from '@upstash/redis';
import { env } from './env.js';
-import { hmacSha256, constantTimeEquals } from './crypto.js';
+import { hmacSha256, constantTimeEquals, sha256Base64Url } from './crypto.js';
const PRESENCE_PREFIX = 'presence:';
const TICKET_TTL_SEC = 600; // 10 min — the client refreshes well before expiry
@@ -107,11 +107,23 @@ export async function notifyMultiplayer(type, toUserId, payload = {}) {
const base = env.MULTIPLAYER_INTERNAL_URL;
if (!base) return { delivered: false, reason: 'unconfigured' };
try {
- const sig = await hmacSha256(env.MULTIPLAYER_SHARED_SECRET, `notify:${toUserId}:${type}`);
+ // Bind the signature to the exact body and a fresh timestamp so a captured
+ // (to,type,sig) tuple can't be replayed with a different payload or after the
+ // short freshness window. The signed string covers the payload hash; the
+ // multiplayer verifier recomputes it over the same serialized payload it acts
+ // on, so a tampered body fails the check. Keep byte-compatible with
+ // verifyNotifySignature in multiplayer/src/presence-token.js.
+ const requestBody = JSON.stringify({ type, to: toUserId, payload });
+ const ts = Math.floor(Date.now() / 1000);
+ const payloadHash = await sha256Base64Url(JSON.stringify(payload ?? {}));
+ const sig = await hmacSha256(
+ env.MULTIPLAYER_SHARED_SECRET,
+ `notify:${toUserId}:${type}:${ts}:${payloadHash}`,
+ );
const res = await fetch(`${base}/internal/notify`, {
method: 'POST',
- headers: { 'content-type': 'application/json', 'x-mp-signature': sig },
- body: JSON.stringify({ type, to: toUserId, payload }),
+ headers: { 'content-type': 'application/json', 'x-mp-signature': sig, 'x-mp-timestamp': String(ts) },
+ body: requestBody,
signal: AbortSignal.timeout(2500),
});
if (!res.ok) return { delivered: false, reason: `http_${res.status}` };
diff --git a/api/_lib/ssrf-guard.js b/api/_lib/ssrf-guard.js
index 80a00add1..2be63917d 100644
--- a/api/_lib/ssrf-guard.js
+++ b/api/_lib/ssrf-guard.js
@@ -104,9 +104,29 @@ export async function assertSafePublicUrl(input, { allowHttp = false } = {}) {
return url;
}
+const MAX_REDIRECTS = 5;
+
// Convenience: assert + fetch. Uses the global fetch. Same options as fetch,
// minus that the URL must pass `assertSafePublicUrl`.
+//
+// Redirects are followed MANUALLY so each Location hop is re-validated with
+// `assertSafePublicUrl` before we connect to it. The default global fetch
+// (`redirect: 'follow'`) would only check the first URL, letting an attacker
+// host a public endpoint that 302s to 169.254.169.254 / RFC1918 and slip past
+// the guard. Hops are bounded by `MAX_REDIRECTS`.
export async function fetchSafePublicUrl(input, init = {}, opts = {}) {
- const url = await assertSafePublicUrl(input, opts);
- return fetch(url.toString(), init);
+ let url = await assertSafePublicUrl(input, opts);
+ let redirects = 0;
+ while (true) {
+ const res = await fetch(url.toString(), { ...init, redirect: 'manual' });
+ if (res.status >= 300 && res.status < 400 && res.headers.get('location')) {
+ if (++redirects > MAX_REDIRECTS) {
+ throw new SsrfBlockedError('too many redirects');
+ }
+ const next = new URL(res.headers.get('location'), url);
+ url = await assertSafePublicUrl(next.toString(), opts);
+ continue;
+ }
+ return res;
+ }
}
diff --git a/api/agents/a2a-paid.js b/api/agents/a2a-paid.js
index a97e9ff49..56afcd923 100644
--- a/api/agents/a2a-paid.js
+++ b/api/agents/a2a-paid.js
@@ -19,6 +19,35 @@ import { assertSafePublicUrl, SsrfBlockedError } from '../_lib/ssrf-guard.js';
const ROUTE = '/api/agents/a2a-paid';
const MAX_FETCH_BYTES = 16 * 1024 * 1024;
+const MAX_REDIRECTS = 5;
+
+// SSRF-safe fetch: re-validate every redirect hop with assertSafePublicUrl
+// before following it. The model URL is fully attacker-controlled, so following
+// redirects with the global `redirect:'follow'` would let an allowlisted public
+// host 302 us to 169.254.169.254 / RFC1918, defeating the guard. Bounded hops.
+async function fetchModelFollowingValidatedRedirects(parsed) {
+ let url = parsed;
+ let redirects = 0;
+ while (true) {
+ const res = await fetch(url.toString(), {
+ redirect: 'manual',
+ headers: { accept: 'model/gltf-binary,model/gltf+json,application/octet-stream' },
+ signal: AbortSignal.timeout(20_000),
+ });
+ if (res.status >= 300 && res.status < 400 && res.headers.get('location')) {
+ if (++redirects > MAX_REDIRECTS) {
+ const e = new Error('too many redirects');
+ e.code = 'fetch_failed';
+ e.status = 502;
+ throw e;
+ }
+ const next = new URL(res.headers.get('location'), url);
+ url = await assertSafePublicUrl(next.toString(), { allowHttp: true });
+ continue;
+ }
+ return res;
+ }
+}
const DESCRIPTION =
'three.ws A2A glTF/GLB Inspector — pay per call (USDC). Fetch a 3D model ' +
@@ -82,12 +111,14 @@ async function fetchAndInspect(targetUrl) {
}
let upstream;
try {
- upstream = await fetch(parsed.toString(), {
- redirect: 'follow',
- headers: { accept: 'model/gltf-binary,model/gltf+json,application/octet-stream' },
- signal: AbortSignal.timeout(20_000),
- });
+ upstream = await fetchModelFollowingValidatedRedirects(parsed);
} catch (err) {
+ if (err instanceof SsrfBlockedError) {
+ const e = new Error(err.message);
+ e.code = 'invalid_url';
+ e.status = 400;
+ throw e;
+ }
const e = new Error(`could not fetch model: ${err.message}`);
e.code = 'fetch_failed';
e.status = 502;
diff --git a/api/artifact.js b/api/artifact.js
index aeba62671..0f82d4830 100644
--- a/api/artifact.js
+++ b/api/artifact.js
@@ -16,6 +16,7 @@ import { sql } from './_lib/db.js';
import { error, wrap } from './_lib/http.js';
import { limits, clientIp } from './_lib/rate-limit.js';
import { getObjectBuffer } from './_lib/r2.js';
+import { assertSafePublicUrl } from './_lib/ssrf-guard.js';
const AGENT_ID_RE = /^[a-z0-9_-]{3,64}$/i;
@@ -36,6 +37,7 @@ const ALLOWED_MODEL_ORIGINS = [
// and risk the artifact panel timing out before first paint.
const MAX_GLB_BYTES = 6 * 1024 * 1024;
const FETCH_TIMEOUT_MS = 8000;
+const MAX_GLB_REDIRECTS = 5;
// Mirrors the actual CSP Claude.ai applies to artifact iframes (scraped at
// github.com/simonw/scrape-claude-artifacts). Setting the same response CSP
@@ -86,11 +88,31 @@ function validateModelUrl(raw) {
return url.toString();
}
+// Follow redirects manually so each hop is re-validated. An allowlisted origin
+// (the list includes wildcard *.vercel.app) could 3xx toward an internal or
+// metadata address; without per-hop checks the global redirect:'follow' would
+// connect there. Each hop must keep an allowlisted https origin AND pass the
+// DNS-resolving SSRF guard (private/loopback/link-local/metadata IPs blocked).
async function fetchExternalGlb(url) {
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS);
try {
- const res = await fetch(url, { signal: ctrl.signal, redirect: 'follow' });
+ let current = url;
+ let redirects = 0;
+ let res;
+ while (true) {
+ if (!validateModelUrl(current)) {
+ throw new Error('redirect target is not a whitelisted https origin');
+ }
+ await assertSafePublicUrl(current);
+ res = await fetch(current, { signal: ctrl.signal, redirect: 'manual' });
+ if (res.status >= 300 && res.status < 400 && res.headers.get('location')) {
+ if (++redirects > MAX_GLB_REDIRECTS) throw new Error('too many redirects');
+ current = new URL(res.headers.get('location'), current).toString();
+ continue;
+ }
+ break;
+ }
if (!res.ok) throw new Error(`upstream ${res.status}`);
const len = Number(res.headers.get('content-length') || 0);
if (len && len > MAX_GLB_BYTES) {
diff --git a/api/ibm/vision.js b/api/ibm/vision.js
index ea7e1c8db..dada3a2db 100644
--- a/api/ibm/vision.js
+++ b/api/ibm/vision.js
@@ -23,6 +23,7 @@ import { cors, method, readJson, error, json, wrap } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { publicUrl } from '../_lib/r2.js';
import { watsonxConfig, watsonxChatComplete } from '../_lib/watsonx.js';
+import { assertSafePublicUrl } from '../_lib/ssrf-guard.js';
// Granite Vision 3.2 (2B) is the default multimodal model on watsonx.ai. Override
// per account/region with WATSONX_VISION_MODEL_ID.
@@ -220,13 +221,38 @@ async function resolveImage(body) {
throw fail(400, 'bad_image', 'provide image (data URL) or imageUrl (https)');
}
+const MAX_IMAGE_REDIRECTS = 5;
+
+// Re-validate every redirect hop before following it. An allowlisted host (the
+// list includes broad CDNs and open-redirect-prone providers) could otherwise
+// 3xx us toward an internal/metadata address. Each hop must stay https, keep an
+// allowlisted host, AND pass the DNS-resolving SSRF guard (private/loopback/
+// link-local/metadata IPs blocked). Bounded by MAX_IMAGE_REDIRECTS.
async function fetchImageAsDataUrl(url) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
let resp;
try {
- resp = await fetch(url, { signal: controller.signal, redirect: 'follow' });
+ let current = url;
+ let redirects = 0;
+ while (true) {
+ const host = hostOf(current);
+ if (!/^https:\/\//i.test(current) || !host || !allowedImageHost(host)) {
+ throw fail(400, 'image_host_not_allowed', 'image redirect target host is not allowed');
+ }
+ await assertSafePublicUrl(current);
+ resp = await fetch(current, { signal: controller.signal, redirect: 'manual' });
+ if (resp.status >= 300 && resp.status < 400 && resp.headers.get('location')) {
+ if (++redirects > MAX_IMAGE_REDIRECTS) {
+ throw fail(502, 'image_fetch_failed', 'too many redirects');
+ }
+ current = new URL(resp.headers.get('location'), current).toString();
+ continue;
+ }
+ break;
+ }
} catch (e) {
+ if (e?.status && e?.code) throw e; // already a structured fail()
throw fail(502, 'image_fetch_failed', `could not fetch image: ${e.message}`);
} finally {
clearTimeout(timer);
diff --git a/mcp-server/src/payments.js b/mcp-server/src/payments.js
index 6712634b9..43bf01475 100644
--- a/mcp-server/src/payments.js
+++ b/mcp-server/src/payments.js
@@ -130,6 +130,14 @@ async function buildAcceptsForTool({ resourceServer, scheme, priceUsd, networks,
/**
* Wrap a tool handler with x402 payment (USDC on Solana, `exact` scheme).
*
+ * The x402 wiring (resource server init, `accepts` requirements, payment
+ * wrapper) is built LAZILY on the first invocation — NOT when the tool is
+ * registered. This keeps tool registration (names/descriptions/schemas)
+ * free of any runtime payment env: `buildServer()` can enumerate every tool
+ * without MCP_SVM_PAYMENT_ADDRESS, and only an actual paid call triggers the
+ * env requirement. The wrapper is memoized so the first call pays the init cost
+ * once and every subsequent call reuses it.
+ *
* @param {object} cfg
* @param {string} cfg.toolName — e.g. "get_pose_seed"
* @param {string} cfg.description — human-readable description
@@ -142,9 +150,9 @@ async function buildAcceptsForTool({ resourceServer, scheme, priceUsd, networks,
* @param {object} [cfg.extra] — extra fields (extra.svm)
* @param {object} [cfg.hooks] — { onBeforeExecution, onAfterExecution, onAfterSettlement }
* @param {Function} handler — async (args, { settle? }) → result
- * @returns {Promise<Function>} MCP tool callback for McpServer.tool()
+ * @returns {Function} MCP tool callback for McpServer.tool()
*/
-export async function paid(cfg, handler) {
+export function paid(cfg, handler) {
const {
toolName,
description,
@@ -166,40 +174,71 @@ export async function paid(cfg, handler) {
throw new Error(`paid(): only the 'exact' scheme is supported on Solana (got '${scheme}')`);
}
- const resourceServer = await getResourceServer();
- const resourceUrl = createToolResourceUrl(toolName);
- const accepts = await buildAcceptsForTool({
- resourceServer,
- scheme,
- priceUsd,
- networks,
- resourceUrl,
- extra,
- });
-
- const bazaar = declareDiscoveryExtension({
- toolName,
- description,
- transport: 'stdio',
- inputSchema,
- example,
- output: outputExample ? { example: outputExample } : undefined,
- });
+ // Lazily build (and memoize) the payment wrapper. This is the ONLY place
+ // that touches payment env (requireSvmPayTo) and the facilitator, so it
+ // runs on first invocation rather than at registration time.
+ let wrapperPromise = null;
+ async function getWrapper() {
+ if (wrapperPromise) return wrapperPromise;
+ wrapperPromise = (async () => {
+ const resourceServer = await getResourceServer();
+ const resourceUrl = createToolResourceUrl(toolName);
+ const accepts = await buildAcceptsForTool({
+ resourceServer,
+ scheme,
+ priceUsd,
+ networks,
+ resourceUrl,
+ extra,
+ });
+
+ const bazaar = declareDiscoveryExtension({
+ toolName,
+ description,
+ transport: 'stdio',
+ inputSchema,
+ example,
+ output: outputExample ? { example: outputExample } : undefined,
+ });
+
+ const wrap = createPaymentWrapper(resourceServer, {
+ accepts,
+ resource: { url: resourceUrl, description, mimeType: 'application/json' },
+ extensions: bazaar,
+ hooks,
+ });
+
+ return wrap(async (args, context) => {
+ const result = await handler(args, context);
+ const text = typeof result === 'string' ? result : JSON.stringify(result);
+ return {
+ content: [{ type: 'text', text }],
+ };
+ });
+ })();
+ return wrapperPromise;
+ }
- const wrap = createPaymentWrapper(resourceServer, {
- accepts,
- resource: { url: resourceUrl, description, mimeType: 'application/json' },
- extensions: bazaar,
- hooks,
- });
+ // The callback McpServer.registerTool() invokes. Defers all payment wiring
+ // to the first real call.
+ return async function paidToolCallback(args, context) {
+ const wrapped = await getWrapper();
+ return wrapped(args, context);
+ };
+}
- return wrap(async (args, context) => {
- const result = await handler(args, context);
- const text = typeof result === 'string' ? result : JSON.stringify(result);
- return {
- content: [{ type: 'text', text }],
- };
- });
+/**
+ * Standard tool error envelope. Every tool's error path returns this shape so
+ * MCP clients can branch on a stable `{ ok: false, error: <code>, message }`
+ * contract instead of the per-tool ad-hoc shapes this server used to emit.
+ *
+ * @param {string} code — machine-readable error code (snake_case)
+ * @param {string} message — human-readable explanation
+ * @param {object} [extra] — optional extra fields merged into the envelope
+ * @returns {{ ok: false, error: string, message: string }}
+ */
+export function toolError(code, message, extra) {
+ return { ok: false, error: code, message, ...(extra || {}) };
}
export { NETWORK_SOLANA_MAINNET };
diff --git a/mcp-server/src/tools/_shared.js b/mcp-server/src/tools/_shared.js
new file mode 100644
index 000000000..9833d189c
--- /dev/null
+++ b/mcp-server/src/tools/_shared.js
@@ -0,0 +1,41 @@
+// Shared helpers for the paid MCP tools.
+//
+// Single-sources the tool input schema: each tool declares its arguments ONCE
+// as a Zod shape (an object of `{ field: ZodType }`), and the JSON Schema the
+// MCP client / x402 bazaar sees is DERIVED from that shape via
+// zod-to-json-schema. This kills the JSON-Schema↔Zod drift class — the two
+// representations can no longer disagree because there is only one source.
+//
+// Re-exports `toolError` so tools can import their error contract + schema
+// helper from a single module.
+
+import { z } from 'zod';
+import { zodToJsonSchema } from 'zod-to-json-schema';
+
+export { toolError } from '../payments.js';
+
+/**
+ * Derive a MCP-shaped JSON Schema from a Zod shape (the same `{ field: ZodType }`
+ * object passed to `McpServer.registerTool({ inputSchema })`).
+ *
+ * The output matches what the tools previously hand-wrote: a top-level
+ * `{ type: 'object', properties, required, additionalProperties: false }`
+ * with no `$schema`/`$ref` envelope, so the external contract MCP clients and
+ * the x402 bazaar see is unchanged.
+ *
+ * @param {Record<string, import('zod').ZodTypeAny>} shape
+ * @returns {object} JSON Schema (draft-07 object schema)
+ */
+export function jsonSchemaFromZod(shape) {
+ const schema = zodToJsonSchema(z.object(shape).strict(), {
+ // Inline everything — MCP clients expect a self-contained object schema,
+ // not a `$ref`-into-`definitions` document.
+ $refStrategy: 'none',
+ target: 'jsonSchema7',
+ });
+ // zod-to-json-schema wraps the result with a `$schema` meta key; strip it so
+ // the emitted schema is byte-for-byte the lean object schema the tools used
+ // to hand-maintain.
+ delete schema.$schema;
+ return schema;
+}
diff --git a/multiplayer/src/guest-token.js b/multiplayer/src/guest-token.js
new file mode 100644
index 000000000..11b0991ef
--- /dev/null
+++ b/multiplayer/src/guest-token.js
@@ -0,0 +1,97 @@
+// Guest-token signing/verification — the account proof for un-walleted players.
+//
+// The game profile account key (playerId) must never be taken from a raw client
+// option: a `pid` set to a victim's wallet or guest id would load and control
+// their saved profile (gold, bank, items) and grief them off their eviction
+// channel. Wallet accounts are proven by a play pass (verifyPlayPass). Guests have
+// no wallet to sign, so the SERVER mints them an identity instead: a random guest
+// id sealed into an HMAC-signed token here. The client echoes the token back on
+// reconnect; the room verifies it and binds the sealed guest id as the account,
+// so a guest id can only ever be claimed by the socket that holds its signed
+// token — another client can't guess or assert it.
+//
+// Format: base64url(JSON{ k:'guest', gid, iat, exp }) + '.' + base64url(HMAC-SHA256).
+// Same construction + shared secret as play-pass.js / presence-token.js so the
+// whole multiplayer trust layer keys off one secret.
+
+import crypto from 'node:crypto';
+
+// 90 days — long enough that a returning guest keeps their progression across
+// sessions, short enough to bound an abandoned id. The client refreshes the token
+// (re-issued on every join below) well before this, so an active guest never lapses.
+const GUEST_TTL_S = 60 * 60 * 24 * 90;
+
+function secret() {
+ return (
+ process.env.MULTIPLAYER_SHARED_SECRET ||
+ process.env.HOLDER_PASS_SECRET ||
+ 'dev-insecure-multiplayer-secret'
+ );
+}
+
+function b64url(buf) {
+ return Buffer.from(buf).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
+}
+
+function hmac(body) {
+ return b64url(crypto.createHmac('sha256', secret()).update(body).digest());
+}
+
+function safeEqual(a, b) {
+ const ba = Buffer.from(a);
+ const bb = Buffer.from(b);
+ if (ba.length !== bb.length) return false;
+ return crypto.timingSafeEqual(ba, bb);
+}
+
+// Guest ids are server-minted with this prefix so they're visibly distinct from
+// wallet accounts and from a client-supplied `g_…` localStorage id (which is no
+// longer trusted as an account key).
+const GUEST_PREFIX = 'gs_';
+
+/**
+ * Mint a fresh, unguessable guest id.
+ * @returns {string}
+ */
+export function newGuestId() {
+ return GUEST_PREFIX + crypto.randomBytes(12).toString('hex');
+}
+
+/**
+ * Seal a guest id into a signed token the client stores and replays on reconnect.
+ * @param {string} gid
+ * @returns {string}
+ */
+export function signGuestToken(gid) {
+ const now = Math.floor(Date.now() / 1000);
+ const body = b64url(JSON.stringify({ k: 'guest', gid, iat: now, exp: now + GUEST_TTL_S }));
+ return `${body}.${hmac(body)}`;
+}
+
+/**
+ * Verify a guest token and return its sealed guest id, or null when the token is
+ * missing, malformed, tampered with, or expired.
+ * @param {unknown} token
+ * @returns {string | null}
+ */
+export function verifyGuestToken(token) {
+ if (typeof token !== 'string' || token.length < 16 || token.length > 4096) return null;
+ const dot = token.indexOf('.');
+ if (dot <= 0) return null;
+ const body = token.slice(0, dot);
+ const sig = token.slice(dot + 1);
+ if (!safeEqual(sig, hmac(body))) return null;
+
+ let payload;
+ try {
+ payload = JSON.parse(Buffer.from(body.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'));
+ } catch {
+ return null;
+ }
+ if (!payload || typeof payload !== 'object' || payload.k !== 'guest') return null;
+ if (typeof payload.exp !== 'number' || payload.exp * 1000 < Date.now()) return null;
+ const now = Date.now() / 1000;
+ if (typeof payload.iat !== 'number' || payload.iat > now + 60) return null;
+ if (typeof payload.gid !== 'string' || !payload.gid.startsWith(GUEST_PREFIX)) return null;
+ return payload.gid;
+}
diff --git a/multiplayer/src/index.js b/multiplayer/src/index.js
index 71c2eddcf..8f6d11cb1 100644
--- a/multiplayer/src/index.js
+++ b/multiplayer/src/index.js
@@ -81,10 +81,14 @@ app.get(['/health', '/healthz'], (_req, res) => {
app.post('/internal/notify', express.json({ limit: '16kb' }), (req, res) => {
const { type, to, payload } = req.body || {};
const sig = req.headers['x-mp-signature'];
+ const ts = req.headers['x-mp-timestamp'];
if (typeof type !== 'string' || typeof to !== 'string' || !type || !to) {
return res.status(400).json({ error: 'bad_request' });
}
- if (!verifyNotifySignature(to, type, sig)) {
+ // The signature is bound to the exact payload and a fresh timestamp, so a leaked
+ // (to,type,sig) tuple can't be replayed with attacker-chosen content or after
+ // the freshness window. Verify against the body we're about to deliver.
+ if (!verifyNotifySignature(to, type, payload || {}, ts, sig)) {
return res.status(401).json({ error: 'bad_signature' });
}
const delivered = socialHub.deliver(to, type, payload || {});
@@ -122,7 +126,19 @@ const transport = new WebSocketTransport({
server: httpServer,
verifyClient(info, next) {
const origin = info.req.headers.origin;
- if (!origin) return next(true); // native clients / curl probes
+ // Origin-less upgrades (native clients / scripted probes) must NOT be a free
+ // pass: a browser always sends Origin, so omitting it was a trivial way to skip
+ // the allowlist entirely. The real access boundary is each room's onAuth (a
+ // signed play pass / presence ticket, or a server-issued guest token), so the
+ // origin allowlist is only a browser-facing CSRF-style filter. We still reject
+ // origin-less handshakes in production — there is no legitimate origin-less
+ // browser client, and the signed-token gate, not a spoofable header, is what
+ // protects the rooms. Non-prod keeps them open for local curl/native dev probes.
+ if (!origin) {
+ if (!IS_PROD) return next(true);
+ console.warn('[multiplayer] rejecting origin-less upgrade');
+ return next(false, 403, 'origin required');
+ }
if (ALLOWED_ORIGINS.includes(origin)) return next(true);
// Allow any Vercel preview deploy that targets the same project — these
// have origins like https://three-ws-<hash>-<team>.vercel.app. We match
@@ -218,8 +234,31 @@ function publicJsonCors(_req, res, next) {
const RATE_WINDOW_MS = 10_000;
const RATE_MAX = 30;
const _rateBuckets = new Map(); // ip -> { windowStart, count }
+
+// Trusted client-IP resolution. X-Forwarded-For is fully client-controlled when a
+// request reaches the app directly, so keying the limiter on it lets a flood rotate
+// a fresh XFF per request and never hit a bucket. We only trust a forwarded IP from
+// our actual fronting proxy:
+// - Fly.io sets Fly-Client-IP to the real edge client IP (it can't be spoofed
+// past the proxy);
+// - TRUSTED_PROXY_IP_HEADER names any other platform's verified client-IP header
+// (e.g. CF-Connecting-IP, X-Real-IP) for non-Fly deploys.
+// Absent a trusted header we fall back to the raw socket peer, which an attacker
+// can't forge. We deliberately do NOT parse X-Forwarded-For as the access key.
+const TRUSTED_IP_HEADER = (process.env.TRUSTED_PROXY_IP_HEADER || '').trim().toLowerCase();
+function clientIp(req) {
+ const fly = req.headers['fly-client-ip'];
+ if (typeof fly === 'string' && fly.trim()) return fly.trim();
+ if (TRUSTED_IP_HEADER) {
+ const h = req.headers[TRUSTED_IP_HEADER];
+ const v = Array.isArray(h) ? h[0] : h;
+ if (typeof v === 'string' && v.trim()) return v.split(',')[0].trim();
+ }
+ return req.socket?.remoteAddress || 'unknown';
+}
+
function rateLimit(req, res, next) {
- const ip = req.headers['x-forwarded-for']?.split(',')[0]?.trim() || req.socket?.remoteAddress || 'unknown';
+ const ip = clientIp(req);
const now = Date.now();
let b = _rateBuckets.get(ip);
if (!b || now - b.windowStart > RATE_WINDOW_MS) { b = { windowStart: now, count: 0 }; _rateBuckets.set(ip, b); }
diff --git a/multiplayer/src/presence-token.js b/multiplayer/src/presence-token.js
index 85d5688da..8c76fc07e 100644
--- a/multiplayer/src/presence-token.js
+++ b/multiplayer/src/presence-token.js
@@ -45,11 +45,32 @@ export function verifyPresenceTicket(token) {
return data.uid;
}
+// Maximum age (seconds) an /internal/notify signature stays valid. The API mints
+// and delivers a notify within a couple of round-trips, so a tight window bounds
+// replay while clearing normal network + clock-skew jitter.
+const NOTIFY_MAX_AGE_S = 120;
+
// Verify the signature on an internal /internal/notify webhook from the API.
-// The API signs HMAC_SHA256(secret, `notify:<to>:<type>`); we recompute and
-// compare in constant time so a third party can't inject fake DMs/events.
-export function verifyNotifySignature(to, type, sig) {
+// The API signs HMAC_SHA256(secret, `notify:<to>:<type>:<ts>:<sha256(payload)>`),
+// so the signature is bound to the exact delivered body and a fresh timestamp —
+// a captured tuple can't be replayed with attacker-chosen content, nor outside
+// the freshness window. We recompute over the SAME payload we're about to deliver
+// (the caller passes the parsed payload it will act on) and compare in constant
+// time. Keep byte-compatible with notifyMultiplayer in api/_lib/presence-store.js.
+export function verifyNotifySignature(to, type, payload, ts, sig) {
if (typeof sig !== 'string' || !sig) return false;
- const expected = crypto.createHmac('sha256', secret()).update(`notify:${to}:${type}`).digest('base64url');
+ const tsNum = Number(ts);
+ if (!Number.isFinite(tsNum)) return false;
+ // Reject stale or future-dated timestamps (replay / forged clock).
+ const nowS = Math.floor(Date.now() / 1000);
+ if (Math.abs(nowS - tsNum) > NOTIFY_MAX_AGE_S) return false;
+ const payloadHash = crypto
+ .createHash('sha256')
+ .update(JSON.stringify(payload ?? {}))
+ .digest('base64url');
+ const expected = crypto
+ .createHmac('sha256', secret())
+ .update(`notify:${to}:${type}:${tsNum}:${payloadHash}`)
+ .digest('base64url');
return timingSafeEqualStr(sig, expected);
}
diff --git a/multiplayer/src/rooms/GameRoom.js b/multiplayer/src/rooms/GameRoom.js
index 9c828e7bc..1341b8284 100644
--- a/multiplayer/src/rooms/GameRoom.js
+++ b/multiplayer/src/rooms/GameRoom.js
@@ -15,7 +15,7 @@ import { Room, matchMaker } from '@colyseus/core';
import { GameState, GamePlayer, ResourceNode, Mob, Slot, Tombstone, Structure } from '../schemas/game.js';
import { REALMS, DEFAULT_REALM, isBlocked, inBounds, realmLayout, fishingSpotNear, portalAt, rollerAt, rollerDelta, inNoPvpZone, wheelLandmark } from './realms.js';
-import { signTransfer, verifyTransfer } from './realm-transfer.js';
+import { signTransfer, verifyTransfer, consumeTransferNonce } from './realm-transfer.js';
import { runCommand, commandManifest } from './commands.js';
import { STACKABLE_ITEMS, isEdible, healValue, scaledHeal, isMount, mountStepMs, rollLoot, itemLabel, clientItemRegistry, cookBurnChance, fishCatchChance, fishDoubleChance } from '../items.js';
import { cleanAvatarUrl } from '../avatar-url.js';
@@ -24,6 +24,8 @@ import { cleanServer } from '../servers.js';
import { evictChannel, payoutChannel, TAKEOVER_CLOSE_CODE } from '../presence-keys.js';
import { socialHub } from '../social-hub.js';
import { verifyPresenceTicket } from '../presence-token.js';
+import { verifyPlayPass } from '../play-pass.js';
+import { newGuestId, signGuestToken, verifyGuestToken } from '../guest-token.js';
import { cosmeticById, evaluatePurchase, currentOffers, clientCatalog } from '../cosmetics.js';
import { marketplaceStore } from '../marketplaceStore.js';
import {
@@ -46,6 +48,20 @@ import {
// Whisperwood, and Pond. A realm's `danger` flag is what gates death-bag drops
// (Task 02): dying in a danger realm spills part of your pack into a tombstone.
+// Platform entry gate (wallet-first sign-in + game-token balance), mirrored from
+// WalkRoom. When a game token is pinned (PLAY_GATE_MINT, falling back to
+// THREE_MINT) every wallet-shaped join must carry a valid play pass proving the
+// signed-in wallet holds ≥ the floor. An unset mint leaves the gate off, but the
+// account-binding in onAuth still applies (a wallet pid always needs a pass; a
+// guest always needs a server-signed guest token) so the profile account can
+// never be claimed from an unsigned option. Read at boot — gate config is fixed
+// for the process lifetime.
+const PLAY_GATE_MINT = (process.env.PLAY_GATE_MINT || process.env.THREE_MINT || '').trim();
+const PLAY_GATE_MIN = (() => {
+ const n = Number(process.env.PLAY_GATE_MIN);
+ return Number.isFinite(n) && n > 0 ? n : 1;
+})();
+
const MAX_CLIENTS_PER_ROOM = 50;
const PATCH_RATE_MS = 1000 / 15;
const SIM_TICK_MS = 250; // respawns, healing, death timers
@@ -190,6 +206,92 @@ function hslToHex(h, s, l) {
}
export class GameRoom extends Room {
+ // Account ownership is proven here, before onJoin, exactly as WalkRoom verifies
+ // its play pass. The game profile account key (playerId) — which loads gold,
+ // bank, inventory, cosmetics and drives the single-session eviction channel —
+ // MUST come only from this verified binding, never from a raw `options.pid`. An
+ // unsigned pid set to a victim's wallet/guest id would otherwise hijack their
+ // whole saved profile and grief them off their eviction channel.
+ //
+ // Two proof shapes:
+ // • Wallet account — proven by a play pass (ed25519-over-nonce minted by
+ // /api/play/verify, sealed with the shared secret). The wallet rides inside
+ // the signed pass; we bind it as the account. A wallet-shaped pid presented
+ // WITHOUT a matching pass is rejected — never trusted on assertion alone.
+ // • Guest account — no wallet to sign, so the server mints the identity: a
+ // random guest id in an HMAC-signed token. The client replays the token on
+ // reconnect; we verify it and bind the sealed id. A guest with no (or an
+ // invalid) token is issued a brand-new id + token here, so a guest id can
+ // only ever be used by the socket that holds its signed token.
+ // The bound account + (for new guests) the fresh token are stashed on
+ // client.userData/auth so onJoin derives playerId from the verified value and
+ // hands any new guest token back to the client to persist.
+ static onAuth(client, options) {
+ // Portal handoff (trusted server-to-server seat reservation). The source room
+ // already verified this account and minted a single-use, HMAC-signed transfer
+ // carrying it; the reservation can't ride a play pass / guest token, so the
+ // account is re-bound from the signed transfer here. Consume the nonce NOW (the
+ // earliest trusted point) so a captured transfer can't be replayed to bind a
+ // victim's account or restore a carry — and stash the verified result so onJoin
+ // applies the carry without re-consuming.
+ const transfer = options?.transfer ? verifyTransfer(options.transfer) : null;
+ if (transfer && consumeTransferNonce(transfer.jti)) {
+ client.userData = {
+ ...(client.userData || {}),
+ account: transfer.account,
+ accountKind: isWalletAddress(transfer.account) ? 'wallet' : 'guest',
+ transfer,
+ };
+ return true;
+ }
+
+ const pass = verifyPlayPass(options?.playPass);
+ if (pass) {
+ // A valid play pass: bind its verified wallet as the account. When the gate
+ // is pinned, also enforce the mint + balance floor so an off-floor wallet
+ // can't ride a pass minted for a different token. Throw (not return false)
+ // so a refusal reaches the client as a `play_pass`-prefixed error.
+ if (PLAY_GATE_MINT) {
+ if (pass.mint !== PLAY_GATE_MINT) throw new Error('play_pass_mismatch');
+ if (!(typeof pass.balance === 'number' && pass.balance >= PLAY_GATE_MIN)) {
+ throw new Error('play_pass_required');
+ }
+ }
+ client.userData = {
+ ...(client.userData || {}),
+ account: pass.wallet,
+ accountKind: 'wallet',
+ playBalance: pass.balance,
+ playExp: pass.exp,
+ };
+ return true;
+ }
+
+ // No play pass. The platform gate, when pinned, requires one for entry.
+ if (PLAY_GATE_MINT) throw new Error('play_pass_required');
+
+ // A wallet-shaped pid with no proving pass is a takeover attempt — reject it
+ // outright rather than load that wallet's profile on a bare assertion.
+ if (isWalletAddress(clean(options?.pid, 80))) throw new Error('play_pass_required');
+
+ // Guest path: trust only a server-signed guest token. A valid one re-binds the
+ // returning guest's id; anything else (missing/forged/expired) gets a brand-new
+ // server-minted id so a guest id can never be claimed by another socket.
+ let gid = verifyGuestToken(options?.guestToken);
+ let issuedToken = null;
+ if (!gid) {
+ gid = newGuestId();
+ issuedToken = signGuestToken(gid);
+ }
+ client.userData = {
+ ...(client.userData || {}),
+ account: gid,
+ accountKind: 'guest',
+ ...(issuedToken ? { newGuestToken: issuedToken } : {}),
+ };
+ return true;
+ }
+
constructor() {
super();
this.maxClients = MAX_CLIENTS_PER_ROOM;
@@ -305,6 +407,24 @@ export class GameRoom extends Room {
this.onMessage('questTurnIn', (c, p) => this._handleTurnIn(c, p));
this.onMessage('chat', (c, p) => this._handleChat(c, p));
+ // Re-check the token gate the same way WalkRoom does: the game server has no
+ // RPC, so "still holding the floor" is re-proven by the client minting a fresh
+ // play pass before the current one's TTL lapses and reconnecting (onAuth
+ // re-validates). To actively evict a wallet that fell below the floor
+ // mid-session, sweep once a minute and drop any client whose bound pass has
+ // expired without a refresh. Only runs when the gate is pinned.
+ if (PLAY_GATE_MINT) {
+ this.clock.setInterval(() => {
+ const nowS = Date.now() / 1000;
+ for (const client of this.clients) {
+ const exp = client.userData?.playExp;
+ if (typeof exp === 'number' && exp < nowS) {
+ try { client.leave(4002, 'play_pass_required'); } catch {}
+ }
+ }
+ }, 60_000);
+ }
+
this.setSimulationInterval(() => this._tick(), SIM_TICK_MS);
}
@@ -341,11 +461,19 @@ export class GameRoom extends Room {
async onJoin(client, options) {
const name = clean(options?.name, 24) || `guest-${client.sessionId.slice(0, 4)}`;
- // Stable account key: the wallet address / persistent guest id the client
- // sends (Task 16), falling back to the ephemeral session id when absent.
- // Tutorial completion, daily assignment, progress, and badges are keyed to
- // it so they survive a disconnect/reconnect.
- const playerId = clean(options?.pid, 80) || client.sessionId;
+ // Stable account key: the VERIFIED account bound in onAuth — a play-pass wallet
+ // or a server-signed guest id — never a raw `options.pid`. Tutorial completion,
+ // daily assignment, progress, badges, the bank, and the single-session eviction
+ // channel all key off it, so trusting it only when proven is what stops another
+ // client from loading or evicting a victim's profile. onAuth always populates
+ // account; the session id is a last-resort fallback that can never collide.
+ const playerId = clean(client.userData?.account, 80) || client.sessionId;
+ // Hand a freshly-minted guest token back to the client so it can persist it and
+ // re-present it on reconnect to keep this guest's progression. Sent before any
+ // other state so the client stores it even if it disconnects early.
+ if (client.userData?.newGuestToken) {
+ try { client.send('guestToken', { token: client.userData.newGuestToken, account: playerId }); } catch {}
+ }
const now = Date.now();
// Single active session per account (Task 16 integrity rule, enforced across
// world instances for Task 23): announce this login on the account's eviction
@@ -422,9 +550,12 @@ export class GameRoom extends Room {
// Arriving through a portal: a signed transfer restores the haul the player
// carried out of the previous realm and lands them at the portal's exit tile
- // instead of the realm's default spawn. An unsigned/expired/tampered token is
- // ignored — the player simply spawns fresh, never gaining forged items.
- const transfer = options?.transfer ? verifyTransfer(options.transfer) : null;
+ // instead of the realm's default spawn. The transfer was verified AND its
+ // single-use nonce consumed in onAuth (which also bound the account from it),
+ // so we read the already-validated result off client.userData here — a replayed
+ // transfer never reaches this point with a fresh nonce, so it can't re-apply a
+ // carry and dupe gold/items the player has since banked or spent.
+ const transfer = client.userData?.transfer || null;
if (transfer && transfer.to === this.realm.name) {
if (transfer.carry) this._applyCarry(p, this.priv.get(client.sessionId), transfer.carry);
const dtx = transfer.tx | 0, dty = transfer.ty | 0;
@@ -690,12 +821,11 @@ export class GameRoom extends Room {
const tx = Number.isFinite(portal.toTx) ? portal.toTx : destRealm.spawn.tx;
const ty = Number.isFinite(portal.toTy) ? portal.toTy : destRealm.spawn.ty;
priv.transferring = true;
- const token = signTransfer({ to: dest, tx, ty, carry: this._snapshotCarry(client, p) });
+ const token = signTransfer({ to: dest, tx, ty, carry: this._snapshotCarry(client, p), account: priv.playerId });
try {
const reservation = await matchMaker.joinOrCreate(`game_${dest}`, {
name: p.name,
avatar: p.cosmetic,
- pid: priv.playerId,
transfer: token,
});
// Persist quests now so the destination room (which reloads them by pid)
diff --git a/multiplayer/src/rooms/realm-transfer.js b/multiplayer/src/rooms/realm-transfer.js
index c39cddc53..991d25eb0 100644
--- a/multiplayer/src/rooms/realm-transfer.js
+++ b/multiplayer/src/rooms/realm-transfer.js
@@ -55,9 +55,46 @@ function safeEqual(a, b) {
return crypto.timingSafeEqual(ba, bb);
}
+// Single-use guard. A transfer token seals a full carry snapshot (gold, items,
+// bank, skills) and is otherwise replayable for its whole TTL — letting a player
+// transfer at high gold, spend/bank it, then replay the same token to restore the
+// snapshot and dupe the difference. So every token carries a random nonce (`jti`)
+// and the destination room consumes it on arrival; a nonce seen twice is rejected.
+// This shared map is the single source of truth across every room in the process
+// (a portal handoff lands in a different GameRoom instance), mirroring the
+// spin-wheel/marketplace replay guards. Entries are swept after a TTL beyond the
+// token window so the set never grows unbounded. (Horizontal scale would back this
+// with the same Redis the presence/profile layers use; the interface is unchanged.)
+const _consumedNonces = new Map(); // jti -> consumedAt (ms)
+const NONCE_TTL_MS = (TTL_SECONDS + 30) * 1000; // cover the token window + clock skew
+
+/**
+ * Atomically consume a transfer nonce. Returns true the first time a given nonce
+ * is presented (the carry may be applied) and false on every subsequent attempt
+ * within the TTL (a replay — the carry must be ignored). Synchronous, so two joins
+ * racing the same token can't both win. A falsy nonce is rejected outright so an
+ * old token minted before nonces existed can never apply a carry.
+ * @param {unknown} jti
+ * @returns {boolean}
+ */
+export function consumeTransferNonce(jti) {
+ if (typeof jti !== 'string' || !jti) return false;
+ const now = Date.now();
+ const prev = _consumedNonces.get(jti);
+ if (prev !== undefined && now - prev <= NONCE_TTL_MS) return false; // already used
+ _consumedNonces.set(jti, now);
+ return true;
+}
+
+// Sweep expired nonces so a long-lived process doesn't accumulate them forever.
+setInterval(() => {
+ const now = Date.now();
+ for (const [jti, at] of _consumedNonces) if (now - at > NONCE_TTL_MS) _consumedNonces.delete(jti);
+}, NONCE_TTL_MS).unref?.();
+
/**
* Seal a portal transfer into a signed token.
- * @param {{ to: string, tx: number, ty: number, carry: object }} payload
+ * @param {{ to: string, tx: number, ty: number, carry: object, account: string }} payload
* @returns {string} `${base64url(body)}.${signature}`
*/
export function signTransfer(payload) {
@@ -68,6 +105,15 @@ export function signTransfer(payload) {
tx: payload.tx,
ty: payload.ty,
carry: payload.carry,
+ // The verified account that minted this transfer (a play-pass wallet or a
+ // server-signed guest id). A portal handoff is a trusted server-to-server
+ // seat reservation that carries no play pass / guest token, so the
+ // destination room's onAuth re-binds the account from this signed field —
+ // the only path by which an account is trusted without a fresh pass/token.
+ account: payload.account,
+ // Random single-use id so the destination room can reject a replayed token
+ // even within its TTL. Bound to the signature, so it can't be swapped.
+ jti: crypto.randomBytes(16).toString('hex'),
iat: now,
exp: now + TTL_SECONDS,
}),
@@ -99,6 +145,12 @@ export function verifyTransfer(token) {
if (typeof payload.to !== 'string' || !payload.to) return null;
if (!Number.isFinite(payload.tx) || !Number.isFinite(payload.ty)) return null;
if (!payload.carry || typeof payload.carry !== 'object') return null;
+ // Every legitimate token carries a single-use nonce; its absence means a forged
+ // or pre-nonce token, which must not be honoured.
+ if (typeof payload.jti !== 'string' || !payload.jti) return null;
+ // The minting account rides along so the destination can re-bind it across the
+ // passless handoff; require it so an old/forged token can't land account-less.
+ if (typeof payload.account !== 'string' || !payload.account) return null;
const now = Date.now() / 1000;
if (typeof payload.exp !== 'number' || payload.exp < now) return null;
diff --git a/pages/home.html b/pages/home.html
index f7c8d85c7..f528951f3 100644
--- a/pages/home.html
+++ b/pages/home.html
@@ -960,55 +960,6 @@
}
.pg-copy:hover { color: var(--text); border-color: var(--text-3); }
- /* ── PRICING TEASER ──────────────────────────────────────── */
- .pricing-grid {
- display: grid; grid-template-columns: repeat(3, 1fr); gap: 1px;
- background: var(--hairline); border: 1px solid var(--hairline);
- border-radius: 14px; overflow: hidden;
- }
- @media (max-width: 860px) { .pricing-grid { grid-template-columns: 1fr; } }
- .pricing-card {
- background: var(--surface-0); padding: 40px 32px;
- display: flex; flex-direction: column; gap: 0;
- transition: background 0.15s; position: relative;
- }
- .pricing-card:hover { background: var(--surface-1); }
- .pricing-card.featured {
- background: var(--surface-1);
- box-shadow: inset 0 0 0 1px rgba(255,255,255,0.25);
- }
- .pricing-badge {
- position: absolute; top: 16px; right: 16px;
- font-family: var(--font-mono); font-size: 10px;
- letter-spacing: 0.15em; text-transform: uppercase;
- background: rgba(255,255,255,0.15); color: #cccccc;
- padding: 3px 9px; border-radius: 99px;
- }
- .pricing-tier {
- font-family: var(--font-mono); font-size: 11px;
- letter-spacing: 0.18em; text-transform: uppercase;
- color: var(--text-3); margin-bottom: 12px;
- }
- .pricing-price {
- font-family: var(--font-display); font-size: 40px;
- font-weight: 600; letter-spacing: -0.03em;
- color: var(--text); margin: 0 0 4px; line-height: 1;
- }
- .pricing-price sub { font-size: 16px; font-weight: 400; color: var(--text-3); }
- .pricing-cycle { font-size: 13px; color: var(--text-3); margin-bottom: 28px; }
- .pricing-feats {
- list-style: none; padding: 0; margin: 0 0 32px; flex: 1;
- display: flex; flex-direction: column; gap: 10px;
- }
- .pricing-feats li {
- display: flex; align-items: flex-start; gap: 10px;
- font-size: 14px; color: var(--text-2); line-height: 1.45;
- }
- .pricing-feats li::before {
- content: "✓"; color: var(--green); font-weight: 700; flex-shrink: 0;
- font-size: 12px; margin-top: 1px;
- }
-
/* ── BOTTOM CTA ──────────────────────────────────────────── */
.cta-card {
padding: 80px 64px; border: 1px solid var(--hairline-strong);
@@ -1026,7 +977,7 @@
footer { border-top: 1px solid var(--hairline); padding: 56px 0; }
.foot-cols {
display: grid;
- grid-template-columns: repeat(5, 1fr);
+ grid-template-columns: repeat(6, 1fr);
gap: 32px; margin-bottom: 48px;
padding-bottom: 40px; border-bottom: 1px solid var(--hairline);
}
@@ -1252,30 +1203,7 @@
.btn.primary:active { background: #e0e0e0; }
.door-screenshot img[src] { transition: transform 0.4s cubic-bezier(.2,.7,.3,1); }
.door:hover .door-screenshot img { transform: scale(1.03); }
- .pricing-card { transition: background 0.15s, transform 0.2s; }
- .pricing-card:hover { transform: translateY(-2px); }
- /* ── PRICING AVATAR STAGE ────────────────────────────── */
- .pricing-stage { position: relative; }
- #pricing-canvas {
- position: absolute;
- top: -200px; left: 0; right: 0; bottom: 0;
- pointer-events: none; z-index: 10;
- }
- .pricing-card.is-active {
- background: var(--surface-1);
- box-shadow: inset 0 0 0 1px rgba(255,255,255,0.12);
- transform: translateY(-2px);
- }
- .pricing-hint {
- text-align: center; margin-top: 20px;
- font-family: var(--font-mono); font-size: 11px;
- letter-spacing: 0.12em; text-transform: uppercase;
- color: var(--text-4);
- }
- @media (max-width: 860px) {
- #pricing-canvas, .pricing-hint { display: none; }
- }
@keyframes stat-in { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: translateY(0); } }
.stat-animated { animation: stat-in 0.5s cubic-bezier(.2,.7,.3,1) both; }
@@ -2542,6 +2470,21 @@
<a class="nav-mi" href="/docs#solana" role="menuitem"><span class="nav-mi-t">Solana SDK</span><span class="nav-mi-d">Attestations + agent-kit</span></a>
</div>
</div>
+ <div class="nav-grp">
+ <button type="button" class="nav-trigger" aria-haspopup="true" aria-expanded="false">Integrations<span class="nav-caret" aria-hidden="true">▾</span></button>
+ <div class="nav-pop wide" role="menu" aria-label="Integrations">
+ <div class="nav-pop-note">Live partner showcases — built on real platforms, running end-to-end.</div>
+ <a class="nav-mi" href="/ibm" role="menuitem"><span class="nav-mi-t">IBM watsonx</span><span class="nav-mi-d">Granite-powered 3D agent demos — the hub</span></a>
+ <a class="nav-mi" href="/ibm/galaxy" role="menuitem"><span class="nav-mi-t">Agent Galaxy</span><span class="nav-mi-d">Granite embeddings → 3D semantic agent map</span></a>
+ <a class="nav-mi" href="/ibm/oracle" role="menuitem"><span class="nav-mi-t">Oracle</span><span class="nav-mi-d">Granite TimeSeries forecasting in 3D</span></a>
+ <a class="nav-mi" href="/ibm/twin" role="menuitem"><span class="nav-mi-t">Digital Twin</span><span class="nav-mi-d">Living market replica + projection</span></a>
+ <a class="nav-mi" href="/ibm/trust-layer" role="menuitem"><span class="nav-mi-t">Trust Layer</span><span class="nav-mi-d">Granite Guardian governs wallet agents</span></a>
+ <a class="nav-mi" href="/ibm/identity" role="menuitem"><span class="nav-mi-t">Identity Firewall</span><span class="nav-mi-d">Granite gate against agent impersonation</span></a>
+ <a class="nav-mi" href="/ibm/proof" role="menuitem"><span class="nav-mi-t">Proof</span><span class="nav-mi-d">On-chain AI notary — forecast → govern → Solana</span></a>
+ <a class="nav-mi" href="/ibm/vision" role="menuitem"><span class="nav-mi-t">Vision</span><span class="nav-mi-d">Granite Vision — image → understanding</span></a>
+ <a class="nav-mi" href="/aws" role="menuitem"><span class="nav-mi-t">AWS Marketplace</span><span class="nav-mi-d">three.ws as an AWS Partner listing</span></a>
+ </div>
+ </div>
<div class="nav-grp">
<button type="button" class="nav-trigger" aria-haspopup="true" aria-expanded="false">Labs<span class="nav-pill-sm" aria-hidden="true">Beta</span><span class="nav-caret" aria-hidden="true">▾</span></button>
<div class="nav-pop wide" role="menu" aria-label="Labs">
@@ -2614,6 +2557,14 @@
<a href="/brain">Brain</a>
<a href="/chat">Chat</a>
<a href="/pay">Pay</a>
+ <div class="dr-h">Integrations</div>
+ <a href="/ibm">IBM watsonx</a>
+ <a href="/ibm/galaxy">Agent Galaxy</a>
+ <a href="/ibm/oracle">Oracle</a>
+ <a href="/ibm/twin">Digital Twin</a>
+ <a href="/ibm/trust-layer">Trust Layer</a>
+ <a href="/ibm/proof">Proof</a>
+ <a href="/aws">AWS Marketplace</a>
<div class="dr-h">Labs · Beta</div>
<a href="/launchpad">Launchpad Studio</a>
<a href="/lipsync">Lipsync</a>
@@ -3870,69 +3821,11 @@
</div>
</section>
-<!-- ── PRICING ────────────────────────────────────────────────────── -->
-<section class="block">
- <div class="wrap-1280">
- <div class="block-head reveal">
- <p class="block-eyebrow"><span class="num">09</span>Pricing</p>
- <h2 class="block-h">Free to start. <em>Scale when you do.</em></h2>
- <p class="block-lede">Open beta is free with no limits. Pro and Enterprise plans unlock higher rate limits, custom domains, and dedicated support.</p>
- </div>
- <div class="pricing-stage" id="pricing-stage">
- <canvas id="pricing-canvas"></canvas>
- <div class="pricing-grid reveal reveal-d1">
- <div class="pricing-card" id="tier-beta" data-tier="beta">
- <div class="pricing-tier">Beta</div>
- <div class="pricing-price">$0<sub>/mo</sub></div>
- <div class="pricing-cycle">Free during open beta</div>
- <ul class="pricing-feats">
- <li>Unlimited agents</li>
- <li>Unlimited embeds</li>
- <li>200+ animation clips</li>
- <li>x402 payments (0% fee)</li>
- <li>Community support</li>
- </ul>
- <a class="btn" href="/create" data-tier-cta="beta">Start for free</a>
- </div>
- <div class="pricing-card featured" id="tier-pro" data-tier="pro">
- <span class="pricing-badge">Most popular</span>
- <div class="pricing-tier">Pro</div>
- <div class="pricing-price">$49<sub>/mo</sub></div>
- <div class="pricing-cycle">After open beta · billed monthly</div>
- <ul class="pricing-feats">
- <li>Everything in Beta</li>
- <li>Custom domain embeds</li>
- <li>Priority CDN &amp; GPU rendering</li>
- <li>Advanced analytics dashboard</li>
- <li>Priority support &amp; SLA</li>
- </ul>
- <a class="btn primary" href="/pricing" data-tier-cta="pro">See full pricing</a>
- </div>
- <div class="pricing-card" id="tier-enterprise" data-tier="enterprise">
- <div class="pricing-tier">Enterprise</div>
- <div class="pricing-price" style="font-size:28px;margin-top:6px;">Custom</div>
- <div class="pricing-cycle">Volume · white-label · SLA</div>
- <ul class="pricing-feats">
- <li>Everything in Pro</li>
- <li>White-label embed &amp; API</li>
- <li>Dedicated infrastructure</li>
- <li>Custom integrations</li>
- <li>Dedicated solutions engineer</li>
- </ul>
- <a class="btn" href="mailto:[email protected]" data-tier-cta="enterprise">Contact us</a>
- </div>
- </div>
- <p class="pricing-hint">Hover a tier — she walks over</p>
- </div>
- </div>
-</section>
-
-
<!-- ── AVATAR DROP ─────────────────────────────────────────────────── -->
<section class="block body-drop" id="body-drop">
<div class="wrap-1280">
<div class="body-drop-content reveal">
- <p class="block-eyebrow"><span class="num">10</span>See it in action</p>
+ <p class="block-eyebrow"><span class="num">09</span>See it in action</p>
<h2 class="body-drop-title">
<span id="drop-sit-line">Your agent</span><br/>
lives <em>here.</em>
@@ -4000,6 +3893,13 @@
<a href="/artifact">Artifact Viewer</a>
<a href="/sitemap">Sitemap</a>
</div>
+ <div class="foot-col">
+ <div class="foot-col-h">Integrations</div>
+ <a href="/ibm">IBM watsonx</a>
+ <a href="/ibm/galaxy">Agent Galaxy</a>
+ <a href="/ibm/trust-layer">Trust Layer</a>
+ <a href="/aws">AWS Marketplace</a>
+ </div>
<div class="foot-col">
<div class="foot-col-h">Company</div>
<a href="/blog">Blog</a>
@@ -5283,312 +5183,6 @@
</script>
<script type="module" src="/src/api-playground.js"></script>
<script type="module" src="/dragon-section.js"></script>
-<script type="module">
-import * as THREE from 'three';
-import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
-import { reserveWebGLContext } from '/src/webgl-budget.js';
-
-const canvas = document.getElementById('pricing-canvas');
-const tiers = [...document.querySelectorAll('#pricing-stage .pricing-card')];
-
-if (canvas && tiers.length && window.matchMedia('(min-width: 861px)').matches) {
- // The renderer is created lazily, only when the pricing section nears the
- // viewport. Creating it at page load would make it one of the oldest WebGL
- // contexts on a page full of <agent-3d> avatars, so the browser's "oldest
- // context wins" eviction would kill the pricing avatar first. Deferring it
- // keeps it young; the webglcontextlost/restored handlers let it recover if
- // it is ever evicted anyway.
- let renderer = null;
- let contextLost = false;
- let sectionVisible = false;
- function ensureRenderer() {
- if (renderer) return renderer;
- renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true });
- renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
- renderer.outputColorSpace = THREE.SRGBColorSpace;
- renderer.toneMapping = THREE.ACESFilmicToneMapping;
- renderer.toneMappingExposure = 1.1;
- // Count this context against the shared budget so <agent-3d> grids on the
- // same page leave room for it (see /src/webgl-budget.js).
- reserveWebGLContext();
- canvas.addEventListener('webglcontextlost', (e) => {
- e.preventDefault();
- contextLost = true;
- }, false);
- canvas.addEventListener('webglcontextrestored', () => {
- contextLost = false;
- resize();
- }, false);
- resize();
- return renderer;
- }
-
- const scene = new THREE.Scene();
- const PX_PER_UNIT = 120;
- const camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0.1, 100);
- camera.position.z = 10;
-
- function updateFrustum() {
- const r = canvas.getBoundingClientRect();
- if (!r.width || !r.height) return;
- const hw = r.width / PX_PER_UNIT / 2;
- const hh = r.height / PX_PER_UNIT / 2;
- camera.left = -hw; camera.right = hw;
- camera.top = hh; camera.bottom = -hh;
- camera.updateProjectionMatrix();
- }
-
- const _v3 = new THREE.Vector3();
- function domToWorld(sx, sy) {
- const r = canvas.getBoundingClientRect();
- _v3.set(
- ((sx - r.left) / r.width) * 2 - 1,
- -((sy - r.top) / r.height) * 2 + 1,
- 0
- );
- _v3.unproject(camera);
- return { x: _v3.x, y: _v3.y };
- }
-
- let avatar = null, mixer = null, rootBone = null, baseRootPos = null;
- let phase = 'loading';
- let activeTier = null;
-
- function resize() {
- const r = canvas.getBoundingClientRect();
- if (!r.width || !r.height) return;
- if (renderer) renderer.setSize(r.width, r.height, false);
- updateFrustum();
- if (avatar && activeTier && phase === 'idle') {
- const t = standOnTopOf(activeTier);
- avatar.position.set(t.x, t.y, 0);
- }
- }
- window.addEventListener('resize', resize);
-
- scene.add(new THREE.AmbientLight(0xffffff, 0.6));
- const keyLight = new THREE.DirectionalLight(0xfff4dc, 2.0);
- keyLight.position.set(3, 6, 5); scene.add(keyLight);
- const rimLight = new THREE.DirectionalLight(0x4060ff, 0.6);
- rimLight.position.set(-4, 3, -2); scene.add(rimLight);
- const fillLight = new THREE.DirectionalLight(0xffeedd, 0.4);
- fillLight.position.set(0, 2, 7); scene.add(fillLight);
-
- const actions = {};
- let currentAction = null;
- const FADE_S = 0.3;
-
- function setAnimation(name, opts = {}) {
- const next = actions[name];
- if (!next || next === currentAction) return;
- const loop = opts.loop !== false;
- next.reset();
- next.setLoop(loop ? THREE.LoopRepeat : THREE.LoopOnce, loop ? Infinity : 1);
- next.clampWhenFinished = !!opts.hold;
- if (currentAction) next.crossFadeFrom(currentAction, FADE_S, false).play();
- else next.fadeIn(FADE_S).play();
- currentAction = next;
- }
-
- function standOnTopOf(tierEl) {
- const r = tierEl.getBoundingClientRect();
- return domToWorld(r.left + r.width / 2, r.top);
- }
-
- let walkT = 0, walkStart = null, walkEnd = null, walkDur = 0.85, walkPeakRise = 0;
- let onArrival = null;
- const WALK_SPEED = 5;
- function smoothstep(t) { return t * t * (3 - 2 * t); }
-
- function beginMove(tierEl) {
- if (activeTier) activeTier.classList.remove('is-active');
- activeTier = tierEl;
- activeTier.classList.add('is-active');
- }
-
- function walkToTier(tierEl) {
- if (!avatar || tierEl === activeTier) return;
- beginMove(tierEl);
- phase = 'walking';
- walkT = 0;
- walkStart = { x: avatar.position.x, y: avatar.position.y };
- walkEnd = standOnTopOf(tierEl);
- const dx = Math.abs(walkEnd.x - walkStart.x);
- walkDur = Math.max(0.4, dx / WALK_SPEED);
- const minX = Math.min(walkStart.x, walkEnd.x);
- const maxX = Math.max(walkStart.x, walkEnd.x);
- const baseY = Math.max(walkStart.y, walkEnd.y);
- let peakY = baseY;
- for (const tt of tiers) {
- const tp = standOnTopOf(tt);
- if (tp.x > minX && tp.x < maxX && tp.y > peakY) peakY = tp.y;
- }
- walkPeakRise = peakY - baseY;
- setAnimation('walk', { loop: true });
- const dir = Math.sign(walkEnd.x - walkStart.x) || 0;
- avatar.rotation.y = dir * (Math.PI / 2);
- }
-
- const CTA_REACTION = { beta: 'wave', pro: 'av-celebrating', enterprise: 'av-brag-claps' };
- const CTA_REACTION_MAX_MS = 3500;
-
- function landOnTier() {
- phase = 'idle';
- const snap = standOnTopOf(activeTier);
- avatar.position.set(snap.x, snap.y, 0);
- setAnimation('idle', { loop: true });
- if (onArrival) {
- const cb = onArrival;
- onArrival = null;
- setTimeout(cb, 300);
- }
- }
-
- let hoverTimer = null, hoverPendingTier = null;
- function scheduleMove(tierEl) {
- if (!tierEl) { clearTimeout(hoverTimer); hoverPendingTier = null; return; }
- if (tierEl === activeTier) { clearTimeout(hoverTimer); hoverPendingTier = null; return; }
- if (tierEl === hoverPendingTier) return;
- clearTimeout(hoverTimer);
- hoverPendingTier = tierEl;
- hoverTimer = setTimeout(() => {
- hoverPendingTier = null;
- if (phase === 'walking') setTimeout(() => scheduleMove(tierEl), 200);
- else walkToTier(tierEl);
- }, 120);
- }
-
- function tierAtPoint(cx, cy) {
- for (const t of tiers) {
- const r = t.getBoundingClientRect();
- if (cx >= r.left && cx <= r.right && cy >= r.top && cy <= r.bottom) return t;
- }
- return null;
- }
-
- const grid = document.querySelector('#pricing-stage .pricing-grid');
- grid.addEventListener('mousemove', e => scheduleMove(tierAtPoint(e.clientX, e.clientY)));
- grid.addEventListener('mouseleave', () => scheduleMove(null));
-
- document.querySelectorAll('#pricing-stage [data-tier-cta]').forEach(cta => {
- cta.addEventListener('click', e => {
- if (!avatar) return;
- const tierEl = document.getElementById('tier-' + cta.dataset.tierCta);
- const reactionClip = CTA_REACTION[tierEl?.dataset.tier] || 'wave';
- const fireReaction = () => {
- setAnimation(reactionClip, { loop: false, hold: true });
- const clipDur = actions[reactionClip]?.getClip().duration ?? 2;
- const playMs = Math.min(clipDur * 1000, CTA_REACTION_MAX_MS);
- setTimeout(() => { if (phase === 'idle') setAnimation('idle', { loop: true }); }, playMs);
- };
- if (tierEl === activeTier && phase === 'idle') {
- e.preventDefault();
- fireReaction();
- } else if (tierEl !== activeTier) {
- e.preventDefault();
- onArrival = fireReaction;
- walkToTier(tierEl);
- }
- });
- });
-
- let mouseNx = 0, mouseNy = 0;
- window.addEventListener('mousemove', e => {
- mouseNx = (e.clientX / window.innerWidth) * 2 - 1;
- mouseNy = (e.clientY / window.innerHeight) * 2 - 1;
- });
-
- const ro = new ResizeObserver(() => {
- if (avatar && activeTier && phase === 'idle') {
- const t = standOnTopOf(activeTier);
- avatar.position.set(t.x, t.y, 0);
- }
- });
- tiers.forEach(t => ro.observe(t));
-
- const CLIPS = ['idle', 'walk', 'wave', 'av-celebrating', 'av-brag-claps'];
- let loaded = false;
-
- const io = new IntersectionObserver(entries => {
- if (!entries[0].isIntersecting || loaded) return;
- loaded = true;
- io.disconnect();
- ensureRenderer();
- resize();
-
- new GLTFLoader().load('/avatars/cz.glb', gltf => {
- avatar = gltf.scene;
- avatar.traverse(n => {
- if (!rootBone && /^(Hips|Root|mixamorig:?Hips)$/i.test(n.name)) rootBone = n;
- });
- scene.add(avatar);
- mixer = new THREE.AnimationMixer(avatar);
-
- Promise.all(CLIPS.map(name =>
- fetch('/animations/clips/' + name + '.json').then(r => r.json())
- )).then(jsons => {
- CLIPS.forEach((name, i) => {
- actions[name] = mixer.clipAction(THREE.AnimationClip.parse(jsons[i]));
- });
- if (rootBone) baseRootPos = rootBone.position.clone();
- const _render = renderer.render.bind(renderer);
- renderer.render = (sc, cam) => {
- try { if (rootBone && baseRootPos) rootBone.position.copy(baseRootPos); } catch (_) {}
- _render(sc, cam);
- };
-
- const pro = document.getElementById('tier-pro');
- activeTier = pro;
- pro.classList.add('is-active');
- const start = standOnTopOf(pro);
- avatar.position.set(start.x, start.y, 0);
- setAnimation('idle', { loop: true });
- phase = 'idle';
- });
- });
- }, { threshold: 0, rootMargin: '400px' });
- io.observe(document.getElementById('pricing-stage'));
-
- // Only draw while the section is actually on screen — saves GPU/CPU and
- // avoids rendering onto a context the browser may have evicted.
- const visObs = new IntersectionObserver(entries => {
- sectionVisible = entries.some(e => e.isIntersecting);
- });
- visObs.observe(document.getElementById('pricing-stage'));
-
- const clock = new THREE.Clock();
- (function tick() {
- requestAnimationFrame(tick);
- try {
- const dt = Math.min(clock.getDelta(), 0.05);
- mixer?.update(dt);
-
- if (phase === 'walking' && avatar && walkStart && walkEnd) {
- walkT += dt;
- const p = Math.min(walkT / walkDur, 1);
- const e = smoothstep(p);
- const x = walkStart.x + (walkEnd.x - walkStart.x) * e;
- const arc = walkPeakRise * 4 * p * (1 - p);
- const y = walkStart.y + (walkEnd.y - walkStart.y) * e + arc;
- avatar.position.set(x, y, 0);
- if (p >= 1) landOnTier();
- }
-
- if (phase === 'idle' && avatar) {
- avatar.rotation.y *= 0.9;
- }
-
- const targetCamX = mouseNx * 0.08;
- const targetCamY = -mouseNy * 0.05;
- camera.position.x += (targetCamX - camera.position.x) * 0.04;
- camera.position.y += (targetCamY - camera.position.y) * 0.04;
-
- if (renderer && !contextLost && sectionVisible) renderer.render(scene, camera);
- } catch (_) {}
- })();
-}
-</script>
-
<script>
// ── Interactive Bento Features ─────────────────────────────────────
(function initBentoInteractives() {
diff --git a/pages/pump-dashboard.html b/pages/pump-dashboard.html
index 24f77deca..a4a98d0fb 100644
--- a/pages/pump-dashboard.html
+++ b/pages/pump-dashboard.html
@@ -1426,21 +1426,58 @@
}
}
+ // Incoming events are queued and flushed once per animation frame. A busy
+ // pump.fun feed can emit many events per second; rendering each one
+ // synchronously thrashes layout and starves the main thread (jank, the
+ // cursor stuttering during repaints). Batching coalesces that work.
+ let _feedQueue = [];
+ let _feedFlushRaf = 0;
+
function handleWsEvent(data) {
const type = data.type || data.event || data.kind || 'unknown';
const ts = data.timestamp || Date.now();
- const item = {
+ _feedQueue.push({
type,
time: new Date(typeof ts === 'number' && ts < 1e12 ? ts * 1000 : ts),
data,
- };
- addFeedItem('pd-live-feed', item);
- addFeedItem('pd-dashboard-feed', item);
- state.feedCount++;
+ });
+ if (!_feedFlushRaf) _feedFlushRaf = requestAnimationFrame(flushFeedQueue);
+ }
+
+ function flushFeedQueue() {
+ _feedFlushRaf = 0;
+ const batch = _feedQueue;
+ _feedQueue = [];
+ if (!batch.length) return;
+
+ // Suppress per-row entry animations during bursts — animating dozens of
+ // prepended rows at once is the main source of feed jank.
+ const burst = batch.length > 6;
+ const liveFeed = $('pd-live-feed');
+ const dashFeed = $('pd-dashboard-feed');
+ if (burst) {
+ liveFeed?.classList.add('pd-no-anim');
+ dashFeed?.classList.add('pd-no-anim');
+ }
+
+ for (const item of batch) {
+ addFeedItem('pd-live-feed', item);
+ addFeedItem('pd-dashboard-feed', item);
+ checkAlerts(item);
+ }
+
+ state.feedCount += batch.length;
+ state.activityCount += batch.length;
$('pd-feed-count').textContent = state.feedCount;
- state.activityCount++;
$('pd-activity-count').textContent = state.activityCount;
- checkAlerts(item);
+
+ if (burst) {
+ // Re-enable animations on the next frame, after the burst is painted.
+ requestAnimationFrame(() => {
+ liveFeed?.classList.remove('pd-no-anim');
+ dashFeed?.classList.remove('pd-no-anim');
+ });
+ }
}
function addFeedItem(feedId, item) {
@@ -1499,26 +1536,37 @@
<div class="pd-feed-detail">${escapeHtml(detail)}</div>
</div>
`;
+ // Only the live feed is filterable; hide the new row up front if it
+ // doesn't match the active filter, instead of re-scanning all rows.
+ if (feedId === 'pd-live-feed' && !rowMatchesFilter(item.type, state.currentFilter)) {
+ div.style.display = 'none';
+ }
+
feed.prepend(div);
while (feed.children.length > 500) feed.lastElementChild.remove();
+ }
- if (feedId === 'pd-live-feed') applyFeedFilter();
+ const FEED_FILTER_GROUPS = {
+ launch: ['launch', 'create', 'mint'],
+ trade: ['trade', 'buy', 'sell'],
+ whale: ['whale', 'whale_trade'],
+ graduation: ['graduation', 'complete'],
+ claim: ['claim', 'fee_claim'],
+ };
+
+ function rowMatchesFilter(type, filter) {
+ if (filter === 'all') return true;
+ const matches = FEED_FILTER_GROUPS[filter] || [filter];
+ return matches.includes(type || '');
}
+ // Called only when the user changes the active filter — a full rescan is
+ // correct here, but it no longer runs on every incoming feed event.
function applyFeedFilter() {
const feed = $('pd-live-feed');
if (!feed) return;
feed.querySelectorAll('.pd-feed-item').forEach((item) => {
- if (state.currentFilter === 'all') { item.style.display = ''; return; }
- const type = item.dataset.type || '';
- const matches = ({
- launch: ['launch', 'create', 'mint'],
- trade: ['trade', 'buy', 'sell'],
- whale: ['whale', 'whale_trade'],
- graduation: ['graduation', 'complete'],
- claim: ['claim', 'fee_claim'],
- }[state.currentFilter]) || [state.currentFilter];
- item.style.display = matches.includes(type) ? '' : 'none';
+ item.style.display = rowMatchesFilter(item.dataset.type, state.currentFilter) ? '' : 'none';
});
}
@@ -2441,13 +2489,25 @@
chart.geom = { x0, x1, y0, y1, tMin, tMax, pMin, pMax };
}
+ // mousemove fires far faster than the screen refreshes; a full chart
+ // re-render per event pegs the main thread and makes the crosshair cursor
+ // flicker. Coalesce to at most one redraw per animation frame.
+ let _chartHoverRaf = 0;
+ let _chartHoverX = 0;
function onChartMove(e) {
+ const canvas = $('pd-market-chart');
+ const rect = canvas.getBoundingClientRect();
+ _chartHoverX = e.clientX - rect.left;
+ if (!_chartHoverRaf) _chartHoverRaf = requestAnimationFrame(drawChartCrosshair);
+ }
+
+ function drawChartCrosshair() {
+ _chartHoverRaf = 0;
const canvas = $('pd-market-chart');
const tip = $('pd-chart-tooltip');
const g = chart.geom;
if (!g || !chart.candles.length) { tip.style.display = 'none'; return; }
- const rect = canvas.getBoundingClientRect();
- const x = e.clientX - rect.left;
+ const x = _chartHoverX;
if (x < g.x0 || x > g.x1) { tip.style.display = 'none'; return; }
const frac = (x - g.x0) / (g.x1 - g.x0);
const t = g.tMin + frac * (g.tMax - g.tMin);
@@ -2751,7 +2811,10 @@
document.addEventListener('chart:tokenChange', (e) => fetchChartData(e.detail.mint, e.detail.symbol));
const marketCanvas = $('pd-market-chart');
marketCanvas.addEventListener('mousemove', onChartMove);
- marketCanvas.addEventListener('mouseleave', () => { $('pd-chart-tooltip').style.display = 'none'; });
+ marketCanvas.addEventListener('mouseleave', () => {
+ if (_chartHoverRaf) { cancelAnimationFrame(_chartHoverRaf); _chartHoverRaf = 0; }
+ $('pd-chart-tooltip').style.display = 'none';
+ });
let _chartResizeRaf = 0;
new ResizeObserver(() => {
cancelAnimationFrame(_chartResizeRaf);
diff --git a/public/nav.html b/public/nav.html
index bf54aeec1..e33015e96 100644
--- a/public/nav.html
+++ b/public/nav.html
@@ -1,474 +1,157 @@
-<nav class="home-nav" aria-label="Primary">
- <button
- type="button"
- class="nav-burger"
- id="home-nav-burger"
- aria-label="Toggle menu"
- aria-expanded="false"
- aria-controls="home-nav-root"
- >
- <span class="nav-burger-bar"></span>
- <span class="nav-burger-bar"></span>
- <span class="nav-burger-bar"></span>
- </button>
- <ul class="nav-root" id="home-nav-root" role="menubar">
- <li class="nav-item nav-has-menu" role="none">
- <button
- type="button"
- class="nav-trigger"
- aria-haspopup="true"
- aria-expanded="false"
- role="menuitem"
- >
- Build<span class="nav-caret" aria-hidden="true">▾</span>
+<header class="nav">
+ <div class="nav-inner">
+ <a class="brand" href="/">
+ <img class="brand-mark" src="/three.svg" alt="three.ws" width="24" height="24" />
+ <span>three.ws</span>
+ </a>
+ <nav class="nav-main" aria-label="Primary">
+ <div class="nav-grp">
+ <button type="button" class="nav-trigger" aria-haspopup="true" aria-expanded="false">Build<span class="nav-caret" aria-hidden="true">▾</span></button>
+ <div class="nav-pop" role="menu" aria-label="Build">
+ <a class="nav-mi" href="/create" role="menuitem"><span class="nav-mi-t">Create agent</span><span class="nav-mi-d">Avatar + brain wizard</span></a>
+ <a class="nav-mi" href="/create/selfie" role="menuitem"><span class="nav-mi-t">Selfie to avatar <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">One photo → rigged 3D avatar</span></a>
+ <a class="nav-mi" href="/play" role="menuitem"><span class="nav-mi-t">Worlds <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">Every coin is a 3D world — drop in &amp; hang out</span></a>
+ <a class="nav-mi" href="/app" role="menuitem"><span class="nav-mi-t">Viewer</span><span class="nav-mi-d">Drag-and-drop GLB</span></a>
+ <a class="nav-mi" href="/playground" role="menuitem"><span class="nav-mi-t">Playground</span><span class="nav-mi-d">Viewer + environment + embed code</span></a>
+ <a class="nav-mi" href="/validation" role="menuitem"><span class="nav-mi-t">glTF Validator</span><span class="nav-mi-d">Khronos spec check</span></a>
+ <a class="nav-mi" href="/voice" role="menuitem"><span class="nav-mi-t">Voice Lab <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">Clone your voice · TTS playground</span></a>
+ </div>
+ </div>
+ <div class="nav-grp">
+ <button type="button" class="nav-trigger" aria-haspopup="true" aria-expanded="false">Discover<span class="nav-caret" aria-hidden="true">▾</span></button>
+ <div class="nav-pop" role="menu" aria-label="Discover">
+ <a class="nav-mi" href="/features" role="menuitem"><span class="nav-mi-t">Features</span><span class="nav-mi-d">Everything an agent gets — interactive tour</span></a>
+ <a class="nav-mi" href="/discover" role="menuitem"><span class="nav-mi-t">ERC-8004 Agents</span><span class="nav-mi-d">On-chain agent directory</span></a>
+ <a class="nav-mi" href="/agents" role="menuitem"><span class="nav-mi-t">Agents Index</span><span class="nav-mi-d">Browse every registered agent</span></a>
+ <a class="nav-mi" href="/reputation" role="menuitem"><span class="nav-mi-t">Reputation Explorer</span><span class="nav-mi-d">On-chain scores &amp; attestations</span></a>
+ <a class="nav-mi" href="/marketplace" role="menuitem"><span class="nav-mi-t">Marketplace</span><span class="nav-mi-d">Buy, sell &amp; remix agents</span></a>
+ <a class="nav-mi" href="/gallery" role="menuitem"><span class="nav-mi-t">Avatar Gallery</span><span class="nav-mi-d">Every public 3D avatar</span></a>
+ <a class="nav-mi" href="/skills" role="menuitem"><span class="nav-mi-t">Skills <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">Browse agent tool packs &amp; capabilities</span></a>
+ <a class="nav-mi" href="/bazaar" role="menuitem"><span class="nav-mi-t">x402 Bazaar</span><span class="nav-mi-d">Browse paid APIs and MCP tools</span></a>
+ <a class="nav-mi" href="/community" role="menuitem"><span class="nav-mi-t">Community</span><span class="nav-mi-d">X, GitHub, and ways to get involved</span></a>
+ </div>
+ </div>
+ <div class="nav-grp">
+ <button type="button" class="nav-trigger" aria-haspopup="true" aria-expanded="false">Embed<span class="nav-caret" aria-hidden="true">▾</span></button>
+ <div class="nav-pop" role="menu" aria-label="Embed">
+ <a class="nav-mi" href="/widgets" role="menuitem"><span class="nav-mi-t">Widgets</span><span class="nav-mi-d">Browse + customize embeddable widgets</span></a>
+ <a class="nav-mi" href="/studio" role="menuitem"><span class="nav-mi-t">Widget Studio</span><span class="nav-mi-d">Pick avatar → copy snippet</span></a>
+ <a class="nav-mi" href="/embed.html" role="menuitem"><span class="nav-mi-t">Embed editor</span><span class="nav-mi-d">Tune mode, size, position</span></a>
+ <a class="nav-mi" href="/avatar-sdk" role="menuitem"><span class="nav-mi-t">Avatar SDK <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">npm · web component · React · GLB upload</span></a>
+ <a class="nav-mi" href="/docs#embedding" role="menuitem"><span class="nav-mi-t">Embed docs</span><span class="nav-mi-d">iframe + oEmbed</span></a>
+ <a class="nav-mi" href="/docs#web-component" role="menuitem"><span class="nav-mi-t">&lt;agent-3d&gt;</span><span class="nav-mi-d">Web component reference</span></a>
+ </div>
+ </div>
+ <div class="nav-grp">
+ <button type="button" class="nav-trigger" aria-haspopup="true" aria-expanded="false">Learn<span class="nav-caret" aria-hidden="true">▾</span></button>
+ <div class="nav-pop" role="menu" aria-label="Learn">
+ <a class="nav-mi" href="/docs" role="menuitem"><span class="nav-mi-t">Docs</span><span class="nav-mi-d">SDKs + API reference</span></a>
+ <a class="nav-mi" href="/tutorials" role="menuitem"><span class="nav-mi-t">Tutorials</span><span class="nav-mi-d">Step-by-step guides</span></a>
+ <a class="nav-mi" href="/brain" role="menuitem"><span class="nav-mi-t">Brain <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">Claude · GPT · DeepSeek · Qwen · Llama</span></a>
+ <a class="nav-mi" href="/chat" role="menuitem"><span class="nav-mi-t">Chat</span><span class="nav-mi-d">Talk to your agent</span></a>
+ <a class="nav-mi" href="/pay" role="menuitem"><span class="nav-mi-t">Pay <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">Agent payments — x402 + USDC</span></a>
+ <a class="nav-mi" href="/docs#solana" role="menuitem"><span class="nav-mi-t">Solana SDK</span><span class="nav-mi-d">Attestations + agent-kit</span></a>
+ </div>
+ </div>
+ <div class="nav-grp">
+ <button type="button" class="nav-trigger" aria-haspopup="true" aria-expanded="false">Labs<span class="nav-pill-sm" aria-hidden="true">Beta</span><span class="nav-caret" aria-hidden="true">▾</span></button>
+ <div class="nav-pop wide" role="menu" aria-label="Labs">
+ <div class="nav-pop-note">Experimental features — actively iterating. Expect rough edges.</div>
+ <a class="nav-mi" href="/launchpad" role="menuitem"><span class="nav-mi-t">Launchpad Studio <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">Build a 3D launchpad · token · concierge</span></a>
+ <a class="nav-mi" href="/lipsync" role="menuitem"><span class="nav-mi-t">Lipsync <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">TTS or mic → in-browser viseme → mouth</span></a>
+ <a class="nav-mi" href="/mocap-studio" role="menuitem"><span class="nav-mi-t">Mocap Studio <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">Record face → save clip → replay</span></a>
+ <a class="nav-mi" href="/pose" role="menuitem"><span class="nav-mi-t">Pose Studio</span><span class="nav-mi-d">Click-to-pose mannequin + export PNG</span></a>
+ <a class="nav-mi" href="/overlay-control" role="menuitem"><span class="nav-mi-t">OBS Overlay</span><span class="nav-mi-d">Stream deck — emote hotkeys, mic</span></a>
+ <a class="nav-mi" href="/walk" role="menuitem"><span class="nav-mi-t">Walk <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">Walk your avatar — multiplayer + AR</span></a>
+ <a class="nav-mi" href="/xr" role="menuitem"><span class="nav-mi-t">XR <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">Place your avatar in the real world</span></a>
+ <a class="nav-mi" href="/gmgn" role="menuitem"><span class="nav-mi-t">GMGN Smart Money <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">Agent narrates smart wallet signals</span></a>
+ <a class="nav-mi" href="/pumpfun" role="menuitem"><span class="nav-mi-t">Pump.fun stream</span><span class="nav-mi-d">Mint agent tokens</span></a>
+ <a class="nav-mi" href="/pump-live" role="menuitem"><span class="nav-mi-t">Live launches</span><span class="nav-mi-d">Real-time mint feed</span></a>
+ <a class="nav-mi" href="/pump-dashboard" role="menuitem"><span class="nav-mi-t">Pump Dashboard</span><span class="nav-mi-d">Watches · scanner · quotes</span></a>
+ <a class="nav-mi" href="/pump-visualizer" role="menuitem"><span class="nav-mi-t">Pump Visualizer</span><span class="nav-mi-d">3D view of trending tokens</span></a>
+ <a class="nav-mi" href="/three-live" role="menuitem"><span class="nav-mi-t">$THREE Live <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">Protocol pulse — live trades in 3D</span></a>
+ <a class="nav-mi" href="/strategy-lab" role="menuitem"><span class="nav-mi-t">Strategy Lab</span><span class="nav-mi-d">DCA + subscriptions</span></a>
+ <a class="nav-mi" href="/club" role="menuitem"><span class="nav-mi-t">Pole Club <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">x402 micro-tip demo — $0.001 / dance</span></a>
+ <a class="nav-mi" href="/shopper" role="menuitem"><span class="nav-mi-t">Endpoint Shopper <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">AI chains x402 endpoints to answer a task</span></a>
+ <a class="nav-mi" href="/tutor" role="menuitem"><span class="nav-mi-t">Pay-As-You-Learn Tutor <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">$0.01 per answer in USDC over x402</span></a>
+ <a class="nav-mi" href="/fact-checker" role="menuitem"><span class="nav-mi-t">Fact Checker <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">$0.10 per claim — cited verdict + attestation</span></a>
+ <a class="nav-mi" href="/arbitrage" role="menuitem"><span class="nav-mi-t">x402 Arbitrage <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">Cheapest endpoint per capability, live</span></a>
+ <a class="nav-mi" href="/providers" role="menuitem"><span class="nav-mi-t">x402 Providers <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">Operator profiles for the paid API catalog</span></a>
+ <a class="nav-mi" href="/unstoppable" role="menuitem"><span class="nav-mi-t">Unstoppable Agent <span class="nav-pill-sm">New</span></span><span class="nav-mi-d">Self-funding agent dashboard, live</span></a>
+ <a class="nav-mi" href="/rider" role="menuitem"><span class="nav-mi-t">Rider (VR)</span><span class="nav-mi-d">Open-source VR music visualization</span></a>
+ <a class="nav-mi" href="/forever" role="menuitem"><span class="nav-mi-t">Forever</span><span class="nav-mi-d">Etch a message into Bitcoin — forever</span></a>
+ <a class="nav-mi" href="/eth-vanity" role="menuitem"><span class="nav-mi-t">ETH vanity (CREATE2)</span><span class="nav-mi-d">Grind a smart-contract address</span></a>
+ <a class="nav-mi" href="/vanity-wallet" role="menuitem"><span class="nav-mi-t">Vanity wallet</span><span class="nav-mi-d">Grind a Solana address</span></a>
+ </div>
+ </div>
+ <a href="/pricing">Pricing</a>
+ </nav>
+ <div class="nav-end">
+ <button type="button" class="nav-walk-toggle" id="home-nav-walk" aria-pressed="false" aria-label="Walk with me — toggle the avatar companion" title="Walk with me">
+ <span class="nav-walk-ico" aria-hidden="true">🚶</span><span class="nav-walk-label">Walk</span>
</button>
- <ul class="nav-menu" role="menu" aria-label="Build">
- <li role="none">
- <a href="/create" role="menuitem"
- ><span class="nav-mi-title">Create agent</span
- ><span class="nav-mi-sub">Avatar + brain wizard</span></a
- >
- </li>
- <li role="none">
- <a href="/create/selfie" role="menuitem"
- ><span class="nav-mi-title">Selfie to avatar<span class="nav-pill" aria-hidden="true">NEW</span></span
- ><span class="nav-mi-sub">One photo → rigged 3D avatar</span></a
- >
- </li>
- <li role="none">
- <a href="/worlds" role="menuitem"
- ><span class="nav-mi-title">Worlds<span class="nav-pill" aria-hidden="true">NEW</span></span
- ><span class="nav-mi-sub">Every coin is a 3D world — drop in &amp; hang out, live</span></a
- >
- </li>
- <li role="none">
- <a href="/app" role="menuitem"
- ><span class="nav-mi-title">Viewer</span
- ><span class="nav-mi-sub">Drag-and-drop GLB</span></a
- >
- </li>
- <li role="none">
- <a href="/playground" role="menuitem"
- ><span class="nav-mi-title">Playground</span
- ><span class="nav-mi-sub">Viewer + environment + embed code</span></a
- >
- </li>
- <li role="none">
- <a href="/validation" role="menuitem"
- ><span class="nav-mi-title">glTF Validator</span
- ><span class="nav-mi-sub">Khronos spec check</span></a
- >
- </li>
- <li role="none">
- <a href="/brain" role="menuitem"
- ><span class="nav-mi-title">Brain<span class="nav-pill" aria-hidden="true">NEW</span></span
- ><span class="nav-mi-sub">Claude · GPT · DeepSeek · Qwen · Llama, side-by-side</span></a
- >
- </li>
- <li role="none">
- <a href="/voice" role="menuitem"
- ><span class="nav-mi-title">Voice Lab<span class="nav-pill" aria-hidden="true">NEW</span></span
- ><span class="nav-mi-sub">Clone your voice · TTS playground</span></a
- >
- </li>
- </ul>
- </li>
- <li class="nav-item" role="none">
- <a href="/pay" class="nav-link-with-badge" role="menuitem"
- >Pay<span class="nav-badge">NEW</span></a
- >
- </li>
- <li class="nav-item" role="none">
- <a href="/marketplace" role="menuitem">Marketplace</a>
- </li>
- <li class="nav-item" role="none">
- <a href="/marketplace?tab=skills" class="nav-link-with-badge" role="menuitem"
- >Skills<span class="nav-badge">NEW</span></a
- >
- </li>
- <li class="nav-item nav-has-menu" role="none">
- <button
- type="button"
- class="nav-trigger"
- aria-haspopup="true"
- aria-expanded="false"
- role="menuitem"
- >
- Discover<span class="nav-caret" aria-hidden="true">▾</span>
- </button>
- <ul class="nav-menu" role="menu" aria-label="Discover">
- <li role="none">
- <a href="/agent-economy" role="menuitem"
- ><span class="nav-mi-title">Agent Economy<span class="nav-pill" aria-hidden="true">LIVE</span></span
- ><span class="nav-mi-sub">Watch two 3D agents buy and sell intelligence on-chain — real SOL, real transaction</span></a
- >
- </li>
- <li role="none">
- <a href="/ibm" role="menuitem"
- ><span class="nav-mi-title">IBM watsonx<span class="nav-pill" aria-hidden="true">NEW</span></span
- ><span class="nav-mi-sub">Granite-powered agents — governance, forecasting, vision &amp; on-chain proof</span></a
- >
- </li>
- <li role="none">
- <a href="/features" role="menuitem"
- ><span class="nav-mi-title">Features</span
- ><span class="nav-mi-sub">Everything an agent gets — interactive tour</span></a
- >
- </li>
- <li role="none">
- <a href="/discover" role="menuitem"
- ><span class="nav-mi-title">ERC-8004 Agents</span
- ><span class="nav-mi-sub">On-chain agent directory</span></a
- >
- </li>
- <li role="none">
- <a href="/agents" role="menuitem"
- ><span class="nav-mi-title">Agents Index</span
- ><span class="nav-mi-sub">Browse every registered agent</span></a
- >
- </li>
- <li role="none">
- <a href="/galaxy" role="menuitem"
- ><span class="nav-mi-title">Agent Galaxy<span class="nav-pill" aria-hidden="true">NEW</span></span
- ><span class="nav-mi-sub">3D star-map of agents, mapped by IBM Granite</span></a
- >
- </li>
- <li role="none">
- <a href="/reputation" role="menuitem"
- ><span class="nav-mi-title">Reputation Explorer</span
- ><span class="nav-mi-sub">On-chain scores &amp; attestations</span></a
- >
- </li>
- <li role="none">
- <a href="/gallery" role="menuitem"
- ><span class="nav-mi-title">Avatar Gallery</span
- ><span class="nav-mi-sub">Every public 3D avatar</span></a
- >
- </li>
- <li role="none">
- <a href="/marketplace?tab=skills" role="menuitem"
- ><span class="nav-mi-title">Skills<span class="nav-pill" aria-hidden="true">NEW</span></span
- ><span class="nav-mi-sub">Browse agent tool packs and capabilities</span></a
- >
- </li>
- <li role="none">
- <a href="/bazaar" role="menuitem"
- ><span class="nav-mi-title">x402 Bazaar</span
- ><span class="nav-mi-sub">Browse paid APIs and MCP tools</span></a
- >
- </li>
- <li role="none">
- <a href="/community" role="menuitem"
- ><span class="nav-mi-title">Community</span
- ><span class="nav-mi-sub">X, GitHub, and ways to get involved</span></a
- >
- </li>
- </ul>
- </li>
- <li class="nav-item nav-has-menu" role="none">
- <button
- type="button"
- class="nav-trigger"
- aria-haspopup="true"
- aria-expanded="false"
- role="menuitem"
- >
- Embed<span class="nav-caret" aria-hidden="true">▾</span>
- </button>
- <ul class="nav-menu" role="menu" aria-label="Embed">
- <li role="none">
- <a href="/widgets" role="menuitem"
- ><span class="nav-mi-title">Widgets</span
- ><span class="nav-mi-sub">Browse + customize embeddable widgets</span></a
- >
- </li>
- <li role="none">
- <a href="/studio" role="menuitem"
- ><span class="nav-mi-title">Widget Studio</span
- ><span class="nav-mi-sub">Pick avatar → copy snippet</span></a
- >
- </li>
- <li role="none">
- <a href="/embed.html" role="menuitem"
- ><span class="nav-mi-title">Embed editor</span
- ><span class="nav-mi-sub">Tune mode, size, position</span></a
- >
- </li>
- <li role="none">
- <a href="/docs#embedding" role="menuitem"
- ><span class="nav-mi-title">Embed docs</span
- ><span class="nav-mi-sub">iframe + oEmbed</span></a
- >
- </li>
- <li role="none">
- <a href="/docs#web-component" role="menuitem"
- ><span class="nav-mi-title">&lt;agent-3d&gt;</span
- ><span class="nav-mi-sub">Web component reference</span></a
- >
- </li>
- <li role="none">
- <a href="/avatar-sdk" role="menuitem"
- ><span class="nav-mi-title">Avatar SDK<span class="nav-pill" aria-hidden="true">NEW</span></span
- ><span class="nav-mi-sub">npm · web component · React · GLB upload</span></a
- >
- </li>
- </ul>
- </li>
- <li class="nav-item nav-has-menu" role="none">
- <button
- type="button"
- class="nav-trigger"
- aria-haspopup="true"
- aria-expanded="false"
- role="menuitem"
- >
- Learn<span class="nav-caret" aria-hidden="true">▾</span>
- </button>
- <ul class="nav-menu" role="menu" aria-label="Learn">
- <li role="none">
- <a href="/brain" role="menuitem"
- ><span class="nav-mi-title">Brain<span class="nav-pill" aria-hidden="true">NEW</span></span
- ><span class="nav-mi-sub">Chat with Claude, GPT, Qwen, DeepSeek, Llama</span></a
- >
- </li>
- <li role="none">
- <a href="/chat" role="menuitem"
- ><span class="nav-mi-title">Chat</span
- ><span class="nav-mi-sub">Talk to your agent</span></a
- >
- </li>
- <li role="none">
- <a href="/tutorials" role="menuitem"
- ><span class="nav-mi-title">Tutorials</span
- ><span class="nav-mi-sub">Step-by-step guides</span></a
- >
- </li>
- <li role="none">
- <a href="/docs" role="menuitem"
- ><span class="nav-mi-title">Docs</span
- ><span class="nav-mi-sub">SDKs + API reference</span></a
- >
- </li>
- <li role="none">
- <a href="/docs#solana" role="menuitem"
- ><span class="nav-mi-title">Solana SDK</span
- ><span class="nav-mi-sub">Attestations + agent-kit</span></a
- >
- </li>
- </ul>
- </li>
- <li class="nav-item nav-has-menu" id="home-nav-labs-li" role="none">
- <button
- type="button"
- class="nav-trigger"
- aria-haspopup="true"
- aria-expanded="false"
- role="menuitem"
- >
- Labs<span class="nav-pill" aria-hidden="true">BETA</span
- ><span class="nav-caret" aria-hidden="true">▾</span>
- </button>
- <ul class="nav-menu nav-menu-labs" role="menu" aria-label="Labs">
- <li class="nav-menu-note" role="none" aria-hidden="true">
- Experimental features — actively iterating. Expect rough edges.
- </li>
- <li role="none">
- <a href="/voice" role="menuitem"
- ><span class="nav-mi-title">Voice Lab<span class="nav-pill" aria-hidden="true">NEW</span></span
- ><span class="nav-mi-sub">Clone your voice · TTS playground · assign to avatars</span></a
- >
- </li>
- <li role="none">
- <a href="/launchpad" role="menuitem"
- ><span class="nav-mi-title">Launchpad Studio<span class="nav-pill" aria-hidden="true">NEW</span></span
- ><span class="nav-mi-sub">Build a 3D launchpad · token · concierge · showroom</span></a
- >
- </li>
- <li role="none">
- <a href="/brain" role="menuitem"
- ><span class="nav-mi-title">Brain<span class="nav-pill" aria-hidden="true">NEW</span></span
- ><span class="nav-mi-sub">Claude · GPT · DeepSeek · Qwen · Llama, side-by-side</span></a
- >
- </li>
- <li role="none">
- <a href="/lipsync" role="menuitem"
- ><span class="nav-mi-title">Lipsync<span class="nav-pill" aria-hidden="true">NEW</span></span
- ><span class="nav-mi-sub">TTS or mic → in-browser viseme → avatar mouth</span></a
- >
- </li>
- <li role="none">
- <a href="/mocap-studio" role="menuitem"
- ><span class="nav-mi-title">Mocap Studio<span class="nav-pill" aria-hidden="true">NEW</span></span
- ><span class="nav-mi-sub">Record face → save clip → replay on any avatar</span></a
- >
- </li>
- <li role="none">
- <a href="/pose" role="menuitem"
- ><span class="nav-mi-title">Pose Studio</span
- ><span class="nav-mi-sub">Click-to-pose 3D mannequin + export PNG</span></a
- >
- </li>
- <li role="none">
- <a href="/overlay-control" role="menuitem"
- ><span class="nav-mi-title">OBS Overlay</span
- ><span class="nav-mi-sub">Stream deck — emote hotkeys, mic, expressions</span></a
- >
- </li>
- <li role="none">
- <a href="/walk" role="menuitem"
- ><span class="nav-mi-title">Walk<span class="nav-pill" aria-hidden="true">NEW</span></span
- ><span class="nav-mi-sub">Walk your avatar — multiplayer + AR</span></a
- >
- </li>
- <li role="none">
- <a href="/xr" role="menuitem"
- ><span class="nav-mi-title">XR<span class="nav-pill" aria-hidden="true">NEW</span></span
- ><span class="nav-mi-sub">Place your avatar in the real world — WebXR &amp; AR</span></a
- >
- </li>
- <li role="none">
- <a href="/gmgn" role="menuitem"
- ><span class="nav-mi-title">GMGN Smart Money<span class="nav-pill" aria-hidden="true">NEW</span></span
- ><span class="nav-mi-sub">3D agent narrates smart wallet signals live</span></a
- >
- </li>
- <li role="none">
- <a href="/pumpfun" role="menuitem"
- ><span class="nav-mi-title">Pump.fun stream</span
- ><span class="nav-mi-sub">Mint agent tokens</span></a
- >
- </li>
- <li role="none">
- <a href="/pump-live" role="menuitem"
- ><span class="nav-mi-title">Live launches</span
- ><span class="nav-mi-sub">Real-time mint feed</span></a
- >
- </li>
- <li role="none">
- <a href="/pump-dashboard" role="menuitem"
- ><span class="nav-mi-title">Pump Dashboard</span
- ><span class="nav-mi-sub">Watches · scanner · quotes</span></a
- >
- </li>
- <li role="none">
- <a href="/pump-visualizer" role="menuitem"
- ><span class="nav-mi-title">Pump Visualizer</span
- ><span class="nav-mi-sub">3D view of trending tokens</span></a
- >
- </li>
- <li role="none">
- <a href="/three-live" role="menuitem"
- ><span class="nav-mi-title">$THREE Live<span class="nav-pill" aria-hidden="true">NEW</span></span
- ><span class="nav-mi-sub">Protocol pulse — live trades in 3D</span></a
- >
- </li>
- <li role="none">
- <a href="/strategy-lab" role="menuitem"
- ><span class="nav-mi-title">Strategy Lab</span
- ><span class="nav-mi-sub">DCA + subscriptions</span></a
- >
- </li>
- <li role="none">
- <a href="/club" role="menuitem"
- ><span class="nav-mi-title">Pole Club<span class="nav-pill" aria-hidden="true">NEW</span></span
- ><span class="nav-mi-sub">x402 micro-tip demo — $0.001 per dance</span></a
- >
- </li>
- <li role="none">
- <a href="/shopper" role="menuitem"
- ><span class="nav-mi-title">Endpoint Shopper<span class="nav-pill" aria-hidden="true">NEW</span></span
- ><span class="nav-mi-sub">AI chains x402 endpoints to answer a task</span></a
- >
- </li>
- <li role="none">
- <a href="/tutor" role="menuitem"
- ><span class="nav-mi-title">Pay-As-You-Learn Tutor<span class="nav-pill" aria-hidden="true">NEW</span></span
- ><span class="nav-mi-sub">$0.01 per answer in USDC over x402</span></a
- >
- </li>
- <li role="none">
- <a href="/fact-checker" role="menuitem"
- ><span class="nav-mi-title">Fact Checker<span class="nav-pill" aria-hidden="true">NEW</span></span
- ><span class="nav-mi-sub">$0.10 per claim — cited verdict + attestation</span></a
- >
- </li>
- <li role="none">
- <a href="/arbitrage" role="menuitem"
- ><span class="nav-mi-title">x402 Arbitrage<span class="nav-pill" aria-hidden="true">NEW</span></span
- ><span class="nav-mi-sub">Cheapest endpoint per capability, live</span></a
- >
- </li>
- <li role="none">
- <a href="/providers" role="menuitem"
- ><span class="nav-mi-title">x402 Providers<span class="nav-pill" aria-hidden="true">NEW</span></span
- ><span class="nav-mi-sub">Operator profiles for the paid API catalog</span></a
- >
- </li>
- <li role="none">
- <a href="/unstoppable" role="menuitem"
- ><span class="nav-mi-title">Unstoppable Agent<span class="nav-pill" aria-hidden="true">NEW</span></span
- ><span class="nav-mi-sub">Self-funding agent dashboard, live</span></a
- >
- </li>
- <li role="none">
- <a href="/rider" role="menuitem"
- ><span class="nav-mi-title">Rider (VR)</span
- ><span class="nav-mi-sub">Open-source VR music visualization</span></a
- >
- </li>
- <li role="none">
- <a href="/forever" role="menuitem"
- ><span class="nav-mi-title">Forever</span
- ><span class="nav-mi-sub">Etch a message into Bitcoin — forever</span></a
- >
- </li>
- <li role="none">
- <a href="/avatar-artifact" role="menuitem"
- ><span class="nav-mi-title">Avatar artifact</span
- ><span class="nav-mi-sub">Standalone Three.js viewer</span></a
- >
- </li>
- <li role="none">
- <a href="/eth-vanity" role="menuitem"
- ><span class="nav-mi-title">ETH vanity (CREATE2)</span
- ><span class="nav-mi-sub">Grind a smart-contract address</span></a
- >
- </li>
- <li role="none">
- <a href="/vanity-wallet" role="menuitem"
- ><span class="nav-mi-title">Vanity wallet</span
- ><span class="nav-mi-sub">Grind a Solana address</span></a
- >
- </li>
- </ul>
- </li>
- <li class="nav-item" role="none">
- <a href="/pricing" role="menuitem">Pricing</a>
- </li>
- <li class="nav-item" id="home-nav-my-agents-li" role="none" hidden>
- <a href="/my-agents" id="home-nav-my-agents" role="menuitem">My Agents</a>
- </li>
- <li class="nav-item" id="home-nav-user-li" role="none" hidden>
- <a href="/dashboard" id="home-nav-user" class="nav-user" role="menuitem"></a>
- </li>
- <li class="nav-item" role="none">
- <button
- type="button"
- class="nav-walk-toggle"
- id="home-nav-walk"
- role="menuitem"
- aria-pressed="false"
- aria-label="Walk with me — toggle the avatar companion"
- title="Walk with me"
- >
- <span class="nav-walk-ico" aria-hidden="true">🚶</span>
- <span class="nav-walk-label">Walk</span>
- </button>
- </li>
- <li class="nav-item" role="none">
- <a href="/login" class="nav-cta" id="home-nav-cta" role="menuitem"
- >Get started</a
- >
- </li>
- </ul>
+ <a href="/my-agents" id="home-nav-my-agents-li" hidden>My Agents</a>
+ <a href="/login" id="home-nav-cta">Sign in</a>
+ <a class="console" href="/dashboard" id="home-nav-user">Console →</a>
+ </div>
+ <button class="nav-toggle" aria-label="Menu" aria-expanded="false" id="nav-toggle">
+ <svg class="open" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"><line x1="2" y1="4" x2="14" y2="4"/><line x1="2" y1="8" x2="14" y2="8"/><line x1="2" y1="12" x2="14" y2="12"/></svg>
+ <svg class="close" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round"><line x1="3" y1="3" x2="13" y2="13"/><line x1="13" y1="3" x2="3" y2="13"/></svg>
+ </button>
+ </div>
+</header>
+<nav class="nav-drawer" id="nav-drawer" aria-label="Mobile" aria-hidden="true">
+ <div class="dr-h">Build</div>
+ <a href="/create">Create agent</a>
+ <a href="/create/selfie">Selfie to avatar</a>
+ <a href="/play">Worlds</a>
+ <a href="/app">Viewer</a>
+ <a href="/playground">Playground</a>
+ <a href="/voice">Voice Lab</a>
+ <div class="dr-h">Discover</div>
+ <a href="/features">Features</a>
+ <a href="/discover">ERC-8004 Agents</a>
+ <a href="/agents">Agents Index</a>
+ <a href="/reputation">Reputation Explorer</a>
+ <a href="/marketplace">Marketplace</a>
+ <a href="/gallery">Avatar Gallery</a>
+ <a href="/skills">Skills</a>
+ <a href="/bazaar">x402 Bazaar</a>
+ <a href="/community">Community</a>
+ <div class="dr-h">Embed</div>
+ <a href="/widgets">Widgets</a>
+ <a href="/studio">Widget Studio</a>
+ <a href="/embed.html">Embed editor</a>
+ <a href="/avatar-sdk">Avatar SDK</a>
+ <div class="dr-h">Learn</div>
+ <a href="/docs">Docs</a>
+ <a href="/tutorials">Tutorials</a>
+ <a href="/brain">Brain</a>
+ <a href="/chat">Chat</a>
+ <a href="/pay">Pay</a>
+ <div class="dr-h">Labs · Beta</div>
+ <a href="/launchpad">Launchpad Studio</a>
+ <a href="/lipsync">Lipsync</a>
+ <a href="/mocap-studio">Mocap Studio</a>
+ <a href="/pose">Pose Studio</a>
+ <a href="/walk">Walk</a>
+ <a href="/xr">XR</a>
+ <a href="/gmgn">GMGN Smart Money</a>
+ <a href="/pumpfun">Pump.fun stream</a>
+ <a href="/three-live">$THREE Live</a>
+ <a href="/club">Pole Club</a>
+ <a href="/shopper">Endpoint Shopper</a>
+ <a href="/tutor">Pay-As-You-Learn Tutor</a>
+ <a href="/fact-checker">Fact Checker</a>
+ <a href="/arbitrage">x402 Arbitrage</a>
+ <a href="/providers">x402 Providers</a>
+ <a href="/unstoppable">Unstoppable Agent</a>
+ <a href="/rider">Rider (VR)</a>
+ <a href="/forever">Forever</a>
+ <div class="dr-h">More</div>
+ <a href="/pricing">Pricing</a>
+ <a href="/my-agents" id="home-nav-drawer-my-agents" hidden>My Agents</a>
+ <div class="sep"></div>
+ <a href="/login" id="home-nav-drawer-cta">Sign in</a>
+ <a class="btn primary" href="/dashboard" style="margin-top:4px;">Console →</a>
</nav>
diff --git a/public/pump-dashboard.css b/public/pump-dashboard.css
index 51e041569..7efb81f98 100644
--- a/public/pump-dashboard.css
+++ b/public/pump-dashboard.css
@@ -549,6 +549,15 @@ html.pump-dashboard-page body {
to { opacity: 1; transform: translateX(0); }
}
+/* During high-rate feed bursts, animating every prepended row at once is the
+ main source of jank — the JS toggles this class to skip the entry animation. */
+.pd-no-anim .pd-feed-item { animation: none; }
+
+/* Respect users who ask the OS to minimize motion. */
+@media (prefers-reduced-motion: reduce) {
+ .pd-feed-item { animation: none; }
+}
+
.pd-feed-item:last-child { border-bottom: none; }
.pd-feed-time {
diff --git a/src/api-playground.js b/src/api-playground.js
index 2dfc805f8..64176df20 100644
--- a/src/api-playground.js
+++ b/src/api-playground.js
@@ -80,12 +80,21 @@
return pgS.key ? pgS.key.value.trim() : '';
}
- // Restore a previously-entered key and persist edits so the playground is
- // usable across reloads without re-pasting credentials.
+ // The API key is a long-lived credential, so never persist it in
+ // localStorage (no expiry, readable by any same-origin script). Keep it in
+ // the in-memory input only, mirrored to sessionStorage so a reload within
+ // the same tab session doesn't force a re-paste; sessionStorage is cleared
+ // when the tab closes. Also purge any key left behind by older builds that
+ // wrote to localStorage.
if (pgS.key) {
- try { pgS.key.value = localStorage.getItem(PG_KEY_STORE) || ''; } catch (_) {}
+ try { localStorage.removeItem(PG_KEY_STORE); } catch (_) {}
+ try { pgS.key.value = sessionStorage.getItem(PG_KEY_STORE) || ''; } catch (_) {}
pgS.key.addEventListener('input', function() {
- try { localStorage.setItem(PG_KEY_STORE, pgGetKey()); } catch (_) {}
+ try {
+ var k = pgGetKey();
+ if (k) sessionStorage.setItem(PG_KEY_STORE, k);
+ else sessionStorage.removeItem(PG_KEY_STORE);
+ } catch (_) {}
pgUpdateCurl();
pgUpdateSdk();
});
diff --git a/src/app.js b/src/app.js
index eba4393b9..59363b3ef 100644
--- a/src/app.js
+++ b/src/app.js
@@ -2173,7 +2173,7 @@ class App {
_flashSaved(avatar) {
const el = document.createElement('div');
el.className = 'save-toast';
- el.innerHTML = `Saved to your account · <a href="/dashboard/#avatars">${avatar.name}</a>`;
+ el.innerHTML = `Saved to your account · <a href="/dashboard/#avatars">${escHtml(avatar.name)}</a>`;
document.body.appendChild(el);
setTimeout(() => el.remove(), 5000);
}
diff --git a/src/brain.js b/src/brain.js
index e4182f1cc..3d4e130c3 100644
--- a/src/brain.js
+++ b/src/brain.js
@@ -1,5 +1,7 @@
// ── brain.js — Persona builder + multi-model playground ─────────────────────
+import { sanitizeUrl } from './shared/sanitize-url.js';
+
// ── Provider registry ────────────────────────────────────────────────────────
const PROVIDERS = [
{ key: 'claude-opus-4-7', label: 'Claude Opus 4.7', short: 'Opus 4.7', network: 'Anthropic', color: '#c8a96e', ctx: '200K', tier: 'Flagship' },
@@ -102,7 +104,7 @@ function inlineMd(s) {
s = s.replace(/\*\*([^*\n]+)\*\*/g, '<strong>$1</strong>');
s = s.replace(/\*([^*\n]+)\*/g, '<em>$1</em>');
s = s.replace(/`([^`\n]+)`/g, '<code class="md-ic">$1</code>');
- s = s.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank" rel="noopener">$1</a>');
+ s = s.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_m, text, url) => `<a href="${sanitizeUrl(url)}" target="_blank" rel="noopener">${text}</a>`);
return s;
}
diff --git a/src/dashboard-next/pages/brain.js b/src/dashboard-next/pages/brain.js
index 1c71bfdc8..3051d04af 100644
--- a/src/dashboard-next/pages/brain.js
+++ b/src/dashboard-next/pages/brain.js
@@ -7,6 +7,7 @@
import { mountShell } from '../shell.js';
import { requireUser, get, put, esc, ApiError } from '../api.js';
+import { sanitizeUrl } from '../../shared/sanitize-url.js';
// ── Provider registry ────────────────────────────────────────────────────
@@ -88,7 +89,7 @@ function inlineMd(s) {
s = s.replace(/\*\*([^*\n]+)\*\*/g, '<strong>$1</strong>');
s = s.replace(/\*([^*\n]+)\*/g, '<em>$1</em>');
s = s.replace(/`([^`\n]+)`/g, '<code class="brn-ic">$1</code>');
- s = s.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank" rel="noopener">$1</a>');
+ s = s.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_m, text, url) => `<a href="${sanitizeUrl(url)}" target="_blank" rel="noopener">${text}</a>`);
return s;
}
diff --git a/src/game/agent-commerce.js b/src/game/agent-commerce.js
index 2804c8a58..f3f421e2b 100644
--- a/src/game/agent-commerce.js
+++ b/src/game/agent-commerce.js
@@ -20,6 +20,7 @@ import {
} from 'three';
import { AnimationManager } from '../animation-manager.js';
import { resolveAvatarUrl, buildAvatar, loadManifest, MANIFEST_URL, CLIP_IDLE } from './avatar-rig.js';
+import { createX402Jumbotron } from './x402-jumbotron.js';
// Where the two agents stand — off to the right of the totem so a player
// entering the town sees them but doesn't spawn on top of them.
@@ -142,6 +143,17 @@ export class AgentCommerce {
this._buildMarker();
this._buildPromptAndPanel();
+ // A big jumbotron behind the agents, facing the plaza, so anyone in the
+ // town can watch the payments land on a screen — not just the player who
+ // walked up and triggered the round. It pulls the real platform-wide x402
+ // feed on its own, then the live local round is pushed into it stage by
+ // stage from _runRound below.
+ this.jumbotron = createX402Jumbotron(scene, {
+ position: [EXCHANGE_CENTER.x, 0, EXCHANGE_CENTER.z - 7],
+ rotationY: 0,
+ width: 12,
+ });
+
// Pull the full clip manifest so gestures can reach any animation (the
// shared emote set is only the first six). Idempotent + cached.
loadManifest();
@@ -290,6 +302,7 @@ export class AgentCommerce {
tick(dt) {
this.seller.tick(dt);
this.buyer.tick(dt);
+ this.jumbotron?.update(dt);
// Billboard the sign to face the camera; breathe the ground ring.
if (this.sign) {
@@ -428,6 +441,7 @@ export class AgentCommerce {
this._gesture(this.seller, 'av-cheering');
this.sessionTotal += 0.01;
+ this.jumbotron?.pushSettlement(settled, intel);
this._renderReceipt(settled, intel);
// Auto-dismiss the panel after the receipt has been read.
this._scheduleHide(9000);
@@ -436,6 +450,7 @@ export class AgentCommerce {
this.seller.say(LINES.seller.error);
this.buyer.say(LINES.buyer.error);
this._gesture(this.seller, 'facepalm');
+ this.jumbotron?.setError(active, err?.message);
this._renderError(active, err?.message);
this._scheduleHide(7000);
} finally {
@@ -445,13 +460,20 @@ export class AgentCommerce {
_scheduleHide(ms) {
clearTimeout(this._hideTimer);
- this._hideTimer = setTimeout(() => this.panel.classList.remove('ac-show'), ms);
+ this._hideTimer = setTimeout(() => {
+ this.panel.classList.remove('ac-show');
+ // Revert the jumbotron's hero back to idle; its payment feed persists.
+ this.jumbotron?.setIdle();
+ }, ms);
}
// Render the panel header + stage stepper. `stage` is the currently-active
// step; everything before it is marked done.
_renderPanel({ topic, stage, amount }) {
if (amount != null) this._amount = amount;
+ // Mirror the live stage onto the in-world jumbotron so the big screen's
+ // stepper animates in lockstep with this HUD panel.
+ this.jumbotron?.setStage({ topic, stage, amount: this._amount });
const activeIdx = STAGES.findIndex((s) => s.id === stage);
const amt = this._amount ? `${(Number(this._amount) / 1e6).toFixed(2)} USDC` : '$0.01 USDC';
const steps = STAGES.map((s, i) => {
@@ -534,6 +556,7 @@ export class AgentCommerce {
clearTimeout(this._hideTimer);
this.seller.dispose();
this.buyer.dispose();
+ this.jumbotron?.dispose(); this.jumbotron = null;
if (this.marker) { this.scene.remove(this.marker); this.marker = null; }
this.prompt?.remove();
this.panel?.remove();
diff --git a/src/game/oracle-ribbon.js b/src/game/oracle-ribbon.js
new file mode 100644
index 000000000..9e2f2eb7f
--- /dev/null
+++ b/src/game/oracle-ribbon.js
@@ -0,0 +1,178 @@
+// Oracle ribbon — the /ibm/oracle 3D forecast line, dropped into the /play world.
+//
+// This is JUST the glowing price-history + Granite forecast line (no grid, no
+// particle field, no HUD, no narrator). It builds as a transparent Three.js
+// Group you can walk around — a floating data sculpture literally standing in
+// the world. Data is real: the live trending pool's candles + IBM Granite
+// TimeSeries forecast from /api/ibm/oracle.
+
+import {
+ BufferGeometry,
+ CatmullRomCurve3,
+ DoubleSide,
+ Float32BufferAttribute,
+ Group,
+ Mesh,
+ MeshBasicMaterial,
+ PlaneGeometry,
+ SphereGeometry,
+ TubeGeometry,
+ Vector3,
+} from 'three';
+
+const IBM = {
+ blueLight: 0x78a9ff,
+ up: 0x42be65,
+ down: 0xfa4d56,
+ flat: 0x8d8d8d,
+ white: 0xf4f4f4,
+};
+const SPAN = 12; // local-units across the time axis (scaled down when mounted)
+const HEIGHT = 5.5; // local-units across the price axis
+
+// The line is pinned to $THREE — the one and only coin. We never surface an
+// arbitrary trending token in the persistent world.
+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+
+function glowTube(points, color, radius, opacity = 1) {
+ const curve = new CatmullRomCurve3(points);
+ const segs = Math.min(600, points.length * 4);
+ const core = new Mesh(
+ new TubeGeometry(curve, segs, radius, 8, false),
+ new MeshBasicMaterial({ color, transparent: true, opacity, depthWrite: false }),
+ );
+ const halo = new Mesh(
+ new TubeGeometry(curve, segs, radius * 2.6, 8, false),
+ new MeshBasicMaterial({ color, transparent: true, opacity: opacity * 0.16, depthWrite: false }),
+ );
+ const grp = new Group();
+ grp.add(core, halo);
+ return grp;
+}
+
+function marker(pos, color, r = 0.13) {
+ const m = new Mesh(new SphereGeometry(r, 20, 20), new MeshBasicMaterial({ color }));
+ m.position.copy(pos);
+ m.add(
+ new Mesh(
+ new SphereGeometry(r * 2.4, 20, 20),
+ new MeshBasicMaterial({ color, transparent: true, opacity: 0.18, depthWrite: false }),
+ ),
+ );
+ return m;
+}
+
+function downsample(arr, max) {
+ if (arr.length <= max) return arr;
+ const step = (arr.length - 1) / (max - 1);
+ const out = [];
+ for (let i = 0; i < max; i++) out.push(arr[Math.round(i * step)]);
+ return out;
+}
+
+// Build the line geometry from an /api/ibm/oracle payload into `group`.
+function buildSeries(group, data) {
+ const history = downsample(data.history || [], 160);
+ if (history.length < 2) return;
+ const forecast = data.forecast || [];
+ const all = [...history, ...forecast].map((p) => p.c).filter(Number.isFinite);
+ const min = Math.min(...all);
+ const max = Math.max(...all);
+ const tMin = history[0].t;
+ const tMax = forecast.length ? forecast[forecast.length - 1].t : history[history.length - 1].t;
+ const span = Math.max(1, tMax - tMin);
+ const xOf = (t) => ((t - tMin) / span) * SPAN - SPAN / 2;
+ const yOf = (c) => (max === min ? 0 : ((c - min) / (max - min)) * HEIGHT - HEIGHT / 2);
+
+ const histPts = history.map((p) => new Vector3(xOf(p.t), yOf(p.c), 0));
+ group.add(glowTube(histPts, IBM.blueLight, 0.035));
+
+ // "Now" seam
+ const seam = histPts[histPts.length - 1];
+ const seamLine = new Mesh(
+ new PlaneGeometry(0.012, HEIGHT * 1.05),
+ new MeshBasicMaterial({ color: IBM.white, transparent: true, opacity: 0.28, side: DoubleSide }),
+ );
+ seamLine.position.set(seam.x, 0, 0);
+ group.add(seamLine);
+ group.add(marker(seam, IBM.white, 0.11));
+
+ if (forecast.length && data.stats) {
+ const direction = data.stats.direction;
+ const dirColor = direction === 'up' ? IBM.up : direction === 'down' ? IBM.down : IBM.flat;
+ const fPts = [seam, ...forecast.map((p) => new Vector3(xOf(p.t), yOf(p.c), 0))];
+ group.add(glowTube(fPts, dirColor, 0.045));
+
+ // Uncertainty ribbon: half-band grows 0 → (high-low)/2 across the horizon.
+ const halfMax = Math.max(0.06, (yOf(data.stats.forecastHigh) - yOf(data.stats.forecastLow)) / 2);
+ const verts = [];
+ for (let i = 0; i < fPts.length; i++) {
+ const hb = halfMax * (i / (fPts.length - 1));
+ verts.push(fPts[i].x, fPts[i].y + hb, 0, fPts[i].x, fPts[i].y - hb, 0);
+ }
+ const ribGeo = new BufferGeometry();
+ ribGeo.setAttribute('position', new Float32BufferAttribute(verts, 3));
+ const idx = [];
+ for (let i = 0; i < fPts.length - 1; i++) {
+ const a = i * 2;
+ idx.push(a, a + 1, a + 2, a + 1, a + 3, a + 2);
+ }
+ ribGeo.setIndex(idx);
+ group.add(
+ new Mesh(
+ ribGeo,
+ new MeshBasicMaterial({
+ color: dirColor,
+ transparent: true,
+ opacity: 0.16,
+ side: DoubleSide,
+ depthWrite: false,
+ }),
+ ),
+ );
+ group.add(marker(fPts[fPts.length - 1], dirColor, 0.15));
+ }
+}
+
+// Mount the forecast line into `scene` as a floating sculpture. Returns an
+// object with update(dt) for a gentle idle bob + spin, and dispose().
+export function mountOracleRibbon(scene, opts = {}) {
+ const pivot = new Group();
+ pivot.position.set(opts.x ?? 11, opts.y ?? 3.4, opts.z ?? -5);
+ pivot.scale.setScalar(opts.scale ?? 0.6);
+ scene.add(pivot);
+
+ const series = new Group();
+ pivot.add(series);
+
+ let t = 0;
+ const baseY = pivot.position.y;
+
+ (async () => {
+ try {
+ const list = await fetch('/api/ibm/oracle?list=trending').then((r) => r.json());
+ const pool = list?.pools?.[0]?.pool;
+ if (!pool) return;
+ const data = await fetch(`/api/ibm/oracle?pool=${encodeURIComponent(pool)}`).then((r) => r.json());
+ if (data && data.history) buildSeries(series, data);
+ } catch {
+ /* offline / rate-limited — the world simply renders without the line */
+ }
+ })();
+
+ return {
+ group: pivot,
+ update(dt) {
+ t += dt;
+ pivot.rotation.y += dt * 0.12;
+ pivot.position.y = baseY + Math.sin(t * 0.8) * 0.12;
+ },
+ dispose() {
+ series.traverse((o) => {
+ if (o.geometry) o.geometry.dispose();
+ if (o.material) (Array.isArray(o.material) ? o.material : [o.material]).forEach((m) => m.dispose());
+ });
+ scene.remove(pivot);
+ },
+ };
+}
diff --git a/src/game/x402-jumbotron.js b/src/game/x402-jumbotron.js
new file mode 100644
index 000000000..8a2825208
--- /dev/null
+++ b/src/game/x402-jumbotron.js
@@ -0,0 +1,427 @@
+// x402 Jumbotron — a second big in-world screen for the $THREE town, standing
+// behind the Agent Exchange and dedicated to watching x402 micropayments land.
+//
+// Where the trading jumbotron (chart-screen.js) shows the coin's price tape, this
+// one shows MONEY MOVING: every $0.01 USDC settlement an agent makes on Solana.
+// Two sources feed it, both real:
+// 1. The platform-wide payment feed (/api/x402-pay?feed=1) — recent paid x402
+// calls from anyone, polled on a timer, so the board is alive the moment a
+// player walks up even if they haven't triggered a round themselves.
+// 2. The local ORACLE↔NOVA round driven by agent-commerce.js — pushed in here
+// stage-by-stage so the stepper animates challenge → sign → verify → settle
+// → confirmed in lockstep with the agents' speech bubbles, then drops the
+// finished receipt onto the top of the feed.
+//
+// The face is an HTML canvas wrapped in a CanvasTexture — the same physical-screen
+// pattern as chart-screen.js — so it updates in place with no DOM overlay. Loading,
+// empty, and error states are painted on the screen itself.
+
+import {
+ Group, Mesh, MeshBasicMaterial, MeshStandardMaterial,
+ PlaneGeometry, CylinderGeometry, BoxGeometry,
+ CanvasTexture, SRGBColorSpace, DoubleSide,
+} from 'three';
+
+const FEED_URL = (limit = 12) => `/api/x402-pay?feed=1&limit=${limit}`;
+const POLL_MS = 8000;
+const REDRAW_MS = 100; // ~10fps — smooth pulse/scroll, cheap on the GPU
+const CW = 1280, CH = 720; // 16:9 canvas backing the screen
+const MAX_ROWS = 6; // recent payments shown on the board
+
+// Stage stepper, keyed to the SSE events /api/x402-pay emits — matches the order
+// agent-commerce.js drives the round through.
+const STAGES = [
+ { id: 'challenge', label: '402' },
+ { id: 'built', label: 'Sign' },
+ { id: 'verified', label: 'Verify' },
+ { id: 'settled', label: 'Settle' },
+ { id: 'done', label: 'Confirmed' },
+];
+
+// Monochrome to match the /play client, with a single green accent for money
+// that has actually settled on-chain (mirrors chart-screen.js's palette).
+const COL = {
+ bg0: '#0a0a0c', bg1: '#121216',
+ line: 'rgba(255,255,255,0.06)',
+ text: '#f5f5f6', dim: '#8c8c92', faint: '#5a5a60',
+ good: '#5fd08a', bad: '#e06c75',
+};
+
+const SIG_MARK = { bullish: '▲', bearish: '▼', neutral: '→' };
+
+function fmtUsdc(micro) {
+ const n = Number(micro);
+ if (!isFinite(n) || n <= 0) return '$0.01';
+ return '$' + (n / 1e6).toFixed(2);
+}
+
+function shortAddr(a) {
+ const s = String(a || '');
+ return s.length > 11 ? `${s.slice(0, 4)}…${s.slice(-4)}` : s || '—';
+}
+
+function shortTx(tx) {
+ const s = String(tx || '');
+ return s.length > 14 ? `${s.slice(0, 7)}…${s.slice(-6)}` : s;
+}
+
+function relTime(ms) {
+ const s = Math.max(0, Math.round((Date.now() - ms) / 1000));
+ if (s < 5) return 'now';
+ if (s < 60) return s + 's';
+ const m = Math.round(s / 60);
+ if (m < 60) return m + 'm';
+ const h = Math.round(m / 60);
+ if (h < 24) return h + 'h';
+ return Math.round(h / 24) + 'd';
+}
+
+function roundRect(ctx, x, y, w, h, r) {
+ ctx.beginPath();
+ ctx.moveTo(x + r, y);
+ ctx.arcTo(x + w, y, x + w, y + h, r);
+ ctx.arcTo(x + w, y + h, x, y + h, r);
+ ctx.arcTo(x, y + h, x, y, r);
+ ctx.arcTo(x, y, x + w, y, r);
+ ctx.closePath();
+}
+
+/**
+ * Build the x402 jumbotron and add it to the scene.
+ * @param {THREE.Scene} scene
+ * @param {{position?:[number,number,number], rotationY?:number, width?:number}} [opts]
+ * @returns {{group, mesh, update, dispose, setStage, pushSettlement, setError, setIdle}}
+ */
+export function createX402Jumbotron(scene, opts = {}) {
+ const position = opts.position || [8, 0, -12];
+ const rotationY = opts.rotationY || 0;
+ const width = opts.width || 12;
+ const height = (width * CH) / CW;
+
+ const group = new Group();
+ group.position.set(position[0], position[1], position[2]);
+ group.rotation.y = rotationY;
+
+ const postH = 3.0;
+ const cy = postH + height / 2;
+
+ // Two posts + a base read as a real jumbotron rig (same construction as the
+ // trading screen so the two boards feel like a matched pair on the plaza).
+ const postMat = new MeshStandardMaterial({ color: 0x141417, roughness: 0.5, metalness: 0.6 });
+ const postX = width / 2 - 0.6;
+ for (const sx of [-postX, postX]) {
+ const post = new Mesh(new CylinderGeometry(0.24, 0.3, postH + height, 16), postMat);
+ post.position.set(sx, (postH + height) / 2, -0.15);
+ post.castShadow = true;
+ group.add(post);
+ }
+ const base = new Mesh(new BoxGeometry(width - 0.4, 0.36, 1.4), postMat);
+ base.position.set(0, 0.18, -0.15); base.castShadow = true; base.receiveShadow = true;
+ group.add(base);
+
+ const bezel = new Mesh(
+ new BoxGeometry(width + 0.5, height + 0.5, 0.36),
+ new MeshStandardMaterial({ color: 0x050506, roughness: 0.4, metalness: 0.7 }),
+ );
+ bezel.position.set(0, cy, -0.2);
+ bezel.castShadow = true;
+ group.add(bezel);
+
+ // The live face: canvas → CanvasTexture → unlit plane (glows like a screen).
+ const canvas = document.createElement('canvas');
+ canvas.width = CW; canvas.height = CH;
+ const ctx = canvas.getContext('2d');
+ const tex = new CanvasTexture(canvas);
+ tex.colorSpace = SRGBColorSpace;
+ tex.anisotropy = 4;
+ const panel = new Mesh(
+ new PlaneGeometry(width, height),
+ new MeshBasicMaterial({ map: tex, side: DoubleSide, toneMapped: false }),
+ );
+ panel.position.set(0, cy, 0.01);
+ panel.userData.x402Jumbotron = true;
+ group.add(panel);
+
+ scene.add(group);
+
+ // ── live state ──────────────────────────────────────────────────────────
+ let globalFeed = []; // normalized rows from the platform-wide feed
+ const localFeed = []; // settlements from the in-world ORACLE↔NOVA round
+ const seenTx = new Set(); // dedup across both sources
+ const firstSeen = new Map(); // row key → t when it first appeared (slide-in)
+ let current = null; // { stage, amount, buyer, seller, topic } while a round runs
+ let errorState = null; // { stage, message }
+ let status = 'loading'; // loading | live | empty | error
+ let sessionTotal = 0; // USD paid by the in-world agents this session
+ let pollTimer = null;
+ let destroyed = false;
+ let acc = 0, t = 0;
+
+ function rowKey(r) { return r.tx || `${r.ts}:${r.label}`; }
+
+ async function fetchFeed() {
+ try {
+ const r = await fetch(FEED_URL(12), { headers: { accept: 'application/json' } });
+ if (!r.ok) throw new Error('HTTP ' + r.status);
+ const data = await r.json();
+ const items = Array.isArray(data?.items) ? data.items : [];
+ globalFeed = items
+ .filter((it) => !seenTx.has(it.tx)) // local rows win the dedup
+ .map((it) => ({
+ ts: Number(it.ts) || Date.now(),
+ label: it.tool ? String(it.tool).replace(/_/g, ' ') : 'x402 call',
+ sub: it.argsSummary ? String(it.argsSummary) : 'on-chain settlement',
+ amount: it.amount,
+ tx: it.tx || null,
+ kind: 'global',
+ }));
+ if (status === 'loading' || status === 'error') {
+ status = (globalFeed.length || localFeed.length) ? 'live' : 'empty';
+ }
+ } catch {
+ if (!globalFeed.length && !localFeed.length) status = 'error';
+ }
+ }
+
+ function poll() {
+ if (destroyed) return;
+ clearTimeout(pollTimer);
+ fetchFeed().finally(() => {
+ if (destroyed) return;
+ pollTimer = setTimeout(poll, POLL_MS);
+ });
+ }
+
+ // Merge both sources, newest first, deduped, capped to the board height.
+ function rows() {
+ const merged = [...localFeed, ...globalFeed]
+ .sort((a, b) => b.ts - a.ts)
+ .slice(0, MAX_ROWS);
+ return merged;
+ }
+
+ // ── canvas rendering ──────────────────────────────────────────────────────
+ function draw() {
+ const pulse = 0.55 + 0.45 * Math.sin(t * 4);
+ const padX = 44;
+
+ // Background
+ const bg = ctx.createLinearGradient(0, 0, 0, CH);
+ bg.addColorStop(0, COL.bg1); bg.addColorStop(1, COL.bg0);
+ ctx.fillStyle = bg; ctx.fillRect(0, 0, CW, CH);
+
+ // Header --------------------------------------------------------------
+ ctx.textAlign = 'left'; ctx.textBaseline = 'alphabetic';
+ ctx.fillStyle = COL.text;
+ ctx.font = '800 34px Inter, system-ui, sans-serif';
+ ctx.fillText('AGENT EXCHANGE', padX, 56);
+ ctx.fillStyle = COL.dim;
+ ctx.font = '600 18px Inter, system-ui, sans-serif';
+ ctx.fillText('LIVE x402 MICROPAYMENTS · SOLANA MAINNET', padX, 82);
+
+ // live/idle badge + session total (top-right)
+ const live = !!current && !errorState;
+ const badgeW = 108, badgeH = 38, bx = CW - padX - badgeW, by = 30;
+ roundRect(ctx, bx, by, badgeW, badgeH, 19);
+ ctx.fillStyle = 'rgba(255,255,255,0.05)'; ctx.fill();
+ ctx.strokeStyle = 'rgba(255,255,255,0.12)'; ctx.lineWidth = 1; ctx.stroke();
+ ctx.beginPath();
+ ctx.arc(bx + 24, by + badgeH / 2, 6, 0, Math.PI * 2);
+ ctx.fillStyle = live ? `rgba(95,208,138,${pulse})`
+ : status === 'error' ? COL.bad : COL.faint;
+ ctx.fill();
+ ctx.fillStyle = COL.text; ctx.font = '700 17px Inter, system-ui, sans-serif';
+ ctx.fillText(live ? 'PAYING' : status === 'error' ? 'OFFLINE' : 'LIVE', bx + 42, by + 25);
+ if (sessionTotal > 0) {
+ ctx.fillStyle = COL.dim; ctx.font = '600 15px Inter, system-ui, sans-serif';
+ ctx.textAlign = 'right';
+ ctx.fillText(`$${sessionTotal.toFixed(2)} paid here this session`, CW - padX, by - 8);
+ ctx.textAlign = 'left';
+ }
+
+ // Stage area ----------------------------------------------------------
+ const stageTop = 116, stageBot = 312;
+ ctx.strokeStyle = COL.line; ctx.lineWidth = 1;
+ ctx.beginPath(); ctx.moveTo(padX, stageBot + 10); ctx.lineTo(CW - padX, stageBot + 10); ctx.stroke();
+
+ if (errorState) {
+ ctx.fillStyle = COL.bad; ctx.font = '800 30px Inter, system-ui, sans-serif';
+ ctx.fillText('✕ Payment failed', padX, stageTop + 44);
+ ctx.fillStyle = COL.dim; ctx.font = '600 20px Inter, system-ui, sans-serif';
+ ctx.fillText(errorState.message || 'No funds were moved.', padX, stageTop + 80);
+ drawStepper(stageTop + 120, errorState.stage, true);
+ } else if (current) {
+ // who → who + amount
+ ctx.fillStyle = COL.text; ctx.font = '800 38px Inter, system-ui, sans-serif';
+ const flow = `${current.buyer} → ${current.seller}`;
+ ctx.fillText(flow, padX, stageTop + 42);
+ ctx.fillStyle = COL.good; ctx.font = '800 32px Inter, system-ui, sans-serif';
+ ctx.textAlign = 'right';
+ ctx.fillText(`${fmtUsdc(current.amount)} USDC`, CW - padX, stageTop + 40);
+ ctx.textAlign = 'left';
+ // active stage label
+ const sIdx = STAGES.findIndex((s) => s.id === current.stage);
+ const labels = {
+ challenge: 'Issuing 402 payment challenge…',
+ built: 'Signing the Solana transfer…',
+ verified: 'Verifying payment with the facilitator…',
+ settled: 'Settling on-chain…',
+ done: 'Confirmed on Solana ✓',
+ };
+ ctx.fillStyle = COL.dim; ctx.font = '600 22px Inter, system-ui, sans-serif';
+ ctx.fillText(labels[current.stage] || 'Processing…', padX, stageTop + 84);
+ drawStepper(stageTop + 124, current.stage, false);
+ } else {
+ // idle hero
+ ctx.fillStyle = COL.text; ctx.font = '800 34px Inter, system-ui, sans-serif';
+ ctx.fillText('Two AI agents paying each other, live on Solana', padX, stageTop + 44);
+ ctx.fillStyle = COL.dim; ctx.font = '600 21px Inter, system-ui, sans-serif';
+ ctx.fillText('Walk up to ORACLE & NOVA and press E to trigger a real $0.01 USDC payment.', padX, stageTop + 82);
+ drawStepper(stageTop + 124, null, false);
+ }
+
+ // Feed ----------------------------------------------------------------
+ ctx.fillStyle = COL.faint; ctx.font = '700 16px Inter, system-ui, sans-serif';
+ ctx.fillText('RECENT PAYMENTS', padX, stageBot + 44);
+ ctx.textAlign = 'right';
+ ctx.fillText('solscan.io ↗', CW - padX, stageBot + 44);
+ ctx.textAlign = 'left';
+
+ const list = rows();
+ const feedTop = stageBot + 64, rowH = 56;
+ if (!list.length) {
+ ctx.fillStyle = COL.dim; ctx.font = '600 20px Inter, system-ui, sans-serif';
+ const msg = status === 'error' ? 'Payment feed unavailable — retrying…'
+ : status === 'loading' ? 'Loading recent on-chain payments…'
+ : 'No payments yet — be the first to trigger one.';
+ ctx.fillText(msg, padX, feedTop + 36);
+ } else {
+ list.forEach((r, i) => {
+ const key = rowKey(r);
+ if (!firstSeen.has(key)) firstSeen.set(key, t);
+ const age = t - firstSeen.get(key);
+ const slide = Math.min(1, age / 0.4); // 0→1 slide-in
+ const y = feedTop + i * rowH + (1 - slide) * 14;
+ const alpha = 0.35 + 0.65 * slide;
+ ctx.globalAlpha = alpha;
+
+ // status dot
+ ctx.beginPath(); ctx.arc(padX + 7, y + 18, 6, 0, Math.PI * 2);
+ ctx.fillStyle = r.kind === 'local' ? COL.good : 'rgba(255,255,255,0.45)';
+ ctx.fill();
+
+ // primary label
+ ctx.fillStyle = COL.text; ctx.font = '700 21px Inter, system-ui, sans-serif';
+ ctx.fillText(r.label, padX + 26, y + 16);
+ // sub
+ ctx.fillStyle = COL.dim; ctx.font = '600 16px Inter, system-ui, sans-serif';
+ ctx.fillText(r.sub, padX + 26, y + 38);
+
+ // amount (right)
+ ctx.textAlign = 'right';
+ ctx.fillStyle = COL.good; ctx.font = '800 22px Inter, system-ui, sans-serif';
+ ctx.fillText(`${fmtUsdc(r.amount)} USDC`, CW - padX, y + 16);
+ // tx + time (right, dim)
+ ctx.fillStyle = COL.faint; ctx.font = '600 15px Inter, system-ui, sans-serif';
+ const meta = (r.tx ? shortTx(r.tx) + ' · ' : '') + relTime(r.ts);
+ ctx.fillText(meta, CW - padX, y + 38);
+ ctx.textAlign = 'left';
+
+ ctx.globalAlpha = 1;
+ if (i < list.length - 1) {
+ ctx.strokeStyle = COL.line; ctx.beginPath();
+ ctx.moveTo(padX, y + rowH - 8); ctx.lineTo(CW - padX, y + rowH - 8); ctx.stroke();
+ }
+ });
+ }
+
+ tex.needsUpdate = true;
+ }
+
+ function drawStepper(y, activeStage, isError) {
+ const padX = 44;
+ const activeIdx = activeStage ? STAGES.findIndex((s) => s.id === activeStage) : -1;
+ const colW = (CW - padX * 2) / STAGES.length;
+ const pulse = 0.5 + 0.5 * Math.sin(t * 4);
+ STAGES.forEach((s, i) => {
+ const cx = padX + colW * i;
+ const done = activeIdx >= 0 && i < activeIdx;
+ const isActive = i === activeIdx;
+ const errHere = isError && isActive;
+ // connector dot bar
+ const barW = colW - 24;
+ roundRect(ctx, cx, y, barW, 4, 2);
+ if (errHere) ctx.fillStyle = COL.bad;
+ else if (done) ctx.fillStyle = '#ffffff';
+ else if (isActive) ctx.fillStyle = `rgba(255,255,255,${0.35 + pulse * 0.5})`;
+ else ctx.fillStyle = 'rgba(255,255,255,0.1)';
+ ctx.fill();
+ // label
+ ctx.fillStyle = errHere ? COL.bad
+ : done ? COL.text : isActive ? COL.dim : COL.faint;
+ ctx.font = '700 15px Inter, system-ui, sans-serif';
+ ctx.fillText(s.label.toUpperCase(), cx, y + 26);
+ });
+ }
+
+ // first paint + go live
+ draw();
+ poll();
+
+ return {
+ group,
+ mesh: panel,
+ // Drive the live in-world round (called by agent-commerce.js).
+ setStage({ topic, stage, amount, buyer = 'NOVA', seller = 'ORACLE' } = {}) {
+ errorState = null;
+ current = { topic, stage: stage || 'challenge', amount, buyer, seller };
+ status = 'live';
+ },
+ // A real settlement landed — drop it on the top of the feed.
+ pushSettlement(payment = {}, intel = {}) {
+ const sig = (intel.signal || '').toLowerCase();
+ const mark = SIG_MARK[sig] || '';
+ const topic = (intel.topic || 'sol').toUpperCase();
+ const entry = {
+ ts: Date.now(),
+ label: 'NOVA → ORACLE',
+ sub: `${mark} ${topic} intel${intel.headline ? ' · ' + intel.headline : ''}`.trim(),
+ amount: payment.amount,
+ tx: payment.tx || null,
+ kind: 'local',
+ };
+ if (entry.tx) seenTx.add(entry.tx);
+ localFeed.unshift(entry);
+ if (localFeed.length > MAX_ROWS) localFeed.length = MAX_ROWS;
+ sessionTotal += (Number(payment.amount) / 1e6) || 0.01;
+ status = 'live';
+ },
+ setError(stage, message) {
+ current = null;
+ errorState = { stage: stage || 'settled', message: message || 'No funds were moved.' };
+ },
+ // Revert the hero to idle (feed persists).
+ setIdle() {
+ current = null;
+ errorState = null;
+ },
+ update(dt) {
+ if (destroyed) return;
+ t += dt;
+ acc += dt;
+ if (acc >= REDRAW_MS / 1000) { acc = 0; draw(); }
+ },
+ dispose() {
+ destroyed = true;
+ clearTimeout(pollTimer);
+ scene.remove(group);
+ group.traverse((n) => {
+ if (n.isMesh) {
+ n.geometry?.dispose?.();
+ const mats = Array.isArray(n.material) ? n.material : [n.material];
+ for (const mm of mats) { mm?.map?.dispose?.(); mm?.dispose?.(); }
+ }
+ });
+ },
+ };
+}
diff --git a/src/ibm-galaxy.js b/src/ibm-galaxy.js
index 5388cf7e4..7aa3a639f 100644
--- a/src/ibm-galaxy.js
+++ b/src/ibm-galaxy.js
@@ -50,6 +50,8 @@ let renderer, scene, camera, controls, raycaster, points, geometry, material, st
let aDim, aHi, aSize, positions, colors; // attribute backing arrays
const pointer = new THREE.Vector2(-2, -2);
let pointerDown = null; // {x,y} to distinguish click from drag
+let rafPending = false; // coalesce hover raycasts to one per frame
+const _pointerClient = { x: 0, y: 0 }; // latest cursor position for tooltip placement
const fly = { active: false, camFrom: new THREE.Vector3(), camTo: new THREE.Vector3(), tgtFrom: new THREE.Vector3(), tgtTo: new THREE.Vector3(), t: 0, dur: 1 };
let idleTimer = 0;
const clock = new THREE.Clock();
@@ -250,12 +252,24 @@ function updateClusterLabels() {
function onPointerMove(e) {
pointer.x = (e.clientX / window.innerWidth) * 2 - 1;
pointer.y = -(e.clientY / window.innerHeight) * 2 + 1;
+ _pointerClient.x = e.clientX;
+ _pointerClient.y = e.clientY;
+ // Pointermove fires far more often than the display refreshes; coalesce the
+ // raycast + tooltip work to one pass per frame via a rAF flag.
+ if (!rafPending) {
+ rafPending = true;
+ requestAnimationFrame(updateHover);
+ }
+}
+
+function updateHover() {
+ rafPending = false;
if (!points) return;
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObject(points);
const idx = pickVisible(hits);
setHover(idx);
- if (idx >= 0) positionTooltip(e.clientX, e.clientY, idx);
+ if (idx >= 0) positionTooltip(_pointerClient.x, _pointerClient.y, idx);
}
// Nearest hit that isn't dimmed away by isolation/search.
diff --git a/src/ibm-proof.js b/src/ibm-proof.js
index b243f3af0..a7eb2c3b8 100644
--- a/src/ibm-proof.js
+++ b/src/ibm-proof.js
@@ -414,8 +414,8 @@ async function verifyProof(sig) {
try {
const r = await fetch(attestUrl(`?verify=${encodeURIComponent(sig)}`));
const v = await r.json();
- if (v.error) { out.innerHTML = `<div class="notice warn">${v.message || v.error}</div>`; return; }
- if (!v.found) { out.innerHTML = `<div class="notice warn">Not found on ${v.network || 'chain'}: ${v.reason || 'no such transaction'}.</div>`; return; }
+ if (v.error) { out.innerHTML = `<div class="notice warn">${escapeHtml(v.message || v.error)}</div>`; return; }
+ if (!v.found) { out.innerHTML = `<div class="notice warn">Not found on ${escapeHtml(v.network || 'chain')}: ${escapeHtml(v.reason || 'no such transaction')}.</div>`; return; }
if (!v.isGraniteProof) {
out.innerHTML = `<div class="notice warn">Transaction found, but its memo is not a Granite Proof.${v.memo ? ` Memo: <span style="font-family:var(--mono)">${escapeHtml(v.memo)}</span>` : ''}</div>`;
return;
@@ -425,13 +425,22 @@ async function verifyProof(sig) {
<b>✓ Verified on-chain.</b> A Granite Proof signed by
<span style="font-family:var(--mono)">${(v.signer || '').slice(0, 8)}…</span> at ${when}.<br />
<span style="font-family:var(--mono);font-size:12px;color:var(--muted)">${escapeHtml(v.memo)}</span><br />
- <a href="${v.explorer}" target="_blank" rel="noopener">View on Solscan ↗</a>
+ ${explorerHref(v.explorer) ? `<a href="${escapeHtml(explorerHref(v.explorer))}" target="_blank" rel="noopener">View on Solscan ↗</a>` : ''}
</div>`;
} catch (e) {
out.innerHTML = `<div class="notice warn">Verification failed: ${e?.message || e}</div>`;
}
}
function escapeHtml(s) { return String(s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c])); }
+// Only trust an http(s) explorer URL from the server; anything else (relative,
+// javascript:, data:, malformed) is dropped so it can't become a live href.
+function explorerHref(u) {
+ if (typeof u !== 'string') return '';
+ try {
+ const parsed = new URL(u);
+ return (parsed.protocol === 'https:' || parsed.protocol === 'http:') ? parsed.toString() : '';
+ } catch (_) { return ''; }
+}
function setupVerifyBar() {
const sub = document.querySelector('.feed .sub');
diff --git a/src/live-economy.js b/src/live-economy.js
index 1143d4374..69a6bc634 100644
--- a/src/live-economy.js
+++ b/src/live-economy.js
@@ -331,21 +331,27 @@ export function updateOverlayPositions() {
}
// ── Flash glow ring ───────────────────────────────────────────────────────
-let flashRing = null;
+// A single reusable ring: built once and re-targeted/-tinted per flash so each
+// payment event doesn't leak a RingGeometry + material on the GPU. It stays in
+// the scene and is shown/hidden via visibility + opacity.
+const flashRing = new THREE.Mesh(
+ new THREE.RingGeometry(1.7, 2.0, 32),
+ new THREE.MeshBasicMaterial({ color: 0xffffff, transparent: true, opacity: 0, side: THREE.DoubleSide, depthWrite: false })
+);
+flashRing.rotation.x = -Math.PI / 2;
+flashRing.visible = false;
+scene.add(flashRing);
let flashTimer = 0;
let flashTarget = null;
export function flashAgent(which) {
flashTarget = which === 'A' ? AGENT_A_POS : AGENT_B_POS;
const color = which === 'A' ? 0xa855f7 : 0x4e8cff;
- if (flashRing) scene.remove(flashRing);
- flashRing = new THREE.Mesh(
- new THREE.RingGeometry(1.7, 2.0, 32),
- new THREE.MeshBasicMaterial({ color, transparent: true, opacity: 0.9, side: THREE.DoubleSide, depthWrite: false })
- );
- flashRing.rotation.x = -Math.PI / 2;
+ flashRing.material.color.setHex(color);
+ flashRing.material.opacity = 0.9;
flashRing.position.set(flashTarget.x, 0.06, flashTarget.z);
- scene.add(flashRing);
+ flashRing.scale.set(1, 1, 1);
+ flashRing.visible = true;
flashTimer = 1.0;
}
@@ -380,12 +386,12 @@ let lastTime = performance.now();
updateBeam(dt);
// Flash ring fade
- if (flashTimer > 0 && flashRing) {
+ if (flashTimer > 0) {
flashTimer -= dt * 1.4;
flashRing.material.opacity = Math.max(0, flashTimer);
const s = 1 + (1 - flashTimer) * 0.6;
flashRing.scale.set(s, s, s);
- if (flashTimer <= 0) { scene.remove(flashRing); flashRing = null; }
+ if (flashTimer <= 0) { flashRing.visible = false; flashRing.material.opacity = 0; }
}
renderer.render(scene, camera);
diff --git a/src/shared/sanitize-url.js b/src/shared/sanitize-url.js
new file mode 100644
index 000000000..4abc9c18b
--- /dev/null
+++ b/src/shared/sanitize-url.js
@@ -0,0 +1,16 @@
+// ── sanitize-url.js — shared URL scheme guard for rendered markdown links ───
+//
+// Used wherever LLM/persona/model output is converted to HTML anchors. Blocks
+// script-bearing schemes (javascript:, data:, vbscript:) while allowing the
+// link shapes that legitimate chat output uses: absolute http(s), site-relative
+// paths, in-page anchors, and mailto:. Anything else collapses to '#'.
+
+const SAFE_URL = /^(?:https?:\/\/|\/(?!\/)|#|mailto:)/i;
+const UNSAFE_SCHEME = /^\s*(?:javascript|data|vbscript):/i;
+
+export function sanitizeUrl(url) {
+ if (typeof url !== 'string') return '#';
+ const trimmed = url.trim();
+ if (!trimmed || UNSAFE_SCHEME.test(trimmed)) return '#';
+ return SAFE_URL.test(trimmed) ? trimmed : '#';
+}
diff --git a/src/walk.js b/src/walk.js
index fb5df1f50..eac4646ed 100644
--- a/src/walk.js
+++ b/src/walk.js
@@ -46,6 +46,7 @@ import { clone as cloneSkinnedScene } from 'three/addons/utils/SkeletonUtils.js'
import nipplejs from 'nipplejs';
import { AnimationManager } from './animation-manager.js';
+import { mountOracleRibbon } from './game/oracle-ribbon.js';
import { WalkNet } from './walk-net.js';
import { getPresenceTicket, friendsClient } from './friends.js';
import { FriendsPanel } from './game/friends-panel.js';
@@ -470,6 +471,16 @@ const FP_EYE_HEIGHT_MULT = 0.9; // fraction of avatar height for eye position
const TOPDOWN_HEIGHT = 18;
const TOPDOWN_LOOK_DOWN = new Vector3(0, -1, 0.001); // slight offset so lookAt works
+// Hot-path scratch — computeCameraForMode runs every frame; reuse these instead
+// of allocating fresh Vector3s per call. _RIGHT is the world +X (pitch) axis;
+// upY (the world +Y / yaw axis, defined below) is reused for the yaw rotation.
+const _RIGHT = new Vector3(1, 0, 0);
+const _camPos = new Vector3();
+const _camLook = new Vector3();
+const _camOffset = new Vector3();
+const _camFpForward = new Vector3();
+const _camResult = { pos: _camPos, look: _camLook };
+
// Restore saved camera mode
try {
const saved = localStorage.getItem(CAMERA_MODE_KEY);
@@ -529,12 +540,14 @@ function updateCameraModeIndicator() {
}
// Compute desired camera position/look for each mode
+// Returns a shared scratch { pos, look } — the caller must read/copy the values
+// in the same frame and must not retain the reference across frames.
function computeCameraForMode(mode, avatarPos, avatarHeight) {
- const pos = new Vector3();
- const look = new Vector3();
+ const pos = _camPos;
+ const look = _camLook;
if (mode === 'follow') {
- const offset = CAM_OFFSET.clone().multiplyScalar(camZoom);
- offset.applyAxisAngle(new Vector3(1, 0, 0), -cameraPitch);
+ const offset = _camOffset.copy(CAM_OFFSET).multiplyScalar(camZoom);
+ offset.applyAxisAngle(_RIGHT, -cameraPitch);
offset.applyAxisAngle(upY, cameraYaw);
pos.copy(avatarPos).add(offset);
look.copy(avatarPos).add(CAM_LOOK_OFFSET);
@@ -551,14 +564,14 @@ function computeCameraForMode(mode, avatarPos, avatarHeight) {
const eyeH = (avatarHeight || 1.8) * FP_EYE_HEIGHT_MULT;
pos.set(avatarPos.x, avatarPos.y + eyeH, avatarPos.z);
// Look in the direction the avatar is facing
- const fpForward = new Vector3(Math.sin(avatarYaw), 0, Math.cos(avatarYaw));
+ const fpForward = _camFpForward.set(Math.sin(avatarYaw), 0, Math.cos(avatarYaw));
look.copy(pos).add(fpForward.multiplyScalar(5));
look.y -= 0.15; // slight downward gaze
} else if (mode === 'topdown') {
pos.set(avatarPos.x, avatarPos.y + TOPDOWN_HEIGHT, avatarPos.z + 0.01);
look.copy(avatarPos);
}
- return { pos, look };
+ return _camResult;
}
// Place the camera at its starting pose immediately so frame 0 isn't blank.
@@ -1714,6 +1727,9 @@ function tick() {
// 4b. Animate the coin totem (billboard + bob + ring spin) when present.
if (coinTotem) coinTotem.update(dt);
+ // 4c. Animate the Granite oracle forecast line (idle bob + slow spin).
+ if (oracleRibbon) oracleRibbon.update(dt);
+
// 5. Update speech bubbles (3D -> 2D projection)
updateSpeechBubbles();
@@ -1747,14 +1763,28 @@ let net = null;
let netConnected = false;
let coinTotem = null; // CoinTotem instance when in a coin community world
+// Granite oracle forecast line — the /ibm/oracle 3D price+forecast ribbon,
+// standing in the world as a floating data sculpture you can walk around.
+const oracleRibbon = mountOracleRibbon(scene);
+
// Remote-avatar template cache. Each distinct GLB URL is fetched once and
// reused (via SkeletonUtils.clone) for every player wearing it, so a room full
-// of the same avatar costs a single download. Keyed by URL → Promise<scene>.
+// of the same avatar costs a single download. Keyed by URL → entry. Each entry
+// refcounts the live RemotePlayers cloning it; when a template falls to zero
+// refs it is eligible for eviction. To keep GPU memory bounded in long-lived
+// busy worlds we cap the number of *idle* (zero-ref) templates kept warm and
+// dispose the geometries/textures/materials of any evicted scene. Templates
+// with live refs are never disposed (their clones share geometry/materials).
+// The local avatar is never stored here (short-circuited below), so disposing a
+// remote template can never free buffers still used by the local avatar.
const _remoteAvatarTemplates = new Map();
+const MAX_IDLE_REMOTE_TEMPLATES = 12;
+
function loadRemoteAvatarTemplate(url) {
if (url === resolvedAvatarUrl && avatarTemplate) return Promise.resolve(avatarTemplate);
- if (_remoteAvatarTemplates.has(url)) return _remoteAvatarTemplates.get(url);
- const p = new GLTFLoader().loadAsync(url).then((gltf) => {
+ let entry = _remoteAvatarTemplates.get(url);
+ if (entry) { entry.lastUsed = performance.now(); return entry.promise; }
+ const promise = new GLTFLoader().loadAsync(url).then((gltf) => {
gltf.scene.traverse((n) => {
if (n.isMesh) {
n.castShadow = true;
@@ -1762,10 +1792,63 @@ function loadRemoteAvatarTemplate(url) {
if (n.material && 'envMapIntensity' in n.material) n.material.envMapIntensity = 0.85;
}
});
+ if (entry) entry.scene = gltf.scene;
return gltf.scene;
+ }).catch((err) => {
+ // A failed load must not poison the cache forever — drop the entry so a
+ // later player can retry, and re-throw for the caller's own handling.
+ if (_remoteAvatarTemplates.get(url) === entry) _remoteAvatarTemplates.delete(url);
+ throw err;
+ });
+ entry = { promise, scene: null, refs: 0, lastUsed: performance.now() };
+ _remoteAvatarTemplates.set(url, entry);
+ return promise;
+}
+
+// A RemotePlayer claims/releases the template URL it is currently cloning so the
+// cache knows when a template is unreferenced and safe to evict.
+function acquireRemoteTemplate(url) {
+ const entry = _remoteAvatarTemplates.get(url);
+ if (entry) { entry.refs++; entry.lastUsed = performance.now(); }
+}
+
+function releaseRemoteTemplate(url) {
+ const entry = _remoteAvatarTemplates.get(url);
+ if (!entry) return;
+ if (entry.refs > 0) entry.refs--;
+ entry.lastUsed = performance.now();
+ pruneRemoteTemplates();
+}
+
+// Evict the least-recently-used idle (zero-ref) templates beyond the cap and
+// dispose their GPU resources.
+function pruneRemoteTemplates() {
+ const idle = [];
+ for (const [url, entry] of _remoteAvatarTemplates) {
+ if (entry.refs <= 0 && entry.scene) idle.push([url, entry]);
+ }
+ if (idle.length <= MAX_IDLE_REMOTE_TEMPLATES) return;
+ idle.sort((a, b) => a[1].lastUsed - b[1].lastUsed);
+ const evictCount = idle.length - MAX_IDLE_REMOTE_TEMPLATES;
+ for (let i = 0; i < evictCount; i++) {
+ const [url, entry] = idle[i];
+ _remoteAvatarTemplates.delete(url);
+ disposeTemplateScene(entry.scene);
+ }
+}
+
+function disposeTemplateScene(scene) {
+ if (!scene) return;
+ scene.traverse((n) => {
+ if (n.geometry) n.geometry.dispose();
+ const mats = Array.isArray(n.material) ? n.material : (n.material ? [n.material] : []);
+ for (const mat of mats) {
+ for (const v of Object.values(mat)) {
+ if (v && v.isTexture) v.dispose();
+ }
+ mat.dispose();
+ }
});
- _remoteAvatarTemplates.set(url, p);
- return p;
}
function isLoadableAvatarUrl(url) {
return typeof url === 'string' && url.length > 0 &&
@@ -1801,6 +1884,7 @@ class RemotePlayer {
this._emoting = false;
this._avatarUrl = initial?.avatar || '';
this._avatarLoadToken = 0;
+ this._heldTemplateUrl = null; // remote-template URL this player currently clones
this._root = root;
this.rig = new Group();
@@ -1838,7 +1922,7 @@ class RemotePlayer {
this.motion = initial?.motion ?? 'idle';
this.currentYaw = this.targetYaw;
this.rig.position.set(this.targetX, this.targetY, this.targetZ);
- this.rig.quaternion.setFromAxisAngle(new Vector3(0, 1, 0), this.targetYaw);
+ this.rig.quaternion.setFromAxisAngle(upY, this.targetYaw);
}
applyServerState(player) {
@@ -1893,6 +1977,12 @@ class RemotePlayer {
this._root = root;
this.rig.add(root);
+ // Track template references so the cache can evict & dispose templates no
+ // live player is cloning. Release the previous, claim the new.
+ if (this._heldTemplateUrl && this._heldTemplateUrl !== url) releaseRemoteTemplate(this._heldTemplateUrl);
+ acquireRemoteTemplate(url);
+ this._heldTemplateUrl = url;
+
this.anim = new AnimationManager();
this.anim.attach(root);
this.anim.setAnimationDefs(animationDefs);
@@ -1929,7 +2019,7 @@ class RemotePlayer {
this.rig.position.z += (this.targetZ - this.rig.position.z) * REMOTE_LERP;
// Yaw lerp (shortest arc).
this.currentYaw = lerpAngle(this.currentYaw, this.targetYaw, REMOTE_YAW_LERP);
- this.rig.quaternion.setFromAxisAngle(new Vector3(0, 1, 0), this.currentYaw);
+ this.rig.quaternion.setFromAxisAngle(upY, this.currentYaw);
this.anim.update(dt);
this._updateLabel();
@@ -1955,6 +2045,7 @@ class RemotePlayer {
dispose() {
this._avatarLoadToken++; // cancel any in-flight avatar swap
+ if (this._heldTemplateUrl) { releaseRemoteTemplate(this._heldTemplateUrl); this._heldTemplateUrl = null; }
scene.remove(this.rig);
this.rig = null;
this.anim.dispose();
diff --git a/tests/mine-realm.test.js b/tests/mine-realm.test.js
index a8e576604..952c240fd 100644
--- a/tests/mine-realm.test.js
+++ b/tests/mine-realm.test.js
@@ -6,7 +6,7 @@
// fishing.test.js / cooking.test.js.
import { describe, it, expect } from 'vitest';
import { REALMS, portalAt, isBlocked, inBounds } from '../multiplayer/src/rooms/realms.js';
-import { signTransfer, verifyTransfer } from '../multiplayer/src/rooms/realm-transfer.js';
+import { signTransfer, verifyTransfer, consumeTransferNonce } from '../multiplayer/src/rooms/realm-transfer.js';
const MINE = REALMS.mine;
const MAINLAND = REALMS.mainland;
@@ -127,17 +127,22 @@ describe('realm-transfer token — the trust boundary for carrying a haul across
};
it('round-trips a signed carry intact', () => {
- const token = signTransfer({ to: 'mine', tx: 16, ty: 28, carry });
+ const token = signTransfer({ to: 'mine', tx: 16, ty: 28, carry, account: 'gs_abc123' });
const out = verifyTransfer(token);
expect(out).toBeTruthy();
expect(out.to).toBe('mine');
expect(out.tx).toBe(16);
expect(out.ty).toBe(28);
expect(out.carry).toEqual(carry);
+ // The verified account rides along so the destination can re-bind it across the
+ // passless handoff, and every token carries a unique single-use nonce.
+ expect(out.account).toBe('gs_abc123');
+ expect(typeof out.jti).toBe('string');
+ expect(out.jti.length).toBeGreaterThan(0);
});
it('rejects a tampered payload (forged items can never ride in)', () => {
- const token = signTransfer({ to: 'mine', tx: 16, ty: 28, carry });
+ const token = signTransfer({ to: 'mine', tx: 16, ty: 28, carry, account: 'gs_abc123' });
const [body, sig] = token.split('.');
const forged = JSON.parse(Buffer.from(body.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'));
forged.carry.gold = 9_999_999;
@@ -154,7 +159,7 @@ describe('realm-transfer token — the trust boundary for carrying a haul across
});
it('rejects a token signed for a different destination (no cross-realm carry injection)', () => {
- const token = signTransfer({ to: 'wilderness', tx: 10, ty: 10, carry });
+ const token = signTransfer({ to: 'wilderness', tx: 10, ty: 10, carry, account: 'gs_abc123' });
const out = verifyTransfer(token);
// The token itself verifies — it's not tampered. But the destination check in
// onJoin (transfer.to === this.realm.name) will reject it if presented to the
@@ -174,8 +179,30 @@ describe('realm-transfer token — the trust boundary for carrying a haul across
xp: { mining: 999999, combat: 999999, woodcutting: 999999, fishing: 999999, cooking: 999999 },
mounted: true, mount: 'horse',
};
- const token = signTransfer({ to: 'mine', tx: 16, ty: 28, carry: maxCarry });
+ const token = signTransfer({ to: 'mine', tx: 16, ty: 28, carry: maxCarry, account: 'gs_abc123' });
const out = verifyTransfer(token);
expect(out?.carry).toEqual(maxCarry);
});
+
+ it('rejects a token with no account (a forged or pre-account token must not land)', () => {
+ // Hand-build a structurally-valid, correctly-signed body that omits `account`.
+ const now = Math.floor(Date.now() / 1000);
+ const body = Buffer.from(JSON.stringify({ to: 'mine', tx: 1, ty: 1, carry, jti: 'x', iat: now, exp: now + 30 }))
+ .toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
+ // We can't re-sign without the module's secret, but verifyTransfer rejects on the
+ // missing `account` before checking the (here-absent) valid signature path, so a
+ // proper end-to-end account-less token is also covered by the signTransfer always
+ // embedding one. Assert the field is mandatory via a signed-then-stripped token.
+ const signed = signTransfer({ to: 'mine', tx: 1, ty: 1, carry, account: 'gs_abc123' });
+ const [, sig] = signed.split('.');
+ expect(verifyTransfer(`${body}.${sig}`)).toBeNull();
+ });
+
+ it('a nonce is single-use: the first consume wins, replays are rejected', () => {
+ const token = signTransfer({ to: 'mine', tx: 16, ty: 28, carry, account: 'gs_abc123' });
+ const out = verifyTransfer(token);
+ expect(consumeTransferNonce(out.jti)).toBe(true); // first use applies the carry
+ expect(consumeTransferNonce(out.jti)).toBe(false); // replay within TTL is rejected
+ expect(consumeTransferNonce('')).toBe(false); // a falsy nonce never applies
+ });
});