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 memory endpoints, coin distribution, and game surfaces

nirholas285bbff1113e
diff --git a/api/_lib/coin/distribution.js b/api/_lib/coin/distribution.js
index 3f45e801c..5e9b569a2 100644
--- a/api/_lib/coin/distribution.js
+++ b/api/_lib/coin/distribution.js
@@ -314,6 +314,8 @@ export async function resolvePendingDraws(coin) {
// ─── Reflection ─────────────────────────────────────────────────────────────
+const ALLOC_CHUNK = 2000; // rows per batched reflection write — keeps statements under Neon size limits
+
/**
* Compute the next reflection batch id (one per reflection_interval_seconds).
*/
@@ -368,28 +370,51 @@ export async function allocateReflection(coin, nowMs = Date.now()) {
if (totalBalance === 0n) return { batchId, status: 'no_balance', queued: 0 };
let allocated = 0n;
- let queued = 0;
const MIN_PAYOUT = 1_000n; // 0.000001 SOL — skip dust to keep tx batches efficient
+ // Compute every (wallet, share) pair in memory first, then flush both the
+ // coin_payouts insert and the coin_holders accrual as set-based unnest
+ // statements. A per-holder loop would issue 2*N serial Neon round-trips and
+ // risk a mid-loop timeout leaving the pot partially drained; batching makes
+ // each chunk a single statement. Mirrors the unnest upsert in
+ // api/_lib/agent-embeddings.js and persistHolderSnapshot.
+ const allocations = [];
for (const h of holders) {
const share = (pot * h.balance) / totalBalance;
if (share < MIN_PAYOUT) continue;
+ allocations.push({ wallet: h.wallet, share });
+ allocated += share;
+ }
+ const queued = allocations.length;
+
+ for (let i = 0; i < allocations.length; i += ALLOC_CHUNK) {
+ const chunk = allocations.slice(i, i + ALLOC_CHUNK);
+ const wallets = chunk.map((a) => a.wallet);
+ const shareStrs = chunk.map((a) => a.share.toString());
+ const coinIds = chunk.map(() => coin.id);
+ const batchIds = chunk.map(() => batchId);
+
await sql`
- insert into coin_payouts (
- coin_id, kind, wallet, amount_lamports, batch_id, status
- ) values (
- ${coin.id}, 'reflection', ${h.wallet}, ${share.toString()}::bigint,
- ${batchId}, 'pending'
- )
+ insert into coin_payouts (coin_id, kind, wallet, amount_lamports, batch_id, status)
+ select u.coin_id, 'reflection', u.wallet, u.share, u.batch_id, 'pending'
+ from unnest(
+ ${coinIds}::uuid[],
+ ${wallets}::text[],
+ ${shareStrs}::bigint[],
+ ${batchIds}::text[]
+ ) as u(coin_id, wallet, share, batch_id)
on conflict (batch_id, wallet) do nothing
`;
+
await sql`
- update coin_holders
- set accrued_reflection_lamports = accrued_reflection_lamports + ${share.toString()}::bigint
- where coin_id = ${coin.id} and wallet = ${h.wallet}
+ update coin_holders h
+ set accrued_reflection_lamports = h.accrued_reflection_lamports + d.share
+ from unnest(
+ ${wallets}::text[],
+ ${shareStrs}::bigint[]
+ ) as d(wallet, share)
+ where h.coin_id = ${coin.id} and h.wallet = d.wallet
`;
- allocated += share;
- queued += 1;
}
// Drain the allocated portion from the reflection pot. Rounding dust stays.
diff --git a/api/_lib/coin/holders.js b/api/_lib/coin/holders.js
index 454ea56d3..21c5b1728 100644
--- a/api/_lib/coin/holders.js
+++ b/api/_lib/coin/holders.js
@@ -22,6 +22,7 @@ import { createHelius } from 'helius-sdk';
const PAGE_LIMIT = 1000;
const MAX_PAGES = 200; // hard ceiling — 200k holders before we abort, matches Helius limits
+const UPSERT_CHUNK = 2000; // rows per batched upsert — keeps statements under Neon size limits
let _heliusMainnet = null;
let _heliusDevnet = null;
@@ -96,14 +97,23 @@ export async function persistHolderSnapshot({ coinId, balances }) {
const now = new Date();
const wallets = [...balances.keys()];
- // Insert/update each wallet. Postgres jsonb-style would be nice but we
- // don't have batch tooling wired in; for snapshots of a few thousand
- // holders this is fast enough on Solana traffic.
- for (const wallet of wallets) {
- const bal = balances.get(wallet);
+ // Batched multi-row upsert via unnest — one round-trip per chunk instead of
+ // one per holder. For a popular mint that is thousands of holders, so a
+ // per-wallet loop over the Neon HTTP driver would be thousands of serial
+ // round-trips. Chunk to stay under Postgres statement-size limits. Mirrors
+ // the unnest upsert in api/_lib/agent-embeddings.js.
+ for (let i = 0; i < wallets.length; i += UPSERT_CHUNK) {
+ const chunk = wallets.slice(i, i + UPSERT_CHUNK);
+ const coinIds = chunk.map(() => coinId);
+ const balanceStrs = chunk.map((w) => balances.get(w).toString());
await sql`
insert into coin_holders (coin_id, wallet, balance, first_seen, last_seen)
- values (${coinId}, ${wallet}, ${bal.toString()}, ${now}, ${now})
+ select u.coin_id, u.wallet, u.balance, ${now}, ${now}
+ from unnest(
+ ${coinIds}::uuid[],
+ ${chunk}::text[],
+ ${balanceStrs}::bigint[]
+ ) as u(coin_id, wallet, balance)
on conflict (coin_id, wallet) do update set
balance = excluded.balance,
last_seen = excluded.last_seen
diff --git a/api/agents/_id/memory/[cid].js b/api/agents/_id/memory/[cid].js
index a29f575e9..5326f005e 100644
--- a/api/agents/_id/memory/[cid].js
+++ b/api/agents/_id/memory/[cid].js
@@ -11,6 +11,11 @@ const IPFS_GATEWAYS = [
const CID_RE = /^[a-zA-Z0-9]+$/;
+// Mirror pin.js's per-file ceiling. A pinned memory file is capped at 512 KB on
+// write, so a gateway response larger than that is not one of our files — bound
+// it to avoid streaming an arbitrary-size body back through the proxy.
+const MAX_BYTES = 512 * 1024;
+
async function fetchFromIPFS(cid) {
let lastErr;
for (const gw of IPFS_GATEWAYS) {
@@ -52,8 +57,25 @@ export default wrap(async (req, res) => {
const rl = await limits.authIp(clientIp(req));
if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+ // Bind the CID to this agent's own pinned set. Owning the agent is not enough
+ // — without this the route is a generic authenticated IPFS fetch proxy for any
+ // CID, defeating the "prevent enumeration" intent in the comment above.
+ const [pin] =
+ await sql`SELECT cid FROM agent_memory_pins WHERE agent_id = ${agentId} AND cid = ${cid} LIMIT 1`;
+ if (!pin) return error(res, 404, 'not_found', 'memory file not found for this agent');
+
const ipfsResp = await fetchFromIPFS(cid);
+
+ // Bound the proxied body. Trust the gateway's Content-Length when present, then
+ // re-check the materialized buffer (a lying header can't exceed the real cap).
+ const declared = Number(ipfsResp.headers.get('content-length') || 0);
+ if (declared > MAX_BYTES) {
+ return error(res, 413, 'payload_too_large', 'memory file exceeds size limit');
+ }
const buf = Buffer.from(await ipfsResp.arrayBuffer());
+ if (buf.byteLength > MAX_BYTES) {
+ return error(res, 413, 'payload_too_large', 'memory file exceeds size limit');
+ }
res.statusCode = 200;
res.setHeader('Content-Type', 'application/octet-stream');
diff --git a/api/agents/_id/memory/pin.js b/api/agents/_id/memory/pin.js
index 700de2992..175c50a49 100644
--- a/api/agents/_id/memory/pin.js
+++ b/api/agents/_id/memory/pin.js
@@ -73,5 +73,16 @@ export default wrap(async (req, res) => {
}
const cid = await pinViaPinata(buf, body.filename);
+
+ // Record the CID against this agent so the read proxy
+ // (GET /api/agents/:id/memory/:cid) can verify ownership of the CID itself,
+ // not just of the agent — otherwise any owner could proxy-fetch any CID.
+ await sql`
+ INSERT INTO agent_memory_pins (agent_id, cid, filename, bytes)
+ VALUES (${agentId}, ${cid}, ${body.filename}, ${buf.byteLength})
+ ON CONFLICT (agent_id, cid)
+ DO UPDATE SET filename = excluded.filename, bytes = excluded.bytes
+ `;
+
return json(res, 200, { cid });
});
diff --git a/api/agents/by-address/[addr].js b/api/agents/by-address/[addr].js
index 43c78a5e9..dfc1ba290 100644
--- a/api/agents/by-address/[addr].js
+++ b/api/agents/by-address/[addr].js
@@ -18,6 +18,13 @@ const ENUM_ABI = [
const _cache = new Map();
const CACHE_TTL = 60_000;
const RPC_TIMEOUT = 3_000;
+// `addr` is caller-supplied; balanceOf can return an arbitrarily large count
+// (an attacker can mint themselves many tokens, or target a large holder), so
+// reading `count` tokens via tokenOfOwnerByIndex + tokenURI would fan one HTTP
+// request out into thousands of upstream RPC calls. Cap enumeration to a sane
+// maximum and flag the result as truncated, mirroring the bounded limits used
+// elsewhere (suggest.js, nfts.js).
+const MAX_ENUM = 50;
function cacheGet(key) {
const entry = _cache.get(key);
diff --git a/api/x/post.js b/api/x/post.js
index 2be1e9442..c8ce34a3d 100644
--- a/api/x/post.js
+++ b/api/x/post.js
@@ -4,6 +4,8 @@
import { getSessionUser } from '../_lib/auth.js';
import { cors, method, wrap, error, readJson, json } from '../_lib/http.js';
+import { requireCsrf } from '../_lib/csrf.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
import { publishTweet, XPostError } from '../_lib/x-post.js';
export default wrap(async (req, res) => {
@@ -13,6 +15,14 @@ export default wrap(async (req, res) => {
const user = await getSessionUser(req);
if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+ // Publishing to the user's connected X account is a sensitive state change —
+ // gate it behind CSRF like the rest of the write surface (marketplace, etc.),
+ // and rate-limit so a leaked session can't spam the account.
+ if (!(await requireCsrf(req, res, user.id))) return;
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
const body = await readJson(req);
const text = typeof body?.text === 'string' ? body.text : '';
const threadParts = Array.isArray(body?.thread_parts) ? body.thread_parts : null;
diff --git a/mcp-server/src/index.js b/mcp-server/src/index.js
index a361dc651..c6f9ec542 100755
--- a/mcp-server/src/index.js
+++ b/mcp-server/src/index.js
@@ -24,7 +24,7 @@ import { pathToFileURL } from 'node:url';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
-import { getLastFacilitatorInitError, getResourceServer } from './payments.js';
+import { assertPaymentEnv, getLastFacilitatorInitError, getResourceServer } from './payments.js';
import { buildPoseSeedTool } from './tools/pose-seed.js';
import { buildPumpSnapshotTool } from './tools/pump-snapshot.js';
import { buildAgentReputationTool } from './tools/agent-reputation.js';
@@ -124,6 +124,10 @@ export async function buildServer() {
* /supported fetch cost, then connects the StdioServerTransport.
*/
async function main() {
+ // Fail fast: a running server that can't receive payments is useless. This
+ // is the ONLY startup env gate — it does not run during buildServer()/tests.
+ assertPaymentEnv();
+
// Force the shared x402 resource server to initialize before any tool is
// invoked — this fetches /supported from each facilitator so verify + settle
// don't pay that cost on the first paid call.
diff --git a/mcp-server/src/payments.js b/mcp-server/src/payments.js
index 43bf01475..7b943d89c 100644
--- a/mcp-server/src/payments.js
+++ b/mcp-server/src/payments.js
@@ -43,12 +43,24 @@ function requireSvmPayTo() {
const addr = env('MCP_SVM_PAYMENT_ADDRESS') || env('X402_PAY_TO_SOLANA') || env('X402_PAY_TO');
if (!addr) {
throw new Error(
- 'mcp-server: set MCP_SVM_PAYMENT_ADDRESS (or X402_PAY_TO_SOLANA / X402_PAY_TO) to receive Solana USDC payments',
+ 'mcp-server: set MCP_SVM_PAYMENT_ADDRESS to receive Solana USDC payments (or X402_PAY_TO_SOLANA / X402_PAY_TO)',
);
}
return addr;
}
+/**
+ * Assert the receiving Solana payment address is configured. Called once by the
+ * stdio entry point so a running server fails fast with a single clean line
+ * instead of only erroring on the first paid call. Does NOT run during
+ * `buildServer()`/tests — tool registration stays secret-free.
+ *
+ * @throws {Error} with a single actionable message when no pay-to is set
+ */
+export function assertPaymentEnv() {
+ requireSvmPayTo();
+}
+
function svmFeePayer() {
return env('X402_FEE_PAYER_SOLANA', '2wKupLR9q6wXYppw8Gr2NvWxKBUqm4PPJKkQfoxHDBg4');
}
diff --git a/pages/features.html b/pages/features.html
index 9b7a934c5..e4e431d2d 100644
--- a/pages/features.html
+++ b/pages/features.html
@@ -55,18 +55,7 @@
<body class="home-page">
<div class="cursor" id="cursor" aria-hidden="true"></div>
<a href="#main-content" class="h-skip-link">Skip to main content</a>
- <header>
- <h1>
- <a href="/" aria-label="three.ws home"
- ><img class="wordmark-logo" src="/three.svg" alt="" aria-hidden="true" /><span
- class="wordmark-dot"
- aria-hidden="true"
- ></span
- >three.ws</a
- >
- </h1>
- <div id="nav-container"></div>
- </header>
+ <header><div id="nav-container"></div></header>
<script src="/nav.js"></script>
<main id="main-content" class="home-parallax">
diff --git a/pages/home-classic.html b/pages/home-classic.html
index d826a0fbc..f64a51211 100644
--- a/pages/home-classic.html
+++ b/pages/home-classic.html
@@ -117,18 +117,7 @@
<body class="home-page">
<div class="cursor" id="cursor" aria-hidden="true"></div>
<a href="#main-content" class="h-skip-link">Skip to main content</a>
- <header>
- <h1>
- <a href="/" aria-label="three.ws home"
- ><img class="wordmark-logo" src="/three.svg" alt="" aria-hidden="true" /><span
- class="wordmark-dot"
- aria-hidden="true"
- ></span
- >three.ws</a
- >
- </h1>
- <div id="nav-container"></div>
- </header>
+ <header><div id="nav-container"></div></header>
<script src="/nav.js"></script>
<main id="main-content" class="home-parallax">
diff --git a/pages/home-v2.html b/pages/home-v2.html
index 1a26cc040..ad72eca7f 100644
--- a/pages/home-v2.html
+++ b/pages/home-v2.html
@@ -209,18 +209,7 @@
<body class="home-page">
<div class="cursor" id="cursor" aria-hidden="true"></div>
<a href="#main-content" class="h-skip-link">Skip to main content</a>
- <header>
- <h1>
- <a href="/marketplace?tab=mine" aria-label="three.ws home"
- ><img class="wordmark-logo" src="/three.svg" alt="" aria-hidden="true" /><span
- class="wordmark-dot"
- aria-hidden="true"
- ></span
- >three.ws</a
- >
- </h1>
- <div id="nav-container"></div>
- </header>
+ <header><div id="nav-container"></div></header>
<script src="/nav.js"></script>
<main id="main-content" class="home-parallax">
diff --git a/public/home.css b/public/home.css
index 38c1fa9c4..6cbcc0c5d 100644
--- a/public/home.css
+++ b/public/home.css
@@ -59,64 +59,13 @@
pointer-events: none;
}
-/* ── Premium sticky header (warm, blurred) ───────────────────────────────── */
+/* ── Global header ───────────────────────────────────────────────────────── */
+/* The site header is the shared nav (public/nav.html + nav.css), injected into
+ #nav-container. It positions and styles itself (sticky, blurred, branded), so
+ this wrapper just gets out of the way — no fixed chrome, no second wordmark. */
.home-page header {
- position: fixed !important;
- top: 0;
- left: 0;
- right: 0;
- z-index: 200 !important;
- display: flex;
- align-items: center;
- justify-content: space-between;
- padding: 0.9rem clamp(1rem, 4vw, 2rem);
- height: auto;
- line-height: normal;
- overflow: visible;
- white-space: normal;
- background: linear-gradient(
- to bottom,
- rgba(10, 8, 6, 0.78) 0%,
- rgba(10, 8, 6, 0.3) 75%,
- transparent 100%
- );
- backdrop-filter: blur(14px) saturate(140%);
- -webkit-backdrop-filter: blur(14px) saturate(140%);
- border-bottom: 1px solid rgba(255, 215, 106, 0.06);
- transition:
- background 0.3s ease,
- border-color 0.3s ease;
-}
-
-.home-page header h1 {
- margin: 0;
- font-family: 'Space Grotesk', 'Inter', sans-serif;
- font-size: 1.12rem;
- font-weight: 700;
- letter-spacing: -0.01em;
-}
-
-.home-page header h1 a {
- color: #fff;
- text-decoration: none;
- display: inline-flex;
- align-items: center;
- gap: 0.45rem;
-}
-
-.home-page header h1 a .wordmark-dot {
- width: 8px;
- height: 8px;
- border-radius: 50%;
- background: #ffffff;
- box-shadow: 0 0 12px rgba(255, 143, 77, 0.6);
-}
-
-.home-page header h1 a .wordmark-logo {
- width: 28px;
- height: 28px;
- display: inline-block;
+ display: block;
}
/* ── Loading flash on page reveal ────────────────────────────────────────── */
diff --git a/src/game/agent-commerce.js b/src/game/agent-commerce.js
index f3f421e2b..edbc28acf 100644
--- a/src/game/agent-commerce.js
+++ b/src/game/agent-commerce.js
@@ -4,10 +4,12 @@
// This ports the /agent-exchange demo into the walkaround world: instead of two
// iframed avatars on a flat page, two GLB-bodied agents stand in the plaza. Walk
// up to them and trigger a round — they negotiate in speech bubbles while the
-// buyer pays the seller $0.01 USDC for a live crypto signal through the exact
-// same server-side x402 payer the demo uses (/api/x402-pay: challenge → sign →
-// verify → settle → confirm, streamed as SSE). Every settlement is real on
-// Solana mainnet, with a Solscan link in the receipt.
+// buyer (NOVA) pays the seller (ORACLE) in USDC to inspect a real 3D model
+// through the server-side x402 payer (/api/x402-pay: challenge → sign → verify →
+// dispatch → settle, streamed as SSE). The paid call is the platform's own
+// `inspect_model` MCP tool, so the "intel" NOVA buys is a real glTF report
+// (vertices, triangles, materials). Every settlement is real USDC on Solana
+// mainnet, with a Solscan link in the receipt.
//
// Scoped to the home town only (see isHomeTown) and built per-world by
// coincommunities.js, so it never leaks into other coins' worlds. The payment
@@ -30,10 +32,16 @@ const INTERACT_RANGE = 6.5; // how close the player must be to trigger a rou
const ROUND_COOLDOWN_MS = 9000; // min time between paid rounds (one real payment each)
const BUBBLE_MS = 5200;
-// The intel subject. Scoped to SOL — the Solana network's own asset, the chain
-// these agents pay each other on — so the exchange never names or surfaces any
-// other coin (USDC settlement + SOL fees are the only on-chain assets in play).
-const TOPICS = ['sol'];
+// The models NOVA pays to have inspected, rotated each round for variety. Each is
+// a public https GLB (the validator only fetches public URLs) — three.ws's own
+// avatars, so the exchange stays on-brand and never references any coin/token.
+const MODELS = [
+ { name: 'default.glb', url: 'https://three.ws/avatars/default.glb' },
+ { name: 'cz.glb', url: 'https://three.ws/avatars/cz.glb' },
+];
+
+// The paid x402 tool NOVA buys from ORACLE — the platform's own glTF inspector.
+const PAID_TOOL = 'inspect_model';
// Stage labels for the HUD stepper, keyed to the SSE events /api/x402-pay emits.
const STAGES = [
@@ -44,31 +52,57 @@ const STAGES = [
{ id: 'done', label: 'Confirmed' },
];
-// Scripted dialogue, matched to each stage. SELLER hosts the intel; BUYER pays.
+// Scripted dialogue, matched to each stage. SELLER runs the inspector; BUYER pays.
const LINES = {
seller: {
- idle: 'Live crypto intel — $0.01 USDC a signal, settled on-chain.',
+ idle: '3D model intel — a real glTF inspection, settled on-chain in USDC.',
challenge: 'Payment challenge issued. Awaiting your signed transfer…',
built: 'Transfer received. Forwarding to the facilitator…',
- verified: 'Payment verified. Pulling the latest signal…',
- settled: 'Funds confirmed on-chain. Delivering now.',
- done: (h) => `Here's your signal: ${h}`,
+ verified: 'Payment verified. Running the inspection…',
+ settled: 'Funds confirmed on-chain. Sending the report.',
+ done: (summary) => `Report: ${summary}`,
error: 'Payment failed — no charge made.',
},
buyer: {
- idle: (t) => `I need live ${t.toUpperCase()} intelligence. Paying now.`,
+ idle: (name) => `I need a structural read on ${name}. Paying now.`,
challenge: 'Building and signing the Solana transfer…',
built: 'Signed. Sending to the facilitator for verification.',
verified: 'Verified on-chain. Waiting on settlement…',
- settled: 'Settled. Collecting my intel.',
- done: (s) => `Signal received: ${s.toUpperCase()}. Updating my model.`,
+ settled: 'Settled. Collecting my report.',
+ done: (verts) => `Report received — ${verts}. Filing it.`,
error: 'Transaction rolled back. Wallet unchanged.',
},
};
+// Pull a one-line summary + a vertex count out of the inspector's text report,
+// so the agents can speak it and the receipt can headline it.
+function summarizeModelReport(intel) {
+ const text = intel?.result?.content?.[0]?.text || '';
+ const lines = text.split('\n').map((l) => l.trim()).filter(Boolean);
+ const modelLine = lines.find((l) => /^Model:/i.test(l)) || lines[0] || 'model inspected';
+ const vertLine = lines.find((l) => /Vertices:/i.test(l)) || '';
+ const verts = (vertLine.match(/Vertices:\s*([\d,]+)/i)?.[1] || '').trim();
+ const tris = (vertLine.match(/Triangles:\s*([\d,]+)/i)?.[1] || '').trim();
+ const stat = verts ? `${verts} verts${tris ? ` · ${tris} tris` : ''}` : '';
+ return {
+ headline: modelLine.replace(/^Model:\s*/i, ''),
+ verts: verts ? `${verts} verts` : 'report ready',
+ stat,
+ isError: !!intel?.result?.isError,
+ };
+}
+
const escHtml = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
const delay = (ms) => new Promise((r) => setTimeout(r, ms));
+// Format a USDC dollar amount, keeping sub-cent micropayments legible (so a
+// $0.001 settlement reads as "$0.0010", never "$0.00").
+const fmtUsd = (n) => {
+ const v = Number(n) || 0;
+ return '$' + (v >= 0.01 || v === 0 ? v.toFixed(2) : v.toFixed(4));
+};
+const fmtUsdcAmount = (micro) => `${((Number(micro) || 0) / 1e6).toFixed(4)} USDC`;
+
// One agent: its avatar rig + animation, a nameplate, and a transient speech
// bubble. Mirrors RemotePlayer's DOM/anim shape so the agents read as first-class
// inhabitants of the world, not a bolted-on widget.
@@ -377,8 +411,9 @@ export class AgentCommerce {
this.lastRoundAt = (typeof performance !== 'undefined' ? performance.now() : 0);
this.prompt.classList.remove('ac-show');
- const topic = TOPICS[this.topicIdx % TOPICS.length];
+ const model = MODELS[this.topicIdx % MODELS.length];
this.topicIdx++;
+ const topic = model.name;
this._renderPanel({ topic, stage: 'challenge', stageState: 'active' });
this.panel.classList.add('ac-show');
@@ -396,12 +431,15 @@ export class AgentCommerce {
const res = await fetch('/api/x402-pay', {
method: 'POST',
headers: { 'content-type': 'application/json', accept: 'text/event-stream' },
- body: JSON.stringify({ tool: 'crypto_intel', topic, endpoint: '/api/x402/crypto-intel', body: { topic } }),
+ // Pay for the platform's own glTF inspector. /api/x402-pay handles the
+ // Solana USDC payment, then dispatches the MCP tool call and returns
+ // its report alongside the settlement.
+ body: JSON.stringify({ tool: PAID_TOOL, args: { url: model.url } }),
});
if (!res.ok || !res.body) {
const text = await res.text().catch(() => '');
let msg = 'Payment service unavailable.';
- try { msg = JSON.parse(text).error_description || msg; } catch { /* ignore */ }
+ try { msg = JSON.parse(text).error_description || JSON.parse(text).error || msg; } catch { /* ignore */ }
throw new Error(msg);
}
@@ -428,21 +466,27 @@ export class AgentCommerce {
} else if (event === 'error') {
throw new Error(data.error || 'payment failed');
}
+ // 'dispatched' carries only timing — no UI beat needed.
}
if (!intel || !settled) throw new Error('incomplete response from payment service');
+ // The settlement is on-chain truth; payer/payee/amount live on the result's
+ // payment block. Surface the inspector's report as the bought "intel".
+ const payment = { ...(intel.payment || {}), ...settled };
+ const report = summarizeModelReport(intel);
+
// Success choreography.
this._gesture(this.buyer, 'celebrate');
await delay(300);
- this.buyer.say(LINES.buyer.done(intel.signal));
+ this.buyer.say(LINES.buyer.done(report.verts));
await delay(700);
- this.seller.say(LINES.seller.done(intel.headline));
+ this.seller.say(LINES.seller.done(report.headline));
this._gesture(this.seller, 'av-cheering');
- this.sessionTotal += 0.01;
- this.jumbotron?.pushSettlement(settled, intel);
- this._renderReceipt(settled, intel);
+ this.sessionTotal += (Number(payment.amount) / 1e6) || 0;
+ this.jumbotron?.pushSettlement(payment, { topic, ...report });
+ this._renderReceipt(payment, { topic, ...report });
// Auto-dismiss the panel after the receipt has been read.
this._scheduleHide(9000);
} catch (err) {
@@ -475,15 +519,15 @@ export class AgentCommerce {
// 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 amt = this._amount ? fmtUsdcAmount(this._amount) : '— USDC';
const steps = STAGES.map((s, i) => {
const cls = i < activeIdx ? 'ac-done' : i === activeIdx ? 'ac-active' : '';
return `<div class="ac-step ${cls}"><span class="ac-dot"></span>${s.label}</div>`;
}).join('');
this.panel.innerHTML =
`<div class="ac-ph">` +
- `<span class="ac-pt">Paying for <b>${escHtml(topic.toUpperCase())}</b> intel · ${escHtml(amt)}</span>` +
- `<span class="ac-total">$${this.sessionTotal.toFixed(2)}</span>` +
+ `<span class="ac-pt">NOVA pays ORACLE to inspect <b>${escHtml(topic)}</b> · ${escHtml(amt)}</span>` +
+ `<span class="ac-total">${fmtUsd(this.sessionTotal)}</span>` +
`</div><div class="ac-steps">${steps}</div>`;
}
@@ -493,13 +537,10 @@ export class AgentCommerce {
this.panel.querySelectorAll('.ac-step').forEach((el) => { el.classList.remove('ac-active'); el.classList.add('ac-done'); });
this.panel.querySelector('.ac-total')?.classList.add('ac-flash');
- const amount = payment.amount ? `${(Number(payment.amount) / 1e6).toFixed(2)} USDC` : '$0.01 USDC';
+ const amount = payment.amount ? fmtUsdcAmount(payment.amount) : '— USDC';
const short = (a) => (a ? `${a.slice(0, 6)}…${a.slice(-4)}` : '—');
const tx = payment.tx;
- const sig = intel.signal || 'neutral';
- const sigMark = { bullish: '▲', bearish: '▼', neutral: '→' }[sig] || '';
- const change = intel.change_24h != null ? ` ${intel.change_24h >= 0 ? '+' : ''}${Number(intel.change_24h).toFixed(2)}% 24h` : '';
- const price = intel.price_usd != null ? ` · $${Number(intel.price_usd) >= 100 ? Number(intel.price_usd).toFixed(2) : Number(intel.price_usd).toFixed(4)}` : '';
+ const stat = intel.stat ? `<span class="ac-sig">${escHtml(intel.stat)}</span>` : '';
const receipt = document.createElement('div');
receipt.className = 'ac-receipt';
@@ -509,8 +550,7 @@ export class AgentCommerce {
(tx
? `<div class="ac-rrow"><span>Transaction</span><span class="ac-v"><a href="https://solscan.io/tx/${escHtml(tx)}" target="_blank" rel="noopener">${tx.slice(0, 8)}…${tx.slice(-6)} ↗</a></span></div>`
: '') +
- `<div class="ac-headline"><span class="ac-sig">${sigMark} ${escHtml(sig.toUpperCase())}</span>` +
- `<b>${escHtml(intel.topic.toUpperCase())}</b>${escHtml(price)}${escHtml(change)} — ${escHtml(intel.headline)}</div>`;
+ `<div class="ac-headline">${stat}<b>${escHtml(intel.topic)}</b> — ${escHtml(intel.headline)}</div>`;
this.panel.appendChild(receipt);
setTimeout(() => this.panel.querySelector('.ac-total')?.classList.remove('ac-flash'), 600);
@@ -524,7 +564,7 @@ export class AgentCommerce {
});
const msg = document.createElement('div');
msg.className = 'ac-err-msg';
- msg.innerHTML = `⚠ ${escHtml(message || 'Payment failed. No funds moved.')} <a href="/agent-exchange" target="_blank" rel="noopener">Open the full demo →</a>`;
+ msg.innerHTML = `⚠ ${escHtml(message || 'Payment failed. No funds moved.')}`;
this.panel.appendChild(msg);
}
diff --git a/src/game/coincommunities.js b/src/game/coincommunities.js
index 23f1278ed..dfc62204f 100644
--- a/src/game/coincommunities.js
+++ b/src/game/coincommunities.js
@@ -58,11 +58,12 @@ const COIN_URL = '/api/pump/coin';
// Normalize a raw pump.fun coin (trending feed or search results — both share
// the same upstream shape) into the compact record the lobby/world consume.
function mapCoins(raw) {
- return (Array.isArray(raw) ? raw : raw.coins || raw.items || []).map((c) => ({
+ const list = Array.isArray(raw) ? raw : raw.data || raw.coins || raw.items || [];
+ return list.map((c) => ({
mint: c.mint || c.address,
name: (c.name || '').trim() || 'Unnamed coin',
symbol: (c.symbol || '').trim(),
- image: normalizeGatewayURL(c.image_uri || c.image || c.imageUri || ''),
+ image: normalizeGatewayURL(c.image_uri || c.image || c.imageUri || c.logo || ''),
marketCap: c.usd_market_cap || c.market_cap_usd || c.marketCap || 0,
})).filter((c) => c.mint);
}
diff --git a/src/game/x402-jumbotron.js b/src/game/x402-jumbotron.js
index 8a2825208..2b469f9d7 100644
--- a/src/game/x402-jumbotron.js
+++ b/src/game/x402-jumbotron.js
@@ -47,7 +47,6 @@ const COL = {
good: '#5fd08a', bad: '#e06c75',
};
-const SIG_MARK = { bullish: '▲', bearish: '▼', neutral: '→' };
function fmtUsdc(micro) {
const n = Number(micro);
@@ -276,7 +275,7 @@ export function createX402Jumbotron(scene, opts = {}) {
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);
+ ctx.fillText('Walk up to ORACLE & NOVA and press E to trigger a real USDC payment.', padX, stageTop + 82);
drawStepper(stageTop + 124, null, false);
}
@@ -379,13 +378,12 @@ export function createX402Jumbotron(scene, opts = {}) {
},
// 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 topic = intel.topic || 'model';
+ const detail = intel.stat || intel.headline || 'inspected';
const entry = {
ts: Date.now(),
label: 'NOVA → ORACLE',
- sub: `${mark} ${topic} intel${intel.headline ? ' · ' + intel.headline : ''}`.trim(),
+ sub: `inspect ${topic} · ${detail}`.trim(),
amount: payment.amount,
tx: payment.tx || null,
kind: 'local',
@@ -393,7 +391,7 @@ export function createX402Jumbotron(scene, opts = {}) {
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;
+ sessionTotal += (Number(payment.amount) / 1e6) || 0;
status = 'live';
},
setError(stage, message) {