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.

fix(agent-trade): show the whole payment flow on devices that cannot grant WebGL

nirholasa68d7993400a
diff --git a/pages/agent-trade.html b/pages/agent-trade.html
index e78b29bc9..450a62fcb 100644
--- a/pages/agent-trade.html
+++ b/pages/agent-trade.html
@@ -12,19 +12,19 @@
<link rel="manifest" href="/manifest.webmanifest" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title data-i18n="agent_trade.meta_title">Agent Commerce · three.ws</title>
- <meta name="description" content="Watch two AI agents pay each other on-chain using x402 — a live Solana transaction, in 3D." data-i18n-attr="content:agent_trade.meta_description">
+ <meta name="description" content="Watch two AI agents pay each other on-chain using x402: a live Solana transaction, rendered in 3D." data-i18n-attr="content:agent_trade.meta_description">
<meta property="og:type" content="website" />
<meta property="og:site_name" content="three.ws" />
<meta property="og:url" content="https://three.ws/agent-trade" />
<meta property="og:title" content="Agent Commerce · three.ws" data-i18n-attr="content:agent_trade.meta_og_title"/>
- <meta property="og:description" content="Watch two AI agents pay each other on-chain using x402 — a live Solana transaction, in 3D." data-i18n-attr="content:agent_trade.meta_og_description"/>
+ <meta property="og:description" content="Watch two AI agents pay each other on-chain using x402: a live Solana transaction, rendered in 3D." data-i18n-attr="content:agent_trade.meta_og_description"/>
<meta property="og:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Agent+Commerce&amp;d=Watch+two+AI+agents+pay+each+other+on-chain+using+x402%3A+a+live+Solana+transaction%2C+rendered+in+3D.&amp;p=%2Fagent-trade" />
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:site" content="@trythreews" />
<meta name="twitter:title" content="Agent Commerce · three.ws" data-i18n-attr="content:agent_trade.meta_twitter_title"/>
- <meta name="twitter:description" content="Watch two AI agents pay each other on-chain using x402 — a live Solana transaction, in 3D." data-i18n-attr="content:agent_trade.meta_twitter_description"/>
+ <meta name="twitter:description" content="Watch two AI agents pay each other on-chain using x402: a live Solana transaction, rendered in 3D." data-i18n-attr="content:agent_trade.meta_twitter_description"/>
<meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Agent+Commerce&amp;d=Watch+two+AI+agents+pay+each+other+on-chain+using+x402%3A+a+live+Solana+transaction%2C+rendered+in+3D.&amp;p=%2Fagent-trade" />
<link rel="stylesheet" href="/fonts/fonts.css">
<link rel="stylesheet" href="/tokens.css">
@@ -100,7 +100,8 @@
/* ── Central floating card ─────────────────────────────────────────── */
#centralCard {
position: fixed; left: 50%; transform: translateX(-50%);
- top: 50%; margin-top: -40px; width: 360px;
+ top: 50%; margin-top: -40px; width: min(360px, calc(100vw - 28px));
+ max-height: calc(100vh - 210px); overflow-y: auto;
background: var(--surface); border: 1px solid var(--border);
border-radius: var(--radius); backdrop-filter: blur(18px);
padding: 18px 22px; z-index: 20;
@@ -114,6 +115,7 @@
}
.c-badge-402 { background: color-mix(in srgb, var(--red) 10%, transparent); border: 1px solid color-mix(in srgb, var(--red) 30%, transparent); color: var(--red); }
.c-badge-ok { background: color-mix(in srgb, var(--green) 10%, transparent); border: 1px solid color-mix(in srgb, var(--green) 30%, transparent); color: var(--green); }
+ .c-badge-idle { background: rgba(8,189,186,0.1); border: 1px solid rgba(8,189,186,0.3); color: var(--teal); }
.c-label { font-size: 0.67rem; text-transform: uppercase; letter-spacing: 0.1em; color: var(--muted); margin-bottom: 6px; font-family: var(--mono); }
.c-price { font-size: 1.7rem; font-weight: 600; font-family: var(--mono); margin: 8px 0 4px; }
.c-price.blue { color: var(--blue); }
@@ -129,7 +131,7 @@
#stepLog {
position: fixed; bottom: 76px; left: 50%; transform: translateX(-50%);
display: flex; gap: 7px; flex-wrap: wrap; justify-content: center;
- z-index: 10; max-width: 600px;
+ z-index: 10; width: min(600px, calc(100vw - 20px));
}
.step-chip {
padding: 4px 11px; border-radius: 20px; font-size: 0.68rem;
@@ -144,18 +146,21 @@
/* ── CTA bar ────────────────────────────────────────────────────────── */
#cta {
position: fixed; bottom: 22px; left: 50%; transform: translateX(-50%);
- display: flex; align-items: center; gap: 10px; z-index: 10;
+ display: flex; align-items: center; justify-content: center; gap: 10px; z-index: 10;
+ width: min(520px, calc(100vw - 24px));
}
#topicSelect {
padding: 9px 14px; background: var(--surface); border: 1px solid var(--border);
border-radius: 8px; color: var(--text); font-family: var(--font);
font-size: 0.86rem; cursor: pointer; backdrop-filter: blur(10px);
- min-width: 200px; appearance: none;
+ flex: 1 1 auto; min-width: 0; max-width: 260px; appearance: none;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='8' viewBox='0 0 12 8'%3E%3Cpath d='M1 1l5 5 5-5' stroke='%238d8d8d' stroke-width='1.5' fill='none' stroke-linecap='round'/%3E%3C/svg%3E");
background-repeat: no-repeat; background-position: right 12px center;
padding-right: 32px;
}
#topicSelect:disabled { opacity: 0.45; cursor: default; }
+ #topicSelect:focus-visible { outline: 2px solid var(--blue); outline-offset: 2px; }
+ #startBtn:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
#startBtn {
padding: 10px 24px; background: var(--blue); color: #fff;
border: none; border-radius: 8px; font-size: 0.9rem; font-weight: 500;
@@ -167,12 +172,15 @@
#startBtn:disabled { opacity: 0.45; cursor: default; }
/* ── Toast ──────────────────────────────────────────────────────────── */
+ /* Anchored to the top: the bottom of the viewport already stacks the step
+ log and the CTA, and a bottom-anchored toast sat on top of both. */
#toast {
- position: fixed; bottom: 88px; left: 50%; transform: translateX(-50%);
+ position: fixed; top: 66px; left: 50%; transform: translateX(-50%);
background: color-mix(in srgb, var(--red) 14%, transparent); border: 1px solid color-mix(in srgb, var(--red) 40%, transparent);
color: var(--red); padding: 10px 20px; border-radius: 8px;
font-size: 0.83rem; z-index: 30; opacity: 0;
- transition: opacity var(--duration-base) var(--ease-standard); pointer-events: none; max-width: 420px; text-align: center;
+ transition: opacity var(--duration-base) var(--ease-standard); pointer-events: none;
+ width: max-content; max-width: min(420px, calc(100vw - 24px)); text-align: center;
}
#toast.show { opacity: 1; }
@@ -191,6 +199,7 @@
.env-block {
background: rgba(0,0,0,0.3); border: 1px solid var(--border); border-radius: 8px;
padding: 14px 16px; font-family: var(--mono); font-size: 0.75rem; line-height: 2.1;
+ overflow-x: auto;
}
.env-k { color: var(--blue); }
.env-c { color: #525252; }
@@ -200,6 +209,9 @@
.cfg-gen code {
font-family: var(--mono); font-size: 0.72rem;
background: rgba(255,255,255,0.05); padding: 2px 6px; border-radius: 4px;
+ /* A one-line shell command is wider than a 320px viewport: wrap it rather
+ than letting it push the whole page sideways. */
+ display: inline-block; max-width: 100%; overflow-wrap: anywhere;
}
.cfg-close {
margin-top: 18px; padding: 9px 20px; background: rgba(69,137,255,0.15);
@@ -250,18 +262,51 @@
.header-links { gap: 2px; margin-left: 4px; }
.header-links a { padding: 4px 7px; font-size: 0.6rem; }
#header { padding: 12px 14px; gap: 8px; }
+ /* Stack the controls: side by side they cannot both stay legible at 320px. */
+ #cta { flex-direction: column; gap: 8px; }
+ #topicSelect, #startBtn { width: 100%; max-width: none; }
+ #stepLog { bottom: 128px; }
+ .step-chip { padding: 3px 8px; font-size: 0.62rem; }
+ #centralCard { max-height: calc(100vh - 280px); padding: 16px; }
+ .bubble { max-width: 160px; font-size: 0.76rem; }
+ }
+ @media (max-width: 460px) {
+ /* Decorative protocol badges go; the network badge and the nav stay, and
+ the header wraps to two rows rather than pushing itself off-screen. */
+ .hbadge { display: none; }
+ #header { flex-wrap: wrap; row-gap: 6px; padding: 10px 12px; }
+ .header-links { order: 3; flex: 1 1 100%; margin-left: 0; justify-content: flex-start; }
+ #hright { order: 2; }
+ }
+
+ /* ── No-WebGL fallback layout ───────────────────────────────────────── */
+ /* Without a 3D stage nothing projects the labels and bubbles into place, so
+ they are laid out as a plain two-column read of the same trade. */
+ body.no-3d .agent-label {
+ top: 78px; transform: none; left: auto; right: auto;
+ }
+ body.no-3d #buyerLabel { left: 16px; align-items: flex-start; text-align: left; }
+ body.no-3d #sellerLabel { right: 16px; align-items: flex-end; text-align: right; }
+ body.no-3d .bubble { top: 168px; transform: none; left: auto; right: auto; }
+ body.no-3d .bubble.hidden { transform: none; }
+ body.no-3d #buyerBubble { left: 16px; }
+ body.no-3d #sellerBubble { right: 16px; }
+ body.no-3d .webgl-fallback {
+ position: fixed; left: 50%; top: 30%; transform: translate(-50%, -50%);
+ width: min(420px, calc(100vw - 32px)); z-index: 1;
}
</style>
<link rel="canonical" href="https://three.ws/agent-trade">
- <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Agent Commerce","description":"Watch two AI agents pay each other on-chain using x402 — a live Solana transaction, rendered in 3D.","url":"https://three.ws/agent-trade","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>
+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Agent Commerce","description":"Watch two AI agents pay each other on-chain using x402: a live Solana transaction, rendered in 3D.","url":"https://three.ws/agent-trade","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>
<meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">
<meta property="og:locale" content="en_US">
- <meta property="og:image:alt" content="Agent Commerce — three.ws">
+ <meta property="og:image:alt" content="Agent Commerce on three.ws">
</head>
<body>
- <canvas id="canvas"></canvas>
+ <h1 class="sr-only" data-i18n="agent_trade.agent_commerce_two_ai_agents_paying_each">Agent Commerce: two AI agents paying each other on Solana with x402</h1>
+ <canvas id="canvas" aria-label="3D scene of the buyer and seller agents trading" role="img"></canvas>
<!-- Header -->
<div id="header">
@@ -274,22 +319,25 @@
<a href="/x402" data-i18n="agent_trade.x402">x402</a>
</nav>
<div id="hright">
- <div id="liveDot"></div>
- <div id="networkBadge">mainnet</div>
+ <div id="liveDot" aria-hidden="true"></div>
+ <div id="networkBadge"><span class="sr-only" data-i18n="agent_trade.solana_network">Solana network </span><span id="networkName">mainnet</span></div>
</div>
</div>
+ <!-- Screen-reader running commentary for the protocol steps -->
+ <div id="srStatus" class="sr-only" role="status" aria-live="polite"></div>
+
<!-- Agent labels (JS positions these over the 3D avatars) -->
<div class="agent-label" id="buyerLabel">
<div class="al-name">Nexus</div>
<div class="al-role">Buyer Agent</div>
- <div class="al-addr" id="buyerAddr">—</div>
+ <div class="al-addr" id="buyerAddr">n/a</div>
<div class="al-bal" id="buyerBal"></div>
</div>
<div class="agent-label" id="sellerLabel">
<div class="al-name">Oracle</div>
<div class="al-role">Seller Agent</div>
- <div class="al-addr" id="sellerAddr">—</div>
+ <div class="al-addr" id="sellerAddr">n/a</div>
</div>
<!-- Speech bubbles -->
@@ -297,13 +345,14 @@
<div class="bubble hidden" id="sellerBubble"></div>
<!-- Central floating card (402 challenge → tx receipt → content) -->
- <div id="centralCard" class="hidden"></div>
+ <div id="centralCard" class="hidden" aria-live="polite"></div>
<!-- Step log -->
- <div id="stepLog"></div>
+ <div id="stepLog" role="list" aria-label="x402 protocol steps" data-i18n-attr="aria-label:agent_trade.x402_protocol_steps"></div>
<!-- CTA -->
<div id="cta">
+ <label class="sr-only" for="topicSelect" data-i18n="agent_trade.analysis_topic">Analysis topic</label>
<select id="topicSelect">
<option value="Solana DeFi outlook" data-i18n="agent_trade.solana_defi_outlook">Solana DeFi outlook</option>
<option value="BTC market sentiment" data-i18n="agent_trade.btc_market_sentiment">BTC market sentiment</option>
@@ -315,18 +364,18 @@
</div>
<!-- Toast -->
- <div id="toast"></div>
+ <div id="toast" role="alert"></div>
<!-- Not-configured overlay -->
<div id="notConfigured" class="hidden" role="dialog" aria-modal="true" aria-labelledby="cfgTitle" aria-describedby="cfgDesc">
<div class="cfg-card" role="document">
<h2 id="cfgTitle" data-i18n="agent_trade.live_demo_not_yet_configured">Live demo not yet configured</h2>
- <p id="cfgDesc" data-i18n-html="agent_trade.this_page_runs_a_real_agent_to">This page runs a <strong>real</strong> agent-to-agent payment: two AI agents settle a tiny SOL transaction on-chain via the x402 protocol. To go live it needs two funded Solana keypairs set as environment variables on the deployment. Until then, here's exactly what the demo does — step by step — and how to enable it.</p>
+ <p id="cfgDesc" data-i18n-html="agent_trade.this_page_runs_a_real_agent_to">This page runs a <strong>real</strong> agent-to-agent payment: two AI agents settle a tiny SOL transaction on-chain via the x402 protocol. To go live it needs two funded Solana keypairs set as environment variables on the deployment. Until then, here is exactly what the demo does, step by step, and how to enable it.</p>
<div class="cfg-walkthrough">
<div class="cfg-wh-head">
<span class="cfg-wh-badge" data-i18n="agent_trade.read_only_walkthrough">Read-only walkthrough</span>
- <span class="cfg-wh-note" data-i18n="agent_trade.a_description_of_the_live_flow_not">A description of the live flow — not a running trade.</span>
+ <span class="cfg-wh-note" data-i18n="agent_trade.a_description_of_the_live_flow_not">A description of the live flow, not a running trade.</span>
</div>
<ol class="cfg-steps">
<li data-i18n-html="agent_trade.request_the_buyer_agent_nexus_asks_the"><b>Request.</b> The buyer agent (Nexus) asks the seller agent (Oracle) for a market analysis.</li>
diff --git a/src/agent-trade.js b/src/agent-trade.js
index 5f0a1c0cc..d9b15d06e 100644
--- a/src/agent-trade.js
+++ b/src/agent-trade.js
@@ -1,13 +1,20 @@
-// Agent-to-agent x402 trade demo — Three.js scene + SSE consumer.
+// Agent-to-agent x402 trade demo: Three.js scene + SSE consumer.
// Two 3D avatars (Nexus buyer, Oracle seller) face each other on glowing
// platforms. A particle beam fires when SOL moves on-chain; each step of
// the x402 protocol animates in real time.
+//
+// The 3D stage is optional. Every device that cannot grant a WebGL context
+// (no GPU, blocklisted driver, exhausted context budget) still gets the whole
+// protocol flow: the scene degrades to a laid-out 2D read of the same events
+// instead of a black void, because the payment story is the product here and
+// the particles are the garnish.
import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { getMeshoptDecoder } from './viewer/internal.js';
+import { createRenderer, WebGLUnavailableError } from './webgl-support.js';
// ── Constants ──────────────────────────────────────────────────────────────
const BUYER_COL = new THREE.Color(0x4589ff); // IBM blue
@@ -17,245 +24,404 @@ const SELLER_POS = new THREE.Vector3( 3.4, 0, 0);
const BEAM_N = 350; // beam particles
const BURST_N = 90; // confirmation burst particles
const AVATAR_GLB = '/avatars/default.glb';
+const RUNNING_LABEL = '⏳ Running…';
+const FALLBACK_LABEL = '▶ Run Trade Demo';
+const NO_VALUE = 'n/a';
-// ── Renderer ───────────────────────────────────────────────────────────────
-const canvas = document.getElementById('canvas');
-const renderer = new THREE.WebGLRenderer({ canvas, antialias: true });
-renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
-renderer.setSize(innerWidth, innerHeight);
-renderer.outputColorSpace = THREE.SRGBColorSpace;
-renderer.toneMapping = THREE.ACESFilmicToneMapping;
-renderer.toneMappingExposure = 1.15;
-renderer.shadowMap.enabled = false;
-
-// ── Scene ──────────────────────────────────────────────────────────────────
-const scene = new THREE.Scene();
-scene.background = new THREE.Color(0x05050e);
-scene.fog = new THREE.FogExp2(0x05050e, 0.038);
-
-// ── Camera ─────────────────────────────────────────────────────────────────
-const camera = new THREE.PerspectiveCamera(52, innerWidth / innerHeight, 0.1, 100);
-camera.position.set(0, 2.9, 9.8);
-
-const controls = new OrbitControls(camera, canvas);
-controls.target.set(0, 1.1, 0);
-controls.enableDamping = true;
-controls.dampingFactor = 0.07;
-controls.minDistance = 4;
-controls.maxDistance = 20;
-controls.maxPolarAngle = Math.PI * 0.68;
-controls.autoRotate = true;
-controls.autoRotateSpeed = 0.35;
-controls.update();
-
-// ── Lights ─────────────────────────────────────────────────────────────────
-scene.add(new THREE.AmbientLight(0x10102a, 4));
-
-const buyerLight = new THREE.PointLight(BUYER_COL, 10, 9);
-buyerLight.position.set(BUYER_POS.x, 2.5, 1.2);
-scene.add(buyerLight);
-
-const sellerLight = new THREE.PointLight(SELLER_COL, 10, 9);
-sellerLight.position.set(SELLER_POS.x, 2.5, 1.2);
-scene.add(sellerLight);
-
-const keyLight = new THREE.DirectionalLight(0xffffff, 1.8);
-keyLight.position.set(2, 6, 3);
-scene.add(keyLight);
-
-// ── Floor ──────────────────────────────────────────────────────────────────
-const grid = new THREE.GridHelper(32, 32, 0x1a1a4e, 0x0c0c24);
-grid.position.y = 0.001;
-scene.add(grid);
-
-const floorGeo = new THREE.PlaneGeometry(32, 32);
-const floorMat = new THREE.MeshStandardMaterial({ color: 0x050510, roughness: 1, metalness: 0 });
-const floor = new THREE.Mesh(floorGeo, floorMat);
-floor.rotation.x = -Math.PI / 2;
-scene.add(floor);
-
-// ── Platforms ──────────────────────────────────────────────────────────────
-function makePlatform(worldPos, col) {
- const g = new THREE.Group();
-
- const discGeo = new THREE.CylinderGeometry(1.15, 1.35, 0.09, 48);
- const discMat = new THREE.MeshStandardMaterial({
- color: 0x0d0d1c, emissive: col, emissiveIntensity: 0.2,
- roughness: 0.3, metalness: 0.8,
- });
- g.add(new THREE.Mesh(discGeo, discMat));
-
- const ringGeo = new THREE.TorusGeometry(1.15, 0.028, 8, 64);
- const ringMat = new THREE.MeshStandardMaterial({ color: col, emissive: col, emissiveIntensity: 1.8 });
- const ring = new THREE.Mesh(ringGeo, ringMat);
- ring.rotation.x = Math.PI / 2;
- ring.position.y = 0.045;
- g.add(ring);
-
- g.position.copy(worldPos);
- scene.add(g);
- return { group: g, ring };
+// ── DOM references ──────────────────────────────────────────────────────────
+const els = {
+ canvas: document.getElementById('canvas'),
+ buyerLabel: document.getElementById('buyerLabel'),
+ sellerLabel: document.getElementById('sellerLabel'),
+ buyerAddr: document.getElementById('buyerAddr'),
+ sellerAddr: document.getElementById('sellerAddr'),
+ buyerBal: document.getElementById('buyerBal'),
+ buyerBubble: document.getElementById('buyerBubble'),
+ sellerBubble: document.getElementById('sellerBubble'),
+ centralCard: document.getElementById('centralCard'),
+ stepLog: document.getElementById('stepLog'),
+ startBtn: document.getElementById('startBtn'),
+ topicSelect: document.getElementById('topicSelect'),
+ networkName: document.getElementById('networkName'),
+ notConfigured:document.getElementById('notConfigured'),
+ toast: document.getElementById('toast'),
+ cfgClose: document.getElementById('cfgClose'),
+ srStatus: document.getElementById('srStatus'),
+};
+
+// ── HTML escaping ────────────────────────────────────────────────────────────
+function escHtml(s) {
+ return String(s == null ? '' : s)
+ .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;').replace(/'/g, '&#39;');
+}
+// Returns null (not '#') for anything that is not an absolute http(s) URL, so a
+// malformed explorer URL renders no link at all rather than a dead one.
+function safeHref(u) {
+ const s = String(u || '').trim();
+ return /^https?:\/\//i.test(s) ? s : null;
}
-const buyerPlatform = makePlatform(BUYER_POS, BUYER_COL);
-const sellerPlatform = makePlatform(SELLER_POS, SELLER_COL);
-
-// ── Background stars ────────────────────────────────────────────────────────
-{
- const N = 1400;
- const pos = new Float32Array(N * 3);
- for (let i = 0; i < N; i++) {
- const th = Math.random() * Math.PI * 2;
- const ph = Math.acos(2 * Math.random() - 1);
- const r = 42 + Math.random() * 8;
- pos[i * 3] = r * Math.sin(ph) * Math.cos(th);
- pos[i * 3 + 1] = r * Math.sin(ph) * Math.sin(th);
- pos[i * 3 + 2] = r * Math.cos(ph);
- }
- const g = new THREE.BufferGeometry();
- g.setAttribute('position', new THREE.BufferAttribute(pos, 3));
- scene.add(new THREE.Points(g, new THREE.PointsMaterial({ color: 0xffffff, size: 0.07, transparent: true, opacity: 0.65 })));
+function fmt(addr) {
+ return addr ? addr.slice(0, 4) + '…' + addr.slice(-4) : NO_VALUE;
}
-// ── Avatar loading ──────────────────────────────────────────────────────────
-const gltfLoader = new GLTFLoader();
-const draco = new DRACOLoader();
-draco.setDecoderPath('https://www.gstatic.com/draco/versioned/decoders/1.5.7/');
-gltfLoader.setDRACOLoader(draco);
-// default.glb is meshopt-compressed — without this decoder every load threw
-// and the scene silently degraded to the capsule fallback figures.
-const meshoptReady = getMeshoptDecoder().then((d) => gltfLoader.setMeshoptDecoder(d));
-
-// Label tracking positions (above each avatar's head)
-const labelPos = {
- buyer: BUYER_POS.clone().add(new THREE.Vector3(0, 2.1, 0)),
- seller: SELLER_POS.clone().add(new THREE.Vector3(0, 2.1, 0)),
-};
+// ── 3D stage ────────────────────────────────────────────────────────────────
+// Everything WebGL lives in here so a device without a context throws once, at
+// construction, and the rest of the page carries on. Returns the handful of
+// hooks the protocol flow drives.
+function buildStage() {
+ const renderer = createRenderer({ canvas: els.canvas, antialias: true }, { fallback: els.canvas });
+ renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
+ renderer.setSize(innerWidth, innerHeight);
+ renderer.outputColorSpace = THREE.SRGBColorSpace;
+ renderer.toneMapping = THREE.ACESFilmicToneMapping;
+ renderer.toneMappingExposure = 1.15;
+ renderer.shadowMap.enabled = false;
+
+ const scene = new THREE.Scene();
+ scene.background = new THREE.Color(0x05050e);
+ scene.fog = new THREE.FogExp2(0x05050e, 0.038);
+
+ const camera = new THREE.PerspectiveCamera(52, innerWidth / innerHeight, 0.1, 100);
+ camera.position.set(0, 2.9, 9.8);
+
+ const controls = new OrbitControls(camera, els.canvas);
+ controls.target.set(0, 1.1, 0);
+ controls.enableDamping = true;
+ controls.dampingFactor = 0.07;
+ controls.minDistance = 4;
+ controls.maxDistance = 20;
+ controls.maxPolarAngle = Math.PI * 0.68;
+ controls.autoRotate = true;
+ controls.autoRotateSpeed = 0.35;
+ controls.update();
+
+ // ── Lights ───────────────────────────────────────────────────────────────
+ scene.add(new THREE.AmbientLight(0x10102a, 4));
+
+ const buyerLight = new THREE.PointLight(BUYER_COL, 10, 9);
+ buyerLight.position.set(BUYER_POS.x, 2.5, 1.2);
+ scene.add(buyerLight);
+
+ const sellerLight = new THREE.PointLight(SELLER_COL, 10, 9);
+ sellerLight.position.set(SELLER_POS.x, 2.5, 1.2);
+ scene.add(sellerLight);
+
+ const keyLight = new THREE.DirectionalLight(0xffffff, 1.8);
+ keyLight.position.set(2, 6, 3);
+ scene.add(keyLight);
+
+ // ── Floor ────────────────────────────────────────────────────────────────
+ const grid = new THREE.GridHelper(32, 32, 0x1a1a4e, 0x0c0c24);
+ grid.position.y = 0.001;
+ scene.add(grid);
+
+ const floor = new THREE.Mesh(
+ new THREE.PlaneGeometry(32, 32),
+ new THREE.MeshStandardMaterial({ color: 0x050510, roughness: 1, metalness: 0 }),
+ );
+ floor.rotation.x = -Math.PI / 2;
+ scene.add(floor);
+
+ // ── Platforms ────────────────────────────────────────────────────────────
+ function makePlatform(worldPos, col) {
+ const g = new THREE.Group();
+
+ const discGeo = new THREE.CylinderGeometry(1.15, 1.35, 0.09, 48);
+ const discMat = new THREE.MeshStandardMaterial({
+ color: 0x0d0d1c, emissive: col, emissiveIntensity: 0.2,
+ roughness: 0.3, metalness: 0.8,
+ });
+ g.add(new THREE.Mesh(discGeo, discMat));
+
+ const ringGeo = new THREE.TorusGeometry(1.15, 0.028, 8, 64);
+ const ringMat = new THREE.MeshStandardMaterial({ color: col, emissive: col, emissiveIntensity: 1.8 });
+ const ring = new THREE.Mesh(ringGeo, ringMat);
+ ring.rotation.x = Math.PI / 2;
+ ring.position.y = 0.045;
+ g.add(ring);
+
+ g.position.copy(worldPos);
+ scene.add(g);
+ return { group: g, ring };
+ }
+
+ const buyerPlatform = makePlatform(BUYER_POS, BUYER_COL);
+ const sellerPlatform = makePlatform(SELLER_POS, SELLER_COL);
+
+ // ── Background stars ─────────────────────────────────────────────────────
+ {
+ const N = 1400;
+ const pos = new Float32Array(N * 3);
+ for (let i = 0; i < N; i++) {
+ const th = Math.random() * Math.PI * 2;
+ const ph = Math.acos(2 * Math.random() - 1);
+ const r = 42 + Math.random() * 8;
+ pos[i * 3] = r * Math.sin(ph) * Math.cos(th);
+ pos[i * 3 + 1] = r * Math.sin(ph) * Math.sin(th);
+ pos[i * 3 + 2] = r * Math.cos(ph);
+ }
+ const g = new THREE.BufferGeometry();
+ g.setAttribute('position', new THREE.BufferAttribute(pos, 3));
+ scene.add(new THREE.Points(g, new THREE.PointsMaterial({ color: 0xffffff, size: 0.07, transparent: true, opacity: 0.65 })));
+ }
+
+ // ── Avatar loading ───────────────────────────────────────────────────────
+ const gltfLoader = new GLTFLoader();
+ const draco = new DRACOLoader();
+ draco.setDecoderPath('https://www.gstatic.com/draco/versioned/decoders/1.5.7/');
+ gltfLoader.setDRACOLoader(draco);
+ // default.glb is meshopt-compressed: without this decoder every load threw
+ // and the scene silently degraded to the capsule fallback figures.
+ const meshoptReady = getMeshoptDecoder().then((d) => gltfLoader.setMeshoptDecoder(d));
+
+ // Label tracking positions (above each avatar's head)
+ const labelPos = {
+ buyer: BUYER_POS.clone().add(new THREE.Vector3(0, 2.1, 0)),
+ seller: SELLER_POS.clone().add(new THREE.Vector3(0, 2.1, 0)),
+ };
-let buyerMesh = null;
-let sellerMesh = null;
-
-function applyTint(gltfScene, col) {
- gltfScene.traverse((child) => {
- if (!child.isMesh) return;
- const mats = Array.isArray(child.material) ? child.material : [child.material];
- const tinted = mats.map((m) => {
- const n = m.clone();
- n.color.multiplyScalar(0.65).addScaledVector(col, 0.38);
- n.emissive = col.clone().multiplyScalar(0.07);
- n.emissiveIntensity = 1;
- return n;
+ let buyerMesh = null;
+ let sellerMesh = null;
+
+ function applyTint(gltfScene, col) {
+ gltfScene.traverse((child) => {
+ if (!child.isMesh) return;
+ const mats = Array.isArray(child.material) ? child.material : [child.material];
+ const tinted = mats.map((m) => {
+ const n = m.clone();
+ n.color.multiplyScalar(0.65).addScaledVector(col, 0.38);
+ n.emissive = col.clone().multiplyScalar(0.07);
+ n.emissiveIntensity = 1;
+ return n;
+ });
+ child.material = tinted.length === 1 ? tinted[0] : tinted;
});
- child.material = tinted.length === 1 ? tinted[0] : tinted;
+ }
+
+ function makeFallbackFigure(col) {
+ const g = new THREE.Group();
+ const bodyMat = new THREE.MeshStandardMaterial({ color: col, emissive: col, emissiveIntensity: 0.12, roughness: 0.6, metalness: 0.3 });
+ g.add(new THREE.Mesh(new THREE.CapsuleGeometry(0.31, 1.0, 8, 16), bodyMat));
+ const head = new THREE.Mesh(new THREE.SphereGeometry(0.25, 16, 16), bodyMat.clone());
+ head.position.y = 1.05;
+ g.add(head);
+ return g;
+ }
+
+ function loadAvatar(worldPos, col, yaw, onLoaded) {
+ meshoptReady.then(() => gltfLoader.load(AVATAR_GLB, (gltf) => {
+ const s = gltf.scene.clone(true);
+ applyTint(s, col);
+ s.position.copy(worldPos);
+ s.rotation.y = yaw;
+ scene.add(s);
+ const box = new THREE.Box3().setFromObject(s);
+ onLoaded(s, new THREE.Vector3(worldPos.x, box.max.y + 0.18, worldPos.z));
+ }, undefined, () => {
+ // GLB failed (CORS in dev? missing file?): use the stylised capsule.
+ const s = makeFallbackFigure(col);
+ s.position.copy(worldPos);
+ s.rotation.y = yaw;
+ scene.add(s);
+ onLoaded(s, new THREE.Vector3(worldPos.x, 2.15, worldPos.z));
+ }));
+ }
+
+ loadAvatar(BUYER_POS, BUYER_COL, 0.12, (m, top) => { buyerMesh = m; labelPos.buyer = top; });
+ loadAvatar(SELLER_POS, SELLER_COL, -0.12, (m, top) => { sellerMesh = m; labelPos.seller = top; });
+
+ // ── Payment beam ─────────────────────────────────────────────────────────
+ const beamPhases = new Float32Array(BEAM_N).map(() => Math.random());
+ const beamSpeeds = new Float32Array(BEAM_N).map(() => 0.28 + Math.random() * 0.55);
+ const beamPos = new Float32Array(BEAM_N * 3);
+
+ const beamGeo = new THREE.BufferGeometry();
+ beamGeo.setAttribute('position', new THREE.BufferAttribute(beamPos, 3));
+ const beamMat = new THREE.PointsMaterial({
+ color: 0x4589ff, size: 0.065, transparent: true, opacity: 0,
+ blending: THREE.AdditiveBlending, depthWrite: false,
});
-}
+ scene.add(new THREE.Points(beamGeo, beamMat));
+
+ let beamActive = false;
+
+ // ── Confirmation burst ───────────────────────────────────────────────────
+ const burstPos = new Float32Array(BURST_N * 3);
+ const burstVels = new Float32Array(BURST_N * 3);
+ const burstGeo = new THREE.BufferGeometry();
+ burstGeo.setAttribute('position', new THREE.BufferAttribute(burstPos, 3));
+ const burstMat = new THREE.PointsMaterial({
+ color: 0x42be65, size: 0.1, transparent: true, opacity: 0,
+ blending: THREE.AdditiveBlending, depthWrite: false,
+ });
+ scene.add(new THREE.Points(burstGeo, burstMat));
-function makeFallbackFigure(col) {
- const g = new THREE.Group();
- const bodyMat = new THREE.MeshStandardMaterial({ color: col, emissive: col, emissiveIntensity: 0.12, roughness: 0.6, metalness: 0.3 });
- g.add(Object.assign(new THREE.Mesh(new THREE.CapsuleGeometry(0.31, 1.0, 8, 16), bodyMat)));
- const head = new THREE.Mesh(new THREE.SphereGeometry(0.25, 16, 16), bodyMat.clone());
- head.position.y = 1.05;
- g.add(head);
- return g;
-}
+ let burstLife = 0;
-function loadAvatar(worldPos, col, yaw, onLoaded) {
- meshoptReady.then(() => gltfLoader.load(AVATAR_GLB, (gltf) => {
- const s = gltf.scene.clone(true);
- applyTint(s, col);
- s.position.copy(worldPos);
- s.rotation.y = yaw;
- scene.add(s);
- const box = new THREE.Box3().setFromObject(s);
- onLoaded(s, new THREE.Vector3(worldPos.x, box.max.y + 0.18, worldPos.z));
- }, undefined, () => {
- // GLB failed (CORS in dev? missing file?) — use stylised capsule
- const s = makeFallbackFigure(col);
- s.position.copy(worldPos);
- s.rotation.y = yaw;
- scene.add(s);
- onLoaded(s, new THREE.Vector3(worldPos.x, 2.15, worldPos.z));
- }));
-}
+ // ── Camera animation ─────────────────────────────────────────────────────
+ const camAnim = {
+ active: false, t: 0, dur: 0,
+ fromPos: new THREE.Vector3(), toPos: new THREE.Vector3(),
+ fromTgt: new THREE.Vector3(), toTgt: new THREE.Vector3(),
+ };
-loadAvatar(BUYER_POS, BUYER_COL, 0.12, (m, top) => { buyerMesh = m; labelPos.buyer = top; });
-loadAvatar(SELLER_POS, SELLER_COL, -0.12, (m, top) => { sellerMesh = m; labelPos.seller = top; });
+ // ── Label & bubble positioning ───────────────────────────────────────────
+ function project(v3) {
+ const v = v3.clone().project(camera);
+ return { x: (v.x * 0.5 + 0.5) * innerWidth, y: (-v.y * 0.5 + 0.5) * innerHeight };
+ }
-// ── Payment beam ────────────────────────────────────────────────────────────
-const beamPhases = new Float32Array(BEAM_N).map(() => Math.random());
-const beamSpeeds = new Float32Array(BEAM_N).map(() => 0.28 + Math.random() * 0.55);
-const beamPos = new Float32Array(BEAM_N * 3);
+ // Clamped to the viewport: at 320px the projected anchor can sit off-screen,
+ // and a label the user cannot read is the same as no label at all.
+ function placeEl(el, worldPos, xOffset = 0, yOffset = 0) {
+ const p = project(worldPos);
+ const halfW = el.offsetWidth / 2 || 0;
+ const x = Math.min(Math.max(p.x + xOffset, halfW + 8), innerWidth - halfW - 8);
+ const y = Math.min(Math.max(p.y + yOffset, el.offsetHeight + 8), innerHeight - 8);
+ el.style.left = `${x}px`;
+ el.style.top = `${y}px`;
+ el.style.transform = 'translate(-50%, -100%)';
+ }
-const beamGeo = new THREE.BufferGeometry();
-beamGeo.setAttribute('position', new THREE.BufferAttribute(beamPos, 3));
-const beamMat = new THREE.PointsMaterial({
- color: 0x4589ff, size: 0.065, transparent: true, opacity: 0,
- blending: THREE.AdditiveBlending, depthWrite: false,
-});
-scene.add(new THREE.Points(beamGeo, beamMat));
+ function updateOverlays() {
+ placeEl(els.buyerLabel, labelPos.buyer, 0, -8);
+ placeEl(els.sellerLabel, labelPos.seller, 0, -8);
-let beamActive = false;
+ if (!els.buyerBubble.classList.contains('hidden')) {
+ placeEl(els.buyerBubble, labelPos.buyer.clone().add(new THREE.Vector3(0, 0.55, 0)), 0, -4);
+ }
+ if (!els.sellerBubble.classList.contains('hidden')) {
+ placeEl(els.sellerBubble, labelPos.seller.clone().add(new THREE.Vector3(0, 0.55, 0)), 0, -4);
+ }
+ }
-function startBeam() {
- beamActive = true;
- beamMat.opacity = 0.92;
+ addEventListener('resize', () => {
+ camera.aspect = innerWidth / innerHeight;
+ camera.updateProjectionMatrix();
+ renderer.setSize(innerWidth, innerHeight);
+ });
+
+ // ── Animation loop ───────────────────────────────────────────────────────
+ const clock = new THREE.Timer();
+
+ (function animate() {
+ requestAnimationFrame(animate);
+ clock.update();
+ const dt = Math.min(clock.getDelta(), 0.1);
+ const t = clock.getElapsed();
+
+ // Idle avatar breath
+ if (buyerMesh) buyerMesh.position.y = Math.sin(t * 0.75) * 0.022;
+ if (sellerMesh) sellerMesh.position.y = Math.sin(t * 0.75 + 1.2) * 0.022;
+
+ // Platform ring pulse
+ buyerPlatform.ring.material.emissiveIntensity = 1.4 + Math.sin(t * 2.0) * 0.5;
+ sellerPlatform.ring.material.emissiveIntensity = 1.4 + Math.sin(t * 2.0 + 1.0) * 0.5;
+
+ // Beam travel
+ if (beamActive) {
+ const B = BUYER_POS, S = SELLER_POS;
+ const spread = 0.13;
+ for (let i = 0; i < BEAM_N; i++) {
+ beamPhases[i] = (beamPhases[i] + beamSpeeds[i] * dt) % 1;
+ const ph = beamPhases[i];
+ beamPos[i * 3] = B.x + (S.x - B.x) * ph + (Math.random() - 0.5) * spread;
+ beamPos[i * 3 + 1] = B.y + 0.9 + (Math.random() - 0.5) * spread;
+ beamPos[i * 3 + 2] = (Math.random() - 0.5) * spread;
+ }
+ beamGeo.attributes.position.needsUpdate = true;
+ beamMat.opacity = 0.75 + Math.sin(t * 14) * 0.18;
+ } else if (beamMat.opacity > 0) {
+ beamMat.opacity = Math.max(0, beamMat.opacity - dt * 2.5);
+ if (beamMat.opacity === 0) beamGeo.attributes.position.needsUpdate = true;
+ }
+
+ // Burst particles
+ if (burstLife > 0) {
+ burstLife -= dt * 0.65;
+ burstMat.opacity = Math.max(0, burstLife);
+ for (let i = 0; i < BURST_N; i++) {
+ burstVels[i * 3 + 1] -= 4.8 * dt; // gravity
+ burstPos[i * 3] += burstVels[i * 3] * dt;
+ burstPos[i * 3 + 1] += burstVels[i * 3 + 1] * dt;
+ burstPos[i * 3 + 2] += burstVels[i * 3 + 2] * dt;
+ }
+ burstGeo.attributes.position.needsUpdate = true;
+ if (burstLife <= 0) burstMat.opacity = 0;
+ }
+
+ // Camera animation
+ if (camAnim.active) {
+ camAnim.t += dt * 1000;
+ const raw = Math.min(camAnim.t / camAnim.dur, 1);
+ const ease = raw < 0.5 ? 2 * raw * raw : 1 - (-2 * raw + 2) ** 2 / 2;
+ camera.position.lerpVectors(camAnim.fromPos, camAnim.toPos, ease);
+ controls.target.lerpVectors(camAnim.fromTgt, camAnim.toTgt, ease);
+ if (raw >= 1) camAnim.active = false;
+ }
+
+ controls.update();
+ updateOverlays();
+ renderer.render(scene, camera);
+ })();
+
+ return {
+ startBeam() {
+ beamActive = true;
+ beamMat.opacity = 0.92;
+ },
+ stopBeam() {
+ beamActive = false;
+ beamMat.opacity = 0;
+ },
+ triggerBurst() {
+ beamActive = false;
+ const s = SELLER_POS;
+ for (let i = 0; i < BURST_N; i++) {
+ burstPos[i * 3] = s.x + (Math.random() - 0.5) * 0.3;
+ burstPos[i * 3 + 1] = s.y + 0.95 + Math.random() * 0.4;
+ burstPos[i * 3 + 2] = s.z + (Math.random() - 0.5) * 0.3;
+ const th = Math.random() * Math.PI * 2;
+ const spd = 1.2 + Math.random() * 2.2;
+ burstVels[i * 3] = Math.cos(th) * spd;
+ burstVels[i * 3 + 1] = (0.5 + Math.random()) * spd;
+ burstVels[i * 3 + 2] = Math.sin(th) * spd * 0.5;
+ }
+ burstGeo.attributes.position.needsUpdate = true;
+ burstMat.opacity = 1;
+ burstLife = 1.2;
+ },
+ flyCamera(toPos, toTgt, dur = 1100) {
+ camAnim.fromPos.copy(camera.position);
+ camAnim.toPos.copy(toPos);
+ camAnim.fromTgt.copy(controls.target);
+ camAnim.toTgt.copy(toTgt);
+ camAnim.t = 0;
+ camAnim.dur = dur;
+ camAnim.active = true;
+ },
+ setAutoRotate(on) { controls.autoRotate = on; },
+ };
}
-// ── Confirmation burst ──────────────────────────────────────────────────────
-const burstPos = new Float32Array(BURST_N * 3);
-const burstVels = new Float32Array(BURST_N * 3);
-const burstGeo = new THREE.BufferGeometry();
-burstGeo.setAttribute('position', new THREE.BufferAttribute(burstPos, 3));
-const burstMat = new THREE.PointsMaterial({
- color: 0x42be65, size: 0.1, transparent: true, opacity: 0,
- blending: THREE.AdditiveBlending, depthWrite: false,
-});
-scene.add(new THREE.Points(burstGeo, burstMat));
-
-let burstLife = 0;
-
-function triggerBurst() {
- beamActive = false;
- const s = SELLER_POS;
- for (let i = 0; i < BURST_N; i++) {
- burstPos[i * 3] = s.x + (Math.random() - 0.5) * 0.3;
- burstPos[i * 3 + 1] = s.y + 0.95 + Math.random() * 0.4;
- burstPos[i * 3 + 2] = s.z + (Math.random() - 0.5) * 0.3;
- const th = Math.random() * Math.PI * 2;
- const spd = 1.2 + Math.random() * 2.2;
- burstVels[i * 3] = Math.cos(th) * spd;
- burstVels[i * 3 + 1] = (0.5 + Math.random()) * spd;
- burstVels[i * 3 + 2] = Math.sin(th) * spd * 0.5;
- }
- burstGeo.attributes.position.needsUpdate = true;
- burstMat.opacity = 1;
- burstLife = 1.2;
+let stage = null;
+try {
+ stage = buildStage();
+} catch (err) {
+ // A device that cannot do WebGL still gets the full protocol read: the labels,
+ // bubbles, step log and receipt cards lay out in 2D under `no-3d`.
+ if (!(err instanceof WebGLUnavailableError)) throw err;
+ document.body.classList.add('no-3d');
}
-// ── DOM references ──────────────────────────────────────────────────────────
-const els = {
- buyerLabel: document.getElementById('buyerLabel'),
- sellerLabel: document.getElementById('sellerLabel'),
- buyerAddr: document.getElementById('buyerAddr'),
- sellerAddr: document.getElementById('sellerAddr'),
- buyerBal: document.getElementById('buyerBal'),
- buyerBubble: document.getElementById('buyerBubble'),
- sellerBubble: document.getElementById('sellerBubble'),
- centralCard: document.getElementById('centralCard'),
- stepLog: document.getElementById('stepLog'),
- startBtn: document.getElementById('startBtn'),
- topicSelect: document.getElementById('topicSelect'),
- networkBadge: document.getElementById('networkBadge'),
- notConfigured:document.getElementById('notConfigured'),
- toast: document.getElementById('toast'),
- cfgClose: document.getElementById('cfgClose'),
-};
+const vec3 = (x, y, z) => new THREE.Vector3(x, y, z);
// ── Config overlay focus management ─────────────────────────────────────────
// The overlay is a modal dialog over a 3D canvas (OrbitControls). Keyboard users
// need: focus moved into it on open, Tab trapped inside it, Escape to dismiss, and
-// focus returned to the trigger on close — otherwise Tab silently escapes to the
+// focus returned to the trigger on close, otherwise Tab silently escapes to the
// canvas and the overlay reads as a dead end.
let cfgLastFocus = null;
@@ -276,11 +442,15 @@ function closeConfigOverlay() {
if (els.notConfigured.classList.contains('hidden')) return;
els.notConfigured.classList.add('hidden');
// Return focus somewhere sensible so the user keeps their place: the original
- // trigger if it's still focusable, else the run button, else the topic select
- // (the run button is disabled when unconfigured and can't take focus).
- const candidates = [cfgLastFocus, els.startBtn, els.topicSelect].filter(
- (el) => el && document.contains(el) && !el.disabled,
- );
+ // trigger if it's still focusable, else the walkthrough re-open button in the
+ // card, else the topic select (the run button is disabled when unconfigured
+ // and can't take focus).
+ const candidates = [
+ cfgLastFocus,
+ els.centralCard.querySelector('[data-action="show-walkthrough"]'),
+ els.startBtn,
+ els.topicSelect,
+ ].filter((el) => el && document.contains(el) && !el.disabled);
candidates[0]?.focus?.();
}
@@ -306,43 +476,11 @@ els.notConfigured.addEventListener('keydown', (e) => {
els.cfgClose.addEventListener('click', closeConfigOverlay);
-// ── Label & bubble positioning ──────────────────────────────────────────────
-function project(v3) {
- const v = v3.clone().project(camera);
- return { x: (v.x * 0.5 + 0.5) * innerWidth, y: (-v.y * 0.5 + 0.5) * innerHeight };
-}
-
-function placeEl(el, worldPos, xOffset = 0, yOffset = 0) {
- const p = project(worldPos);
- el.style.left = `${p.x + xOffset}px`;
- el.style.top = `${p.y + yOffset}px`;
- el.style.transform = 'translate(-50%, -100%)';
-}
-
-function updateOverlays() {
- placeEl(els.buyerLabel, labelPos.buyer, 0, -8);
- placeEl(els.sellerLabel, labelPos.seller, 0, -8);
-
- if (!els.buyerBubble.classList.contains('hidden')) {
- const bp = labelPos.buyer.clone().add(new THREE.Vector3(0, 0.55, 0));
- placeEl(els.buyerBubble, bp, 0, -4);
- }
- if (!els.sellerBubble.classList.contains('hidden')) {
- const sp = labelPos.seller.clone().add(new THREE.Vector3(0, 0.55, 0));
- placeEl(els.sellerBubble, sp, 0, -4);
- }
-}
-
-// ── HTML escaping ────────────────────────────────────────────────────────────
-function escHtml(s) {
- return String(s == null ? '' : s)
- .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
- .replace(/"/g, '&quot;').replace(/'/g, '&#39;');
-}
-function safeHref(u) {
- const s = String(u || '').trim();
- return /^https?:\/\//i.test(s) ? s : '#';
-}
+// Dismissing the overlay used to strand the walkthrough with no way back. The
+// idle card carries a control that re-opens it.
+els.centralCard.addEventListener('click', (e) => {
+ if (e.target.closest('[data-action="show-walkthrough"]')) openConfigOverlay();
+});
// ── Bubble helpers ──────────────────────────────────────────────────────────
function showBubble(side, text) {
@@ -362,6 +500,31 @@ function showCard(html) {
}
function hideCard() { els.centralCard.classList.add('hidden'); }
+// Pre-run state, drawn from the live pre-flight response: what the trade will
+// cost, who gets paid, on which network, and what the button will do.
+function showReadyCard(cfg) {
+ showCard(`
+ <div class="c-badge c-badge-idle">x402 · oracle-market-analysis</div>
+ <div class="c-label">Ready to trade</div>
+ <div class="c-price blue">${escHtml(cfg.priceSol ?? '?')} SOL</div>
+ <div class="c-row">Buyer <span>${escHtml(fmt(cfg.buyer?.address))}</span></div>
+ <div class="c-row">Seller <span>${escHtml(fmt(cfg.seller?.address))}</span></div>
+ <div class="c-row">Network <span>${escHtml(cfg.network || NO_VALUE)}</span></div>
+ <div class="c-content">Pick a topic and run the demo. Nexus pays Oracle on Solana, then Oracle delivers the analysis it was paid for.</div>
+ `);
+}
+
+// Pre-run state when no wallets are configured: says why the button is off and
+// keeps the walkthrough one click away.
+function showUnconfiguredCard() {
+ showCard(`
+ <div class="c-badge c-badge-402">Live demo offline</div>
+ <div class="c-label">x402 · oracle-market-analysis</div>
+ <div class="c-content">This deployment has no funded agent wallets, so nothing can be paid on-chain right now. The walkthrough explains each step of the trade and how to enable it.</div>
+ <button class="cfg-close" type="button" data-action="show-walkthrough">Show the walkthrough</button>
+ `);
+}
+
// ── Step log ─────────────────────────────────────────────────────────────────
const STEP_NAMES = ['init', 'request', 'challenged', 'paying', 'confirmed', 'delivering', 'delivered'];
const chips = {};
@@ -371,17 +534,28 @@ function buildStepLog() {
STEP_NAMES.forEach((s) => {
const c = document.createElement('div');
c.className = 'step-chip';
+ c.setAttribute('role', 'listitem');
c.textContent = s;
els.stepLog.appendChild(c);
chips[s] = c;
});
}
+function announce(msg) {
+ if (els.srStatus) els.srStatus.textContent = msg;
+}
+
function setChip(name, state) {
const c = chips[name];
if (!c) return;
c.classList.remove('active', 'done', 'error');
if (state) c.classList.add(state);
+ if (state === 'active') {
+ c.setAttribute('aria-current', 'step');
+ announce(`Step: ${name}`);
+ } else {
+ c.removeAttribute('aria-current');
+ }
}
// ── Toast ────────────────────────────────────────────────────────────────────
@@ -390,32 +564,20 @@ function showToast(msg) {
els.toast.textContent = msg;
els.toast.classList.add('show');
clearTimeout(toastTimer);
- toastTimer = setTimeout(() => els.toast.classList.remove('show'), 5000);
-}
-
-// ── Camera animation ─────────────────────────────────────────────────────────
-const camAnim = { active: false, t: 0, dur: 0, fromPos: new THREE.Vector3(), toPos: new THREE.Vector3(), fromTgt: new THREE.Vector3(), toTgt: new THREE.Vector3() };
-
-function flyCamera(toPos, toTgt, dur = 1100) {
- camAnim.fromPos.copy(camera.position);
- camAnim.toPos.copy(toPos);
- camAnim.fromTgt.copy(controls.target);
- camAnim.toTgt.copy(toTgt);
- camAnim.t = 0;
- camAnim.dur = dur;
- camAnim.active = true;
+ toastTimer = setTimeout(() => els.toast.classList.remove('show'), 8000);
}
// ── SSE event handling ────────────────────────────────────────────────────────
+// The idle label is captured from the DOM rather than hardcoded, so a run does
+// not silently reset a translated button back to English.
+let idleLabel = null;
+
function setRunning(on) {
+ if (on && idleLabel === null) idleLabel = els.startBtn.textContent.trim() || FALLBACK_LABEL;
els.startBtn.disabled = on;
els.topicSelect.disabled = on;
- els.startBtn.textContent = on ? '⏳ Running…' : '▶ Run Trade Demo';
- if (!on) controls.autoRotate = true;
-}
-
-function fmt(addr) {
- return addr ? addr.slice(0, 4) + '…' + addr.slice(-4) : '—';
+ els.startBtn.textContent = on ? RUNNING_LABEL : (idleLabel || FALLBACK_LABEL);
+ if (!on) stage?.setAutoRotate(true);
}
function handleEvent(ev) {
@@ -431,9 +593,9 @@ function handleEvent(ev) {
}
}
if (ev.seller?.address) els.sellerAddr.textContent = fmt(ev.seller.address);
- if (ev.network) els.networkBadge.textContent = ev.network;
- controls.autoRotate = false;
- flyCamera(new THREE.Vector3(0, 2.6, 8.8), new THREE.Vector3(0, 1.1, 0), 1200);
+ if (ev.network) els.networkName.textContent = ev.network;
+ stage?.setAutoRotate(false);
+ stage?.flyCamera(vec3(0, 2.6, 8.8), vec3(0, 1.1, 0), 1200);
break;
}
@@ -451,14 +613,14 @@ function handleEvent(ev) {
const m = ev.manifest || {};
const price = m.price || {};
const usdStr = price.usd != null ? ` ≈ $${price.usd}` : '';
- showBubble('seller', `402 — ${price.sol} SOL required`);
+ showBubble('seller', `402: ${price.sol} SOL required`);
showCard(`
- <div class="c-badge c-badge-402">⟶ 402 Payment Required</div>
+ <div class="c-badge c-badge-402">402 Payment Required</div>
<div class="c-label">x402 Protocol · oracle-market-analysis</div>
<div class="c-price blue">${escHtml(price.sol ?? '?')} SOL${escHtml(usdStr)}</div>
<div class="c-row">Recipient <span>${escHtml(fmt(m.recipient))}</span></div>
- <div class="c-row">Network <span>${escHtml(m.network || '—')}</span></div>
- <div class="c-row">Memo <span>${escHtml(m.memo || '—')}</span></div>
+ <div class="c-row">Network <span>${escHtml(m.network || NO_VALUE)}</span></div>
+ <div class="c-row">Memo <span>${escHtml(m.memo || NO_VALUE)}</span></div>
<div class="c-row">Currency <span>${escHtml(m.currency || 'SOL')}</span></div>
`);
setTimeout(() => setChip('challenged', 'done'), 700);
@@ -470,16 +632,16 @@ function handleEvent(ev) {
hideBubble('seller');
hideCard();
showBubble('buyer', `Sending ${ev.sol} SOL on-chain…`);
- startBeam();
+ stage?.startBeam();
// Fly camera to watch the beam from a low angle
- flyCamera(new THREE.Vector3(0, 1.6, 7.2), new THREE.Vector3(0, 0.9, 0), 950);
+ stage?.flyCamera(vec3(0, 1.6, 7.2), vec3(0, 0.9, 0), 950);
break;
}
case 'confirmed': {
setChip('paying', 'done');
setChip('confirmed', 'active');
- triggerBurst();
+ stage?.triggerBurst();
hideBubble('buyer');
setTimeout(() => showBubble('seller', 'Payment confirmed ✓'), 350);
if (ev.newBuyerSol != null) {
@@ -488,13 +650,14 @@ function handleEvent(ev) {
}
const sigShort = ev.signature ? ev.signature.slice(0, 8) + '…' + ev.signature.slice(-6) : '';
const usdStr = ev.usd != null ? ` ≈ $${ev.usd}` : '';
+ const explorer = safeHref(ev.explorer);
showCard(`
<div class="c-badge c-badge-ok">✓ Transaction Confirmed</div>
<div class="c-label">On-Chain · ${escHtml(ev.sol)} SOL${escHtml(usdStr)}</div>
<div class="c-price green">${escHtml(ev.sol)} SOL</div>
<div class="c-row">Signature <span>${escHtml(sigShort)}</span></div>
<div class="c-row">Network <span>${escHtml(ev.network || 'solana')}</span></div>
- ${ev.explorer ? `<a class="c-link" href="${escHtml(safeHref(ev.explorer))}" target="_blank" rel="noopener">View on Solscan →</a>` : ''}
+ ${explorer ? `<a class="c-link" href="${escHtml(explorer)}" target="_blank" rel="noopener">View on Solscan →</a>` : ''}
`);
setTimeout(() => setChip('confirmed', 'done'), 800);
break;
@@ -508,7 +671,7 @@ function handleEvent(ev) {
hideCard();
}, 200);
// Fly back to a wide view
- flyCamera(new THREE.Vector3(0, 3.0, 9.5), new THREE.Vector3(0, 1.2, 0), 1100);
+ stage?.flyCamera(vec3(0, 3.0, 9.5), vec3(0, 1.2, 0), 1100);
break;
}
@@ -516,26 +679,36 @@ function handleEvent(ev) {
setChip('delivering', 'done');
setChip('delivered', 'done');
hideBubble('seller');
- controls.autoRotate = true;
+ stage?.setAutoRotate(true);
+ const explorer = safeHref(ev.explorer);
showCard(`
<div class="c-badge c-badge-ok">✓ Skill Delivered</div>
<div class="c-label">${escHtml(ev.provider || 'AI')} · ${escHtml(ev.topic || '')}</div>
<div class="c-content">${escHtml(ev.content || '')}</div>
<div class="c-powered">
Powered by ${escHtml(ev.model || ev.provider || '')}
- ${ev.explorer ? `&nbsp;·&nbsp;<a class="c-link" style="display:inline" href="${escHtml(safeHref(ev.explorer))}" target="_blank" rel="noopener">tx →</a>` : ''}
+ ${explorer ? `&nbsp;·&nbsp;<a class="c-link" style="display:inline" href="${escHtml(explorer)}" target="_blank" rel="noopener">tx →</a>` : ''}
</div>
`);
+ announce('Trade complete. The analysis is on screen.');
setRunning(false);
break;
}
case 'error': {
STEP_NAMES.forEach((s) => { if (chips[s]?.classList.contains('active')) setChip(s, 'error'); });
- showToast(ev.message || 'Something went wrong');
+ const msg = ev.message || 'Something went wrong';
+ showToast(msg);
+ announce(`Demo stopped: ${msg}`);
setRunning(false);
- beamActive = false;
- beamMat.opacity = 0;
+ stage?.stopBeam();
+ // A deployment with no wallets can never run: say so where the answer is,
+ // rather than leaving a toast the user has to interpret.
+ if (ev.code === 'not_configured') {
+ els.startBtn.disabled = true;
+ showUnconfiguredCard();
+ openConfigOverlay();
+ }
break;
}
}
@@ -551,9 +724,9 @@ function startDemo() {
hideCard();
hideBubble('buyer');
hideBubble('seller');
- beamActive = false;
- beamMat.opacity = 0;
+ stage?.stopBeam();
buildStepLog();
+ announce(`Starting the x402 trade demo for ${topic}.`);
const es = new EventSource(`/api/agent-trade/demo?topic=${encodeURIComponent(topic)}`);
currentEs = es;
@@ -566,12 +739,17 @@ function startDemo() {
es.close();
currentEs = null;
}
- } catch { /* malformed event — ignore */ }
+ } catch { /* malformed event: ignore */ }
};
es.onerror = () => {
- showToast('Stream error — check wallet config and try again.');
+ // Only a genuinely broken stream reaches here: a completed run closes the
+ // EventSource in onmessage above.
+ if (currentEs !== es) return;
+ showToast('The live stream dropped before the trade finished. Check your connection, then run it again.');
+ announce('The live stream dropped before the trade finished.');
setRunning(false);
+ stage?.stopBeam();
es.close();
currentEs = null;
};
@@ -583,89 +761,24 @@ els.startBtn.addEventListener('click', startDemo);
async function checkConfig() {
try {
const r = await fetch('/api/agent-trade/demo?check=1');
- if (!r.ok) return;
+ if (!r.ok) throw new Error(`pre-flight ${r.status}`);
const d = await r.json();
if (!d.configured) {
openConfigOverlay();
els.startBtn.disabled = true;
- } else {
- if (d.buyer?.address) els.buyerAddr.textContent = fmt(d.buyer.address);
- if (d.seller?.address) els.sellerAddr.textContent = fmt(d.seller.address);
- if (d.network) els.networkBadge.textContent = d.network;
- }
- } catch { /* API unreachable — leave button enabled, it will error gracefully */ }
-}
-
-// ── Resize ────────────────────────────────────────────────────────────────────
-window.addEventListener('resize', () => {
- camera.aspect = innerWidth / innerHeight;
- camera.updateProjectionMatrix();
- renderer.setSize(innerWidth, innerHeight);
-});
-
-// ── Animation loop ─────────────────────────────────────────────────────────────
-const clock = new THREE.Timer();
-
-(function animate() {
- requestAnimationFrame(animate);
- clock.update();
- const dt = Math.min(clock.getDelta(), 0.1);
- const t = clock.getElapsed();
-
- // Idle avatar breath
- if (buyerMesh) buyerMesh.position.y = Math.sin(t * 0.75) * 0.022;
- if (sellerMesh) sellerMesh.position.y = Math.sin(t * 0.75 + 1.2) * 0.022;
-
- // Platform ring pulse
- buyerPlatform.ring.material.emissiveIntensity = 1.4 + Math.sin(t * 2.0) * 0.5;
- sellerPlatform.ring.material.emissiveIntensity = 1.4 + Math.sin(t * 2.0 + 1.0) * 0.5;
-
- // Beam travel
- if (beamActive) {
- const B = BUYER_POS, S = SELLER_POS;
- const spread = 0.13;
- for (let i = 0; i < BEAM_N; i++) {
- beamPhases[i] = (beamPhases[i] + beamSpeeds[i] * dt) % 1;
- const ph = beamPhases[i];
- beamPos[i * 3] = B.x + (S.x - B.x) * ph + (Math.random() - 0.5) * spread;
- beamPos[i * 3 + 1] = B.y + 0.9 + (Math.random() - 0.5) * spread;
- beamPos[i * 3 + 2] = (Math.random() - 0.5) * spread;
+ showUnconfiguredCard();
+ return;
}
- beamGeo.attributes.position.needsUpdate = true;
- beamMat.opacity = 0.75 + Math.sin(t * 14) * 0.18;
- } else if (beamMat.opacity > 0) {
- beamMat.opacity = Math.max(0, beamMat.opacity - dt * 2.5);
- if (beamMat.opacity === 0) beamGeo.attributes.position.needsUpdate = true;
+ if (d.buyer?.address) els.buyerAddr.textContent = fmt(d.buyer.address);
+ if (d.seller?.address) els.sellerAddr.textContent = fmt(d.seller.address);
+ if (d.network) els.networkName.textContent = d.network;
+ showReadyCard(d);
+ } catch {
+ // The pre-flight is unreachable. Leave the button live (the run itself
+ // reports the real failure) but say why the wallets are blank.
+ showToast('Could not reach the demo API for a status check. Running the demo will report what failed.');
}
-
- // Burst particles
- if (burstLife > 0) {
- burstLife -= dt * 0.65;
- burstMat.opacity = Math.max(0, burstLife);
- for (let i = 0; i < BURST_N; i++) {
- burstVels[i * 3 + 1] -= 4.8 * dt; // gravity
- burstPos[i * 3] += burstVels[i * 3] * dt;
- burstPos[i * 3 + 1] += burstVels[i * 3 + 1] * dt;
- burstPos[i * 3 + 2] += burstVels[i * 3 + 2] * dt;
- }
- burstGeo.attributes.position.needsUpdate = true;
- if (burstLife <= 0) burstMat.opacity = 0;
- }
-
- // Camera animation
- if (camAnim.active) {
- camAnim.t += dt * 1000;
- const raw = Math.min(camAnim.t / camAnim.dur, 1);
- const ease = raw < 0.5 ? 2 * raw * raw : 1 - (-2 * raw + 2) ** 2 / 2;
- camera.position.lerpVectors(camAnim.fromPos, camAnim.toPos, ease);
- controls.target.lerpVectors(camAnim.fromTgt, camAnim.toTgt, ease);
- if (raw >= 1) camAnim.active = false;
- }
-
- controls.update();
- updateOverlays();
- renderer.render(scene, camera);
-})();
+}
checkConfig();
buildStepLog();