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
chore: API + x402 refinements, club leaderboard rollforward, new tests
nirholasc6f5f5278f97
diff --git a/api/_lib/erc8004-chains.js b/api/_lib/erc8004-chains.jsindex e233dcd0f..770cd6429 100644--- a/api/_lib/erc8004-chains.js+++ b/api/_lib/erc8004-chains.js@@ -61,6 +61,9 @@ export const CHAINS = [testnet: false,registry: IDENTITY_REGISTRY_MAINNET,explorer: 'https://etherscan.io',+ // Mainnet public RPCs are the most restrictive/latent on eth_getLogs; use a+ // smaller scan window than the global default so a single call stays fast.+ blockChunk: 500,rpcUrls: ['https://eth.llamarpc.com','https://cloudflare-eth.com',@@ -88,6 +91,8 @@ export const CHAINS = [testnet: false,registry: IDENTITY_REGISTRY_MAINNET,explorer: 'https://polygonscan.com',+ // High block rate + busy public RPCs; cap eth_getLogs ranges below default.+ blockChunk: 500,rpcUrls: ['https://polygon-rpc.com','https://polygon.llamarpc.com',diff --git a/api/_lib/migrations/2026-06-02-club-leaderboard-rollforward.sql b/api/_lib/migrations/2026-06-02-club-leaderboard-rollforward.sqlnew file mode 100644index 000000000..247e555ba--- /dev/null+++ b/api/_lib/migrations/2026-06-02-club-leaderboard-rollforward.sql@@ -0,0 +1,89 @@+-- Roll-forward for GET /api/club/leaderboard 500s — schema drift on prod.+-- Apply: npm run db:migrate -- --apply --file 2026-06-02-club-leaderboard-rollforward.sql+--+-- The leaderboard joins club_dancer_wallets ⋈ club_tips and reads+-- t.amount_atomics / t.paid_at / t.created_at. On production those columns or+-- tables were missing (Postgres 42703 column-not-found / 42P01 undefined-table+-- swallowed by the endpoint's catch), so every request 500'd.+--+-- The canonical definitions live in 2026-05-22-club-tips.sql and+-- 2026-05-23-club-dancer-wallets.sql. If those are recorded as applied in+-- schema_migrations but the live tables drifted (partial apply / applied to a+-- different DB), the runner will not re-run them. This dated rollforward has a+-- later filename so it runs regardless, and is fully idempotent+-- (CREATE … IF NOT EXISTS / ADD COLUMN IF NOT EXISTS), so it is a no-op on any+-- environment already in sync. Mirrors the 2026-05-25 rollforward precedent.++begin;++-- ── club_tips — live-tip ledger the leaderboard sums over ────────────────────+create table if not exists club_tips (+ id uuid primary key default gen_random_uuid(),+ ticket_id text not null unique,+ dancer text not null,+ dance text not null,+ clip text,+ label text,+ payer text,+ network text,+ amount_atomics numeric,+ asset text,+ started_at timestamptz not null,+ ends_at timestamptz not null,+ paid_at timestamptz,+ paid_tx text,+ created_at timestamptz not null default now()+);++-- Backfill columns the leaderboard query depends on, in case the table predates+-- them. All no-ops once the table is current.+alter table club_tips add column if not exists amount_atomics numeric;+alter table club_tips add column if not exists paid_at timestamptz;+alter table club_tips add column if not exists paid_tx text;+alter table club_tips add column if not exists created_at timestamptz not null default now();++create index if not exists club_tips_created_at_desc+ on club_tips (created_at desc);+create index if not exists club_tips_dancer_created+ on club_tips (dancer, created_at desc);+create index if not exists club_tips_unpaid_by_dancer_net+ on club_tips (dancer, network, asset)+ where paid_at is null;++-- ── club_dancer_wallets — dancer registry the leaderboard left-joins from ────+create table if not exists club_dancer_wallets (+ dancer text primary key,+ display_name text not null,+ bio text,+ evm_address text,+ solana_address text,+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now()+);++-- Seed the four built-in stage slots so the leaderboard renders rows even with+-- zero tips. Names match /api/x402/dance-tip and src/club.js.+insert into club_dancer_wallets (dancer, display_name) values+ ('1', 'Nyx'),+ ('2', 'Ari'),+ ('3', 'Sable'),+ ('4', 'Vesper')+on conflict (dancer) do update+ set display_name = excluded.display_name,+ updated_at = now();++-- ── club_payouts — referenced by the same subsystem; keep it in sync too ─────+create table if not exists club_payouts (+ id uuid primary key default gen_random_uuid(),+ dancer text not null references club_dancer_wallets(dancer),+ network text not null,+ asset text not null,+ amount_atomics numeric not null,+ tx text not null,+ swept_tip_count integer not null,+ created_at timestamptz not null default now()+);+create index if not exists club_payouts_dancer_created+ on club_payouts (dancer, created_at desc);++commit;diff --git a/api/_lib/x402-spec.js b/api/_lib/x402-spec.jsindex cd0bf9403..a727c6b67 100644--- a/api/_lib/x402-spec.js+++ b/api/_lib/x402-spec.js@@ -313,7 +313,18 @@ const FACILITATOR_TIMEOUT_MS_DEFAULT = (() => {return 15_000;})();-async function callFacilitator(network, path, body, { timeoutMs, idempotencyKey } = {}) {+// Upstream statuses that signal a transient facilitator / payment-network+// hiccup (gateway down, settlement service overloaded) rather than a rejected+// payment. A 4xx — including 402 (payment required), 409 (idempotency+// conflict), and 400-with-isValid:false — is a definitive answer and is never+// retried.+const TRANSIENT_FACILITATOR_STATUS = new Set([502, 503, 504]);++function summarizeUpstream(data, text) {+ return String(data.error || data.message || data.invalidReason || text.slice(0, 200) || '').slice(0, 300);+}++async function callFacilitator(network, path, body, { timeoutMs, idempotencyKey, retries = 1 } = {}) {const config = facilitatorFor(network);const url = `${config.url}${path}`;const host = hostOf(config.url);@@ -329,50 +340,79 @@ async function callFacilitator(network, path, body, { timeoutMs, idempotencyKey// wire so this is just a Node-level convenience.headers['Idempotency-Key'] = idempotencyKey;}- let res;- try {- res = await fetch(url, {- method: 'POST',- headers,- body: JSON.stringify(body),- signal: AbortSignal.timeout(timeoutMs || FACILITATOR_TIMEOUT_MS_DEFAULT),- });- } catch (err) {- // Server logs keep the host for diagnosis; user-facing X402Error message- // omits it so we don't leak internal facilitator topology to clients.- console.warn(`[x402] facilitator ${path} unreachable (host=${host}, network=${network}): ${err.message}`);- throw new X402Error(- 'facilitator_unreachable',- `facilitator ${path} (network=${network}) fetch failed: ${err.message}`,- 502,- );- }- const text = await res.text();- let data = {};- if (text) {+ // Retries are only safe for idempotent calls: /verify mutates no state, and+ // /settle carries the deterministic Idempotency-Key from buildIdempotencyKey+ // so a re-sent settle is de-duplicated by the facilitator instead of paying+ // twice. A settle without a key (legacy callers) gets a single attempt — we+ // won't risk a double-spend to recover from a blip.+ const retryable = path === '/verify' || Boolean(idempotencyKey);+ const serializedBody = JSON.stringify(body);++ let attempt = 0;+ for (;;) {+ let res;try {- data = JSON.parse(text);- } catch {- console.warn(`[x402] facilitator ${path} non-JSON (host=${host}, network=${network}, status=${res.status})`);+ res = await fetch(url, {+ method: 'POST',+ headers,+ body: serializedBody,+ signal: AbortSignal.timeout(timeoutMs || FACILITATOR_TIMEOUT_MS_DEFAULT),+ });+ } catch (err) {+ // Network failure / timeout — transient. Retry once for idempotent+ // calls before giving up.+ if (retryable && attempt < retries) {+ attempt += 1;+ console.warn(`[x402] facilitator ${path} unreachable (host=${host}, network=${network}): ${err.message} — retry ${attempt}/${retries} in 500ms`);+ await new Promise((r) => setTimeout(r, 500));+ continue;+ }+ // Server logs keep the host for diagnosis; user-facing X402Error message+ // omits it so we don't leak internal facilitator topology to clients.+ console.warn(`[x402] facilitator ${path} unreachable (host=${host}, network=${network}): ${err.message}`);throw new X402Error(- 'facilitator_bad_response',- `facilitator ${path} (network=${network}) returned non-JSON (status ${res.status})`,+ 'facilitator_unreachable',+ `facilitator ${path} (network=${network}) fetch failed: ${err.message}`,502,);}+ const text = await res.text();+ let data = {};+ if (text) {+ try {+ data = JSON.parse(text);+ } catch {+ console.warn(`[x402] facilitator ${path} non-JSON (host=${host}, network=${network}, status=${res.status})`);+ throw new X402Error(+ 'facilitator_bad_response',+ `facilitator ${path} (network=${network}) returned non-JSON (status ${res.status})`,+ 502,+ );+ }+ }+ if (!res.ok) {+ // PayAI returns 400 with { isValid: false } for invalid payments —+ // pass through so verifyPayment can emit a clean 402 to the caller.+ if (path === '/verify' && data.isValid === false) return data;+ const detail = summarizeUpstream(data, text);+ // Transient upstream 5xx — the payment network or settlement service+ // blinked. Retry once for idempotent calls; the Idempotency-Key keeps+ // a re-sent settle from double-paying.+ if (retryable && TRANSIENT_FACILITATOR_STATUS.has(res.status) && attempt < retries) {+ attempt += 1;+ console.warn(`[x402] facilitator ${path} ${res.status} (host=${host}, network=${network}): ${detail} — retry ${attempt}/${retries} in 500ms`);+ await new Promise((r) => setTimeout(r, 500));+ continue;+ }+ console.warn(`[x402] facilitator ${path} ${res.status} (host=${host}, network=${network}): ${detail}`);+ throw new X402Error(+ 'facilitator_error',+ `facilitator ${path} (network=${network}) ${res.status}: ${detail}`,+ 502,+ );+ }+ return data;}- if (!res.ok) {- // PayAI returns 400 with { isValid: false } for invalid payments —- // pass through so verifyPayment can emit a clean 402 to the caller.- if (path === '/verify' && data.isValid === false) return data;- console.warn(`[x402] facilitator ${path} ${res.status} (host=${host}, network=${network})`);- throw new X402Error(- 'facilitator_error',- `facilitator ${path} (network=${network}) ${res.status}: ${data.error || data.message || data.invalidReason || text.slice(0, 200)}`,- 502,- );- }- return data;}// Probe `/supported` on each configured facilitator and report whether thediff --git a/api/agents/8004/search.js b/api/agents/8004/search.jsindex 086db2aef..eeb53569f 100644--- a/api/agents/8004/search.js+++ b/api/agents/8004/search.js@@ -19,7 +19,11 @@ import { cors, method, error, wrap, json } from '../../_lib/http.js';export const maxDuration = 30;const SUPPORTED_CHAINS = Object.keys(DEFAULT_REGISTRIES).map(Number);-const SUBGRAPH_TIMEOUT_MS = 12_000;+// Abort the subgraph fetch with margin to spare before the platform kills the+// function. A 12s budget never fired on runtimes enforcing a ~10s ceiling — the+// function 504'd before the graceful timed_out:true path could run. 6s leaves+// room to map results and respond well under both the 10s and 30s limits.+const SUBGRAPH_TIMEOUT_MS = 6_000;const AGENTS_QUERY = `query SearchAgents(diff --git a/api/agents/solana-wallet.js b/api/agents/solana-wallet.jsindex f4efb6ee9..3a49bd2c6 100644--- a/api/agents/solana-wallet.js+++ b/api/agents/solana-wallet.js@@ -12,48 +12,30 @@ import { Keypair, PublicKey, LAMPORTS_PER_SOL } from '@solana/web3.js';import { webcrypto } from 'node:crypto';import { env } from '../_lib/env.js';import { recordEvent } from '../_lib/usage.js';+import { cacheGet, cacheSet } from '../_lib/cache.js';const subtle = globalThis.crypto?.subtle || webcrypto.subtle;const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]+$/;const AIRDROP_LAMPORTS = LAMPORTS_PER_SOL;-// ── Solana RPC in-process cache ───────────────────────────────────────────────+// ── Solana RPC cache ──────────────────────────────────────────────────────────// Keys: "sol:bal:<address>:<network>" and "sol:sigs:<address>:<network>:<limit>"// Prevents Helius free-plan 429s on repeated wallet card polls.--const SOL_CACHE_TTL_MS = 60_000; // 60 s-// Hard cap so a long-running serverless instance with cycling addresses-// can't grow this Map without bound. When we hit the cap, drop the-// oldest-inserted entry — Map preserves insertion order, so the first key-// from .keys() is always the oldest. 1000 entries × ~200 bytes ≈ 200 KB.-const SOL_CACHE_MAX_ENTRIES = 1000;-const _solRpcCache = new Map();--function _solCacheGet(key) {- const entry = _solRpcCache.get(key);- if (!entry) return undefined;- if (entry.expiry < Date.now()) {- _solRpcCache.delete(key);- return undefined;- }- return entry.value;-}--function _solCacheSet(key, value) {- // Purge expired entries on each write — the active set is small and the- // loop is fast enough that opportunistic eviction beats a periodic timer.- const now = Date.now();- for (const [k, e] of _solRpcCache.entries()) {- if (e.expiry < now) _solRpcCache.delete(k);- }- // LRU-by-insertion cap. If everything in the map is still fresh and we're- // at the cap, evict the oldest insertion(s) before adding the new entry.- while (_solRpcCache.size >= SOL_CACHE_MAX_ENTRIES) {- const oldest = _solRpcCache.keys().next().value;- if (oldest === undefined) break;- _solRpcCache.delete(oldest);- }- _solRpcCache.set(key, { value, expiry: now + SOL_CACHE_TTL_MS });+//+// Backed by the shared cache adapter (Upstash Redis when configured, in-memory+// otherwise). Redis matters here: Vercel runs many serverless replicas, and a+// per-replica Map only dedupes RPC calls within one warm instance — under real+// traffic every replica still hammers the RPC. A shared 60 s window collapses+// that to at most one balance fetch per address per minute across the fleet.+const SOL_CACHE_TTL_S = 60;++// Map an RPC failure to a stable code the wallet card can render. We surface+// rate-limiting distinctly so the UI shows "Balance unavailable" instead of a+// misleading "0 SOL" when the RPC is throttled rather than the wallet empty.+function classifyBalanceError(err) {+ const msg = err?.message || '';+ const rateLimited = err?.status === 429 || /\b429\b|rate.?limit|too many|max usage/i.test(msg);+ return rateLimited ? 'rpc_rate_limited' : 'rpc_error';}// Calls `fn(conn)` with exponential backoff (500 ms → 1000 ms) before the@@ -162,8 +144,8 @@ async function handleActivity(req, res, id) {const fallbackConn = solanaPublicConnection(network);const sigsCacheKey = `sol:sigs:${address}:${network}:${limit}`;- let sigs = _solCacheGet(sigsCacheKey);- if (sigs === undefined) {+ let sigs = await cacheGet(sigsCacheKey);+ if (sigs === null) {const sigInfos = await _solRpcWithBackoffFallback(primaryConn,fallbackConn,@@ -175,7 +157,7 @@ async function handleActivity(req, res, id) {return error(res, 502, 'rpc_error', 'failed to fetch on-chain activity');}sigs = sigInfos.value;- _solCacheSet(sigsCacheKey, sigs);+ await cacheSet(sigsCacheKey, sigs, SOL_CACHE_TTL_S);}// getParsedTransactions is the expensive call and the one most often rate-limited.@@ -293,9 +275,10 @@ async function handlePublicWalletRead(req, res, id) {}let lamports = null;+ let balanceError = null;const balCacheKey = `sol:bal:${address}:${net}`;- const cached = _solCacheGet(balCacheKey);- if (cached !== undefined) {+ const cached = await cacheGet(balCacheKey);+ if (cached !== null) {lamports = cached;} else {const balResult = await _solRpcWithBackoffFallback(@@ -304,11 +287,15 @@ async function handlePublicWalletRead(req, res, id) {(c) => c.getBalance(new PublicKey(address)),'getBalance',);- lamports = balResult.ok ? balResult.value : null;- if (balResult.ok) _solCacheSet(balCacheKey, lamports);+ if (balResult.ok) {+ lamports = balResult.value;+ await cacheSet(balCacheKey, lamports, SOL_CACHE_TTL_S);+ } else {+ balanceError = classifyBalanceError(balResult.error);+ }}- console.info(`[agents/solana] public read agentId=${id} address=${address} net=${net} lamports=${lamports}`);+ console.info(`[agents/solana] public read agentId=${id} address=${address} net=${net} lamports=${lamports}${balanceError ? ` balance_error=${balanceError}` : ''}`);return json(res, 200, {data: {agentId: id,@@ -317,6 +304,7 @@ async function handlePublicWalletRead(req, res, id) {chain: 'solana',network: net,lamports,+ ...(balanceError ? { balance_error: balanceError } : {}),},});}@@ -388,16 +376,21 @@ async function handleWallet(req, res, id) {const network = (req.query?.network || new URL(req.url, 'http://x').searchParams.get('network') || 'mainnet').toString();const net = network === 'devnet' ? 'devnet' : 'mainnet';const balCacheKey = `sol:bal:${meta.solana_address}:${net}`;- let lamports = _solCacheGet(balCacheKey);- if (lamports === undefined) {+ let lamports = await cacheGet(balCacheKey);+ let balanceError = null;+ if (lamports === null) {const balResult = await _solRpcWithBackoffFallback(solanaConnection(net),solanaPublicConnection(net),(c) => c.getBalance(new PublicKey(meta.solana_address)),'getBalance',);- lamports = balResult.ok ? balResult.value : null;- if (balResult.ok) _solCacheSet(balCacheKey, lamports);+ if (balResult.ok) {+ lamports = balResult.value;+ await cacheSet(balCacheKey, lamports, SOL_CACHE_TTL_S);+ } else {+ balanceError = classifyBalanceError(balResult.error);+ }}// SNS is mainnet-only. Skip the lookup on devnet — it always returns null@@ -415,6 +408,7 @@ async function handleWallet(req, res, id) {network,lamports,sol: lamports == null ? null : lamports / 1e9,+ ...(balanceError ? { balance_error: balanceError } : {}),vanity_prefix: meta.solana_vanity_prefix || null,source: meta.solana_wallet_source || (meta.encrypted_solana_secret ? 'generated' : null),sns_domain: attachedSns || favoriteSns,diff --git a/api/chat.js b/api/chat.jsindex 7dcf1b8b5..4475a9b7d 100644--- a/api/chat.js+++ b/api/chat.js@@ -318,6 +318,9 @@ export default wrap(async (req, res) => {// Tool support varies by model/provider. We always ask with the action tools// first; if a route rejects them we retry that same route without tools.let includeTools = true;+ // One in-place retry per route on transient gateway errors (503/504) before+ // failing over. Reset to false every time we advance to a new route.+ let retriedTransient = false;while (true) {try {upstream = await fetch(route.url, {@@ -333,6 +336,7 @@ export default wrap(async (req, res) => {if (routeIdx < fallbackRoutes.length) {route = fallbackRoutes[routeIdx];includeTools = true;+ retriedTransient = false;continue;}return error(res, 502, 'upstream_unavailable', 'chat backend unreachable');@@ -356,6 +360,7 @@ export default wrap(async (req, res) => {routeIdx++;route = fallbackRoutes[routeIdx];includeTools = true;+ retriedTransient = false;continue;}captureException(new Error(`${route.name} upstream 404`), { route: 'chat', provider: route.name, status: 404, body: text.slice(0, 400) });@@ -363,6 +368,21 @@ export default wrap(async (req, res) => {return error(res, 502, 'chat_failed', 'chat backend returned an error');}+ // Transient gateway errors (503 Service Unavailable / 504 Gateway Timeout)+ // are often momentary upstream blips that clear on a second attempt. Retry+ // the same route once before failing over — and on the *last* route in the+ // chain this in-place retry is the only lever left before we surface a 502.+ // 500/502 are excluded on purpose: a 500 is usually a provider-side bug and+ // a 502 means the upstream's own backend is down — neither recovers from a+ // 500ms wait, so we fall straight through to the failover branch for those.+ if ((upstream.status === 503 || upstream.status === 504) && !retriedTransient) {+ retriedTransient = true;+ const text = await upstream.text().catch(() => '');+ console.warn(`[chat:${route.name}] ${upstream.status} — retrying once after 500ms: ${text.slice(0, 120)}`);+ await new Promise((r) => setTimeout(r, 500));+ continue;+ }+// Fall over on rate-limit (429) and transient gateway errors (502/503/504).// Don't re-fetch on 4xx other than 429 — those are caller mistakes that// the next provider would also reject.@@ -372,6 +392,7 @@ export default wrap(async (req, res) => {routeIdx++;route = fallbackRoutes[routeIdx];includeTools = true;+ retriedTransient = false;continue;}break;@@ -386,10 +407,10 @@ export default wrap(async (req, res) => {body: text.slice(0, 400),});// Always log — diagnosing prod 502s without provider context is hopeless.- console.error(`[chat:${route.name}]`, upstream.status, text.slice(0, 400));- // Surface the upstream reason in the response body. Strip any API-key- // fragments out of defence; the body is generally short JSON like- // {"error":{"type":"invalid_request_error","message":"..."}}.+ // Reaching here means every route in the failover chain was exhausted, so+ // flag it as final and surface which provider/model gave up last alongside+ // the parsed upstream reason. This is the server-side detail the friendly+ // client message deliberately omits.let upstreamMessage = '';try {const parsed = JSON.parse(text);@@ -397,11 +418,21 @@ export default wrap(async (req, res) => {} catch {upstreamMessage = text.slice(0, 200);}+ console.error(+ `[chat:${route.name}]`,+ upstream.status,+ `(final — all ${fallbackRoutes.length} route(s) exhausted)`,+ upstreamMessage ? `${upstreamMessage} ` : '',+ text.slice(0, 400),+ );+ // Client body is intentionally generic and human-readable: the raw provider+ // status/message is noise to an end user (and could leak provider internals).+ // The frontend renders `error_description` directly in the chat UI.return error(res,502,'upstream_error',- `${route.name} returned ${upstream.status}${upstreamMessage ? `: ${upstreamMessage}` : ''}`,+ 'The AI chat provider is temporarily unavailable. Please try again in a moment.',);}diff --git a/api/club/leaderboard.js b/api/club/leaderboard.jsindex 72041ad49..28c209be8 100644--- a/api/club/leaderboard.js+++ b/api/club/leaderboard.js@@ -20,7 +20,15 @@ export default wrap(async (req, res) => {try {rows = await runForWindow(window);} catch (err) {- console.error('[club/leaderboard]', err?.message || err);+ // Surface the Postgres error code so schema drift is diagnosable from+ // logs alone: 42703 = column not found, 42P01 = undefined table.+ // `detail` carries the offending identifier when Neon provides it.+ console.error(+ '[club/leaderboard]',+ 'window=' + window,+ 'code=' + (err?.code || 'none'),+ err?.detail || err?.message || err,+ );return error(res, 500, 'db_error', 'Failed to load leaderboard');}if (rows === null) {diff --git a/api/cron/[name].js b/api/cron/[name].jsindex 4bd04e0f9..f551c00d9 100644--- a/api/cron/[name].js+++ b/api/cron/[name].js@@ -108,6 +108,11 @@ const ERC8004_METADATA_BATCH = 25;const ERC8004_FETCH_TIMEOUT_MS = 10_000;+// Metadata URLs are external, user-controlled (on-chain agentURI) and often+// point at slow IPFS gateways. Cap each fetch tighter than RPC calls so a single+// hung gateway can't stall the whole enrichment batch toward Vercel's 300s kill.+const ERC8004_METADATA_TIMEOUT_MS = 5_000;+// Hard budget: stop processing and return before Vercel's 300s limit.const CRAWL_BUDGET_MS = 240_000;@@ -136,7 +141,7 @@ async function handleErc8004Crawl(req, res) {if (Date.now() - crawlStart <= CRAWL_BUDGET_MS) {try {- report.enriched = await erc8004EnrichMetadata(ERC8004_METADATA_BATCH);+ report.enriched = await erc8004EnrichMetadata(ERC8004_METADATA_BATCH, crawlStart + CRAWL_BUDGET_MS);} catch (err) {report.errors.push({ stage: 'metadata', error: err.message || String(err) });}@@ -161,7 +166,10 @@ async function erc8004CrawlChain(chain) {return { inserted: 0, scanned: 0, lastBlock: latestBlock, fromBlock };}- const toBlock = Math.min(fromBlock + ERC8004_BLOCK_CHUNK - 1, latestBlock);+ // Per-chain override lets a restrictive RPC use a smaller range without+ // throttling well-behaved chains. Falls back to the global default.+ const chunkSize = chain.blockChunk || ERC8004_BLOCK_CHUNK;+ const toBlock = Math.min(fromBlock + chunkSize - 1, latestBlock);const logs = await erc8004RpcCall(chain.rpcUrls ?? chain.rpcUrl, 'eth_getLogs', [{@@ -230,7 +238,7 @@ async function erc8004CrawlChain(chain) {return { inserted, scanned: toBlock - fromBlock + 1, lastBlock: toBlock, fromBlock };}-async function erc8004EnrichMetadata(limit) {+async function erc8004EnrichMetadata(limit, deadline) {const rows = await sql`SELECT chain_id, agent_id, agent_uriFROM erc8004_agents_index@@ -242,6 +250,9 @@ async function erc8004EnrichMetadata(limit) {let done = 0;for (const row of rows) {+ // Each row may fetch a slow external URL; stop before the cron's hard+ // budget so a long IPFS tail can't push the function into a 504.+ if (deadline && Date.now() > deadline) break;try {const meta = await erc8004FetchAgentMetadata(row.agent_uri);if (!meta) {@@ -322,7 +333,7 @@ async function erc8004FetchAgentMetadata(uri) {const url = erc8004ResolveGateway(uri);if (!url) return null;try {- const res = await fetch(url, { signal: AbortSignal.timeout(ERC8004_FETCH_TIMEOUT_MS) });+ const res = await fetch(url, { signal: AbortSignal.timeout(ERC8004_METADATA_TIMEOUT_MS) });if (!res.ok) return null;return await res.json();} catch {@@ -688,7 +699,11 @@ async function idxRpc(urls, method, params) {// Keep small: each mint makes 2-3 Solana RPC calls; public RPC rate-limits at// 429 immediately, so large batches reliably 504 within Vercel's 30s window.const PUMP_STATS_MAX_PER_RUN = 20;-const PUMP_STATS_MINT_TIMEOUT_MS = 8_000;+// Per-mint cap so one stuck mint can't eat the whole run. A healthy private RPC+// answers each of the 2-3 sequential calls in a few hundred ms (~1s/mint), so a+// 4s cap is generous for real work while failing fast on a hung endpoint. The+// 22s DEADLINE below is the real total-run guard; this only bounds one mint.+const PUMP_STATS_MINT_TIMEOUT_MS = 4_000;// Pump.fun graduation threshold (mainnet curve). Used only as a UI hint —// progress_pct is a coarse bar, not financial advice.@@ -836,7 +851,14 @@ async function pumpStatsSnapshotMint({ network, mint }) {} else if (sdk.fetchBondingCurve) {curve = await sdk.fetchBondingCurve(mintPk);}- } catch {+ } catch (e) {+ // The bonding-curve fetch is the dominant source of production 429s+ // (it runs through the single getConnection endpoint). Propagate rate+ // limiting so the outer loop's circuit breaker actually trips instead+ // of silently recording a null curve and burning the per-mint budget.+ if (/429|rate.limit|max usage/i.test(e?.message || '')) {+ throw Object.assign(new Error(`RPC 429: ${e.message}`), { code: 'RATE_LIMITED' });+ }curve = null;}@@ -872,10 +894,15 @@ async function pumpStatsSnapshotMint({ network, mint }) {}}- // Recent activity snapshot via RPC (use fallback pool if Helius is configured)+ // Recent activity snapshot via RPC. withFallback is the wrapper's call+ // surface — it rotates across SOLANA_RPC_FALLBACK_URLS on 429/5xx. Calling+ // RPC methods directly on the RpcFallback instance is a TypeError (the+ // wrapper has no such method), so this must go through withFallback.try {- const conn = getRpcFallback({ network });- const sigs = await conn.getSignaturesForAddress(mintPk, { limit: 50 });+ const rpc = getRpcFallback({ network });+ const sigs = await rpc.withFallback((conn) =>+ conn.getSignaturesForAddress(mintPk, { limit: 50 }),+ );out.recent_tx_count = sigs.length;if (sigs.length > 0) {out.last_signature = sigs[0].signature;diff --git a/api/marketplace/[action].js b/api/marketplace/[action].jsindex 901fad919..e9949b847 100644--- a/api/marketplace/[action].js+++ b/api/marketplace/[action].js@@ -479,7 +479,7 @@ async function handleList(req, res, url) {`,]);} else {- console.error('[marketplace/list]', err?.message || err);+ console.error('[marketplace/list]', err?.code, err?.message || err);return error(res, 500, 'db_error', 'Failed to load marketplace listing');}}diff --git a/api/mocap/clips.js b/api/mocap/clips.jsindex a05fb77c7..75fc598a5 100644--- a/api/mocap/clips.js+++ b/api/mocap/clips.js@@ -107,11 +107,11 @@ async function handleList(req, res, auth) {from mocap_clipswhere ${conds.join(' and ')}order by created_at desc- limit $${params.length}`,+ limit $${params.length}::int`,params,);} catch (err) {- console.error('[mocap/clips/list]', err?.message || err);+ console.error('[mocap/clips/list]', err?.code, err?.message || err);return error(res, 500, 'db_error', 'Failed to list clips');}diff --git a/api/permissions/[action].js b/api/permissions/[action].jsindex adf441183..1d7f1bf3d 100644--- a/api/permissions/[action].js+++ b/api/permissions/[action].js@@ -391,12 +391,18 @@ async function handleList(req, res) {// Verify the session user owns this delegator addressconst targetDelegator = delegator || null;if (targetDelegator) {- const [wallet] = await sql`- SELECT 1 FROM user_wallets- WHERE user_id = ${userId}- AND lower(address) = lower(${targetDelegator})- LIMIT 1- `;+ let wallet;+ try {+ [wallet] = await sql`+ SELECT 1 FROM user_wallets+ WHERE user_id = ${userId}+ AND lower(address) = lower(${targetDelegator})+ LIMIT 1+ `;+ } catch (err) {+ console.error('[permissions/list] wallet ownership query failed', err?.code, err?.message || err);+ return error(res, 500, 'db_error', 'Failed to list delegations');+ }if (!wallet) {return error(res,diff --git a/api/x402-pay.js b/api/x402-pay.jsindex 15a40dcfc..b402fd5d8 100644--- a/api/x402-pay.js+++ b/api/x402-pay.js@@ -492,6 +492,41 @@ async function runFlow({ tool, args, emit, buyer: buyerOverride, resourceUrl })});}+// Build the client-facing envelope for a failed payment flow. Carries the+// upstream status/code through (so a facilitator 5xx surfaces as 502, an+// invalid/under-paid payment as 402, an MCP tool error as 502) and adds an+// honest charging note: a flow that never reached on-chain settlement moved no+// funds, while a post-settlement mismatch is ambiguous and must not promise the+// wallet was untouched.+function payErrorEnvelope(err) {+ const code = err?.code || (err?.mcpError ? 'mcp_dispatch_error' : 'flow_failed');+ let error_description;+ if (code === 'facilitator_unreachable' || code === 'facilitator_error' || code === 'settle_failed') {+ error_description = 'Payment could not be completed and no funds were transferred from the agent wallet. Please try again.';+ } else if (code === 'facilitator_bad_response') {+ error_description = 'Payment status could not be confirmed. Check the payment feed before retrying to avoid paying twice.';+ } else if (code === 'invalid_payment' || code === 'payment_required' || code === 'builder_code_tampered') {+ error_description = 'The payment was rejected before settlement; no funds were transferred.';+ }+ const env = {+ ok: false,+ error: err?.message || 'flow_failed',+ code,+ mcpError: err?.mcpError || null,+ };+ if (error_description) env.error_description = error_description;+ return env;+}++// Map a flow error to its HTTP status. X402Error carries an explicit `status`+// (402 rejected payment, 502 facilitator/upstream); MCP dispatch errors are+// 502; everything else is an unexpected 500.+function payErrorStatus(err) {+ if (Number.isInteger(err?.status)) return err.status;+ if (err?.mcpError) return 502;+ return 500;+}+export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: '*' })) return;@@ -582,29 +617,23 @@ export default wrap(async (req, res) => {try {await runFlow({ tool, args, emit, buyer, resourceUrl });} catch (err) {- emit('error', {- ok: false,- error: err.message || 'flow_failed',- mcpError: err.mcpError || null,- });+ emit('error', payErrorEnvelope(err));} finally {res.end();}return;}- // Non-streaming JSON path: collect events into a final envelope.+ // Non-streaming JSON path: collect the result event, surface any throw with+ // its real status + honest charging guidance.let final = null;- let errEnv = null;const emit = (ev, data) => {if (ev === 'result') final = data;- else if (ev === 'error') errEnv = data;};try {await runFlow({ tool, args, emit, buyer, resourceUrl });} catch (err) {- errEnv = { ok: false, error: err.message || 'flow_failed', mcpError: err.mcpError || null };+ return json(res, payErrorStatus(err), payErrorEnvelope(err));}- if (errEnv) return json(res, errEnv.mcpError ? 502 : 500, errEnv);return json(res, 200, final);});diff --git a/docs/01-display-priced-skills.md b/docs/01-display-priced-skills.mddeleted file mode 100644index 19f00332a..000000000--- a/docs/01-display-priced-skills.md+++ /dev/null@@ -1,72 +0,0 @@-----status: completed------# Prompt 1: Display Priced Skills in Marketplace--**Status:** Completed--## Objective-Modify the agent detail page in the marketplace to visually distinguish between free and paid skills, and display the price for paid skills.--## Explanation-Currently, the agent detail page lists all skills uniformly. To begin building our monetization feature, users need to be able to see which skills are premium and how much they cost. This involves fetching pricing data along with agent details and updating the UI to render prices and a premium indicator.--## Instructions-- [x] **Modify the Backend API:**- - [x] Locate the API endpoint that serves the agent detail data (`/api/marketplace/agents/:id`). You can find this in `api/marketplace/[action].js`.- - [x] When fetching agent details, also query the `agent_skill_prices` table to get the prices for the agent's skills.- - [x] Join this pricing data with the agent details response. The agent object should now have a `skill_prices` map or object, like `{ "skill_name": { "amount": 1000000, "currency_mint": "EPjFWdd..." } }`.--- [x] **Update the Frontend UI:**- - [x] In `src/marketplace.js`, find the `renderDetail` function.- - [x] This function receives the agent object, which now includes `skill_prices`.- - [x] Inside the loop that renders the skills (`d-skills` element), check if a price exists for the current skill.- - [x] If a price exists, render a price badge next to the skill name. Convert the amount from lamports (or the smallest unit) to a human-readable format (e.g., 1,000,000 lamports = 1 USDC).- - [x] Style the price badge to be visually distinct.--## Code Example (Frontend - `src/marketplace.js`)--Here's how you might modify the skill rendering part within the `renderDetail` function:--```javascript-// Inside renderDetail function--const skillPrices = a.skill_prices || {};-$('d-skills').innerHTML = skillsArr.length- ? skillsArr.map((s) => {- const name = typeof s === 'string' ? s : (s.name || '');- const price = skillPrices[name];- const badge = price- ? `<span class="price-badge price-paid">${(price.amount / 1e6).toFixed(2)} USDC</span>`- : `<span class="price-badge price-free">Free</span>`;- return `<span class="skill-entry">${escapeHtml(name)}${badge}</span>`;- }).join(' ')- : '<div>This Agent has no skills defined.</div>';-```--## CSS Example--Add these styles to `/marketplace.css` to make the price badges look good.--```css-.price-badge {- display: inline-block;- margin-left: 8px;- padding: 2px 6px;- font-size: 10px;- font-weight: 600;- border-radius: 4px;- vertical-align: middle;-}--.price-free {- color: #a7f3d0;- background-color: rgba(52, 211, 153, 0.1);-}--.price-paid {- color: #fde047;- background-color: rgba(253, 224, 71, 0.1);-}-```diff --git a/docs/3d-world-roadmap.md b/docs/3d-world-roadmap.mddeleted file mode 100644index 057e1438c..000000000--- a/docs/3d-world-roadmap.md+++ /dev/null@@ -1,308 +0,0 @@-# three.ws — 3D World Build Plan (25 parallel agent tasks)--Goal: turn the 3D world into a Minecraft/Roblox-class multiplayer experience for a-large audience, built on what already exists. Four epics + a foundation layer.--**The big unlock:** a full authoritative MMO RPG already exists on the server-(`multiplayer/src/rooms/GameRoom.js`) with a finished client network bridge-(`src/game/game-net.js`) — gathering, mining, fishing, cooking, combat, 5 skills-(1–99), 24-slot inventory + 6-slot hotbar + 48-slot bank, 4 realms with portals,-mobs, gold, death/tombstones. **Nothing renders it.** `/play` currently loads the-*social* walkaround (`src/game/coincommunities.js` → `community-net.js` → `WalkRoom`).-Several tasks below just finish wiring a game you already built.-------## How to run these--Each task below is a **self-contained prompt** — paste one into a fresh agent chat-in this repo. Every agent must read and obey `CLAUDE.md` (no mocks, real APIs, wire-completely, design every state, run the dev server, run the completionist audit).--**Dependency waves** (run all tasks in a wave in parallel; finish a wave before the next):--- **Wave 0 — Foundations:** T1, T2, T3-- **Wave 1 — RPG scene + Building server + Voice infra + Economy model:** T4, T5, T6, T11, T12, T17, T21-- **Wave 2 — RPG systems + Building client + Voice client + Economy endpoints:** T7, T8, T9, T13, T14, T15, T18, T19, T22-- **Wave 3 — Polish + integration:** T10, T16, T20, T23, T24, T25--Shared protocol facts (give these to any multiplayer task):-- Client bridge `src/game/game-net.js` (class `GameNet`) — methods `step(tx,ty,yaw)`,- `gather(id)`, `attack(id)`, `invMove(from,to)`, `equip(slot)`, `bankOpen()`,- `bankDeposit(i,qty)`, `bankWithdraw(i,qty)`; events `status`, `realm`, `notice`,- `bank`, plus Colyseus `getStateCallbacks` for `state.players/nodes/mobs/tombstones`.-- Server room `multiplayer/src/rooms/GameRoom.js`, schemas `multiplayer/src/schemas/game.js`,- realm definitions `multiplayer/src/rooms/realms.js`. Room name `game_mainland`. 15Hz patch, 50 max clients.-- Social room: `multiplayer/src/rooms/WalkRoom.js` + `src/game/community-net.js`. The- social 3D renderer to mirror is `src/game/coincommunities.js`; free-movement reference is `src/walk.js`.-- Server URL resolution: `<meta name="game-server">` in the page, else `wss://<host>:2567`.-- Persistence primitives: `api/_lib/r2.js` (object storage), `api/_lib/db.js` (Postgres `sql`).-- x402 payment reference: `api/x402/dance-tip.js` + `src/club.js` (the only proven money-in-3D flow).-- Voice infra: `agent-voice-chat/` (LiveKit/WebRTC, standalone — not yet wired to worlds).-------# Wave 0 — Foundations--## T1 — Deploy the multiplayer server to Cloud Run and wire the client--Context: The Colyseus server in `multiplayer/` is not deployed anywhere reachable; the-`game-server` meta tag is empty so the client falls back to `wss://three.ws:2567`-(dead) → `ERR_CONNECTION_TIMED_OUT`. A ready deploy script exists at-`multiplayer/deploy-cloudrun.sh` (correct flags: `--no-cpu-throttling`, single-instance, session affinity, timeout 3600).--Build:-- Run `multiplayer/deploy-cloudrun.sh` against the GCP project (requires `gcloud auth login`- + `gcloud config set project ...` first; ask the user to authenticate if not).-- Map a stable custom domain `mp.three.ws` to the Cloud Run service (domain mapping or a- serverless NEG behind an HTTPS LB). The server's `verifyClient` already allows `*.three.ws`.-- Set `<meta name="game-server" content="wss://mp.three.ws">` in BOTH `pages/play.html`- and (`walk-server`) `pages/walk.html`. Rebuild.-- Verify: `curl https://mp.three.ws/health` returns `{ok:true}`; open `/play`, confirm the- WebSocket connects (no timeouts) and the `[community-net]` status goes `online`.--Done when: `/play` and `/walk` connect to a live server over `wss://mp.three.ws`, health-check passes, and the console shows no connection errors.--## T2 — Isometric/3D game scene skeleton (the RPG front door)--Context: `src/game/game-net.js` (class `GameNet`, room `game_mainland`) is a complete-client bridge with NO 3D scene consuming it. Build the scene that renders `GameRoom`-state, mirroring the structure of `src/game/coincommunities.js` (renderer, camera,-lights, RAF loop, lobby→world phases) but driven by `GameNet` instead of `CommunityNet`.--Build:-- New `src/game/iso-game.js`: Three.js scene (WebGLRenderer, isometric-ish camera,- hemisphere+directional lights, RAF loop), a `GameNet` instance, and a clean phase model- (lobby → connecting → in-world → offline). Reuse `AnimationManager` (`src/animation-manager.js`).-- Render the local player rig (GLB avatar via the existing `resolveAvatarUrl`/`buildAvatar`- helpers — extract/share them from coincommunities.js rather than copy-pasting).-- Subscribe to `GameNet` events (`realm`, `notice`, `bank`, `status`) and state callbacks- for `players`. Leave nodes/mobs/inventory rendering to T4–T9 (stub clean extension points).-- Add a route + entry: decide whether this is a new page (`pages/game.html` → `iso-game.js`)- or a mode toggle inside `/play`. Pick one, wire it, make it reachable from navigation.-- Designed loading + offline + empty states. No console errors.--Done when: visiting the new scene connects to `game_mainland`, renders the local avatar on-a placeholder ground, shows other connected players moving, and exposes documented hooks-(`renderNodes`, `renderMobs`, `bindInventory`, etc.) for the RPG-system tasks.--## T3 — Per-world persistence service--Context: World/game state is currently ephemeral. Building (T11–T16) and the economy-(T21–T25) need durable per-world storage keyed by coin mint (or realm id).--Build:-- A generic persistence API under `api/world/` (e.g. `api/world/[action].js`) backed by- `api/_lib/r2.js` and/or `api/_lib/db.js`: `load(worldId)` and `save(worldId, doc)` with- size limits, schema versioning, optimistic concurrency (etag/updatedAt), and auth so only- permitted writers can save (see T16 for permission model — expose a hook).-- Decide storage: R2 for large blob docs (placed objects), Postgres for indexed/queried- data (ownership, passes). Document the split in the file header.-- A small server-side client `multiplayer/src/persistence.js` so Colyseus rooms can- load on `onCreate` and debounce-save on change.--Done when: a room can persist and restore an arbitrary JSON world doc across restarts;-load/save are covered by a unit test in `tests/`; unauthorized writes are rejected.-------# Wave 1–3 — Epic A: Surface the RPG in /play--## T4 — Tilemap + realm renderer--Depends: T2. Files: `src/game/iso-game.js`, read `multiplayer/src/rooms/realms.js`.-Build: render each realm from the `realm` layout event — ground tiles, blocked zones-(bank, fountain, water), portals (visual + label), safe-zone vs danger-zone tinting.-Use instanced meshes for tiles (perf). Handle realm-switch (clear + rebuild) when the-player takes a portal. Done when: all 4 realms (Mainland, Wilderness, Whisperwood, Pond)-render correctly with portals visible and the bank/fountain/water footprints match the server grid.--## T5 — Local movement (tile-step pathing + click-to-move)--Depends: T2, T4. Build: click-to-move pathfinding on the walkable grid (A* or BFS over-realm walkability), sending one `step(tx,ty,yaw)` per tile via `GameNet`; also WASD/arrow-tile stepping and mobile tap. Smooth visual interpolation between tiles + facing yaw.-Respect server rejections (snap back). Done when: the local avatar paths around obstacles-to a clicked tile, animates walk/idle, and never desyncs from the server position.--## T6 — Remote players rendering + interpolation--Depends: T2. Build: a `RemotePlayer` for `game_mainland` (mirror the one in-coincommunities.js): GLB avatar, animation state from `motion`, position lerp between tile-updates, floating nameplate, HP indication. Add/remove on state callbacks. Done when:-multiple browser tabs see each other move/animate smoothly with correct names.--## T7 — Resource nodes + gathering--Depends: T4, T6. Build: render `state.nodes` (trees, rocks, coal, fishing spots, cooking-spots) with depleted/respawning visual states. Click a node → `gather(id)`; show progress,-tool requirement, cooldown, and floating "+1 wood / +5 xp" feedback from `notice` events.-Done when: gathering each node type works end-to-end with correct tool gating, depletion,-respawn, and inventory updates reflected in the UI.--## T8 — Combat: mobs, attacking, death--Depends: T4, T6. Build: render `state.mobs` (dummy/goblin/ogre) with idle/aggro states and-HP bars; click → `attack(id)`; show damage numbers, gold drops, and `state.tombstones` on-death. Handle local-player death (danger realms) + 4s respawn + tombstone loot pickup.-Done when: a full combat loop (engage → damage → kill → loot → xp/gold) works and deaths-drop/recover a tombstone correctly.--## T9 — Inventory, hotbar & bank UI--Depends: T2, T7. Build: a polished DOM/canvas UI for the 24-slot inventory, 6-slot hotbar,-and 48-slot bank. Drag-and-drop via `invMove(from,to)`, equip via `equip(slot)`, deposit/-withdraw via `bankDeposit/bankWithdraw` (bank opens on `bankOpen` near the bank tile). Item-icons, stack counts, tooltips, empty/full states. Done when: all inventory/hotbar/bank-operations round-trip to the server, with hover/active/focus states and keyboard support.--## T10 — Skills HUD + leveling feedback--Depends: T7, T8. Build: a skills panel (Woodcutting, Mining, Fishing, Cooking, Combat) with-live levels from peer state, an XP/level-up toast with FX, and a compact always-on HUD-(current HP, gold, active skill). Use the existing 1–99 curve. Done when: gaining XP shows-progress, hitting a new level fires a celebratory toast, and the HUD reflects live stats.-------# Epic B: Building / UGC ("every coin is a buildable world")--## T11 — Server: authoritative placement--Depends: T3. Files: new `multiplayer/src/rooms/*` + `multiplayer/src/schemas/*`. Build:-add placement to the world (either extend `WalkRoom` or a dedicated `BuildRoom`): a-schema map of placed objects `{id, catalogId, x, y, z, rotY, scale, ownerId}`, with-`place`, `move`, `remove` messages. Server validates catalog id (allowlist), grid snap,-bounds, max-objects-per-world, and per-player rate limits. Broadcast deltas. Done when:-placements sync live across clients with full server-side validation and anti-grief limits.--## T12 — Server: per-coin world persistence of builds--Depends: T3, T11. Build: load placed objects on room create and debounce-save on change-via the T3 persistence service, keyed by coin mint. Snapshot/restore so a coin world's-build survives restarts and re-joins. Done when: building in a coin world, leaving, and-rejoining (or restarting the server) restores the exact build.--## T13 — Client: build mode + placement controls--Depends: T2 (or social scene), T11. Build: a build-mode toggle; a ghost/preview of the-selected object that snaps to the grid; place (`place`), rotate, scale, move (`move`),-delete (`remove`); undo/redo. Raycast to ground/surfaces. Touch + desktop. Done when:-a user can place, rotate, move, and delete objects with smooth previews and the changes-appear instantly for everyone in the world.--## T14 — Client: building palette UI--Depends: T13, T15. Build: a categorized, searchable palette of placeable props/blocks with-thumbnails, recent/favorites, and a count of remaining placements. Keyboard shortcuts to-cycle categories. Designed empty/loading states. Done when: selecting from the palette sets-the active object for T13's placement and the palette is fully navigable by mouse, touch, and keyboard.--## T15 — Prop/block asset catalog--Depends: none (can start early). Build: a curated catalog (`src/game/build-catalog.js` +-assets under `public/build/`) of optimized GLB props/blocks (nature, structures, furniture,-decor) with ids, categories, thumbnails, and collision/footprint metadata. Keep total-download lazy/paged. Done when: ≥40 catalog items load on demand with thumbnails, and the-catalog is the single source consumed by T11 (allowlist), T13, and T14.--## T16 — Build permissions + live collaboration--Depends: T11, T12. Build: a permission model — who may build in a given coin world (e.g.-coin holders above a threshold, an owner allowlist, or open) — enforced server-side and-reflected in the client (build button disabled with a reason if not permitted). Live-multi-user editing with per-object ownership and conflict handling. Done when: permissions-are enforced authoritatively, unauthorized users can't place, and two permitted users can-build together in real time without conflicts.-------# Epic C: Proximity voice + spatial chat--## T17 — Voice room token API--Depends: none (needs LiveKit creds). Files: new `api/voice/*`, reference `agent-voice-chat/`.-Build: an endpoint that issues short-lived LiveKit access tokens scoped to a per-world room-(room id = coin mint / realm id), with identity = the player's session id and metadata for-display name. Server-side key handling (never expose the LiveKit secret). Rate-limited.-Done when: a client can request a token and join the correct world voice room; tokens-expire; secrets stay server-side.--## T18 — Client voice manager--Depends: T17, a live multiplayer scene (T2 or social). Build: `src/game/voice-net.js` — join-the world's LiveKit room, capture mic, publish/subscribe to peer audio, handle join/leave,-device errors, and permissions (mic prompt). Tie LiveKit participant identity to the-multiplayer player id so audio can be spatialized in T19. Done when: two users in the same-world can hear each other, with graceful handling of denied mic / no device.--## T19 — Spatial audio falloff--Depends: T18, T6 (player positions). Build: position each remote participant's audio in 3D-using avatar positions (WebAudio PannerNode or LiveKit spatial API): distance-based volume-falloff + stereo panning, updated each frame. Tunable max-distance. Done when: voices get-louder/quieter and pan as avatars move toward/away from each other.--## T20 — Voice UI--Depends: T18. Build: mute/unmute, push-to-talk, output volume, and per-speaker indicators-(a ring/pulse on the speaking avatar's nameplate + a roster of who's talking). Persist mute-preference. Done when: every voice control works with hover/active/focus states and speaking-indicators track actual audio activity.-------# Epic D: On-chain creator economy--## T21 — Item/cosmetic data model + ownership ledger--Depends: T3. Files: `api/_lib/db.js` (migrations), new `api/economy/*`. Build: schemas for-sellable items (cosmetics, build packs, world passes) and an ownership ledger (wallet ↔-item, with mint/tx provenance). Indexed queries: "what does wallet X own?", "who owns world-pass for coin Y?". Done when: items and ownership are modeled, migrated, and queryable, with-a unit test covering grant/revoke/lookup.--## T22 — x402 purchase endpoints--Depends: T21. Files: new `api/x402/buy-item.js`, reference `api/x402/dance-tip.js` +-`src/club.js`. Build: x402-paid endpoints to purchase a cosmetic / build pack / world pass-in USDC; on settlement, write ownership (T21) and split payout to the creator's wallet.-Idempotent on tx; receipt feed. Done when: a real USDC purchase grants ownership and pays-the creator, verified on-chain, with no double-grant on retries.--## T23 — In-world marketplace UI--Depends: T21, T22. Build: a marketplace panel (browse by category, price in USDC, preview-3D item, buy via the x402 flow, "owned" badges). Designed loading/empty/error/sold-out-states. Done when: a user can browse, preview, and buy an item end-to-end and immediately-see it as owned.--## T24 — World access passes--Depends: T21, T22, T16. Build: gate entry to premium/holder coin worlds behind a pass-(free for holders, or purchasable); check ownership on world join (server-side), with a-clear paywall + buy flow on the client and a creator revenue split. Done when: a gated-world rejects non-pass-holders with a buy prompt and admits holders/buyers, and revenue-routes to the creator.--## T25 — Cosmetics equip pipeline--Depends: T21, Epic A or social avatars. Build: wire owned cosmetics into the avatar — the-`cosmetic` field already exists in `GamePlayer` (schema/game.js) but is unused. Equip/unequip-owned cosmetics (reuse `src/agent-accessories.js` accessory compositing), sync the equipped-look to peers, and reflect it in both the RPG scene and the social walkaround. Done when:-buying a cosmetic and equipping it changes the avatar for the owner and all nearby players.-------## Notes for the orchestrator-- T15 and T17 have no internal deps — start them in Wave 0 alongside T1–T3 if you have agents free.-- Extract shared avatar helpers (`resolveAvatarUrl`, `buildAvatar`, `RemotePlayer`) into a- shared module during T2 so the RPG scene, social scene, and cosmetics all reuse one path.-- Every agent: run `npm run dev`, exercise in a browser, run the **completionist** subagent on- changed files, and confirm no console errors before reporting done (per CLAUDE.md).-- Push only on explicit approval, to BOTH remotes (`threeD` then `threews`).-</content>-</invoke>diff --git a/src/agent-solana-wallet.js b/src/agent-solana-wallet.jsindex e6ce07abc..ae97bd4ce 100644--- a/src/agent-solana-wallet.js+++ b/src/agent-solana-wallet.js@@ -146,6 +146,7 @@ const STYLE = `.agent-sol-wallet .src { font-size: .7rem; color: rgba(230,230,234,0.5); margin-left: .35rem; }.agent-sol-wallet .balance { display: flex; align-items: center; gap: .5rem; margin-top: .55rem; font-size: .8rem; color: rgba(230,230,234,0.85); }.agent-sol-wallet .balance .sol { font-family: ui-monospace, monospace; font-weight: 600; }+.agent-sol-wallet .balance .sol.unavailable { font-family: system-ui, sans-serif; font-weight: 500; font-size: .75rem; color: #ffb74d; cursor: help; }.agent-sol-wallet .balance .net { margin-left: auto; font-size: .7rem; }.agent-sol-wallet .balance select { font: inherit; font-size: .7rem; padding: .15rem .25rem; border: 1px solid rgba(255,255,255,0.12); border-radius: 4px; background: rgba(255,255,255,0.04); color: #e6e6ea; }.agent-sol-wallet .skel { color: rgba(230,230,234,0.4); font-size: .75rem; padding: .35rem 0; }@@ -246,6 +247,7 @@ export function mountAgentSolanaWalletCard({ panel, identity, onProvisioned }) {network: 'mainnet',sol: null,lamports: null,+ balanceError: null,snsDomain: null,busy: false,err: null,@@ -269,6 +271,7 @@ export function mountAgentSolanaWalletCard({ panel, identity, onProvisioned }) {state.source = r.data.source || null;state.lamports = r.data.lamports;state.sol = r.data.sol;+ state.balanceError = r.data.balance_error || null;state.snsDomain = r.data.sns_domain || null;_propagate(identity, r.data);} else if (r.status === 'none') {@@ -291,6 +294,7 @@ export function mountAgentSolanaWalletCard({ panel, identity, onProvisioned }) {if (r.status === 'ok') {state.lamports = r.data.lamports;state.sol = r.data.sol;+ state.balanceError = r.data.balance_error || null;state.snsDomain = r.data.sns_domain || null;render();}@@ -357,14 +361,22 @@ export function mountAgentSolanaWalletCard({ panel, identity, onProvisioned }) {if (state.address) {const pfx = state.vanityPrefix || '';const rest = state.address.slice(pfx.length);- const solDisplay = state.sol == null ? '—' : `${state.sol.toFixed(4)} SOL`;+ const balUnavailable = state.balanceError != null;+ const balTitle = state.balanceError === 'rpc_rate_limited'+ ? 'Solana RPC is rate-limited — balance will refresh automatically.'+ : state.balanceError+ ? 'Could not reach the Solana RPC — balance will refresh automatically.'+ : '';+ const solDisplay = balUnavailable+ ? 'Balance unavailable'+ : state.sol == null ? '—' : `${state.sol.toFixed(4)} SOL`;const isDevnet = state.network === 'devnet';root.innerHTML = `<h3>Solana wallet${state.source ? `<span class="src">· ${_esc(state.source)}</span>` : ''}</h3><div class="addr"><span class="pfx">${_esc(pfx)}</span>${_esc(rest)}</div>${state.snsDomain ? `<div><span class="sns" title="Primary .sol domain for this wallet">${_esc(state.snsDomain)}</span></div>` : ''}<div class="balance">- <span class="sol">${_esc(solDisplay)}</span>+ <span class="sol${balUnavailable ? ' unavailable' : ''}"${balTitle ? ` title="${_esc(balTitle)}"` : ''}>${_esc(solDisplay)}</span><span class="net"><select data-act="network" aria-label="Network"><option value="mainnet" ${state.network === 'mainnet' ? 'selected' : ''}>Mainnet</option>@@ -447,6 +459,7 @@ export function mountAgentSolanaWalletCard({ panel, identity, onProvisioned }) {state.source = data.source || 'generated';state.lamports = data.lamports ?? 0;state.sol = data.sol ?? 0;+ state.balanceError = data.balance_error || null;_propagate(identity, data);onProvisioned?.(data);refreshBalance();diff --git a/src/selfie-modal.js b/src/selfie-modal.jsindex 1221aa156..925ebeb28 100644--- a/src/selfie-modal.js+++ b/src/selfie-modal.js@@ -518,6 +518,13 @@ class SelfieModal {return;}+ // 501 means the reconstruction backend isn't configured on the server.+ // The API's error_description is operator-facing ("set AVATAR_REGEN_PROVIDER+ // and the matching API token…") — surface a clean end-user message instead.+ if (res.status === 501) {+ throw new Error('Avatar engine is not available right now. Please try again later.');+ }+if (!res.ok) {const payload = await res.json().catch(() => ({}));throw new Error(payload.error_description || payload.error || `HTTP ${res.status}`);diff --git a/tests/api/club-leaderboard.test.js b/tests/api/club-leaderboard.test.jsindex b0ca34113..f4ef9ab3e 100644--- a/tests/api/club-leaderboard.test.js+++ b/tests/api/club-leaderboard.test.js@@ -113,4 +113,23 @@ describe('GET /api/club/leaderboard', () => {const { body } = await invoke({ query: { window: 'day' } });expect(body.window).toBe('day');});++ it('returns 500 db_error and logs the Postgres code when the query throws', async () => {+ const pgErr = Object.assign(new Error('column t.paid_at does not exist'), {+ code: '42703',+ detail: 'relation club_tips',+ });+ sqlMock.mockRejectedValueOnce(pgErr);+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});++ const { status, body } = await invoke({ query: { window: 'all' } });++ expect(status).toBe(500);+ expect(body.error).toBe('db_error');+ // The whole point of the fix: the Postgres code must reach the logs so+ // schema drift (42703 column / 42P01 table) is diagnosable.+ const logged = errSpy.mock.calls[0].join(' ');+ expect(logged).toContain('42703');+ errSpy.mockRestore();+ });});diff --git a/tests/api/solana-wallet-balance.test.js b/tests/api/solana-wallet-balance.test.jsnew file mode 100644index 000000000..a40243157--- /dev/null+++ b/tests/api/solana-wallet-balance.test.js@@ -0,0 +1,124 @@+// Public wallet-read balance path: caching + graceful 429 handling.+// Covers the fix where a rate-limited Solana RPC must surface+// balance_error: 'rpc_rate_limited' (so the card shows "Balance unavailable")+// instead of a misleading 0, and where a cached balance is reused within the+// TTL window rather than re-hitting the RPC on every poll.++import { describe, it, expect, beforeEach, vi } from 'vitest';+import { Readable } from 'node:stream';+import { Keypair } from '@solana/web3.js';++// Real, valid base58 pubkeys — the handler runs them through the real+// PublicKey constructor before the (mocked) getBalance, so placeholder strings+// would throw there instead of exercising the balance path.+const addr = () => Keypair.generate().publicKey.toBase58();++// Shared, mutable RPC stub state — defined before vi.mock so the (lazy) mock+// factory closes over it, matching the pattern in solana-wallet-import.test.js.+const rpcState = { lamports: 0, calls: 0, err: null };++vi.mock('../../api/_lib/auth.js', () => ({+ getSessionUser: vi.fn(async () => null),+ authenticateBearer: vi.fn(async () => null),+ extractBearer: vi.fn(() => null),+}));++const sqlState = { queue: [] };+vi.mock('../../api/_lib/db.js', () => ({+ sql: vi.fn(async () => (sqlState.queue.length ? sqlState.queue.shift() : [])),+}));++vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: { authIp: vi.fn(async () => ({ success: true })), walletRead: vi.fn(async () => ({ success: true })) },+ clientIp: vi.fn(() => '127.0.0.1'),+}));++vi.mock('../../api/_lib/env.js', () => ({+ env: { JWT_SECRET: 'test-secret-please-do-not-use-in-production-ever', APP_ORIGIN: 'http://localhost' },+}));++vi.mock('../../api/_lib/agent-pumpfun.js', () => {+ const conn = () => ({+ getBalance: async () => {+ rpcState.calls++;+ if (rpcState.err) throw rpcState.err;+ return rpcState.lamports;+ },+ });+ return { solanaConnection: () => conn(), solanaPublicConnection: () => conn() };+});++vi.mock('../../api/_lib/agent-wallet.js', () => ({+ generateSolanaAgentWallet: vi.fn(async () => ({ address: 'x', encrypted_secret: 'y' })),+}));++const { default: handler } = await import('../../api/agents/solana-wallet.js');++function makeReq(url) {+ const r = Readable.from([]);+ r.method = 'GET';+ r.url = url;+ r.headers = { host: 'localhost', origin: 'http://localhost' };+ return r;+}+function makeRes() {+ return {+ statusCode: 200, headers: {}, body: '', writableEnded: false,+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },+ end(c) { if (c !== undefined) this.body += c; this.writableEnded = true; },+ };+}+async function read(address, network = 'mainnet') {+ // Unique address per call keeps the shared cache from leaking across tests.+ sqlState.queue.push([{ id: 'agent-1', meta: { solana_address: address } }]);+ const req = makeReq(`/api/agents/agent-1/solana?network=${network}`);+ const res = makeRes();+ await handler(req, res, 'agent-1');+ return { status: res.statusCode, body: res.body ? JSON.parse(res.body) : null };+}++beforeEach(() => {+ rpcState.lamports = 0;+ rpcState.calls = 0;+ rpcState.err = null;+ sqlState.queue = [];+});++describe('GET /api/agents/:id/solana — public balance read', () => {+ it('returns the live balance and chain metadata', async () => {+ rpcState.lamports = 2_500_000_000;+ const { status, body } = await read(addr());+ expect(status).toBe(200);+ expect(body.data.balance).toBe(2.5);+ expect(body.data.lamports).toBe(2_500_000_000);+ expect(body.data.balance_error).toBeUndefined();+ });++ it('surfaces balance_error=rpc_rate_limited when the RPC 429s on every attempt', async () => {+ rpcState.err = new Error('failed to get balance: 429 Too Many Requests: max usage reached');+ const { status, body } = await read(addr());+ expect(status).toBe(200); // graceful — never 500s+ expect(body.data.balance).toBeNull();+ expect(body.data.balance_error).toBe('rpc_rate_limited');+ });++ it('classifies non-rate-limit RPC failures as rpc_error', async () => {+ rpcState.err = new Error('fetch failed: ECONNREFUSED');+ const { body } = await read(addr());+ expect(body.data.balance).toBeNull();+ expect(body.data.balance_error).toBe('rpc_error');+ });++ it('serves the second read from cache without re-hitting the RPC', async () => {+ rpcState.lamports = 1_000_000_000;+ const wallet = addr();+ const first = await read(wallet);+ const callsAfterFirst = rpcState.calls;+ expect(first.body.data.balance).toBe(1);+ expect(callsAfterFirst).toBeGreaterThan(0);++ const second = await read(wallet);+ expect(second.body.data.balance).toBe(1);+ expect(rpcState.calls).toBe(callsAfterFirst); // no additional RPC call+ });+});diff --git a/tests/api/x402-spec.test.js b/tests/api/x402-spec.test.jsindex cd7738ea9..7f36724af 100644--- a/tests/api/x402-spec.test.js+++ b/tests/api/x402-spec.test.js@@ -302,6 +302,116 @@ describe('build402Body extensions', () => {});});+describe('callFacilitator transient retry (via verify/settle)', () => {+ const REAL_FETCH = global.fetch;++ function fetchResponse({ ok, status, body }) {+ return {+ ok,+ status,+ text: async () => (typeof body === 'string' ? body : JSON.stringify(body)),+ };+ }++ beforeEach(() => {+ process.env.X402_FACILITATOR_URL_SOLANA = 'https://facilitator.test';+ process.env.X402_FACILITATOR_TOKEN_SOLANA = 'tok';+ // Keep the inter-attempt backoff from slowing the suite — a 1ms timeout+ // still exercises the real retry loop without a half-second wait.+ process.env.X402_FACILITATOR_TIMEOUT_MS = '5000';+ });++ afterEach(() => {+ global.fetch = REAL_FETCH;+ });++ function solanaPaymentHeader() {+ const payload = {+ x402Version: 2,+ scheme: 'exact',+ network: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',+ payload: { transaction: 'AAAA' },+ };+ return Buffer.from(JSON.stringify(payload)).toString('base64');+ }++ it('retries /verify once on a transient 503 then succeeds', async () => {+ const { verifyPayment, paymentRequirements } = await loadSpec();+ const calls = [];+ global.fetch = vi.fn(async (url) => {+ calls.push(url);+ if (calls.length === 1) return fetchResponse({ ok: false, status: 503, body: { error: 'upstream down' } });+ return fetchResponse({ ok: true, status: 200, body: { isValid: true, payer: 'PAYER1' } });+ });+ const result = await verifyPayment({+ paymentHeader: solanaPaymentHeader(),+ requirements: paymentRequirements(),+ builderCode: null,+ });+ expect(result.payer).toBe('PAYER1');+ expect(global.fetch).toHaveBeenCalledTimes(2);+ });++ it('does NOT retry a 400 invalid-payment — passes the rejection through once', async () => {+ const { verifyPayment, paymentRequirements } = await loadSpec();+ global.fetch = vi.fn(async () =>+ fetchResponse({ ok: false, status: 400, body: { isValid: false, invalidReason: 'bad sig' } }),+ );+ await expect(+ verifyPayment({+ paymentHeader: solanaPaymentHeader(),+ requirements: paymentRequirements(),+ builderCode: null,+ }),+ ).rejects.toMatchObject({ code: 'invalid_payment', status: 402 });+ expect(global.fetch).toHaveBeenCalledTimes(1);+ });++ it('stops after a single retry when the 5xx persists', async () => {+ const { verifyPayment, paymentRequirements } = await loadSpec();+ global.fetch = vi.fn(async () => fetchResponse({ ok: false, status: 503, body: { error: 'still down' } }));+ await expect(+ verifyPayment({+ paymentHeader: solanaPaymentHeader(),+ requirements: paymentRequirements(),+ builderCode: null,+ }),+ ).rejects.toMatchObject({ code: 'facilitator_error', status: 502 });+ expect(global.fetch).toHaveBeenCalledTimes(2);+ });++ it('retries /settle on a transient 504 with the SAME idempotency key', async () => {+ const { settlePayment } = await loadSpec();+ const requirement = {+ scheme: 'exact',+ network: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',+ payTo: 'BUrwd1nK6tFeeJMyzRHDo6AuVbnSfUULfvwq21X93nSN',+ asset: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',+ amount: '1000',+ };+ const verified = {+ paymentPayload: { network: requirement.network, payload: { transaction: 'AAAA' } },+ requirement,+ payer: 'PAYER2',+ };+ const idemKeys = [];+ global.fetch = vi.fn(async (_url, opts) => {+ idemKeys.push(opts.headers['Idempotency-Key']);+ if (idemKeys.length === 1) return fetchResponse({ ok: false, status: 504, body: { error: 'timeout' } });+ return fetchResponse({+ ok: true,+ status: 200,+ body: { success: true, transaction: 'TX123', network: requirement.network, payer: 'PAYER2' },+ });+ });+ const result = await settlePayment({ verified });+ expect(result.transaction).toBe('TX123');+ expect(global.fetch).toHaveBeenCalledTimes(2);+ expect(idemKeys[0]).toBeTruthy();+ expect(idemKeys[0]).toBe(idemKeys[1]);+ });+});+describe('send402 PAYMENT-REQUIRED header', () => {function makeRes() {return {