Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(x402): pay the agent-exchange showcase from the platform wallet over a fixed allowlist
nirholasbb5369b6d0c1
diff --git a/api/x402-pay.js b/api/x402-pay.jsindex 1b3cbfd5c..e36587885 100644--- a/api/x402-pay.js+++ b/api/x402-pay.js@@ -280,6 +280,14 @@ const ALLOWED_TOOLS = new Set(['search_public_avatars',]);+// In-house x402 routes the public showcase pages buy from the shared platform+// wallet (/agent-exchange drives the crypto-intel one). This branch is+// unauthenticated, exactly like the MCP `tool` path above, and it spends real+// USDC per call, so what it can buy is a fixed server-side allowlist and never+// a caller-supplied URL. Arbitrary endpoints go through handleExternalPay,+// which is owner-authenticated and pays from that owner's own agent wallet.+const SHOWCASE_ENDPOINTS = new Set(['/api/x402/crypto-intel']);+const SOLANA_RPC = env.SOLANA_RPC_URL;const USDC_MAINNET_MINT = env.X402_ASSET_MINT_SOLANA;@@ -890,6 +898,75 @@ function payErrorStatus(err) {return 500;}+// Buy one of the in-house SHOWCASE_ENDPOINTS from the shared platform wallet and+// stream the payment lifecycle. This is what /agent-exchange runs: the two 3D+// avatars are a view over a real x402 purchase of /api/x402/crypto-intel, so the+// flow here is the same probe → sign → settle path an external agent would take+// against the same public route. Unauthenticated by design (a viewer has no+// wallet), bounded by the per-IP and global rate limits already applied on the+// POST path plus the platform wallet's own balance.+async function handleShowcasePay(req, res, input, ip) {+ const endpoint = String(input.endpoint || '');+ if (!SHOWCASE_ENDPOINTS.has(endpoint)) {+ log.warn('showcase_endpoint_rejected', { endpoint: endpoint.slice(0, 120), ip });+ return json(res, 400, {+ error: 'invalid_endpoint',+ error_description: 'that endpoint is not payable from the showcase wallet',+ allowed: [...SHOWCASE_ENDPOINTS],+ });+ }++ let buyer;+ try {+ buyer = loadAgentKeypair();+ } catch {+ return json(res, 503, {+ error: 'config_missing',+ error_description: 'payment processing not available',+ });+ }++ const url = resolveResourceUrl(req, endpoint);+ const body = input.body && typeof input.body === 'object' ? input.body : {};+ const wantsStream =+ (req.headers.accept || '').includes('text/event-stream') || input.stream === true;++ // No spendGuard: the platform wallet has no per-agent daily policy to charge+ // against. The rate limiters upstream are the ceiling for this path.+ const flowArgs = {+ url,+ method: 'POST',+ body,+ buyer,+ spendGuard: null,+ serviceLabel: typeof input.service_label === 'string' ? input.service_label : null,+ };++ if (wantsStream) {+ sseInit(res);+ const emit = (ev, data) => sseSend(res, ev, data);+ try {+ await runExternalFlow({ ...flowArgs, emit });+ } catch (err) {+ emit('error', payErrorEnvelope(err));+ } finally {+ res.end();+ }+ return;+ }++ let final = null;+ const emit = (ev, data) => {+ if (ev === 'result') final = data;+ };+ try {+ await runExternalFlow({ ...flowArgs, emit });+ } catch (err) {+ return json(res, payErrorStatus(err), payErrorEnvelope(err));+ }+ return json(res, 200, final);+}+// Pay an arbitrary external x402 endpoint from the owner's agent wallet. This is// the money core behind the wallet hub Pay tab. Owner-authenticated + ownership-// gated; the agent key is decrypted server-side via recoverSolanaAgentKeypair@@ -1074,6 +1151,12 @@ export default wrap(async (req, res) => {return handleExternalPay(req, res, input, ip);}+ // Showcase pay: an in-house /api/x402/* route bought from the platform wallet+ // for a public demo page. Allowlisted server-side (SHOWCASE_ENDPOINTS).+ if (typeof input.endpoint === 'string' && input.endpoint) {+ return handleShowcasePay(req, res, input, ip);+ }+const tool = String(input.tool || '');const args = input.args && typeof input.args === 'object' ? input.args : {};if (!ALLOWED_TOOLS.has(tool)) {diff --git a/pages/agent-exchange.html b/pages/agent-exchange.htmlindex becb18893..92f4bc590 100644--- a/pages/agent-exchange.html+++ b/pages/agent-exchange.html@@ -1,19 +1,19 @@<!doctype html><html lang="en"><head>- <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <script>/* three.ws theme boot, no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script><meta charset="utf-8" /><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover" />- <title data-i18n="agent_exchange.meta_title">Agent Exchange — 3D AI agents paying each other in real time · three.ws</title>+ <title data-i18n="agent_exchange.meta_title">Agent Exchange: 3D AI agents paying each other in real time · three.ws</title><meta name="description" content="Two AI agents with 3D bodies negotiate and pay each other for live crypto intel using x402 micropayments on Solana. Every transaction is real and confirmed on-chain." data-i18n-attr="content:agent_exchange.meta_description"/><link rel="canonical" href="https://three.ws/agent-exchange" /><meta property="og:type" content="website" />- <meta property="og:title" content="Agent Exchange — AI agents paying each other in real time" data-i18n-attr="content:agent_exchange.meta_og_title"/>+ <meta property="og:title" content="Agent Exchange: AI agents paying each other in real time" data-i18n-attr="content:agent_exchange.meta_og_title"/><meta property="og:description" content="Two 3D AI agents buy and sell crypto intel for real USDC on Solana. Watch every transaction confirm on-chain." data-i18n-attr="content:agent_exchange.meta_og_description"/><meta property="og:url" content="https://three.ws/agent-exchange" /><meta property="og:image" content="https://three.ws/api/page-og?s=crypto&t=Agent+Exchange&d=Two+AI+agents+with+3D+bodies+negotiate+and+pay+each+other+for+live+crypto+intel+using+x402+micropayments+on+Solana.+Every+transaction+is+real+and+confirmed&p=%2Fagent-exchange" /><meta name="twitter:card" content="summary_large_image" />- <meta name="twitter:title" content="Agent Exchange — AI agents paying each other in real time" data-i18n-attr="content:agent_exchange.meta_twitter_title"/>+ <meta name="twitter:title" content="Agent Exchange: AI agents paying each other in real time" data-i18n-attr="content:agent_exchange.meta_twitter_title"/><meta name="twitter:description" content="Two 3D AI agents paying each other for real crypto intel. USDC on Solana. On-chain." data-i18n-attr="content:agent_exchange.meta_twitter_description"/><meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&t=Agent+Exchange&d=Two+AI+agents+with+3D+bodies+negotiate+and+pay+each+other+for+live+crypto+intel+using+x402+micropayments+on+Solana.+Every+transaction+is+real+and+confirmed&p=%2Fagent-exchange" /><link rel="icon" href="/favicon.ico" sizes="any" />@@ -59,6 +59,13 @@grid-template-rows: 52px 1fr auto;height:100%;}+ /* Grid and flex children default to min-width:auto, which refuses to shrink+ below their content. The body never scrolls, so on a 320px screen that+ silently clips the top bar and the stage strip off the right edge instead+ of wrapping or scrolling them. Opting out lets each row shrink and hand+ overflow to the scroller that owns it (.stages). */+ #app > * { min-width:0; }+ .topbar > *, .topic-row, .stages, #exchange > * { min-width:0; }/* ── Top bar ─────────────────────────────────────────── */.topbar {@@ -244,14 +251,26 @@.signal-bullish { background:rgba(34,215,122,0.15); color:var(--green); border:1px solid rgba(34,215,122,0.3); }.signal-bearish { background:rgba(255,79,106,0.13); color:var(--red); border:1px solid rgba(255,79,106,0.3); }.signal-neutral { background:rgba(245,166,35,0.13); color:var(--amber); border:1px solid rgba(245,166,35,0.3); }+ .receipt .r-rationale { margin-top:6px; font-size:12.5px; color:var(--muted); line-height:1.5; }++ /* The arena IS the content, so the document heading exists for assistive+ tech and search engines rather than for sighted layout. */+ .sr-only {+ position:absolute; width:1px; height:1px; padding:0; margin:-1px;+ overflow:hidden; clip:rect(0 0 0 0); white-space:nowrap; border:0;+ }/* ── Mobile ──────────────────────────────────────────── */+ /* The top bar wraps instead of clipping: the body never scrolls, so a+ fixed-height bar would silently cut the session total off at 320px.+ Every topic chip stays reachable at every width; hiding the tail of the+ list would make a selectable topic unselectable on a phone. */@media (max-width:640px) {- #app { grid-template-rows: 48px 1fr auto; }- .agents { grid-template-columns:1fr 1fr; }+ #app { grid-template-rows: auto 1fr auto; }+ .topbar { flex-wrap:wrap; gap:8px 10px; padding:8px 14px; }+ .tx-ticker { order:3; flex-basis:100%; font-size:11px; }.bubble { display:none; }- .exchange { padding:10px 14px 16px; }- .topics .t-chip:nth-child(n+5) { display:none; }+ #exchange { padding:10px 14px 16px; }.pay-btn { align-self:stretch; justify-content:center; }}@media (prefers-reduced-motion:reduce) { .pay-btn.busy .spin,.stage.active .si,.nr-dot { animation:none; } }@@ -293,7 +312,7 @@<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 Exchange — three.ws">+ <meta property="og:image:alt" content="Agent Exchange · three.ws"><meta name="twitter:site" content="@trythreews"></head><body>@@ -314,13 +333,17 @@<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M12 8v4l3 3"/></svg>x402 demo</a>- <a class="tb-btn" href="/x402" title="x402 — the payment trust layer behind these settlements" data-i18n-attr="title:agent_exchange.x402_the_payment_trust_layer_title">+ <a class="tb-btn" href="/x402" title="x402: the payment trust layer behind these settlements" data-i18n-attr="title:agent_exchange.x402_the_payment_trust_layer_title"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>Trust Layer</a></div></header>+ <h1 class="sr-only" data-i18n="agent_exchange.page_heading">+ Agent Exchange: two 3D AI agents buying and selling live crypto intel for real USDC on Solana+ </h1>+<!-- ── Arena: two agents face each other ─────────────── --><section id="arena" aria-label="Two AI agents"><div class="agents">@@ -349,7 +372,7 @@</div><button class="pay-btn" id="payBtn" type="button" data-i18n-html="agent_exchange.buy_intel_0_01_usdc"><span class="spin" aria-hidden="true"></span>- <span class="lbl">Buy intel — $0.01 USDC</span>+ <span class="lbl">Buy intel · $0.01 USDC</span></button></div>diff --git a/src/agent-exchange.js b/src/agent-exchange.jsindex 2e435ca11..ecf779e75 100644--- a/src/agent-exchange.js+++ b/src/agent-exchange.js@@ -1,8 +1,14 @@// ── agent-exchange.js ────────────────────────────────────────────────────────// Two 3D AI avatars buying and selling live crypto intel for real USDC via x402.// Agent A (seller) hosts /api/x402/crypto-intel. Agent B (buyer) pays $0.01 per-// call through the server-side x402 payer at /api/x402-pay, which handles the-// challenge → sign → verify → settle → confirm flow and streams SSE events.+// call through the server-side x402 payer at /api/x402-pay, which probes the 402+// challenge, signs the Solana transfer, replays the request with the payment,+// and streams each step back as SSE events.+//+// The stage strip below mirrors those SSE events one-for-one. It deliberately+// carries no step the server does not report: an x402 purchase of an external+// route verifies and settles inside the paid request itself, so there is no+// separate verify or dispatch signal to show.//// Every on-chain confirmation is real: real USDC on Solana mainnet, real Solscan// link. The avatars are iframed into the page and driven via postMessage.@@ -20,34 +26,33 @@ const TOPICS = [{ id: 'bnb', label: '⬡ BNB' },];-// Stage config matches the SSE event names /api/x402-pay emits.+// Stage config matches the SSE event names /api/x402-pay emits, one stage per+// event, plus the terminal 'done' the client resolves once the result lands.// narration: plain-language line shown to the viewer as each stage arrives.const STAGE_DEFS = [- { id: 'challenge', label: '402 Challenge', narration: 'The seller issued a $0.01 USDC payment challenge — the buyer is building a Solana transaction.' },- { id: 'built', label: 'Build tx', narration: 'Transaction signed. Submitting to the x402 facilitator for verification…' },- { id: 'verified', label: 'Verify', narration: 'Payment verified by the facilitator. Dispatching the intel request…' },- { id: 'dispatched', label: 'Dispatch', narration: 'Request dispatched — the intel agent is preparing the market signal.' },- { id: 'settled', label: 'Settle', narration: 'Settling USDC on Solana mainnet — a real on-chain transfer is confirming.' },+ { id: 'challenge', label: '402 Challenge', narration: 'The intel agent answered with a $0.01 USDC payment challenge. The buyer is building a Solana transaction.' },+ { id: 'built', label: 'Sign tx', narration: 'Transaction signed. Replaying the request with the payment attached…' },+ { id: 'settled', label: 'Settle', narration: 'Settling USDC on Solana mainnet. A real on-chain transfer is confirming.' },{ id: 'done', label: 'Confirmed', narration: 'Confirmed on-chain. Intel delivered.' },];-// Terminal failure stage — rendered alongside the flow stages but hidden until+// Terminal failure stage: rendered alongside the flow stages but hidden until// a payment errors out, times out, or is rejected. It always reflects the final// failure reason so the viewer sees exactly where the exchange stopped.const ERROR_STAGE = { id: 'failed', label: 'Failed', narration: 'Payment did not complete. No funds were moved.' };// How long a single x402-pay request may run before we abort it and surface a-// timeout. The full challenge→settle flow is fast; 30s covers a slow facilitator-// or RPC without leaving the viewer staring at a hung "Paying…" button.+// timeout. The full challenge to settle flow is fast; 30s covers a slow+// facilitator or RPC without leaving the viewer staring at a hung "Paying…"+// button.const PAY_TIMEOUT_MS = 30000;-// Agent scripts — lines spoken at each stage of the exchange.+// Agent scripts: lines spoken at each stage of the exchange.const LINES = {A: {idle: 'I have live crypto intel. $0.01 USDC per signal, settled on-chain.',challenge: 'Payment challenge issued. Awaiting your signed transaction…',- built: 'Transaction received. Forwarding to the facilitator…',- verified: 'Payment verified. Preparing the intel…',+ built: 'Transaction received. Verifying and settling now…',settled: 'Funds confirmed on-chain. Delivering now.',done: (headline) => `Here's your signal: ${headline}`,error: 'Payment failed. No charge made.',@@ -55,8 +60,7 @@ const LINES = {B: {idle: (topic) => `I need live ${topic.toUpperCase()} intelligence. Initiating payment.`,challenge: 'Building and signing the Solana transfer…',- built: 'Signed. Sending to the facilitator for verification.',- verified: 'Verified on-chain. Waiting for settlement…',+ built: 'Signed. Sending the paid request through.',settled: 'Settled. Collecting my intel.',done: (signal) => `Signal received: ${signal.toUpperCase()}. Updating my model.`,error: 'Transaction rolled back. Wallet unchanged.',@@ -78,14 +82,22 @@ const els = {bubbleBText: $('bubbleBText'),topics: $('topics'),payBtn: $('payBtn'),- payLabel: null, // set in init()stages: $('stages'),receipt: $('receipt'),- totalUsdc: $('totalUsdc'),narration: $('narration'),walletState: $('walletState'),};+// #txTicker and #payBtn both carry data-i18n-html, so the runtime translator+// swaps their innerHTML after first paint and any child captured at init would+// become a detached node that silently stops updating. Resolve these two at use+// time instead of caching them.+const totalUsdc = () => $('totalUsdc');+function setPayLabel(text) {+ const lbl = els.payBtn.querySelector('.lbl');+ if (lbl) lbl.textContent = text;+}+// ── State ─────────────────────────────────────────────────────────────────────let activeTopic = 'sol';let busy = false;@@ -187,31 +199,47 @@ function resetStages() {}// ── Receipt renderer ──────────────────────────────────────────────────────────+// Signal classes are looked up, never interpolated: the signal string comes off+// the wire, and a class name is one of the few places escHtml cannot help.+const SIGNAL_CLASS = { bullish: 'signal-bullish', bearish: 'signal-bearish', neutral: 'signal-neutral' };+const SIGNAL_GLYPH = { bullish: '▲', bearish: '▼', neutral: '→' };++// Solana signatures and addresses are base58. Anything else is not a value we+// will put in an href or a receipt field.+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,90}$/;+function shortB58(v, head, tail) {+ const s = typeof v === 'string' ? v : '';+ if (!BASE58_RE.test(s)) return 'unavailable';+ return `${s.slice(0, head)}…${s.slice(-tail)}`;+}+function renderReceipt(payment, intel) {const humanAmount = payment.amount ? Number(payment.amount) / 1e6 : 0.01;const amountStr = `${humanAmount.toFixed(4)} USDC`;const usdEqStr = formatUsdcEq(humanAmount);- const amount = usdEqStr ? `${amountStr} <span style="color:rgba(255,255,255,.45);font-size:0.9em">${usdEqStr}</span>` : amountStr;- const payer = payment.payer ? `${payment.payer.slice(0, 8)}…${payment.payer.slice(-4)}` : '—';- const payTo = payment.payTo ? `${payment.payTo.slice(0, 8)}…${payment.payTo.slice(-4)}` : '—';- const txShort = payment.tx ? `${payment.tx.slice(0, 10)}…${payment.tx.slice(-6)}` : null;- const explorer = payment.tx ? `https://solscan.io/tx/${payment.tx}` : null;- const signalCls = `signal-${intel.signal}`;- const signalEmoji = { bullish: '▲', bearish: '▼', neutral: '→' }[intel.signal] || '';-- const changeStr = intel.change_24h != null+ const amount = usdEqStr ? `${escHtml(amountStr)} <span style="color:rgba(255,255,255,.45);font-size:0.9em">${escHtml(usdEqStr)}</span>` : escHtml(amountStr);+ const payer = escHtml(shortB58(payment.payer, 8, 4));+ const payTo = escHtml(shortB58(payment.payTo, 8, 4));+ const tx = typeof payment.tx === 'string' && BASE58_RE.test(payment.tx) ? payment.tx : null;+ const txShort = tx ? escHtml(shortB58(tx, 10, 6)) : null;+ const explorer = tx ? `https://solscan.io/tx/${encodeURIComponent(tx)}` : null;+ const signal = SIGNAL_CLASS[intel.signal] ? intel.signal : 'neutral';+ const signalCls = SIGNAL_CLASS[signal];+ const signalGlyph = SIGNAL_GLYPH[signal];++ const changeStr = Number.isFinite(intel.change_24h)? ` ${intel.change_24h >= 0 ? '+' : ''}${intel.change_24h.toFixed(2)}% 24h`: '';- const priceStr = intel.price_usd != null+ const priceStr = Number.isFinite(intel.price_usd)? ` · $${intel.price_usd >= 100 ? intel.price_usd.toFixed(2) : intel.price_usd.toFixed(4)}`: '';els.receipt.innerHTML =`<div class="r-head">` +`<span class="r-badge">` +- `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg>` ++ `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 6 9 17l-5-5"/></svg>` +`Confirmed on-chain · ${amount}</span>` +- `<span class="r-time">${new Date().toLocaleTimeString()}</span>` ++ `<span class="r-time">${escHtml(new Date().toLocaleTimeString())}</span>` +`</div>` +`<div class="r-grid">` +`<div class="rf"><span class="k">Payer (buyer agent)</span><span class="v">${payer}</span></div>` +@@ -222,9 +250,10 @@ function renderReceipt(payment, intel) {: '') +`</div>` +`<div class="r-headline">` +- `<span class="r-signal ${signalCls}">${signalEmoji} ${intel.signal.toUpperCase()}</span>` +- `<strong>${escHtml(intel.topic.toUpperCase())}</strong>${escHtml(priceStr)}${escHtml(changeStr)} · ` ++ `<span class="r-signal ${signalCls}">${signalGlyph} ${escHtml(signal.toUpperCase())}</span>` ++ `<strong>${escHtml(String(intel.topic || '').toUpperCase())}</strong>${escHtml(priceStr)}${escHtml(changeStr)} · ` +escHtml(intel.headline) ++ (intel.rationale ? `<div class="r-rationale">${escHtml(intel.rationale)}</div>` : '') +`</div>`;els.receipt.classList.add('show');@@ -235,7 +264,7 @@ function renderReceipt(payment, intel) {function showEmptyState() {els.narration.innerHTML =`<div class="nr-pre">` +- `<span class="nr-kicker">What you'll watch —</span>` ++ `<span class="nr-kicker">What you'll watch:</span>` +`<span>Intel Agent issues a $0.01 USDC challenge</span>` +`<span class="nr-arrow">→</span>` +`<span>Buyer signs a Solana transaction</span>` +@@ -268,7 +297,7 @@ function narrateDone(intelObj, paymentObj) {els.narration.innerHTML =`<div class="nr-done">` +`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 6 9 17l-5-5"/></svg>` +- `${escHtml(amount)} USDC settled — ${escHtml(topic)} intelligence delivered.${txLink}` ++ `${escHtml(amount)} USDC settled. ${escHtml(topic)} intelligence delivered.${txLink}` +`</div>`;}@@ -285,12 +314,12 @@ async function checkWallet() {`Demo wallet not configured` +`</div>` +`<div class="ws-body">` +- `This demo settles real USDC on Solana mainnet. The agent wallet isn't configured right now — live settlements are paused. ` ++ `This demo settles real USDC on Solana mainnet. The agent wallet isn't configured right now, so live settlements are paused. ` +`To enable: set <span class="ws-mono">X402_AGENT_SOLANA_SECRET_BASE58</span> and fund the wallet.` +`</div>`;els.payBtn.disabled = true;} else if (typeof b.usdc === 'number' && b.usdc < 0.01) {- const addr = b.address ? `${b.address.slice(0, 8)}…${b.address.slice(-4)}` : '—';+ const addr = b.address ? `${b.address.slice(0, 8)}…${b.address.slice(-4)}` : 'unavailable';els.walletState.className = 'show ws-low';els.walletState.innerHTML =`<div class="ws-head">` +@@ -298,12 +327,12 @@ async function checkWallet() {`Agent wallet low on USDC` +`</div>` +`<div class="ws-body">` +- `The buyer wallet holds ${b.usdc.toFixed(4)} USDC — below the $0.01 minimum for a live settlement. ` ++ `The buyer wallet holds ${b.usdc.toFixed(4)} USDC, below the $0.01 minimum for a live settlement. ` +`Fund <span class="ws-mono">${escHtml(addr)}</span> with USDC on Solana mainnet to run the demo.` +`</div>`;}} catch {- // Network failures silently ignored — don't block the page.+ // Network failures silently ignored so they never block the page.}}@@ -313,14 +342,14 @@ async function doPurchase() {busy = true;els.payBtn.classList.add('busy');els.payBtn.disabled = true;- els.payLabel.textContent = 'Paying…';+ setPayLabel('Paying…');resetStages();// Show "initiating" in the narration region immediately.els.narration.innerHTML =`<div class="nr-live">` +`<span class="nr-dot" aria-hidden="true"></span>` +- `<span class="nr-text">Initiating payment — connecting to the x402 facilitator…</span>` ++ `<span class="nr-text">Initiating payment. Connecting to the x402 endpoint…</span>` +`</div>`;// Both agents react to the initiation.@@ -372,23 +401,11 @@ async function doPurchase() {sayA(LINES.A.challenge);} else if (event === 'built') {setStage('built', 'done', `${data.build_ms} ms`);- setStage('verified', 'active', 'facilitator…');- activeStage = 'verified';+ setStage('settled', 'active', 'on-chain…');+ activeStage = 'settled';narrate('built', `(${data.build_ms} ms)`);sayB(LINES.B.built);sayA(LINES.A.built);- } else if (event === 'verified') {- setStage('verified', 'done', `${data.verify_ms} ms`);- setStage('dispatched', 'active', 'dispatching…');- activeStage = 'dispatched';- narrate('verified', `(${data.verify_ms} ms)`);- sayB(LINES.B.verified);- sayA(LINES.A.verified);- } else if (event === 'dispatched') {- setStage('dispatched', 'done', `${data.dispatch_ms} ms`);- setStage('settled', 'active', 'on-chain…');- activeStage = 'settled';- narrate('dispatched');} else if (event === 'settled') {setStage('settled', 'done', `${data.settle_ms} ms · ${data.tx ? data.tx.slice(0, 8) + '…' : ''}`);setStage('done', 'active');@@ -398,7 +415,7 @@ async function doPurchase() {sayB(LINES.B.settled);sayA(LINES.A.settled);} else if (event === 'result') {- // result carries { ok, tool, args, result: <intelObj>, payment: <paymentObj>, durations }+ // result carries { ok, result: <intelObj>, payment: <paymentObj>, resource, durations }if (data.result != null) intel = data.result;if (data.payment) settled = { ...settled, ...data.payment };} else if (event === 'error') {@@ -425,9 +442,12 @@ async function doPurchase() {// Update session total.const paidAmount = settled.amount ? Number(settled.amount) / 1e6 : 0.01;sessionTotal += paidAmount;- els.totalUsdc.textContent = `$${sessionTotal.toFixed(2)}`;- els.totalUsdc.classList.add('flash');- setTimeout(() => els.totalUsdc.classList.remove('flash'), 600);+ const ticker = totalUsdc();+ if (ticker) {+ ticker.textContent = `${sessionTotal.toFixed(2)}`;+ ticker.classList.add('flash');+ setTimeout(() => ticker.classList.remove('flash'), 600);+ }renderReceipt(settled, intel);@@ -436,7 +456,7 @@ async function doPurchase() {focusReceipt();} catch (err) {- // A timeout surfaces as an AbortError — translate it into a clear reason.+ // A timeout surfaces as an AbortError; translate it into a clear reason.const timedOut = err?.name === 'AbortError';const reason = timedOut? `No response in ${Math.round(PAY_TIMEOUT_MS / 1000)}s`@@ -452,8 +472,8 @@ async function doPurchase() {gestureA('idle');const headline = timedOut- ? 'Payment timed out — no funds moved'- : 'Payment failed — no funds moved';+ ? 'Payment timed out, no funds moved'+ : 'Payment failed, no funds moved';const body = timedOut? 'The payment service did not respond in time. No USDC left the wallet. Pick a topic and try again.': escHtml(reason);@@ -477,7 +497,7 @@ async function doPurchase() {busy = false;els.payBtn.classList.remove('busy');els.payBtn.disabled = false;- els.payLabel.textContent = 'Buy intel — $0.01 USDC';+ setPayLabel('Buy intel · $0.01 USDC');}}@@ -543,7 +563,7 @@ function buildTopics() {}function mountAvatars() {- // Agent A (seller) — faces right (mirror = true flips the avatar).+ // Agent A (seller) sits on the left of the arena.const aqA = new URLSearchParams();aqA.set('model', '/avatars/default.glb');aqA.set('bg', 'transparent');@@ -553,7 +573,7 @@ function mountAvatars() {aqA.set('overlayMode', '1');els.frameA.src = `/avatar-embed.html?${aqA}`;- // Agent B (buyer) — same setup on the right side.+ // Agent B (buyer) uses the same setup on the right side.const aqB = new URLSearchParams();aqB.set('model', '/avatars/default.glb');aqB.set('bg', 'transparent');@@ -565,8 +585,6 @@ function mountAvatars() {}function init() {- els.payLabel = els.payBtn.querySelector('.lbl');-buildTopics();renderStages();mountAvatars();