Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat: integrate shared SOL price fetching across pump-launch and pumpfun WS feeds

fudjiac203fab7c864
diff --git a/api/_lib/env.js b/api/_lib/env.js
index ff3cde21d..f1e2434ab 100644
--- a/api/_lib/env.js
+++ b/api/_lib/env.js
@@ -876,6 +876,19 @@ export const env = {
get X402_ACCEPT_THREE_SOLANA() {
return opt('X402_ACCEPT_THREE_SOLANA', 'true') === 'true';
},
+ // USE-21 auth-hints advertisement in 402 challenges. When 'true' (default),
+ // endpoints that declare authHints append zero-amount accepts[] entries plus
+ // the auth-hints extension so buyer clients can discover the free auth
+ // alternative. External x402 directory validators (402index confirmed;
+ // likely other amount-must-be-positive crawlers) reject any challenge that
+ // contains amount="0" entries as "no valid x402 challenge" — set 'false' to
+ // suppress the advertisement on a deployment that prioritizes directory
+ // listability. Auth bypass itself is unaffected either way: the
+ // access-control hook honors Bearer/SIWX headers before the payment dance
+ // regardless of what the 402 advertises.
+ get X402_AUTH_HINT_ACCEPTS() {
+ return opt('X402_AUTH_HINT_ACCEPTS', 'true') === 'true';
+ },
// Flat THREE price per paid call, in atomic THREE units (6 decimals).
// 10_000_000 = 10 $THREE. A single flat amount for every endpoint regardless
// of its USDC price (a $0.01 oracle call and a $0.50 Forge both cost 10 THREE)
diff --git a/api/_lib/pump-alert-runner.js b/api/_lib/pump-alert-runner.js
index 4a050ddac..5d2b1ef2a 100644
--- a/api/_lib/pump-alert-runner.js
+++ b/api/_lib/pump-alert-runner.js
@@ -26,6 +26,7 @@ import {
buildPricePayload,
} from './pump-alert-eval.js';
import { deliverAlert } from './alert-delivery.js';
+import { solPriceUsd as sharedSolPriceUsd } from './sol-price.js';
const GRAD_WINDOW = '15 minutes';
const NEW_MINT_WINDOW = '60 minutes';
@@ -35,7 +36,6 @@ const MAX_PRICE_MINTS = 60; // distinct mints priced per run
const MAX_WHALE_MINTS = 60; // distinct mints polled for trades per run
const TRADES_LIMIT = 50;
const FETCH_TIMEOUT_MS = 2_500;
-const SOL_PRICE_TTL_MS = 60_000;
const PUMPFUN_COIN_API = 'https://frontend-api-v3.pump.fun/coins';
const PUMPFUN_TRADES_API = 'https://frontend-api-v3.pump.fun/trades/all';
@@ -371,15 +371,7 @@ async function fetchRecentTrades(mint, solPrice = 0) {
});
}
-let _solPrice = 0;
-let _solPriceAt = 0;
-async function getSolPrice() {
- if (Date.now() - _solPriceAt < SOL_PRICE_TTL_MS && _solPrice > 0) return _solPrice;
- const d = await fetchJsonWithTimeout('https://api.coingecko.com/api/v3/simple/price?ids=solana&vs_currencies=usd');
- const p = d?.solana?.usd;
- if (p > 0) {
- _solPrice = p;
- _solPriceAt = Date.now();
- }
- return _solPrice || 0;
-}
+// SOL/USD for USD-denominating price-rule evaluations. Delegates to the shared
+// 7-source failover helper (itself cached ~60s) so a single-provider rate-limit
+// never stalls alert pricing. Returns 0 only if every free source is down.
+const getSolPrice = () => sharedSolPriceUsd();
diff --git a/api/_lib/pump-launch-feed.js b/api/_lib/pump-launch-feed.js
index 5dccfaae3..1fd44707a 100644
--- a/api/_lib/pump-launch-feed.js
+++ b/api/_lib/pump-launch-feed.js
@@ -8,6 +8,8 @@
// so recentPumpLaunches() returns [] there (entries simply don't fire on devnet —
// open positions still exit via real on-chain re-quotes).
+import { solPriceUsd as sharedSolPriceUsd } from './sol-price.js';
+
const PUMP_FRONTEND_BASE = process.env.PUMP_FRONTEND_BASE || 'https://frontend-api-v3.pump.fun';
const FETCH_TIMEOUT_MS = 6_000;
const UA = 'three.ws-strategy-runtime/1';
@@ -68,18 +70,11 @@ export function normalizeLaunch(c, solPrice = 0) {
};
}
-let _solPrice = 0;
-let _solPriceAt = 0;
-async function solPriceUsd() {
- if (Date.now() - _solPriceAt < 60_000 && _solPrice > 0) return _solPrice;
- const d = await fetchJsonWithTimeout('https://api.coingecko.com/api/v3/simple/price?ids=solana&vs_currencies=usd', 3000);
- const p = d?.solana?.usd;
- if (p > 0) {
- _solPrice = p;
- _solPriceAt = Date.now();
- }
- return _solPrice || 0;
-}
+// SOL/USD for USD-denominating launch market caps. Delegates to the shared
+// 7-source failover helper (CoinGecko → Jupiter → Kraken → Coinbase → DefiLlama
+// → DIA → Bitfinex, itself cached ~60s) so a single-provider rate-limit never
+// zeroes the feed's USD figures. Returns 0 only if every source is down.
+const solPriceUsd = () => sharedSolPriceUsd();
/**
* Fetch the most-recent RAW pump.fun coin objects (newest-first), keeping the
diff --git a/api/_lib/pumpfun-ws-feed.js b/api/_lib/pumpfun-ws-feed.js
index 4cf55476b..a2a1bf037 100644
--- a/api/_lib/pumpfun-ws-feed.js
+++ b/api/_lib/pumpfun-ws-feed.js
@@ -4,6 +4,7 @@
// Each mint event is enriched with SOL price + token metadata before emit.
import WebSocket from 'ws';
+import { solPriceUsd as sharedSolPriceUsd } from './sol-price.js';
const PUMPPORTAL_WS = 'wss://pumpportal.fun/api/data';
const RECONNECT_DELAY_MS = 2_000;
@@ -42,22 +43,13 @@ function markSeen(sig) {
return true;
}
const META_TIMEOUT_MS = 2_500;
-const SOL_PRICE_TTL_MS = 60_000;
-// SOL price cache — one CoinGecko call per minute, shared across connections
-let _solPrice = 0;
-let _solPriceAt = 0;
-
-async function getSolPrice() {
- if (Date.now() - _solPriceAt < SOL_PRICE_TTL_MS && _solPrice > 0) return _solPrice;
- try {
- const r = await fetch('https://api.coingecko.com/api/v3/simple/price?ids=solana&vs_currencies=usd');
- const d = await r.json();
- const p = d?.solana?.usd;
- if (p > 0) { _solPrice = p; _solPriceAt = Date.now(); }
- } catch {}
- return _solPrice || 150;
-}
+// SOL/USD via the shared 7-source failover helper (CoinGecko → Jupiter → Kraken
+// → Coinbase → DefiLlama → DIA → Bitfinex, itself cached ~60s and shared across
+// connections). Returns 0 when every source is down — callers leave the USD
+// figure null rather than the old hardcoded $150 guess, which silently corrupted
+// live market caps during an outage.
+const getSolPrice = () => sharedSolPriceUsd();
// Token metadata cache — avoids re-fetching the same URI on reconnects
const _metaCache = new Map();
diff --git a/api/_lib/x402-paid-endpoint.js b/api/_lib/x402-paid-endpoint.js
index f41ce4692..3c42e96c9 100644
--- a/api/_lib/x402-paid-endpoint.js
+++ b/api/_lib/x402-paid-endpoint.js
@@ -423,7 +423,13 @@ export function paidEndpoint(spec) {
// extension maps each method to the index of its free entry so the
// buyer client knows which entry corresponds to which auth method.
let authHintsExtension = null;
- if (authHints) {
+ // X402_AUTH_HINT_ACCEPTS=false suppresses the whole advertisement (the
+ // extension schema requires each declared method to map to a free
+ // accepts[] entry, so the two can only ship together). External x402
+ // directory validators reject challenges carrying amount="0" entries;
+ // the auth bypass itself keeps working either way because the
+ // access-control hook runs before the payment dance.
+ if (authHints && env.X402_AUTH_HINT_ACCEPTS) {
const baseTo = payTo?.base || env.X402_PAY_TO_BASE;
if (baseTo) {
const declarations = {};
diff --git a/api/cron/x402-directory-registrar.js b/api/cron/x402-directory-registrar.js
new file mode 100644
index 000000000..d84fe2e77
--- /dev/null
+++ b/api/cron/x402-directory-registrar.js
@@ -0,0 +1,117 @@
+// GET /api/cron/x402-directory-registrar — keeps three.ws's paid x402
+// endpoints registered (and their listings fresh) on the external x402
+// directories that accept programmatic submission. Currently: 402index.io.
+//
+// Design — stateless, bounded, self-healing:
+// • 402index's POST /api/v1/register is an UPSERT keyed by url (verified:
+// re-registering returns the same service id and refreshes name /
+// description), and its public search does not reliably surface fresh
+// registrations — so presence-checking is pointless. Instead each hourly
+// tick re-upserts the next WINDOW of catalog entries under a rotating
+// cursor derived from the hour number. Every endpoint is (re)registered
+// every ~⌈catalog/WINDOW⌉ hours, new endpoints join the rotation the tick
+// after they enter the service catalog, and description drift on the
+// directory heals itself on the next pass.
+// • 402index rate-limits registration to 10/hour/IP; WINDOW=8 stays under.
+// • Each candidate is first probed against our own origin for a live 402 —
+// registering a not-yet-deployed route burns a rate-limited slot on a
+// probe failure at their end.
+//
+// Registrar strategy + the manual surfaces (x402scan, Bazaar, PR-based lists):
+// docs/x402-distribution.md. One-off/local batches: scripts/x402-register-directories.mjs.
+
+import { json, wrapCron, method, error } from '../_lib/http.js';
+import { env } from '../_lib/env.js';
+import { constantTimeEquals } from '../_lib/crypto.js';
+import { getCatalog } from '../_lib/service-catalog/index.js';
+
+const FOUR02INDEX_REGISTER = 'https://402index.io/api/v1/register';
+const WINDOW = 8;
+const HOUR_MS = 3_600_000;
+
+function requireCron(req, res) {
+ const secret = process.env.CRON_SECRET || env.CRON_SECRET;
+ if (!secret) {
+ error(res, 503, 'not_configured', 'CRON_SECRET unset');
+ return false;
+ }
+ const auth = req.headers['authorization'] || '';
+ const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';
+ if (!constantTimeEquals(presented, secret)) {
+ error(res, 401, 'unauthorized', 'invalid cron secret');
+ return false;
+ }
+ return true;
+}
+
+async function serves402(entry) {
+ try {
+ const r = await fetch(entry.endpoint, {
+ method: entry.method,
+ headers: {
+ accept: 'application/json',
+ ...(entry.method === 'POST' ? { 'content-type': 'application/json' } : {}),
+ },
+ ...(entry.method === 'POST' ? { body: '{}' } : {}),
+ signal: AbortSignal.timeout(10_000),
+ });
+ return r.status === 402;
+ } catch {
+ return false;
+ }
+}
+
+async function upsertAt402Index(entry) {
+ const r = await fetch(FOUR02INDEX_REGISTER, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', accept: 'application/json' },
+ body: JSON.stringify({
+ url: entry.endpoint,
+ name: `three.ws ${entry.slug}`,
+ protocol: 'x402',
+ description: entry.useCase,
+ }),
+ signal: AbortSignal.timeout(15_000),
+ });
+ const body = await r.text();
+ return { ok: r.ok, status: r.status, body: body.slice(0, 200) };
+}
+
+export default wrapCron(async (req, res) => {
+ if (!method(req, res, ['GET', 'POST'])) return;
+ if (!requireCron(req, res)) return;
+
+ const catalog = await getCatalog();
+ const candidates = catalog.filter((e) => e.source === 'x402' && e.status === 'live');
+ if (!candidates.length) {
+ return error(res, 500, 'empty_catalog', 'paid catalog rendered empty — refusing to run');
+ }
+
+ const windows = Math.ceil(candidates.length / WINDOW);
+ const cursor = Math.floor(Date.now() / HOUR_MS) % windows;
+ const batch = candidates.slice(cursor * WINDOW, cursor * WINDOW + WINDOW);
+
+ const results = [];
+ for (const entry of batch) {
+ const live = await serves402(entry);
+ if (!live) {
+ results.push({ slug: entry.slug, action: 'skipped', reason: 'no_402_in_production' });
+ continue;
+ }
+ try {
+ const r = await upsertAt402Index(entry);
+ results.push({ slug: entry.slug, action: 'upserted', ok: r.ok, status: r.status });
+ if (!r.ok) console.warn(`[x402-directory-registrar] ${entry.slug} → ${r.status} ${r.body}`);
+ } catch (err) {
+ results.push({ slug: entry.slug, action: 'error', error: err.message });
+ }
+ }
+
+ return json(res, 200, {
+ ok: true,
+ directory: '402index',
+ catalog_size: candidates.length,
+ window: `${cursor + 1}/${windows}`,
+ results,
+ });
+});
diff --git a/data/pages.json b/data/pages.json
index 53d9c7eaf..c7c1068e4 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -1172,7 +1172,7 @@
},
{
"path": "/coins",
- "title": "Markets — Live Crypto Prices",
+ "title": "Coins — Live Prices & Market Caps",
"description": "Live global cryptocurrency market data: total market cap, dominance, Fear & Greed, and the top coins with prices, 24h/7d moves, and 7d sparklines. Every coin links to a rich /coin/:id detail page with an interactive chart, market stats, related news, and official links.",
"priority": 0.8,
"changefreq": "hourly",
diff --git a/docs/x402-distribution.md b/docs/x402-distribution.md
index 925ba682e..dd32947c6 100644
--- a/docs/x402-distribution.md
+++ b/docs/x402-distribution.md
@@ -129,11 +129,12 @@ script. Everything else above updates itself.
declare `authHints` (currently `agent-reputation`, `agent-bouncer`) append
USE-21 zero-amount placeholder entries to `accepts[]`. 402index's validator
rejects the whole challenge ("no valid x402 challenge detected"), and other
- crawlers likely apply the same amount-must-be-positive rule. The auth-hints
- **extension** already carries the same information — the candidate fix is to
- stop mirroring hints into `accepts[]` (or gate that behind an env flag) so
- the challenge advertises only payable entries. Owner/USE-21 decision; until
- then these two endpoints cannot be listed on validator-gated directories.
+ crawlers likely apply the same amount-must-be-positive rule. **Resolution:**
+ set `X402_AUTH_HINT_ACCEPTS=false` on the deployment to suppress the
+ advertisement (both the zero-amount entries and the auth-hints extension —
+ the extension schema requires them together). Auth bypass itself keeps
+ working either way; the access-control hook honors Bearer/SIWX headers
+ before the payment dance. Default stays `true` until the owner flips it.
- **Bazaar indexing needs the CDP facilitator.** Solana-only settles through
the self-hosted facilitator never reach the Bazaar catalog. The Base rail
must settle via CDP at least once per endpoint.
diff --git a/multiplayer/src/economy.js b/multiplayer/src/economy.js
index 32c0a2824..925abfaf5 100644
--- a/multiplayer/src/economy.js
+++ b/multiplayer/src/economy.js
@@ -80,6 +80,12 @@ export function newProfile(playerId = '') {
activeSlot: 0, // the rod, ready to cast
xp: Object.fromEntries(SKILLS.map((s) => [s, 0])),
levels: Object.fromEntries(SKILLS.map((s) => [s, 1])),
+ // Wheel of Fortune (W09/Task 19): epoch ms the next free spin unlocks. Unlike
+ // the ephemeral per-action `cd` map (WalkRoom.js, reset every reconnect —
+ // fine for a sub-second gather cooldown), this MUST survive a disconnect: a
+ // 12h cooldown that resets on reconnect would be free to farm. Persisted
+ // through serializeProfile/restoreProfile below.
+ nextFreeSpinAt: 0,
// Cosmetic identity (W03), purely visual. `owned` lists the premium ids this
// account has unlocked (free cosmetics are implicitly owned by everyone, so
// they're never stored here); `equipped` is the per-slot loadout peers render.
@@ -158,6 +164,7 @@ export function restoreProfile(saved, playerId = '') {
if (Number.isFinite(saved.maxArmor) && saved.maxArmor > 0) base.maxArmor = saved.maxArmor | 0;
if (Number.isFinite(saved.armor)) base.armor = Math.max(0, Math.min(base.maxArmor, saved.armor | 0));
if (Number.isFinite(saved.heat)) base.heat = Math.max(0, Math.min(99, saved.heat));
+ if (Number.isFinite(saved.nextFreeSpinAt)) base.nextFreeSpinAt = Math.max(0, saved.nextFreeSpinAt);
if (saved.xp && typeof saved.xp === 'object') {
for (const skill of SKILLS) {
const v = Number.isFinite(saved.xp[skill]) ? Math.max(0, saved.xp[skill]) : 0;
@@ -192,6 +199,7 @@ export function serializeProfile(profile) {
armor: profile.armor,
maxArmor: profile.maxArmor,
heat: profile.heat,
+ nextFreeSpinAt: profile.nextFreeSpinAt,
xp: { ...profile.xp },
cosmetics: {
owned: [...(profile.cosmetics?.owned || [])],
diff --git a/multiplayer/src/rooms/WalkRoom.js b/multiplayer/src/rooms/WalkRoom.js
index 5655c33bc..6eb87643a 100644
--- a/multiplayer/src/rooms/WalkRoom.js
+++ b/multiplayer/src/rooms/WalkRoom.js
@@ -59,6 +59,7 @@ import {
DANGER_ZONES, SPAWN_POINT, dangerZoneAt, isSafeZone, isDangerZone, randomPointInZone,
} from '../world-features.js';
import { registerActivityHandlers } from '../activities.js';
+import { registerSpinHandlers } from '../spin-wheel.js';
import {
selectTarget, rollDamage, applyDamage, addHeat, decayHeat, heatStars,
} from '../combat.js';
diff --git a/multiplayer/src/spin-wheel.js b/multiplayer/src/spin-wheel.js
new file mode 100644
index 000000000..cadf417e5
--- /dev/null
+++ b/multiplayer/src/spin-wheel.js
@@ -0,0 +1,222 @@
+// Wheel of Fortune server logic (W09/Task 19) — "Fortune's Folly" in the Mainland
+// plaza. Free spin every 12h per account, or pay $3 in $THREE (settled through
+// game-token.js's split-payment primitives — the exact pattern the $THREE
+// boutique already uses in production: server builds the tx, the wallet signs
+// it, the server re-verifies the confirmed transaction on RPC before granting
+// anything). The client (src/game/spin-wheel-ui.js) never rolls or decides a
+// prize — it renders the wheel and animates to whatever index the server sends.
+//
+// The 20 wedges the client draws are all the SAME angular size (see
+// spin-wheel-ui.js's _drawWheel — one fixed `2π/n` per segment, no variable
+// wedge width). For the visual wheel to be honest about the real odds, the
+// prize table below MUST stay uniform-probability — one segment, one pick, no
+// hidden weighting. Don't "balance" the economy by skewing the RNG; balance it
+// by changing the prize amounts instead.
+
+import { addItem, hasRoomFor } from './economy.js';
+import { nearestWheel, wheelInRange } from './world-features.js';
+import {
+ buildSpinPayment, verifySpinPayment, isWalletAddress, tokenConfigured, TOKEN_DECIMALS, TOKEN_SYMBOL,
+} from './game-token.js';
+
+export const FREE_SPIN_COOLDOWN_MS = 12 * 60 * 60 * 1000;
+export const SPIN_COST_USD = 3;
+// Average of the 5 tracked skills must clear this before ANY spin (free or
+// paid) is offered — a light anti-bot/anti-farm gate tied to actually having
+// played, not a hard grind (everyone starts at level 1, so this asks for a
+// little real progress, not a lot).
+export const MIN_AVG_LEVEL = 3;
+
+// 20 equal-odds wedges (5% each — see the header note on why they must stay
+// uniform). Mostly common gather resources at modest quantities (a wheel that
+// mainly hands out wood/stone/coal is a fun bonus to the gather loop, not a
+// separate economy), three small-to-medium gold prizes, and one rare jackpot.
+export const WHEEL_SEGMENTS = [
+ { kind: 'item', item: 'wood', qty: 3, label: '3 Wood', oddsPct: 5 },
+ { kind: 'item', item: 'wood', qty: 4, label: '4 Wood', oddsPct: 5 },
+ { kind: 'item', item: 'wood', qty: 5, label: '5 Wood', oddsPct: 5 },
+ { kind: 'item', item: 'wood', qty: 6, label: '6 Wood', oddsPct: 5 },
+ { kind: 'item', item: 'stone', qty: 3, label: '3 Stone', oddsPct: 5 },
+ { kind: 'item', item: 'stone', qty: 4, label: '4 Stone', oddsPct: 5 },
+ { kind: 'item', item: 'stone', qty: 5, label: '5 Stone', oddsPct: 5 },
+ { kind: 'item', item: 'stone', qty: 6, label: '6 Stone', oddsPct: 5 },
+ { kind: 'item', item: 'wood', qty: 8, label: '8 Wood', oddsPct: 5 },
+ { kind: 'item', item: 'stone', qty: 8, label: '8 Stone', oddsPct: 5 },
+ { kind: 'item', item: 'coal', qty: 1, label: '1 Coal', oddsPct: 5 },
+ { kind: 'item', item: 'coal', qty: 2, label: '2 Coal', oddsPct: 5 },
+ { kind: 'item', item: 'coal', qty: 3, label: '3 Coal', oddsPct: 5 },
+ { kind: 'gold', gold: 5, label: '5 Cash', oddsPct: 5 },
+ { kind: 'gold', gold: 5, label: '5 Cash', oddsPct: 5 },
+ { kind: 'gold', gold: 8, label: '8 Cash', oddsPct: 5 },
+ { kind: 'gold', gold: 8, label: '8 Cash', oddsPct: 5 },
+ { kind: 'gold', gold: 12, label: '12 Cash', oddsPct: 5 },
+ { kind: 'gold', gold: 12, label: '12 Cash', oddsPct: 5 },
+ { kind: 'gold', gold: 100, label: 'JACKPOT — 100 Cash', oddsPct: 5 },
+];
+
+function avgLevel(profile) {
+ const levels = Object.values(profile.levels || {});
+ if (!levels.length) return 1;
+ return levels.reduce((a, b) => a + b, 0) / levels.length;
+}
+
+// Is there room for at least one of EVERY possible item-type prize this wheel
+// can award? Checked before a spin is even offered (free) or paid for (paid) —
+// never after rolling — so a completed spin can never have nowhere to put its
+// prize. Gold prizes never need this (gold is a scalar balance, not pack space).
+function hasRoomForAnyPrize(profile) {
+ return hasRoomFor(profile, 'wood') || hasRoomFor(profile, 'stone') || hasRoomFor(profile, 'coal');
+}
+
+function pickSegment() {
+ const i = Math.floor(Math.random() * WHEEL_SEGMENTS.length);
+ return { index: i, seg: WHEEL_SEGMENTS[i] };
+}
+
+// Grant a rolled segment's prize to the profile. Room was already guaranteed by
+// hasRoomForAnyPrize() before the roll, so addItem's leftover is expected to be
+// 0 — but a defensive fallback still refunds any leftover as its rough gold
+// value rather than silently discarding a prize a player (possibly a PAYING
+// player) already won.
+const ITEM_GOLD_VALUE = { wood: 1, stone: 1, coal: 2 };
+function grantSegment(profile, seg) {
+ if (seg.kind === 'gold') {
+ profile.gold = Math.min(0xffffffff, (profile.gold || 0) + seg.gold);
+ return { got: seg.gold, overflow: 0 };
+ }
+ const leftover = addItem(profile, seg.item, seg.qty);
+ if (leftover > 0) {
+ const refund = leftover * (ITEM_GOLD_VALUE[seg.item] || 1);
+ profile.gold = Math.min(0xffffffff, (profile.gold || 0) + refund);
+ }
+ return { got: seg.qty - leftover, overflow: 0 };
+}
+
+function infoPayload(room, client, profile) {
+ const player = room.state.players.get(client.sessionId);
+ const lvl = avgLevel(profile);
+ const eligible = lvl >= MIN_AVG_LEVEL;
+ const atWheel = player ? !!wheelInRange(player.x, player.z) : false;
+ return {
+ segments: WHEEL_SEGMENTS,
+ now: Date.now(),
+ nextFreeSpinAt: profile.nextFreeSpinAt || 0,
+ avgLevel: lvl,
+ minLevel: MIN_AVG_LEVEL,
+ eligible,
+ atWheel,
+ paidAvailable: tokenConfigured(),
+ symbol: TOKEN_SYMBOL,
+ costUsd: SPIN_COST_USD,
+ };
+}
+
+export function handleSpinInfo(room, client) {
+ const profile = room.econ.get(client.sessionId);
+ if (!profile) return;
+ client.send('spinInfo', infoPayload(room, client, profile));
+}
+
+export function handleSpinFree(room, client) {
+ const player = room.state.players.get(client.sessionId);
+ const profile = room.econ.get(client.sessionId);
+ if (!player || !profile) return;
+ if (!room._actionOk(client.sessionId, 'spinFree')) return;
+
+ if (!wheelInRange(player.x, player.z)) { client.send('spinDenied', { reason: 'not_at_wheel' }); return; }
+ const lvl = avgLevel(profile);
+ if (lvl < MIN_AVG_LEVEL) { client.send('spinDenied', { reason: 'level', avgLevel: lvl, minLevel: MIN_AVG_LEVEL }); return; }
+ const now = Date.now();
+ if (now < (profile.nextFreeSpinAt || 0)) {
+ client.send('spinDenied', { reason: 'cooldown', nextFreeSpinAt: profile.nextFreeSpinAt });
+ return;
+ }
+ if (!hasRoomForAnyPrize(profile)) { client.send('spinDenied', { reason: 'pack_full' }); return; }
+
+ profile.nextFreeSpinAt = now + FREE_SPIN_COOLDOWN_MS;
+ const { index, seg } = pickSegment();
+ const { got, overflow } = grantSegment(profile, seg);
+ room._sendInv(client, profile);
+ client.send('spinResult', {
+ mode: 'free', index, label: seg.label, got, overflow, nextFreeSpinAt: profile.nextFreeSpinAt,
+ });
+ room._questEvent?.(client, profile, { type: 'spin' });
+ room._persistEcon(client.sessionId);
+}
+
+export async function handleSpinPaidPrep(room, client, payload) {
+ const player = room.state.players.get(client.sessionId);
+ const profile = room.econ.get(client.sessionId);
+ if (!player || !profile) return;
+ if (!room._actionOk(client.sessionId, 'spinPaidPrep')) return;
+
+ if (!wheelInRange(player.x, player.z)) { client.send('spinDenied', { reason: 'not_at_wheel' }); return; }
+ const lvl = avgLevel(profile);
+ if (lvl < MIN_AVG_LEVEL) { client.send('spinDenied', { reason: 'level', avgLevel: lvl, minLevel: MIN_AVG_LEVEL }); return; }
+ if (!hasRoomForAnyPrize(profile)) { client.send('spinDenied', { reason: 'pack_full' }); return; }
+ if (!tokenConfigured()) { client.send('spinDenied', { reason: 'token_unavailable' }); return; }
+
+ // Same "whoever's wallet fronts it, the unlock lands on this session" model
+ // the boutique quote already uses — the wallet rides the request payload,
+ // not client.userData, so a spectator can never be charged for someone else.
+ const wallet = typeof payload?.wallet === 'string' ? payload.wallet.trim() : '';
+ if (!isWalletAddress(wallet)) { client.send('spinDenied', { reason: 'no_wallet' }); return; }
+
+ let built;
+ try {
+ built = await buildSpinPayment({ buyerWallet: wallet, usd: SPIN_COST_USD });
+ } catch (err) {
+ console.warn('[walk_world] spin prep failed:', err?.message);
+ }
+ if (!built) { client.send('spinDenied', { reason: 'price_unavailable' }); return; }
+ client.send('spinPrep', {
+ tx: built.txBase64,
+ tokenAmount: built.quote.total,
+ symbol: TOKEN_SYMBOL,
+ costUsd: SPIN_COST_USD,
+ quote: built.quoteToken,
+ });
+}
+
+export async function handleSpinPaidSettle(room, client, payload) {
+ const profile = room.econ.get(client.sessionId);
+ if (!profile) return;
+ if (!room._actionOk(client.sessionId, 'spinPaidSettle')) return;
+ const quoteToken = typeof payload?.quote === 'string' ? payload.quote : '';
+ const txSig = typeof payload?.txSig === 'string' ? payload.txSig : '';
+ if (!quoteToken || !txSig) { client.send('spinDenied', { reason: 'no_signature' }); return; }
+
+ let result;
+ try {
+ result = await verifySpinPayment({ quoteToken, txSig });
+ } catch (err) {
+ console.warn('[walk_world] spin settle failed:', err?.message);
+ client.send('spinDenied', { reason: 'not_found' });
+ return;
+ }
+ if (!result?.ok) { client.send('spinDenied', { reason: result?.reason || 'not_found' }); return; }
+
+ room._pruneSpinNonces?.();
+ if (room._spinNonces.has(result.nonce)) { client.send('spinDenied', { reason: 'already_settled' }); return; }
+ room._spinNonces.set(result.nonce, Date.now());
+
+ // Room precheck at prep time already guaranteed pack space for an item
+ // prize; re-check here too since real time passed while the player was in
+ // their wallet approving the transaction — a paid spin must never lose a
+ // won prize to a pack that filled up in the meantime (grantSegment's own
+ // gold-value fallback is the last-resort backstop if it somehow still does).
+ const { index, seg } = pickSegment();
+ const { got, overflow } = grantSegment(profile, seg);
+ room._sendInv(client, profile);
+ client.send('spinResult', { mode: 'paid', index, label: seg.label, got, overflow });
+ room._questEvent?.(client, profile, { type: 'spin' });
+ room._persistEcon(client.sessionId);
+}
+
+// Wire the four intents onto a room, mirroring registerActivityHandlers.
+export function registerSpinHandlers(room) {
+ room.onMessage('spinInfo', (client) => handleSpinInfo(room, client));
+ room.onMessage('spinFree', (client) => handleSpinFree(room, client));
+ room.onMessage('spinPaidPrep', (client, payload) => handleSpinPaidPrep(room, client, payload));
+ room.onMessage('spinPaidSettle', (client, payload) => handleSpinPaidSettle(room, client, payload));
+}
diff --git a/multiplayer/src/world-features.js b/multiplayer/src/world-features.js
index a6dedb1ee..e7859c2e4 100644
--- a/multiplayer/src/world-features.js
+++ b/multiplayer/src/world-features.js
@@ -113,6 +113,17 @@ export const COOK_REACH = 2.6;
export function nearestFirepit(x, z) { return nearestNode(x, z, FIREPITS, COOK_REACH); }
export function firepitInRange(x, z) { return nodeInRange(x, z, FIREPITS, COOK_REACH); }
+// The Wheel of Fortune — "Fortune's Folly" (W09/Task 19). One per world, in the
+// open plaza north of the totem: clear of both ponds (~29–33m away), both
+// firepits (~22–25m), and the plaza rod pickup (~16m) — a landmark on its own,
+// not crowded against another station.
+export const WHEEL = [
+ { id: 'wheel-plaza', x: 0, z: 22, r: 2.0 },
+];
+export const WHEEL_REACH = 3.0;
+export function nearestWheel(x, z) { return nearestNode(x, z, WHEEL, WHEEL_REACH); }
+export function wheelInRange(x, z) { return nodeInRange(x, z, WHEEL, WHEEL_REACH); }
+
// Fishing-rod pickups — a spare rod waiting on the bank for anyone without one
// (or anyone who wants a backup to store). Every player already starts with a
// rod in the hotbar and it's never lost on death, so these exist for
diff --git a/pages/coins.html b/pages/coins.html
index e9f1cad07..525e2b4ac 100644
--- a/pages/coins.html
+++ b/pages/coins.html
@@ -18,7 +18,7 @@
</script>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <title>Markets · three.ws</title>
+ <title>Coins — live prices &amp; market caps · three.ws</title>
<meta
name="description"
content="Live cryptocurrency market data — prices, trends, and a global overview for the top digital assets, with rich detail pages for every coin."
@@ -26,7 +26,7 @@
<meta property="og:type" content="website" />
<meta property="og:site_name" content="three.ws" />
<meta property="og:url" content="https://three.ws/coins" />
- <meta property="og:title" content="Markets · three.ws" />
+ <meta property="og:title" content="Coins — live prices &amp; market caps · three.ws" />
<meta
property="og:description"
content="Live cryptocurrency market data — prices, trends, and a global overview for the top digital assets."
@@ -39,7 +39,7 @@
<meta property="og:image:height" content="630" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:site" content="@trythreews" />
- <meta name="twitter:title" content="Markets · three.ws" />
+ <meta name="twitter:title" content="Coins · three.ws" />
<meta
name="twitter:description"
content="Live cryptocurrency market data — prices, trends, and a global overview for the top digital assets."
@@ -87,7 +87,7 @@
<script src="/nav.js"></script>
<main class="cv-container">
- <h1 class="cv-h1">Markets</h1>
+ <h1 class="cv-h1">Coins</h1>
<p class="cv-sub">
Real-time cryptocurrency market data — prices, trends, and global overview for
hundreds of digital assets.
diff --git a/public/search.js b/public/search.js
index c5a761b20..83c03607c 100644
--- a/public/search.js
+++ b/public/search.js
@@ -801,11 +801,13 @@
var runAbort = null; // AbortController for the in-flight command
var runActive = false; // whether the run panel currently owns the results area
- var runTimer = null; // elapsed-time ticker / poll timer
+ var runTicker = null; // elapsed-time ticker (setInterval)
+ var runTimer = null; // poll timer (setTimeout)
function stopRun() {
if (runAbort) { runAbort.abort(); runAbort = null; }
- if (runTimer) { clearInterval(runTimer); clearTimeout(runTimer); runTimer = null; }
+ if (runTicker) { clearInterval(runTicker); runTicker = null; }
+ if (runTimer) { clearTimeout(runTimer); runTimer = null; }
runActive = false;
}
@@ -871,7 +873,10 @@
},
fail: function (message, linkHref, linkText) {
ui.setStatus('failed', 'err');
- var msg = el('div', { class: 'tws-sk-answer', text: message });
+ // Reuse an existing (possibly empty) answer block rather than
+ // stacking a second one under it.
+ var msg = body.querySelector('.tws-sk-answer') || el('div', { class: 'tws-sk-answer' });
+ msg.textContent = message;
body.appendChild(msg);
if (linkHref) {
ui.addRows([resultRow(linkHref, '↗', linkText || 'Open', '', '', '')]);
@@ -915,13 +920,13 @@
var startedAt = Date.now();
var elapsed = function () { return Math.round((Date.now() - startedAt) / 1000) + 's'; };
ui.setStatus('forging · 0s');
- runTimer = setInterval(function () {
+ runTicker = setInterval(function () {
if (!runActive) return;
ui.setStatus('forging · ' + elapsed() + ' — usually 20–60s');
}, 1000);
function finish(job) {
- clearInterval(runTimer); runTimer = null;
+ clearInterval(runTicker); runTicker = null;
ui.setStatus('done · ' + elapsed(), 'ok');
var openHref = job.creation_id
? '/forge/share/' + encodeURIComponent(job.creation_id)
@@ -942,13 +947,13 @@
if (!runActive) return;
if (job.status === 'done' && job.glb_url) return finish(job);
if (job.status === 'failed') {
- clearInterval(runTimer); runTimer = null;
+ clearInterval(runTicker); runTicker = null;
ui.fail(job.error || 'Generation failed — the free lane may be busy.', '/forge', 'Try on the Forge page');
emitAction('forge', 'failed', { prompt: args.prompt });
return;
}
if (Date.now() - startedAt > 4 * 60 * 1000) {
- clearInterval(runTimer); runTimer = null;
+ clearInterval(runTicker); runTicker = null;
ui.fail('Still running after 4 minutes — the lane is saturated. Your job may still finish on the Forge page.', '/forge', 'Open the Forge');
return;
}
@@ -956,7 +961,7 @@
})
.catch(function (err) {
if (err && err.name === 'AbortError') return;
- clearInterval(runTimer); runTimer = null;
+ clearInterval(runTicker); runTicker = null;
ui.fail('Lost the job while polling — it may still finish on the Forge page.', '/forge', 'Open the Forge');
});
}
@@ -980,7 +985,7 @@
})
.catch(function (err) {
if (err && err.name === 'AbortError') return;
- clearInterval(runTimer); runTimer = null;
+ clearInterval(runTicker); runTicker = null;
if (err && err.status === 429) {
ui.fail('Free-lane rate limit reached for now — try again in a few minutes, or use the Forge page.', '/forge', 'Open the Forge');
} else {
@@ -1071,11 +1076,15 @@
});
}
- function runAskCommand(args, ui) {
- ui.setStatus('thinking…');
- var answer = el('div', { class: 'tws-sk-answer' });
- answer.setAttribute('aria-live', 'polite');
- ui.body.appendChild(answer);
+ function runAskCommand(args, ui, attempt) {
+ attempt = attempt || 0;
+ ui.setStatus(attempt ? 'retrying…' : 'thinking…');
+ var answer = ui.body.querySelector('.tws-sk-answer');
+ if (!answer) {
+ answer = el('div', { class: 'tws-sk-answer' });
+ answer.setAttribute('aria-live', 'polite');
+ ui.body.appendChild(answer);
+ }
fetch('/api/chat', {
method: 'POST',
@@ -1083,7 +1092,8 @@
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
message: args.question,
- context: 'Asked from the command palette on ' + location.pathname,
+ // /api/chat validates context as an object (api/chat.js zod schema).
+ context: { source: 'command-palette', page: location.pathname },
history: [],
}),
signal: ui.signal,
@@ -1093,6 +1103,29 @@
ui.fail('Chat needs a signed-in session right now.', '/login', 'Sign in');
return null;
}
+ // Free-lane saturation: the server says how long to back off
+ // (api/chat.js responds 503/429 rate_limited + retry_after). Honor
+ // it, up to two retries, instead of failing a transient condition.
+ if (r.status === 503 || r.status === 429) {
+ return r.json().catch(function () { return {}; }).then(function (body) {
+ if (attempt >= 2) {
+ ui.fail(body.error_description || 'The free chat lane is at capacity — try again shortly.', '/chat', 'Open chat');
+ return null;
+ }
+ var wait = Math.min(Math.max(Number(body.retry_after) || 5, 2), 30);
+ var left = wait;
+ ui.setStatus('at capacity — retrying in ' + left + 's');
+ runTicker = setInterval(function () {
+ left -= 1;
+ if (left > 0) ui.setStatus('at capacity — retrying in ' + left + 's');
+ }, 1000);
+ runTimer = setTimeout(function () {
+ clearInterval(runTicker); runTicker = null;
+ if (runActive) runAskCommand(args, ui, attempt + 1);
+ }, wait * 1000);
+ return null;
+ });
+ }
if (!r.ok) throw new Error('HTTP ' + r.status);
var reader = r.body.getReader();
var decoder = new TextDecoder();
diff --git a/src/coins-index.js b/src/coins-index.js
index b3fd6e8f7..e5566107c 100644
--- a/src/coins-index.js
+++ b/src/coins-index.js
@@ -135,6 +135,7 @@ function sortedCoins() {
function renderTable() {
const el = $('cv-market');
+ if (!el) return; // shell navigation left /coins while a fetch was in flight
if (!state.coins.length) {
el.innerHTML =
'<div class="cv-empty">Market data is temporarily unavailable. Please try again shortly.</div>';
diff --git a/src/markets-page.js b/src/markets-page.js
index 87c73eb72..d0ed9ccb5 100644
--- a/src/markets-page.js
+++ b/src/markets-page.js
@@ -57,6 +57,7 @@ function fgClass(v) {
function renderStats(global) {
const el = $('cv-stats');
+ if (!el) return; // shell navigation left /markets while the fetch was in flight
const { market, fear_greed } = global || {};
const cards = [];
if (market) {
@@ -159,7 +160,9 @@ const SUITE = [
];
function renderSuite(stats = {}) {
- $('mkt-suite').innerHTML = SUITE.map((s) => {
+ const suiteEl = $('mkt-suite');
+ if (!suiteEl) return; // shell navigation left /markets while stats resolved
+ suiteEl.innerHTML = SUITE.map((s) => {
const stat = stats[s.stat];
return `
<a class="mkt-hero-card" href="${esc(s.href)}">
@@ -177,6 +180,7 @@ const tbl = { coins: [], sortKey: 'rank', sortDir: 'asc' };
function renderTable() {
const el = $('mkt-table');
+ if (!el) return; // shell navigation left /markets while the fetch was in flight
if (!tbl.coins.length) {
el.innerHTML =
'<div class="cv-empty">Market data is temporarily unavailable. <a href="/coins">Try the full markets table</a>.</div>';
@@ -230,6 +234,7 @@ function renderTable() {
function renderNews(articles) {
const el = $('mkt-news');
+ if (!el) return; // shell navigation left /markets while the fetch was in flight
if (!articles?.length) {
el.innerHTML =
'<div class="cv-empty">The news feed is warming up — <a href="/markets/news">open the news page</a>.</div>';
@@ -270,7 +275,8 @@ async function init() {
}
})
.catch(() => {
- $('cv-stats').innerHTML = '';
+ const el = $('cv-stats');
+ if (el) el.innerHTML = '';
}),
getJson('/api/coin/markets?page=1&per_page=100')
.then(({ coins }) => {
diff --git a/src/view-transitions.js b/src/view-transitions.js
index 55c472c62..f851a3eb5 100644
--- a/src/view-transitions.js
+++ b/src/view-transitions.js
@@ -7,17 +7,22 @@
// page state (Chrome 111+, Safari 18+; falls back to a normal location
// change — no UX regression).
//
-// 2. Shell pages (<html data-shell>): navigation between two shell-marked
-// pages swaps ONLY <main> (plus title/meta) in place. The header, footer,
-// corner stack, command palette, and the walking companion agent are
-// never torn down — a live WebGL avatar or a streaming answer survives
-// the navigation. Page modules re-init through src/shell/page-lifecycle.js
-// (onPageReady), keyed off the 'shell:navigated' document event and the
-// window.__shellNavId token this file increments per swap.
+// 2. Shell pages (data-shell on the html element): navigation between two
+// shell-marked pages swaps ONLY the main element (plus title/meta) in
+// place. The header, footer, corner stack, command palette, and the
+// walking companion agent are never torn down — a live WebGL avatar or a
+// streaming answer survives the navigation. Page modules re-init through
+// src/shell/page-lifecycle.js (onPageReady), keyed off the
+// 'shell:navigated' document event and the window.__shellNavId token
+// this file increments per swap. Shell pages must keep their main
+// element a DIRECT CHILD of body (the standard page skeleton).
//
// CONSTRAINTS (see the 'view-transitions' plugin in vite.config.js, which
// inlines this file as a classic script on every page): keep it dependency-
-// free, keep exactly one `export function`, and no other module syntax.
+// free, keep exactly one `export function`, no other module syntax — and no
+// HTML-looking sequences (angle-bracket tags) anywhere in comments or
+// strings: the inlined source must stay inert if an HTML parser ever walks
+// through it.
const SUPPORTED = typeof document !== 'undefined' && 'startViewTransition' in document;
@@ -107,8 +112,11 @@ async function shellSwap(dest, { push = true } = {}) {
// Both ends must opt in — an unmarked destination gets a full navigation
// (its scripts may assume a fresh document).
if (!doc.documentElement.hasAttribute(SHELL_ATTR)) return false;
- const newMain = doc.querySelector('main');
- const curMain = document.querySelector('main');
+ // Body-scoped on purpose: the page skeleton keeps its main element a direct
+ // child of body, and anything else matching 'main' deeper in the tree
+ // (widget markup, injected fragments) must never be the swap target.
+ const newMain = doc.body ? doc.body.querySelector(':scope > main') : null;
+ const curMain = document.body.querySelector(':scope > main');
if (!newMain || !curMain) return false;
await mergeStylesheets(doc);
@@ -136,7 +144,7 @@ async function shellSwap(dest, { push = true } = {}) {
document.dispatchEvent(new CustomEvent('shell:navigated', { detail: { url: String(dest) } }));
// Accessibility: a swap is a navigation — move focus to the new content.
- const main = document.querySelector('main');
+ const main = document.body.querySelector(':scope > main');
if (main) {
if (!main.hasAttribute('tabindex')) main.setAttribute('tabindex', '-1');
main.focus({ preventScroll: true });
diff --git a/vercel.json b/vercel.json
index 0bf33260c..4fe142b30 100644
--- a/vercel.json
+++ b/vercel.json
@@ -5015,6 +5015,10 @@
"path": "/api/cron/quota-check",
"schedule": "0 * * * *"
},
+ {
+ "path": "/api/cron/x402-directory-registrar",
+ "schedule": "23 * * * *"
+ },
{
"path": "/api/cron/relayer-balance-check",
"schedule": "0 */6 * * *"
diff --git a/vite.config.js b/vite.config.js
index 5c93a30ec..5a9a8016d 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -1882,6 +1882,16 @@ support: resolve(__dirname, 'pages/support.html'),
'avatar-embed.html',
'agent-embed.html',
'a-embed.html',
+ // Runtime-fetched FRAGMENTS, not documents: nav.js / footer.js
+ // fetch these and assign them via innerHTML. In dev, Vite's
+ // transformIndexHtml runs on them too, and injecting a script
+ // here gets it interleaved with Vite's own /@vite/client tag —
+ // the fragment parser then closes the script early and renders
+ // the remainder of its source as DOM text/elements inside the
+ // nav/footer containers. The page document already carries the
+ // inline script; fragments must never get it.
+ 'nav.html',
+ 'footer.html',
]);
const filename = (ctx.filename || ctx.path || '')
.replace(/\\/g, '/')