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: cosmetics earnings/leaderboard/split APIs, flex, live feed stream + community/walk updates

nirholas21377776bb96
diff --git a/api/_lib/feed.js b/api/_lib/feed.js
index 56cfe3cf5..f2c21e396 100644
--- a/api/_lib/feed.js
+++ b/api/_lib/feed.js
@@ -146,6 +146,42 @@ export function pushPaymentEvent({ actor, usdcAtomic, recipientLabel, txSig, exp
});
}
+// Per-user throttle window for member-join events. A returning user signs in
+// often; we only want one "joined" line per person per window so the feed shows
+// real arrivals without spamming on every login or popup re-auth.
+const MEMBER_JOIN_TTL_S = 6 * 60 * 60; // 6h
+
+/**
+ * Publish a 'member-join' feed event when someone signs in, throttled to once
+ * per `userKey` per MEMBER_JOIN_TTL_S so re-logins don't spam the ticker.
+ * Best-effort and fire-and-forget — never throws, returns the stored record or
+ * null (throttled / Redis down / no display name).
+ *
+ * @param {object} opts
+ * @param {string} opts.userKey stable per-user key for throttling (id or handle)
+ * @param {string} opts.actor short public display name ("alice")
+ * @param {string} [opts.handle] X/social handle without '@', for click-through
+ */
+export async function publishMemberJoin({ userKey, actor, handle } = {}) {
+ const r = redis();
+ const name = String(actor || '').trim().slice(0, 32);
+ if (!r || !name) return null;
+ const key = String(userKey || handle || name).slice(0, 80);
+ try {
+ // SET NX EX: claims the window atomically; null reply means already seen.
+ const claimed = await r.set(`feed:joined:${key}`, '1', { nx: true, ex: MEMBER_JOIN_TTL_S });
+ if (!claimed) return null;
+ } catch (err) {
+ console.warn('[feed] member-join throttle check failed:', err?.message);
+ return null;
+ }
+ return publishFeedEvent({
+ type: 'member-join',
+ actor: name,
+ handle: handle ? String(handle).replace(/^@/, '').slice(0, 40) : undefined,
+ });
+}
+
// Short-lived in-process read cache. The widget is mounted on every page and
// polls this endpoint continuously, so without dedup each poll becomes a Redis
// command — at platform scale that alone can exhaust the Upstash request quota.
diff --git a/api/community/auth/callback.js b/api/community/auth/callback.js
index 98c7eca14..3d9344734 100644
--- a/api/community/auth/callback.js
+++ b/api/community/auth/callback.js
@@ -7,6 +7,18 @@
import { text, wrap } from '../../_lib/http.js';
import { env } from '../../_lib/env.js';
import { cc, setUserSession, UnconfiguredError } from '../../_lib/coin-communities.js';
+import { publishMemberJoin } from '../../_lib/feed.js';
+
+// Surface a signed-in user in the live ticker. Fire-and-forget on a non-critical
+// path: the throttle in publishMemberJoin keeps re-logins from spamming, and any
+// failure (no display name, Redis down) degrades silently to no event.
+function announceSignIn(user) {
+ if (!user) return;
+ const actor = user.username || user.handle || user.displayName || user.name || null;
+ if (!actor) return;
+ const handle = user.username || user.handle || null;
+ publishMemberJoin({ userKey: user.id || user.userId || actor, actor, handle }).catch(() => {});
+}
function page({ ok, user = null, message = '' }) {
// The opener verifies event.origin === APP_ORIGIN before trusting this.
@@ -55,6 +67,7 @@ export default wrap(async (req, res) => {
throw new Error('missing challenge code');
}
setUserSession(res, session);
+ announceSignIn(session.user);
return text(res, 200, page({ ok: true, user: session.user }), {
'content-type': 'text/html; charset=utf-8',
});
diff --git a/api/cosmetics/earnings.js b/api/cosmetics/earnings.js
new file mode 100644
index 000000000..c8304c1f4
--- /dev/null
+++ b/api/cosmetics/earnings.js
@@ -0,0 +1,45 @@
+// GET /api/cosmetics/earnings?creator=<solanaWallet>
+//
+// Real, settled cosmetic creator earnings (R25) for a creator wallet: lifetime +
+// 30-day totals, paid vs. pending, per-coin and per-cosmetic breakdowns, and recent
+// sales. Reads the settled-sale ledger — never estimated. Powers the creator
+// earnings view in the dashboard. Public read keyed on the wallet (the numbers are
+// derived from public on-chain settlements); no secrets are exposed.
+
+import { cors, json, method, wrap, error } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { creatorEarnings, isWallet } from '../_lib/cosmetics-economy.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const url = new URL(req.url, 'http://x');
+ const creator = String(url.searchParams.get('creator') || '').trim();
+ if (!isWallet(creator)) {
+ return error(res, 400, 'creator_required', 'query parameter "creator" must be a Solana wallet address');
+ }
+
+ let earnings;
+ try {
+ earnings = await creatorEarnings(creator);
+ } catch (err) {
+ console.warn('[cosmetics/earnings] read failed:', err?.message);
+ earnings = null;
+ }
+ // A creator with no sales yet → zeroed totals, not a 404, so the dashboard
+ // renders the designed empty state.
+ if (!earnings) {
+ earnings = {
+ creatorWallet: creator,
+ currency: 'USDC',
+ totals: { sales: 0, buyers: 0, earnedUsdc: 0, paidUsdc: 0, pendingUsdc: 0, earned30dUsdc: 0, grossUsdc: 0, firstSaleAt: null, lastSaleAt: null },
+ perCoin: [], perCosmetic: [], recent: [],
+ };
+ }
+
+ return json(res, 200, earnings, { 'cache-control': 'no-store' });
+});
diff --git a/api/cosmetics/leaderboard.js b/api/cosmetics/leaderboard.js
new file mode 100644
index 000000000..b15370396
--- /dev/null
+++ b/api/cosmetics/leaderboard.js
@@ -0,0 +1,36 @@
+// GET /api/cosmetics/leaderboard?limit=<n>
+//
+// The platform-wide cosmetics flex surface (R25): rarest fits (premium cosmetics
+// ranked by on-chain scarcity), top collectors (rarity-weighted flex score), top
+// creators (real settled cosmetic earnings in USDC), and the latest sales. Every
+// number is read straight from the settled-sale ledger — nothing simulated. Public
+// + briefly cached so the /play flex panel and any embed can poll it cheaply.
+
+import { cors, json, method, wrap, error } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { cosmeticsLeaderboard } from '../_lib/cosmetics-economy.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const url = new URL(req.url, 'http://x');
+ const limit = Math.max(1, Math.min(50, Number(url.searchParams.get('limit')) || 12));
+
+ let board;
+ try {
+ board = await cosmeticsLeaderboard({ limit });
+ } catch (err) {
+ // No DB / cold table → an honest empty board, not a 500. The flex surface
+ // renders its empty state ("be the first to flex a rare fit").
+ console.warn('[cosmetics/leaderboard] read failed:', err?.message);
+ board = { currency: 'USDC', rarestFits: [], topCollectors: [], topCreators: [], recent: [] };
+ }
+
+ return json(res, 200, board, {
+ 'cache-control': 'public, max-age=15, s-maxage=30, stale-while-revalidate=60',
+ });
+});
diff --git a/api/cosmetics/split.js b/api/cosmetics/split.js
new file mode 100644
index 000000000..1d8bca218
--- /dev/null
+++ b/api/cosmetics/split.js
@@ -0,0 +1,69 @@
+// /api/cosmetics/split — per-coin cosmetic revenue-split config (R25).
+//
+// GET ?mint=<mint> → the coin's effective split config (creator wallet +
+// share). Public: the share that applies to a sale is not
+// a secret, and the shop shows it on the buy button.
+// POST { mint, bps, ts, signature, signer }
+// → set the coin's creator share. Authorized by an ed25519
+// signature from the coin's creator wallet over
+// splitConfigMessage() (verified server-side). Clamped to
+// the platform ceiling. Returns the new effective config.
+//
+// The creator never sets where the money goes — the creator wallet is resolved
+// from launch records / on-chain — only HOW MUCH of each sale they take, up to the
+// cap. So a config write can't redirect another coin's revenue.
+
+import { cors, json, method, wrap, error, readJson } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { getSplitConfig, setSplitConfig, splitConfigMessage, isMint, MAX_CREATOR_BPS } from '../_lib/cosmetics-economy.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: '*', credentials: true })) return;
+
+ if (req.method === 'GET') {
+ if (!method(req, res, ['GET'])) return;
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const url = new URL(req.url, 'http://x');
+ const mint = String(url.searchParams.get('mint') || '').trim();
+ if (!isMint(mint)) return error(res, 400, 'bad_mint', 'query parameter "mint" must be a coin mint');
+ let config;
+ try {
+ config = await getSplitConfig(mint);
+ } catch (err) {
+ console.warn('[cosmetics/split] config read failed:', err?.message);
+ // Fail open to the platform default so the shop can still price the sale.
+ config = { mint, creatorWallet: null, splitBps: 0, source: 'none', isDefault: true, updatedAt: null, maxBps: MAX_CREATOR_BPS };
+ }
+ // The message the creator must sign to change it — handed to the client so it
+ // can build the exact signing payload without guessing the format.
+ const ts = Math.floor(Date.now() / 1000);
+ return json(res, 200, {
+ ...config,
+ signTemplate: { ts, message: splitConfigMessage({ mint, bps: config.splitBps, ts }) },
+ }, { 'cache-control': 'no-store' });
+ }
+
+ if (!method(req, res, ['POST'])) return;
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests — slow down');
+
+ let body;
+ try { body = await readJson(req); } catch { return error(res, 400, 'bad_json', 'invalid request body'); }
+
+ try {
+ const config = await setSplitConfig({
+ mint: String(body?.mint || ''),
+ bps: body?.bps,
+ ts: body?.ts,
+ signature: String(body?.signature || ''),
+ signer: String(body?.signer || ''),
+ });
+ return json(res, 200, config, { 'cache-control': 'no-store' });
+ } catch (err) {
+ if (err && err.expose && err.status) return error(res, err.status, err.code || 'error', err.message);
+ console.error('[cosmetics/split] set failed:', err);
+ return error(res, 500, 'internal', 'something went wrong');
+ }
+});
diff --git a/api/feed-stream.js b/api/feed-stream.js
new file mode 100644
index 000000000..cb4ba4f6a
--- /dev/null
+++ b/api/feed-stream.js
@@ -0,0 +1,135 @@
+// GET /api/feed-stream — Server-Sent Events for the live activity ticker.
+//
+// The widget (public/feed.js) does one fast GET /api/feed for first paint, then
+// opens this stream. Every event produced anywhere on the platform (see
+// api/_lib/feed.js) lands in the capped Redis list `feed:events`; this handler
+// tails that list and pushes only the events that appear AFTER the client
+// connected, so new activity reaches an open tab within one poll tick (~1.5s)
+// instead of the 20s the bare poll path settles for.
+//
+// Why poll Redis instead of native pub/sub? The Upstash REST client this repo
+// uses has no long-lived SUBSCRIBE; a cheap LRANGE of the list head every tick
+// (one command, deduped by event id) survives Vercel's stateless model and costs
+// far less than every open tab independently polling /api/feed. One warm function
+// fans a single Redis read out to its connected clients.
+//
+// Vercel: registered with maxDuration 300 in vercel.json so the connection can
+// stay open up to the Hobby ceiling; we send a `retry` directive and close just
+// before the hard timeout, and EventSource reconnects automatically.
+
+import { Redis } from '@upstash/redis';
+import { cors, method } from './_lib/http.js';
+import { env } from './_lib/env.js';
+
+const FEED_KEY = 'feed:events';
+const HEARTBEAT_MS = 15_000;
+const POLL_MS = 1_500;
+const HEAD_N = 30; // how far back we scan each tick for unseen events
+const MAX_DURATION_MS = 275_000; // close before Vercel's 300s hard timeout
+
+function redis() {
+ if (!env.UPSTASH_REDIS_REST_URL || !env.UPSTASH_REDIS_REST_TOKEN) return null;
+ return new Redis({ url: env.UPSTASH_REDIS_REST_URL, token: env.UPSTASH_REDIS_REST_TOKEN });
+}
+
+function parseRow(row) {
+ if (row && typeof row === 'object') return row; // Upstash auto-deserializes
+ if (typeof row !== 'string') return null;
+ try { return JSON.parse(row); } catch { return null; }
+}
+
+export default async function handleFeedStream(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ res.writeHead(200, {
+ 'Content-Type': 'text/event-stream; charset=utf-8',
+ 'Cache-Control': 'no-cache, no-transform',
+ 'Connection': 'keep-alive',
+ // Vercel's edge gateway buffers responses by default; without this it holds
+ // SSE frames until the function returns, defeating the stream.
+ 'X-Accel-Buffering': 'no',
+ });
+
+ let closed = false;
+ const send = (event, data) => {
+ if (closed || res.writableEnded) return;
+ res.write(`event: ${event}\n`);
+ res.write(`data: ${JSON.stringify(data)}\n\n`);
+ };
+
+ const r = redis();
+ send('hello', { ts: Date.now() });
+ // No Redis configured (e.g. local dev): keep the socket alive with heartbeats
+ // so the client's fallback poll path still runs, but emit nothing.
+ if (!r) {
+ const hb = setInterval(() => {
+ if (closed || res.writableEnded) { clearInterval(hb); return; }
+ res.write(':hb\n\n');
+ }, HEARTBEAT_MS);
+ const stop = () => { closed = true; clearInterval(hb); try { res.end(); } catch {} };
+ req.on('close', stop); res.on('close', stop);
+ return;
+ }
+
+ // Snapshot the current head so we only push events that arrive AFTER connect —
+ // the client already rendered the backlog from GET /api/feed.
+ const seen = new Set();
+ let primed = false;
+ let polling = false;
+
+ const tick = async () => {
+ if (closed || polling) return;
+ polling = true;
+ try {
+ const rows = await r.lrange(FEED_KEY, 0, HEAD_N - 1);
+ const fresh = [];
+ for (const row of rows || []) {
+ const obj = parseRow(row);
+ if (!obj || !obj.id) continue;
+ if (!seen.has(obj.id)) {
+ seen.add(obj.id);
+ if (primed) fresh.push(obj); // skip the initial backlog
+ }
+ }
+ primed = true;
+ // List is newest-first; emit oldest→newest so the client prepends in order.
+ for (let i = fresh.length - 1; i >= 0; i--) send('event', fresh[i]);
+ // Bound the seen-set so a long-lived connection can't grow unbounded.
+ if (seen.size > HEAD_N * 8) {
+ const keep = (rows || []).map(parseRow).filter(Boolean).map((o) => o.id);
+ seen.clear();
+ for (const id of keep) if (id) seen.add(id);
+ }
+ } catch (err) {
+ console.error('[feed-stream] poll failed', err?.message || err);
+ } finally {
+ polling = false;
+ }
+ };
+
+ const startMs = Date.now();
+ const heartbeat = setInterval(() => {
+ if (closed || res.writableEnded) return;
+ if (Date.now() - startMs > MAX_DURATION_MS) {
+ res.write('retry: 1000\n\n');
+ cleanup();
+ return;
+ }
+ res.write(':hb\n\n');
+ }, HEARTBEAT_MS);
+ const poll = setInterval(tick, POLL_MS);
+
+ function cleanup() {
+ if (closed) return;
+ closed = true;
+ clearInterval(heartbeat);
+ clearInterval(poll);
+ if (!res.writableEnded) { try { res.end(); } catch { /* torn down */ } }
+ }
+
+ req.on('close', cleanup);
+ req.on('error', cleanup);
+ res.on('close', cleanup);
+ res.on('error', cleanup);
+}
diff --git a/public/feed.css b/public/feed.css
index 955f1a0e5..643fa22f6 100644
--- a/public/feed.css
+++ b/public/feed.css
@@ -206,6 +206,7 @@ a.tws-feed-item:focus-visible {
.tws-feed-ico[data-kind='level-up'] { color: var(--warn, #fbbf24); }
.tws-feed-ico[data-kind='world-join'] { color: #7dd3fc; }
.tws-feed-ico[data-kind='jackpot'] { color: var(--warn, #fbbf24); }
+.tws-feed-ico[data-kind='member-join'] { color: #5eead4; }
.tws-feed-body {
flex: 1 1 auto;
diff --git a/public/feed.js b/public/feed.js
index a796d9378..7043218b7 100644
--- a/public/feed.js
+++ b/public/feed.js
@@ -1,8 +1,10 @@
// three.ws live activity ticker — the site-wide "something is always happening
// here" widget. Self-mounting: nav.js loads this on every page. Renders a small
// pulsing pill bottom-left that expands into a live panel of recent platform
-// events (coin buys, agent deploys, level-ups, world joins). Polls GET /api/feed
-// and prepends anything new.
+// events (coin buys, agent deploys, member sign-ins, level-ups, world joins).
+// Loads the backlog once from GET /api/feed, then subscribes to /api/feed-stream
+// (SSE) so new activity appears in real time; a slow poll stays on as a backstop
+// and to refresh relative timestamps. Falls back to polling where SSE is absent.
//
// Opt out per page with <html data-feed="off"> or window.__twsFeedOff = true.
// The data source and event shape live in api/_lib/feed.js.
@@ -93,6 +95,11 @@
href: function (e) { return e.agentId ? '/agent/' + encodeURIComponent(e.agentId) : '/discover'; },
parts: function (e) { return [bold(e.name || e.actor || 'A new agent'), ' just joined three.ws']; },
},
+ 'member-join': {
+ icon: '✷',
+ href: function (e) { return e.handle ? 'https://x.com/' + encodeURIComponent(e.handle) : '/play'; },
+ parts: function (e) { return [bold('@' + (e.handle || e.actor || 'someone')), ' just joined three.ws']; },
+ },
'agent-onchain': {
icon: '⛓',
href: function (e) { return e.agentId ? '/agent/' + encodeURIComponent(e.agentId) : '/discover'; },
@@ -248,9 +255,11 @@
document.addEventListener('visibilitychange', function () {
if (document.hidden) {
stopPolling();
+ stopStream();
} else {
poll();
startPolling();
+ startStream();
}
});
// Hide entirely while a page element is fullscreen (immersive 3D etc.).
@@ -401,6 +410,17 @@
return added;
}
+ // Reflect freshly-merged events into the UI. Shared by the poll and the SSE
+ // stream so both paths animate in identically.
+ function onIngest(added, first) {
+ if (open) {
+ if (first || added) render();
+ else refreshTimes();
+ } else {
+ updatePill();
+ }
+ }
+
function poll() {
fetch(API, { headers: { accept: 'application/json' }, credentials: 'omit' })
.then(function (r) {
@@ -411,13 +431,7 @@
errored = false;
var first = !loaded;
loaded = true;
- var added = merge(Array.isArray(data.events) ? data.events : []);
- if (open) {
- if (first || added) render();
- else refreshTimes();
- } else {
- updatePill();
- }
+ onIngest(merge(Array.isArray(data.events) ? data.events : []), first);
})
.catch(function () {
errored = true;
@@ -428,6 +442,35 @@
});
}
+ // ── Real-time stream ─────────────────────────────────────────────────────
+ // EventSource pushes new events within ~1.5s of them happening (vs the poll's
+ // 20s). The poll stays on as a slow backstop that also refreshes "Nm ago"
+ // labels and reconciles anything the stream missed across a reconnect. When
+ // EventSource is unavailable the poll alone carries the feed.
+ var es = null;
+ function startStream() {
+ if (typeof EventSource === 'undefined' || es) return;
+ try {
+ es = new EventSource('/api/feed-stream');
+ } catch (_) {
+ es = null;
+ return;
+ }
+ es.addEventListener('event', function (msg) {
+ var ev = null;
+ try { ev = JSON.parse(msg.data); } catch (_) { return; }
+ if (!ev) return;
+ loaded = true;
+ errored = false;
+ onIngest(merge([ev]), false);
+ });
+ // On error EventSource auto-reconnects; nothing to do. The backstop poll
+ // covers the gap. We deliberately don't tear down on error.
+ }
+ function stopStream() {
+ if (es) { try { es.close(); } catch (_) {} es = null; }
+ }
+
function startPolling() {
stopPolling();
pollTimer = setInterval(function () {
@@ -451,6 +494,7 @@
mount();
poll();
startPolling();
+ startStream();
}
if (document.readyState === 'loading') {
diff --git a/src/game/coincommunities-ui.js b/src/game/coincommunities-ui.js
index 0238c4ac1..70caf30b9 100644
--- a/src/game/coincommunities-ui.js
+++ b/src/game/coincommunities-ui.js
@@ -789,7 +789,7 @@ export class CommunityUI {
// discoverable on touch too; clicking it routes the player through the gate.
const holdersBadge = el('button', {
type: 'button', class: 'cc-card-holders',
- title: `Holders only — hold $8+ of ${sym} to enter this coin’s gated world`,
+ title: `Holders only — hold ${sym} to enter this coin’s gated world`,
'aria-label': `Enter the ${sym} holders-only world`,
onclick: (e) => { e.stopPropagation(); this.h.onEnter(c, 'holders'); },
}, [el('span', { class: 'cc-card-holders-ico', 'aria-hidden': 'true', text: '🔒' }), document.createTextNode('Holders')]);
@@ -871,6 +871,98 @@ export class CommunityUI {
setTimeout(done, 280); // fallback if transitionend never fires
}
+ // Reveal the creator-only gate control once the server confirms ownership.
+ setWorldCreator(isCreator) {
+ if (this.gateBtn) this.gateBtn.hidden = !isCreator;
+ }
+
+ // Creator gate config (R24). A small modal where the coin's creator sets the
+ // token amount a wallet must hold to enter the Holders world, or removes the
+ // requirement. `onSave(minTokens)` returns a promise that resolves to the saved
+ // config or rejects with a coded error; we drive the busy/error states off it.
+ openGateConfig(coin, { minTokens = 0, onSave } = {}) {
+ this.closeGateConfig();
+ const sym = coin?.symbol ? '$' + String(coin.symbol).replace(/^\$/, '').toUpperCase() : 'this coin';
+ const input = el('input', {
+ type: 'number', min: '0', step: '1', inputmode: 'numeric',
+ class: 'cc-gatecfg-input', value: minTokens > 0 ? String(minTokens) : '',
+ placeholder: 'e.g. 1000000', 'aria-label': `Minimum ${sym} to enter the holders world`,
+ });
+ const errLine = el('p', { class: 'cc-gatecfg-err', hidden: true });
+ const hint = el('p', { class: 'cc-gatecfg-hint', text: `Leave blank to use the default ($-value) floor. Set a number to require that many ${sym} on-chain.` });
+ const saveBtn = el('button', { type: 'button', class: 'cc-gate-btn cc-gate-primary', text: 'Save gate' });
+ const clearBtn = el('button', {
+ type: 'button', class: 'cc-gate-btn cc-gate-ghost',
+ text: minTokens > 0 ? 'Remove gate' : 'Cancel',
+ });
+ const busy = (on) => {
+ saveBtn.disabled = on; clearBtn.disabled = on; input.disabled = on;
+ saveBtn.textContent = on ? 'Saving…' : 'Save gate';
+ };
+ const fail = (msg) => { errLine.textContent = msg; errLine.hidden = false; busy(false); };
+ const commit = async (value) => {
+ errLine.hidden = true;
+ busy(true);
+ try {
+ await onSave?.(value);
+ this.closeGateConfig();
+ this.toast(value > 0 ? `Holders world now needs ${fmtCompact(value)} ${sym}.` : 'Holders gate removed — default floor applies.', 'success');
+ } catch (err) {
+ fail(err?.message || 'Couldn’t save the gate. Try again.');
+ }
+ };
+ saveBtn.onclick = () => {
+ const v = Math.floor(Number(input.value));
+ if (!Number.isFinite(v) || v <= 0) return fail('Enter a positive number of tokens, or use Remove gate.');
+ commit(v);
+ };
+ clearBtn.onclick = () => { if (minTokens > 0) commit(0); else this.closeGateConfig(); };
+ input.onkeydown = (e) => { if (e.key === 'Enter') { e.preventDefault(); saveBtn.click(); } e.stopPropagation(); };
+
+ const body = el('div', { class: 'cc-gate-body' }, [
+ el('h3', { class: 'cc-gate-title', text: 'Holders world gate' }),
+ el('p', { class: 'cc-gate-msg', text: `Require holding ${sym} to enter this coin’s Holders world.` }),
+ el('label', { class: 'cc-gatecfg-row' }, [
+ el('span', { class: 'cc-gatecfg-label', text: `Minimum ${sym}` }), input,
+ ]),
+ hint, errLine,
+ el('div', { class: 'cc-gate-actions' }, [saveBtn, clearBtn]),
+ ]);
+ const modal = el('div', {
+ class: 'cc-gate-modal', role: 'dialog', 'aria-modal': 'true', 'aria-label': 'Holders world gate',
+ }, [
+ el('div', { class: 'cc-gate-head' }, [
+ el('span', { class: 'cc-gate-tag', text: '🔑 Creator' }),
+ el('button', { type: 'button', class: 'cc-gate-x', 'aria-label': 'Close', text: '×', onclick: () => this.closeGateConfig() }),
+ ]),
+ body,
+ ]);
+ const overlay = el('div', {
+ class: 'cc-gate-overlay', onclick: (e) => { if (e.target === overlay) this.closeGateConfig(); },
+ }, [modal]);
+ this._gateCfg = overlay;
+ this._gateCfgKey = (e) => { if (e.key === 'Escape') { e.stopPropagation(); this.closeGateConfig(); } };
+ document.addEventListener('keydown', this._gateCfgKey, true);
+ this._gateCfgOpener = document.activeElement instanceof HTMLElement ? document.activeElement : null;
+ document.body.appendChild(overlay);
+ this._gateCfgTrapRelease = this._trapFocus(overlay);
+ requestAnimationFrame(() => { overlay.classList.add('cc-on'); input.focus(); });
+ }
+
+ closeGateConfig() {
+ const o = this._gateCfg;
+ if (!o) return;
+ this._gateCfg = null;
+ if (this._gateCfgKey) { document.removeEventListener('keydown', this._gateCfgKey, true); this._gateCfgKey = null; }
+ if (this._gateCfgTrapRelease) { this._gateCfgTrapRelease(); this._gateCfgTrapRelease = null; }
+ if (this._gateCfgOpener?.isConnected) this._gateCfgOpener.focus();
+ this._gateCfgOpener = null;
+ o.classList.remove('cc-on');
+ const done = () => o.remove();
+ o.addEventListener('transitionend', done, { once: true });
+ setTimeout(done, 280);
+ }
+
setHolderGate(state, data = {}) {
if (!this._gate) this.openHolderGate(data);
const body = this._gateBody;
@@ -1377,19 +1469,24 @@ export class CommunityUI {
this.buyBtnLabel.textContent = coin.symbol ? 'Buy $' + coin.symbol.toUpperCase() : 'Buy';
if (coin.image) { this.coinImg.src = coin.image; this.coinImg.style.display = ''; }
else this.coinImg.style.display = 'none';
+ this.refreshTierBadge(coin);
+ this.chatLog.textContent = '';
+ this._unread = 0;
+ this.chatUnread.hidden = true;
+ this.pingText.hidden = true;
+ }
+
+ // The Holders badge states the real entry bar: a creator-set token threshold
+ // (R24) reads "1M $SYM+", otherwise the USD floor reads "$8+". Extracted so the
+ // creator can update it live after saving a new gate without rebuilding the HUD.
+ refreshTierBadge(coin) {
const holders = coin.tier === 'holders';
this.tierBadge.hidden = !holders;
- // State the real bar: a creator-set token threshold (R24) reads "1M $SYM+",
- // otherwise the USD floor reads "$8+".
const sym = coin.symbol ? '$' + String(coin.symbol).replace(/^\$/, '').toUpperCase() : '';
const req = coin.holderMinTokens > 0
? `${fmtCompact(coin.holderMinTokens)} ${sym}+`
: `$${coin.holderMinUsd ? Math.round(coin.holderMinUsd * 100) / 100 : 8}+`;
this.tierBadge.textContent = holders ? `🔒 Holders · ${req}` : '';
- this.chatLog.textContent = '';
- this._unread = 0;
- this.chatUnread.hidden = true;
- this.pingText.hidden = true;
}
showLobby() {
diff --git a/src/game/coincommunities.css b/src/game/coincommunities.css
index 735849871..6582031d1 100644
--- a/src/game/coincommunities.css
+++ b/src/game/coincommunities.css
@@ -1024,6 +1024,7 @@ html, body {
}
#cc-toast.cc-on { opacity: 1; transform: translate(-50%, 0); }
#cc-toast[data-kind="warn"] { border-color: rgba(216, 192, 138, 0.5); }
+#cc-toast[data-kind="success"] { border-color: rgba(138, 216, 168, 0.5); }
/* ── Native buy modal ───────────────────────────────────────────────────── */
.cc-buy-overlay {
@@ -1795,6 +1796,35 @@ html, body {
.cc-shop-btn:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
.cc-shop-btn-ico { font-size: 14px; line-height: 1; }
+/* Creator-only holders-gate button (R24) — mirrors the shop button, accented. */
+.cc-gate-cfg-btn {
+ flex: none; pointer-events: auto;
+ display: inline-flex; align-items: center; gap: 7px;
+ margin-left: 4px; padding: 9px 13px;
+ background: rgba(255, 255, 255, 0.04); color: var(--cc-text);
+ border: 1px solid var(--cc-edge); border-radius: var(--cc-radius);
+ font-weight: 700; font-size: 12px; letter-spacing: 0.04em; text-transform: uppercase;
+ cursor: pointer; white-space: nowrap;
+ transition: transform 0.12s ease, border-color 0.12s ease, background 0.12s ease;
+}
+.cc-gate-cfg-btn:hover { border-color: var(--cc-edge-hi); background: rgba(255, 255, 255, 0.08); transform: translateY(-1px); }
+.cc-gate-cfg-btn:active { transform: translateY(1px); }
+.cc-gate-cfg-btn:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
+.cc-gate-cfg-ico { font-size: 14px; line-height: 1; }
+
+/* Gate-config modal fields (reuses .cc-gate-overlay/.cc-gate-modal/.cc-gate-btn). */
+.cc-gatecfg-row { display: flex; flex-direction: column; gap: 6px; width: 100%; margin-top: 6px; text-align: left; }
+.cc-gatecfg-label { font-size: 12px; font-weight: 700; letter-spacing: 0.03em; text-transform: uppercase; color: var(--cc-dim); }
+.cc-gatecfg-input {
+ width: 100%; box-sizing: border-box; padding: 10px 12px;
+ background: var(--cc-bg2); color: var(--cc-text);
+ border: 1px solid var(--cc-edge); border-radius: var(--cc-radius);
+ font-size: 15px; font-variant-numeric: tabular-nums;
+}
+.cc-gatecfg-input:focus-visible { outline: 2px solid #fff; outline-offset: 1px; border-color: var(--cc-edge-hi); }
+.cc-gatecfg-hint { margin: 8px 0 0; font-size: 12px; line-height: 1.5; color: var(--cc-dim); text-align: left; }
+.cc-gatecfg-err { margin: 8px 0 0; font-size: 12.5px; line-height: 1.45; color: #e7cccc; text-align: left; }
+
.cc-shop {
position: fixed; inset: 0; z-index: 92;
display: grid; place-items: center; padding: 20px;
diff --git a/src/game/coincommunities.js b/src/game/coincommunities.js
index d1c23fffe..2474b0ffb 100644
--- a/src/game/coincommunities.js
+++ b/src/game/coincommunities.js
@@ -44,7 +44,7 @@ import { HOME_TOWN, isHomeTown } from './home-town.js';
import { AgentCommerce } from './agent-commerce.js';
import { WorldLife } from './npc/world-life.js';
import { VoiceChat, voiceSupported } from './voice-chat.js';
-import { requestHolderPass, signInWithX, ensureSolanaWallet, relinkSolanaWallet, getSession } from '../community/town-auth.js';
+import { requestHolderPass, signInWithX, ensureSolanaWallet, relinkSolanaWallet, getSession, getWorldGate, setWorldGate } from '../community/town-auth.js';
import { ensurePlayAccess } from './play-gate.js';
import { clearStoredPass, fetchPlayConfig, signInToPlay, loadStoredPass, storePass } from './play-auth.js';
import { PlaySystems } from './play-systems.js';
@@ -253,6 +253,8 @@ export class CoinCommunities {
onRename: (name) => this._rename(name),
onBuy: () => this._openBuy(),
onShop: () => this._toggleShop(),
+ // Creator-only (R24): set/clear the token threshold for the Holders world.
+ onConfigureGate: () => this._configureGate(),
onVoiceToggle: () => this._toggleVoice(),
// Build structures toolbar (R20): pick a composite piece, rotate it, share a
// screenshot of the build, or open this coin's featured builds.
@@ -1236,11 +1238,15 @@ export class CoinCommunities {
// Key ownership + purchases on the verified wallet when we have one;
// the shop falls back to the persisted guest id otherwise.
account: this.account || '',
+ // The coin world we're in (R25): ties a cosmetic sale to this coin so a
+ // configurable share of the settled USDC pays out to the coin's creator.
+ coinMint: this.coin?.mint || '',
onPreview: (item) => this.equipCosmeticPreview(item),
onEndPreview: () => this.unequipCosmeticPreview(),
// A premium item was just bought (R22) — now owned for this account.
- // Keep it previewing so the buyer sees what they unlocked.
- onPurchased: (item) => { this._previewItem = item; },
+ // Equip it live so the buyer immediately sees what they unlocked
+ // (durable cross-world equip persistence lands in R23).
+ onPurchased: (item) => { this.equipCosmeticPreview(item); },
});
}
this._shop.toggle();
@@ -1701,6 +1707,8 @@ export class CoinCommunities {
};
this.buildHud.setCreator(this._buildPerms.creator);
this.buildHud.setUsage(this._buildPerms.used, this._buildPerms.cap);
+ // R24: the same server-proven creator flag reveals the holder-gate control.
+ this.ui.setWorldCreator(this._buildPerms.creator);
}
// Clear the per-player meter + creator tool — on leave and on every (re)connect,
@@ -1710,6 +1718,35 @@ export class CoinCommunities {
this._buildPerms = { creator: false, cap: 0, used: 0, clearMaxRadius: 12 };
this.buildHud.setCreator(false);
this.buildHud.setUsage(0, 0);
+ this.ui.setWorldCreator(false);
+ }
+
+ // Creator gate config (R24): open the modal to set or clear the token threshold
+ // a wallet must hold to enter this coin's Holders world. Reads the current value
+ // first so the input is pre-filled, then writes through the creator-only
+ // endpoint (which re-verifies ownership server-side). Only the coin's verified
+ // creator ever reaches this — the button is hidden otherwise.
+ async _configureGate() {
+ const coin = this.coin;
+ if (!coin?.mint) return;
+ let current = 0;
+ try {
+ const cfg = await getWorldGate(coin.mint);
+ current = cfg?.minTokens || 0;
+ } catch { /* fall back to a blank form — the save still validates server-side */ }
+ this.ui.openGateConfig(coin, {
+ minTokens: current,
+ onSave: async (minTokens) => {
+ const saved = await setWorldGate(coin.mint, minTokens);
+ const next = saved?.minTokens || 0;
+ // Keep the in-world Holders badge honest without tearing down the HUD.
+ if (this.coin) {
+ this.coin = { ...this.coin, holderMinTokens: next };
+ this.ui.refreshTierBadge(this.coin);
+ }
+ return saved;
+ },
+ });
}
// Creator moderation: clear a disc of blocks around where the player stands, or
diff --git a/src/game/cosmetics-flex.js b/src/game/cosmetics-flex.js
new file mode 100644
index 000000000..d418380e2
--- /dev/null
+++ b/src/game/cosmetics-flex.js
@@ -0,0 +1,285 @@
+// Rarest Fits — the /play cosmetics flex surface (R25).
+//
+// A platform-wide status board that drives the Roblox-style "rare fit" loop: the
+// scarcest premium cosmetics (fewest owners), the top collectors by a rarity-
+// weighted flex score, the top earning coin creators, and the live drip of recent
+// unlocks. Every number comes from /api/cosmetics/leaderboard — settled sales only,
+// nothing simulated. Each fit and creator links back into the coin world it's tied
+// to (/play?coin=<mint>), closing the loop from "I want that fit" to "go where it's
+// worn". Self-contained: appends its own overlay + scoped styles, like coin-buy.js.
+//
+// $THREE is the only coin; cosmetic VALUE is quoted in $THREE in the shop, while
+// these flex numbers report the USDC that actually settled — the asset, never a
+// coin to hold.
+
+const ENDPOINT = '/api/cosmetics/leaderboard';
+
+let _open = null; // the live overlay controller, so a second open refocuses it
+
+function el(tag, props = {}, kids = []) {
+ const n = document.createElement(tag);
+ for (const [k, v] of Object.entries(props)) {
+ if (k === 'class') n.className = v;
+ else if (k === 'text') n.textContent = v;
+ else if (k === 'html') n.innerHTML = v;
+ else if (k.startsWith('on') && typeof v === 'function') n.addEventListener(k.slice(2), v);
+ else if (v !== null && v !== undefined && v !== false) n.setAttribute(k, v === true ? '' : v);
+ }
+ for (const kid of [].concat(kids)) if (kid != null && kid !== false) n.appendChild(typeof kid === 'string' ? document.createTextNode(kid) : kid);
+ return n;
+}
+
+const RARITY_LABEL = { common: 'Common', rare: 'Rare', epic: 'Epic', legendary: 'Legendary' };
+const shortAddr = (a) => (a && a.length > 10 ? `${a.slice(0, 4)}…${a.slice(-4)}` : a || '');
+const isWallet = (a) => typeof a === 'string' && /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(a);
+const fmtUsd = (n) => '$' + (Number(n) || 0).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
+const accountLabel = (a) => (isWallet(a) ? shortAddr(a) : 'Guest');
+
+/**
+ * Open the Rarest Fits board. Idempotent — a second call refocuses.
+ * @param {{ coinMint?: string }} [opts] the current world, highlighted in the board.
+ */
+export function openCosmeticsFlex(opts = {}) {
+ if (_open) { _open.focus(); return _open; }
+ _open = new FlexBoard(opts || {});
+ return _open;
+}
+
+class FlexBoard {
+ constructor({ coinMint = '' } = {}) {
+ this.coinMint = coinMint || '';
+ this._injectStyles();
+ this._build();
+ this._load();
+ }
+
+ focus() { this.closeBtn?.focus(); }
+
+ _build() {
+ this.closeBtn = el('button', {
+ class: 'cf-close', type: 'button', 'aria-label': 'Close rarest fits',
+ onclick: () => this.close(),
+ }, [el('span', { 'aria-hidden': 'true', text: '✕' })]);
+
+ this.body = el('div', { class: 'cf-body' });
+
+ this.panel = el('div', {
+ class: 'cf-panel', role: 'dialog', 'aria-modal': 'false', 'aria-label': 'Rarest fits leaderboard',
+ }, [
+ el('div', { class: 'cf-head' }, [
+ el('div', { class: 'cf-title' }, [
+ el('span', { class: 'cf-title-main', text: 'Rarest Fits' }),
+ el('span', { class: 'cf-title-sub', text: 'Who owns the scarcest looks — and the creators earning from them' }),
+ ]),
+ this.closeBtn,
+ ]),
+ this.body,
+ ]);
+
+ this.root = el('div', { class: 'cf-root', id: 'cc-flex', hidden: true }, [this.panel]);
+ this.root.addEventListener('click', (e) => { if (e.target === this.root) this.close(); });
+ this._onKey = (e) => { if (e.key === 'Escape' && !this.root.hidden) { e.stopPropagation(); this.close(); } };
+ document.addEventListener('keydown', this._onKey, true);
+ document.body.appendChild(this.root);
+ requestAnimationFrame(() => { this.root.hidden = false; this.root.classList.add('cf-in'); this.focus(); });
+ }
+
+ _status(msg, kind = '') {
+ this.body.replaceChildren(el('div', { class: `cf-status cf-${kind}`, role: 'status', 'aria-live': 'polite' }, [msg]));
+ }
+
+ async _load() {
+ this._status('Loading the flex board…', 'pending');
+ // Skeleton-ish: a brief pending line, then real data or an honest empty/error.
+ try {
+ const r = await fetch(`${ENDPOINT}?limit=12`, { headers: { accept: 'application/json' } });
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
+ const data = await r.json();
+ this._render(data);
+ } catch (err) {
+ this.body.replaceChildren(
+ el('div', { class: 'cf-status cf-error', role: 'status' }, [
+ 'Couldn’t load the flex board. ',
+ el('button', { class: 'cf-retry', type: 'button', text: 'Retry', onclick: () => this._load() }),
+ ]),
+ );
+ }
+ }
+
+ _render(data) {
+ const rarestFits = data?.rarestFits || [];
+ const topCollectors = data?.topCollectors || [];
+ const topCreators = data?.topCreators || [];
+ const recent = data?.recent || [];
+
+ const empty = !rarestFits.length && !topCollectors.length && !recent.length;
+ if (empty) {
+ this.body.replaceChildren(el('div', { class: 'cf-empty' }, [
+ el('div', { class: 'cf-empty-glyph', 'aria-hidden': 'true', text: '✦' }),
+ el('div', { class: 'cf-empty-title', text: 'No fits owned yet' }),
+ el('div', { class: 'cf-empty-sub', text: 'Be the first to buy a premium cosmetic — your fit tops the rarity board, and the coin’s creator earns a cut.' }),
+ ]));
+ return;
+ }
+
+ const sections = [];
+
+ // ── Rarest fits ──────────────────────────────────────────────────────
+ if (rarestFits.length) {
+ sections.push(el('section', { class: 'cf-sec' }, [
+ el('h3', { class: 'cf-sec-h', text: 'Rarest fits' }),
+ el('div', { class: 'cf-fits' }, rarestFits.map((f) => this._fitCard(f))),
+ ]));
+ }
+
+ // ── Top collectors ───────────────────────────────────────────────────
+ if (topCollectors.length) {
+ sections.push(el('section', { class: 'cf-sec' }, [
+ el('h3', { class: 'cf-sec-h', text: 'Top collectors' }),
+ el('ol', { class: 'cf-rank' }, topCollectors.map((c, i) => el('li', { class: 'cf-rank-row' }, [
+ el('span', { class: 'cf-rank-n', text: String(i + 1) }),
+ el('span', { class: 'cf-rank-who', text: accountLabel(c.account) }),
+ el('span', { class: 'cf-rank-meta', text: `${c.fits} fit${c.fits === 1 ? '' : 's'}` }),
+ el('span', { class: 'cf-rank-score', title: 'Rarity-weighted flex score', text: `${c.flexScore} flex` }),
+ ]))),
+ ]));
+ }
+
+ // ── Top creators (real USDC earnings) ────────────────────────────────
+ if (topCreators.length) {
+ sections.push(el('section', { class: 'cf-sec' }, [
+ el('h3', { class: 'cf-sec-h', text: 'Top earning creators' }),
+ el('ol', { class: 'cf-rank' }, topCreators.map((c, i) => el('li', { class: 'cf-rank-row' }, [
+ el('span', { class: 'cf-rank-n', text: String(i + 1) }),
+ el('span', { class: 'cf-rank-who', text: shortAddr(c.wallet) }),
+ el('span', { class: 'cf-rank-meta', text: `${c.sales} sale${c.sales === 1 ? '' : 's'}` }),
+ el('span', { class: 'cf-rank-score', text: fmtUsd(c.earnedUsdc) }),
+ ]))),
+ ]));
+ }
+
+ // ── Recent unlocks ───────────────────────────────────────────────────
+ if (recent.length) {
+ sections.push(el('section', { class: 'cf-sec' }, [
+ el('h3', { class: 'cf-sec-h', text: 'Recent unlocks' }),
+ el('ul', { class: 'cf-recent' }, recent.map((r) => el('li', { class: 'cf-recent-row' }, [
+ el('span', { class: `cf-pill cf-r-${r.rarity}`, text: RARITY_LABEL[r.rarity] || r.rarity }),
+ el('span', { class: 'cf-recent-name', text: r.name }),
+ el('span', { class: 'cf-recent-by', text: `by ${accountLabel(r.buyer)}` }),
+ r.mint ? this._worldLink(r.mint, 'visit world') : el('span', {}),
+ ]))),
+ ]));
+ }
+
+ this.body.replaceChildren(...sections);
+ }
+
+ _fitCard(f) {
+ const worn = f.worldMint
+ ? this._worldLink(f.worldMint, 'Visit world →')
+ : el('span', { class: 'cf-fit-noworld', text: 'Untied' });
+ const here = f.worldMint && f.worldMint === this.coinMint;
+ return el('div', { class: 'cf-fit' + (here ? ' cf-fit-here' : '') }, [
+ f.previewImage
+ ? el('img', { class: 'cf-fit-img', src: f.previewImage, alt: '', loading: 'lazy' })
+ : el('div', { class: 'cf-fit-img cf-fit-img-ph', 'aria-hidden': 'true', text: '✦' }),
+ el('div', { class: 'cf-fit-info' }, [
+ el('div', { class: 'cf-fit-name', text: f.name }),
+ el('div', { class: 'cf-fit-sub' }, [
+ el('span', { class: `cf-pill cf-r-${f.rarity}`, text: RARITY_LABEL[f.rarity] || f.rarity }),
+ el('span', { class: 'cf-fit-owners', text: `${f.owners} owner${f.owners === 1 ? '' : 's'}` }),
+ ]),
+ worn,
+ ]),
+ ]);
+ }
+
+ // A link back into a coin world. Uses the same /play?coin=<mint> deep link the
+ // scene already honours, so clicking a fit takes you where it's worn.
+ _worldLink(mint, label) {
+ return el('a', {
+ class: 'cf-worldlink',
+ href: `/play?coin=${encodeURIComponent(mint)}`,
+ title: 'Enter this coin’s world',
+ text: label,
+ });
+ }
+
+ close() {
+ if (!this.root) return;
+ document.removeEventListener('keydown', this._onKey, true);
+ this.root.classList.remove('cf-in');
+ const root = this.root;
+ setTimeout(() => { try { root.remove(); } catch {} }, 180);
+ this.root = null;
+ if (_open === this) _open = null;
+ }
+
+ _injectStyles() {
+ if (document.getElementById('cc-flex-styles')) return;
+ const css = `
+ .cf-root{position:fixed;inset:0;z-index:60;display:flex;align-items:center;justify-content:center;
+ background:rgba(6,8,14,.62);backdrop-filter:blur(6px);opacity:0;transition:opacity .18s ease;padding:16px}
+ .cf-root.cf-in{opacity:1}
+ .cf-panel{width:min(680px,96vw);max-height:88vh;display:flex;flex-direction:column;overflow:hidden;
+ background:#0e1018;color:#e9eaf2;border:1px solid #23263a;border-radius:16px;
+ box-shadow:0 24px 80px rgba(0,0,0,.55);transform:translateY(8px);transition:transform .18s ease}
+ .cf-root.cf-in .cf-panel{transform:translateY(0)}
+ .cf-head{display:flex;align-items:flex-start;justify-content:space-between;gap:12px;
+ padding:18px 20px 14px;border-bottom:1px solid #1c1f30}
+ .cf-title-main{display:block;font-size:18px;font-weight:700;letter-spacing:-.01em}
+ .cf-title-sub{display:block;font-size:12.5px;color:#9aa0b8;margin-top:2px}
+ .cf-close{background:#171a28;border:1px solid #262a40;color:#cfd2e6;width:34px;height:34px;border-radius:9px;
+ cursor:pointer;font-size:14px;line-height:1;transition:background .12s,border-color .12s}
+ .cf-close:hover{background:#202438;border-color:#363b58}
+ .cf-close:focus-visible{outline:2px solid #6f7bff;outline-offset:2px}
+ .cf-body{padding:14px 20px 22px;overflow:auto}
+ .cf-status{padding:28px 8px;text-align:center;color:#9aa0b8;font-size:14px}
+ .cf-status.cf-error{color:#ffb4b4}
+ .cf-retry{margin-left:6px;background:#262a40;border:1px solid #3a3f5e;color:#e9eaf2;border-radius:7px;
+ padding:4px 10px;cursor:pointer;font-size:13px}
+ .cf-retry:hover{background:#30364f}
+ .cf-empty{text-align:center;padding:34px 12px;color:#aeb4cc}
+ .cf-empty-glyph{font-size:34px;opacity:.5}
+ .cf-empty-title{font-size:16px;font-weight:650;margin-top:6px;color:#e9eaf2}
+ .cf-empty-sub{font-size:13px;margin-top:6px;max-width:42ch;margin-inline:auto;line-height:1.5}
+ .cf-sec{margin-top:18px}
+ .cf-sec:first-child{margin-top:2px}
+ .cf-sec-h{font-size:12px;text-transform:uppercase;letter-spacing:.06em;color:#8b91ac;margin:0 0 10px}
+ .cf-fits{display:grid;grid-template-columns:repeat(auto-fill,minmax(190px,1fr));gap:10px}
+ .cf-fit{display:flex;gap:10px;align-items:center;background:#141726;border:1px solid #20243a;border-radius:12px;padding:10px}
+ .cf-fit-here{border-color:#6f7bff;box-shadow:0 0 0 1px rgba(111,123,255,.4) inset}
+ .cf-fit-img{width:48px;height:48px;border-radius:9px;object-fit:cover;background:#1c2032;flex:none}
+ .cf-fit-img-ph{display:flex;align-items:center;justify-content:center;font-size:20px;color:#5a6086}
+ .cf-fit-info{min-width:0;flex:1}
+ .cf-fit-name{font-weight:650;font-size:13.5px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
+ .cf-fit-sub{display:flex;align-items:center;gap:6px;margin:4px 0 6px}
+ .cf-fit-owners{font-size:11.5px;color:#9aa0b8}
+ .cf-fit-noworld{font-size:11.5px;color:#6b7090}
+ .cf-pill{font-size:10.5px;font-weight:700;text-transform:uppercase;letter-spacing:.03em;
+ padding:2px 7px;border-radius:999px;border:1px solid transparent}
+ .cf-r-common{color:#c3c8db;background:#1d2133;border-color:#2a3047}
+ .cf-r-rare{color:#7fb6ff;background:#13233b;border-color:#234668}
+ .cf-r-epic{color:#caa6ff;background:#241a3b;border-color:#4a3a6e}
+ .cf-r-legendary{color:#ffd479;background:#2c2410;border-color:#5e4d1d}
+ .cf-worldlink{font-size:11.5px;color:#8aa0ff;text-decoration:none;border-bottom:1px dashed transparent}
+ .cf-worldlink:hover{border-bottom-color:#8aa0ff}
+ .cf-rank{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:2px}
+ .cf-rank-row{display:flex;align-items:center;gap:10px;padding:8px 10px;border-radius:9px}
+ .cf-rank-row:nth-child(odd){background:#12141f}
+ .cf-rank-n{width:20px;text-align:center;font-variant-numeric:tabular-nums;color:#7b819c;font-size:12px}
+ .cf-rank-who{flex:1;font-weight:600;font-size:13px}
+ .cf-rank-meta{font-size:12px;color:#9aa0b8}
+ .cf-rank-score{font-size:12.5px;font-weight:650;color:#bfe3c8;font-variant-numeric:tabular-nums}
+ .cf-recent{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:2px}
+ .cf-recent-row{display:flex;align-items:center;gap:8px;padding:7px 10px;border-radius:9px;font-size:12.5px}
+ .cf-recent-row:nth-child(odd){background:#12141f}
+ .cf-recent-name{font-weight:600}
+ .cf-recent-by{color:#9aa0b8}
+ .cf-recent-row .cf-worldlink{margin-left:auto}
+ @media (max-width:520px){.cf-fits{grid-template-columns:1fr}}
+ `;
+ const style = el('style', { id: 'cc-flex-styles', text: css });
+ document.head.appendChild(style);
+ }
+}
diff --git a/src/game/cosmetics-purchase.js b/src/game/cosmetics-purchase.js
index 917195b49..49f98ed65 100644
--- a/src/game/cosmetics-purchase.js
+++ b/src/game/cosmetics-purchase.js
@@ -43,7 +43,7 @@ export function resolveShopAccount(explicitWallet) {
// Run the x402 USDC payment for one cosmetic. Resolves with the settled ticket
// ({ ok, owned, newlyOwned, payer, network, … }); rejects with an Error on
// failure or { code:'cancelled' } when the buyer dismisses the wallet.
-export async function purchaseCosmetic(item, { account } = {}) {
+export async function purchaseCosmetic(item, { account, coin } = {}) {
if (!window.X402?.pay) {
throw new Error('Payment widget still loading — try again in a second.');
}
@@ -64,7 +64,16 @@ export async function purchaseCosmetic(item, { account } = {}) {
// primer unavailable — proceed to the payment modal anyway.
}
- const url = `${PURCHASE_ENDPOINT}?id=${encodeURIComponent(item.id)}&account=${encodeURIComponent(acct)}`;
+ // When bought inside a coin's /play world, tie the sale to that coin (R25) so a
+ // configurable share of the settled USDC pays out to the coin's creator. The
+ // server resolves the creator + share from the mint — the client only declares
+ // which world the purchase happened in; it never sets where the money goes.
+ // Falls back to the world in the URL (the /play deep link keeps ?coin=<mint>),
+ // so the tie holds even when the caller doesn't pass an explicit mint.
+ const coinMint = coin || currentWorldMint();
+ const coinParam = coinMint && /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(coinMint)
+ ? `&coin=${encodeURIComponent(coinMint)}` : '';
+ const url = `${PURCHASE_ENDPOINT}?id=${encodeURIComponent(item.id)}&account=${encodeURIComponent(acct)}${coinParam}`;
const out = await window.X402.pay({
endpoint: url,
method: 'GET',
diff --git a/src/game/cosmetics-shop.js b/src/game/cosmetics-shop.js
index d1441d503..8c848e30f 100644
--- a/src/game/cosmetics-shop.js
+++ b/src/game/cosmetics-shop.js
@@ -103,6 +103,13 @@ export class CosmeticsShop {
el('span', { class: 'cc-shop-title-main', text: 'Cosmetics' }),
el('span', { class: 'cc-shop-title-sub', text: 'Preview live on your avatar' }),
]),
+ // Rarest Fits — the platform flex board (R25). Lazy-loaded on click so
+ // it never weighs down the shop bundle.
+ el('button', {
+ class: 'cc-shop-flex', type: 'button', title: 'See the rarest fits & top earning creators',
+ 'aria-label': 'Open rarest fits leaderboard',
+ onclick: () => this._openFlex(),
+ }, [el('span', { 'aria-hidden': 'true', text: '✦' }), el('span', { class: 'cc-shop-flex-text', text: 'Rarest Fits' })]),
this.closeBtn,
]),
this.filters,
@@ -320,6 +327,18 @@ export class CosmeticsShop {
return el('div', { class: 'cc-shop-glyph', 'aria-hidden': 'true', text: SLOT_GLYPH[item.slot] || '✦' });
}
+ // Open the Rarest Fits flex board (R25), highlighting the current coin world.
+ // Lazy chunk — the leaderboard UI only loads when a player asks for it.
+ async _openFlex() {
+ try {
+ const { openCosmeticsFlex } = await import('./cosmetics-flex.js');
+ openCosmeticsFlex({ coinMint: this.h.coinMint || '' });
+ } catch (err) {
+ log.warn('[shop] flex board failed to load', err?.message);
+ this._status('Couldn’t open the flex board. Try again in a moment.', 'error');
+ }
+ }
+
// ── purchase (R22) ──────────────────────────────────────────────────────────
// Run the real x402 USDC payment for a locked item and, on the server's
// confirmation, flip the card to owned. Every state is honest: pending while
@@ -332,7 +351,7 @@ export class CosmeticsShop {
this._swapAction(card, item);
this._status(`Settling payment for ${item.name}…`, 'pending');
try {
- const ticket = await purchaseCosmetic(item, { account: this.account });
+ const ticket = await purchaseCosmetic(item, { account: this.account, coin: this.h.coinMint });
this.buyingId = null;
item.owned = true;
if (card) {
diff --git a/src/walk.js b/src/walk.js
index bbe42bae0..d94c5d0c7 100644
--- a/src/walk.js
+++ b/src/walk.js
@@ -2022,6 +2022,14 @@ class RemotePlayer {
this.rig.add(root);
scene.add(this.rig);
+ // This peer's equipped cosmetic loadout (R23). Measure the body's height so
+ // props anchor correctly (mountProp scales/places by it), then dress them in
+ // the same applyLoadout the local player uses. Re-measured + re-applied after
+ // any avatar swap, and re-applied when they change their fit.
+ this._avatarHeight = measureRigHeight(root);
+ this._cosWire = initial?.cosmetics || '';
+ this._applyCosmetics();
+
this.anim = new AnimationManager();
this.anim.attach(root);
this.anim.setAnimationDefs(animationDefs);
@@ -2079,6 +2087,23 @@ class RemotePlayer {
this._avatarUrl = player.avatar;
this._swapAvatar(player.avatar);
}
+ // Live cosmetic change — they equipped/unequipped something.
+ if (player.cosmetics !== undefined && player.cosmetics !== this._cosWire) {
+ this._applyCosmetics(player.cosmetics);
+ }
+ }
+
+ // (Re)dress this peer in their equipped loadout. Idempotent — re-applies only
+ // when the wire changed — and shares applyLoadout with the local avatar so one
+ // wardrobe renders the same in every world.
+ _applyCosmetics(wire) {
+ const next = typeof wire === 'string' ? wire : (this._cosWire || '');
+ this._cosWire = next;
+ if (!this.rig || !this._avatarHeight) return;
+ if (this.cosmetics && this._cosApplied === next) return;
+ this._cosApplied = next;
+ try { this.cosmetics?.dispose(); } catch { /* already gone */ }
+ this.cosmetics = applyLoadout(this.rig, this._avatarHeight, next);
}
// Replace the visible body with the player's own avatar GLB. Loads (cached)
@@ -2108,6 +2133,12 @@ class RemotePlayer {
this._root = root;
this.rig.add(root);
+ // New body, new proportions: re-measure and re-dress so worn cosmetics fit
+ // the swapped avatar (tint binds to the new meshes; props re-anchor to it).
+ this._avatarHeight = Math.max(0.5, box.max.y - box.min.y);
+ this._cosApplied = null;
+ this._applyCosmetics();
+
// Track template references so the cache can evict & dispose templates no
// live player is cloning. Release the previous, claim the new.
if (this._heldTemplateUrl && this._heldTemplateUrl !== url) releaseRemoteTemplate(this._heldTemplateUrl);
@@ -2153,6 +2184,7 @@ class RemotePlayer {
this.rig.quaternion.setFromAxisAngle(upY, this.currentYaw);
this.anim.update(dt);
+ this.cosmetics?.tick(dt);
this._updateLabel();
}
@@ -2177,6 +2209,7 @@ class RemotePlayer {
dispose() {
this._avatarLoadToken++; // cancel any in-flight avatar swap
if (this._heldTemplateUrl) { releaseRemoteTemplate(this._heldTemplateUrl); this._heldTemplateUrl = null; }
+ try { this.cosmetics?.dispose(); } catch { /* already gone */ }
scene.remove(this.rig);
this.rig = null;
this.anim.dispose();
@@ -2184,6 +2217,12 @@ class RemotePlayer {
}
}
+// Head-anchor height for a freshly built body, used to scale/place worn props.
+function measureRigHeight(root) {
+ const b = new Box3().setFromObject(root);
+ return Math.max(0.5, b.max.y - b.min.y);
+}
+
const _tmpV3 = new Vector3();
function motionToClipName(motion) {
@@ -2248,6 +2287,9 @@ function startNet() {
coinName: COIN_PARAMS.name,
coinSymbol: COIN_PARAMS.symbol,
coinImage: COIN_PARAMS.image,
+ // The equipped cosmetic loadout (R23), carried in from the player's account /
+ // the cross-world mirror so peers see their fit on arrival.
+ cosmetics: getPlayCosmetics(),
// Publish account presence (Task 15) so friends see this player online in
// this coin world, and so DMs can deliver here live. No-op when signed out.
getPresence: getPresenceTicket,
@@ -2268,7 +2310,7 @@ function startNet() {
remotePlayers.set(sessionId, new RemotePlayer(sessionId, {
x: player.x, y: player.y, z: player.z, yaw: player.yaw,
motion: player.motion, name: player.name, color: player.color,
- avatar: player.avatar, agent: player.agent,
+ avatar: player.avatar, agent: player.agent, cosmetics: player.cosmetics,
}));
renderOnlineCount();
});
diff --git a/tests/cosmetics-purchase.test.js b/tests/cosmetics-purchase.test.js
index 0925e1825..985dc7c0a 100644
--- a/tests/cosmetics-purchase.test.js
+++ b/tests/cosmetics-purchase.test.js
@@ -81,8 +81,10 @@ async function loadOwnership({ withRedis }) {
}
describe('cosmetics ownership ledger', () => {
+ // Each scenario re-imports the module fresh (resetModules) with its own
+ // @upstash/redis doMock, so no cross-test mock leakage.
beforeEach(() => { vi.resetModules(); });
- afterEach(() => { vi.unmock('@upstash/redis'); vi.resetModules(); });
+ afterEach(() => { vi.resetModules(); });
it('normalizeAccountId accepts wallets + guest ids, rejects junk', async () => {
const { normalizeAccountId } = await loadOwnership({ withRedis: false });
@@ -145,9 +147,11 @@ async function call(query) {
describe('cosmetic-purchase endpoint boundary', () => {
beforeEach(() => {
- // Minimal x402 config so the 402 challenge can build a Solana accept.
+ // Minimal x402 config so the 402 challenge can build a Solana accept — the
+ // Solana leg needs both a payout address and a co-signing fee payer.
process.env.X402_PAY_TO_SOLANA = 'BUrwd1nK6tFeeJMyzRHDo6AuVbnSfUULfvwq21X93nSN';
process.env.X402_ASSET_MINT_SOLANA = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+ process.env.X402_FEE_PAYER_SOLANA = 'BUrwd1nK6tFeeJMyzRHDo6AuVbnSfUULfvwq21X93nSN';
});
it('rejects missing id / account', async () => {
@@ -159,7 +163,7 @@ describe('cosmetic-purchase endpoint boundary', () => {
expect((await call({ id: 'nope', account: 'guest-1' })).status).toBe(404);
const free = await call({ id: 'hat-baseball', account: 'guest-1' });
expect(free.status).toBe(400);
- expect(free.parsed.code).toBe('not_purchasable');
+ expect(free.parsed.error).toBe('not_purchasable');
});
it('issues a 402 priced in USDC for a premium cosmetic', async () => {
diff --git a/vercel.json b/vercel.json
index c99968288..abe5b0469 100644
--- a/vercel.json
+++ b/vercel.json
@@ -11,6 +11,10 @@
"includeFiles": "examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json",
"maxDuration": 300
},
+ "api/feed-stream.js": {
+ "includeFiles": "examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json",
+ "maxDuration": 300
+ },
"api/avatars/[id].js": {
"includeFiles": "examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json",
"maxDuration": 300