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(play): holder-gated Holders worlds for Coin Communities

overstepping71dd5a26c69a
diff --git a/api/_lib/holder-pass.js b/api/_lib/holder-pass.js
new file mode 100644
index 000000000..553c3bd94
--- /dev/null
+++ b/api/_lib/holder-pass.js
@@ -0,0 +1,72 @@
+// Holder pass — a short-lived, HMAC-signed token proving a CoinCommunities user
+// holds at least HOLDER_MIN_USD worth of a specific coin.
+//
+// Why this exists: the multiplayer server (a standalone Colyseus process) gates
+// entry into a coin's *holder world* but has no Solana RPC or price feed of its
+// own. So the on-chain truth is computed once, here on the Vercel side
+// (api/community/holder-pass.js reads the user's linked wallet and prices its
+// balance), and the result is sealed into a compact token the game server can
+// verify with nothing but a shared secret. The wallet is taken from the
+// authenticated CoinCommunities session — never the client — so a pass can't be
+// minted for someone else's wallet.
+//
+// Format: base64url(JSON(payload)) + '.' + base64url(HMAC-SHA256(body)).
+// Payload: { mint, wallet, usd, tier:'holders', iat, exp }. Verification lives
+// in multiplayer/src/holder-pass.js, byte-for-byte compatible with sign() here.
+
+import crypto from 'node:crypto';
+
+// The USD floor a wallet must clear to enter a coin's holder world. One knob,
+// shared by the issuer (here) and surfaced to the client so the gate UI can
+// state the exact requirement.
+export const HOLDER_MIN_USD = Number(process.env.HOLDER_MIN_USD) || 8;
+
+// Lifetime of an issued pass. Long enough to finish loading into a world after
+// the check, short enough that a sold-off wallet can't linger on an old pass.
+const PASS_TTL_S = 10 * 60;
+
+// Dev fallback keeps the gate working end-to-end on a laptop with no env set;
+// production MUST set HOLDER_PASS_SECRET (warned below) or the gate is bypassable
+// by anyone who reads this source.
+const DEV_SECRET = 'three-ws-holder-pass-dev-secret';
+
+let _warned = false;
+function secret() {
+ const s = process.env.HOLDER_PASS_SECRET;
+ if (s) return s;
+ if (!_warned) {
+ _warned = true;
+ console.warn(
+ '[holder-pass] HOLDER_PASS_SECRET is not set — using the insecure dev secret. ' +
+ 'Set HOLDER_PASS_SECRET in production or the holder gate can be forged.',
+ );
+ }
+ return DEV_SECRET;
+}
+
+function b64url(buf) {
+ return Buffer.from(buf).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
+}
+
+function hmac(body) {
+ return b64url(crypto.createHmac('sha256', secret()).update(body).digest());
+}
+
+/**
+ * Seal a verified holding into a signed pass.
+ * @param {{ mint: string, wallet: string, usd: number }} claims
+ * @returns {string} the compact pass token
+ */
+export function signHolderPass({ mint, wallet, usd }) {
+ const now = Math.floor(Date.now() / 1000);
+ const payload = {
+ mint,
+ wallet,
+ usd: Math.round((Number(usd) || 0) * 100) / 100,
+ tier: 'holders',
+ iat: now,
+ exp: now + PASS_TTL_S,
+ };
+ const body = b64url(JSON.stringify(payload));
+ return `${body}.${hmac(body)}`;
+}
diff --git a/api/community/holder-pass.js b/api/community/holder-pass.js
new file mode 100644
index 000000000..7efe6dde1
--- /dev/null
+++ b/api/community/holder-pass.js
@@ -0,0 +1,91 @@
+// POST /api/community/holder-pass?token=<mint>
+//
+// Mints a holder pass — proof a signed-in user holds at least HOLDER_MIN_USD of
+// a coin — so the multiplayer server can admit them into that coin's gated
+// Holders world without running Solana RPC itself.
+//
+// The check is on the user's *authenticated* wallet: we read the linked Solana
+// wallet from their CoinCommunities session server-side, price its on-chain
+// balance of this exact mint (Helius DAS + Jupiter, via the shared balances
+// lib), and only then sign a pass. The browser never supplies the wallet, so a
+// pass can't be minted against someone else's address.
+//
+// Responses (always 200 unless the request itself is bad):
+// { eligible: true, usd, amount, minUsd, wallet, holderPass } — admit
+// { eligible: false, usd, amount, minUsd, wallet } — short; UI
+// shows buy CTA
+// Auth/wallet problems are real errors the gate UI routes on:
+// 401 auth_required — not signed in to CoinCommunities
+// 403 wallet_required — signed in but no linked Solana wallet
+import { cors, error, json, method, wrap } from '../_lib/http.js';
+import { clientIp, limits } from '../_lib/rate-limit.js';
+import { cc, userAuthHeaders, isValidToken, UnconfiguredError } from '../_lib/coin-communities.js';
+import { getBalances } from '../_lib/balances.js';
+import { HOLDER_MIN_USD, signHolderPass } from '../_lib/holder-pass.js';
+
+const SOL_MINT = 'So11111111111111111111111111111111111111112';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+ res.setHeader('cache-control', 'no-store');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const token = new URL(req.url, 'http://x').searchParams.get('token');
+ if (!isValidToken(token)) {
+ return error(res, 400, 'validation_error', 'valid token query param required');
+ }
+
+ const headers = userAuthHeaders(req);
+ if (!headers) {
+ return error(res, 401, 'auth_required', 'sign in with X to enter a holder world');
+ }
+
+ let api;
+ try {
+ api = cc();
+ } catch (err) {
+ if (err instanceof UnconfiguredError) {
+ return error(res, 503, 'cc_unconfigured', 'CoinCommunities is not configured');
+ }
+ throw err;
+ }
+
+ // The wallet is taken from the authenticated session — never the request body.
+ const w = await api.getWallets({ headers });
+ if (w.error) {
+ if (w.error.statusCode === 401) {
+ return error(res, 401, 'auth_required', 'session expired — sign in again');
+ }
+ return error(res, 502, 'upstream_error', w.error.message || 'failed to read wallets');
+ }
+ const wallet = (w.data?.wallets ?? []).find((x) => x.chainType === 'svm')?.address || null;
+ if (!wallet) {
+ return error(res, 403, 'wallet_required', 'link a Solana wallet to verify your holdings');
+ }
+
+ // Price the wallet's on-chain holding of this exact coin.
+ let balances;
+ try {
+ balances = await getBalances({ chain: 'solana', address: wallet });
+ } catch (err) {
+ const status = err?.status === 503 ? 503 : 502;
+ return error(res, status, 'balance_unavailable', err?.message || 'could not read on-chain balance');
+ }
+
+ const holding =
+ token === SOL_MINT
+ ? balances?.native
+ : (balances?.tokens ?? []).find((t) => t.mint === token);
+ const usd = Math.round((holding?.usd || 0) * 100) / 100;
+ const amount = holding?.amount || 0;
+ const minUsd = HOLDER_MIN_USD;
+
+ if (usd >= minUsd) {
+ const holderPass = signHolderPass({ mint: token, wallet, usd });
+ return json(res, 200, { data: { eligible: true, usd, amount, minUsd, wallet, holderPass } });
+ }
+ return json(res, 200, { data: { eligible: false, usd, amount, minUsd, wallet } });
+});
diff --git a/multiplayer/src/holder-pass.js b/multiplayer/src/holder-pass.js
new file mode 100644
index 000000000..9d0a553c1
--- /dev/null
+++ b/multiplayer/src/holder-pass.js
@@ -0,0 +1,69 @@
+// Holder pass verification — the game-server half of holder-gated worlds.
+//
+// The Vercel API (api/_lib/holder-pass.js) prices a user's on-chain holding and
+// seals { mint, wallet, usd, tier, iat, exp } into an HMAC-SHA256 token. This
+// process re-derives the signature with the same shared secret and checks it,
+// so WalkRoom.onAuth can admit a client into a coin's holder world without ever
+// touching Solana RPC or a price feed. Keep this byte-for-byte compatible with
+// the signer.
+
+import crypto from 'node:crypto';
+
+const DEV_SECRET = 'three-ws-holder-pass-dev-secret';
+
+let _warned = false;
+function secret() {
+ const s = process.env.HOLDER_PASS_SECRET;
+ if (s) return s;
+ if (!_warned) {
+ _warned = true;
+ console.warn(
+ '[holder-pass] HOLDER_PASS_SECRET is not set — using the insecure dev secret. ' +
+ 'Set HOLDER_PASS_SECRET in production or holder worlds can be entered with a forged pass.',
+ );
+ }
+ return DEV_SECRET;
+}
+
+function b64url(buf) {
+ return Buffer.from(buf).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
+}
+
+function hmac(body) {
+ return b64url(crypto.createHmac('sha256', secret()).update(body).digest());
+}
+
+// Constant-time compare so a forged token can't be brute-forced byte by byte.
+function safeEqual(a, b) {
+ const ba = Buffer.from(a);
+ const bb = Buffer.from(b);
+ if (ba.length !== bb.length) return false;
+ return crypto.timingSafeEqual(ba, bb);
+}
+
+/**
+ * Verify a holder pass and return its payload, or null if the token is missing,
+ * malformed, tampered with, or expired.
+ * @param {unknown} token
+ * @returns {{ mint: string, wallet: string, usd: number, tier: string, iat: number, exp: number } | null}
+ */
+export function verifyHolderPass(token) {
+ if (typeof token !== 'string' || token.length < 16 || token.length > 4096) return null;
+ const dot = token.indexOf('.');
+ if (dot <= 0) return null;
+ const body = token.slice(0, dot);
+ const sig = token.slice(dot + 1);
+ if (!safeEqual(sig, hmac(body))) return null;
+
+ let payload;
+ try {
+ payload = JSON.parse(Buffer.from(body.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'));
+ } catch {
+ return null;
+ }
+ if (!payload || typeof payload !== 'object') return null;
+ if (payload.tier !== 'holders') return null;
+ if (typeof payload.exp !== 'number' || payload.exp * 1000 < Date.now()) return null;
+ if (typeof payload.mint !== 'string') return null;
+ return payload;
+}
diff --git a/multiplayer/src/index.js b/multiplayer/src/index.js
index a2557622f..c4af3c909 100644
--- a/multiplayer/src/index.js
+++ b/multiplayer/src/index.js
@@ -116,11 +116,13 @@ if (REDIS_URI) {
}
const gameServer = new Server({ transport, ...(driver && { driver }), ...(presence && { presence }) });
-// Each coin is its own world: filterBy(['coin']) makes joinOrCreate match only
-// rooms sharing the same community coin (mint), so players of the same coin land
-// together while different coins stay isolated. A missing coin resolves to the
-// shared mainland world (see WalkRoom.onCreate / schemas.js).
-gameServer.define('walk_world', WalkRoom).filterBy(['coin']);
+// Each coin is its own world, split by access tier: filterBy(['coin','tier'])
+// makes joinOrCreate match only rooms sharing the same community coin (mint) AND
+// the same tier, so a coin's open General world and its gated Holders world are
+// separate instances, and different coins stay isolated. A missing coin resolves
+// to the shared mainland world; a missing tier is the open General world (see
+// WalkRoom.onCreate / onAuth / schemas.js).
+gameServer.define('walk_world', WalkRoom).filterBy(['coin', 'tier']);
gameServer.define('game_mainland', GameRoom);
gameServer
diff --git a/multiplayer/src/rooms/WalkRoom.js b/multiplayer/src/rooms/WalkRoom.js
index e017a8a97..5e350131d 100644
Binary files a/multiplayer/src/rooms/WalkRoom.js and b/multiplayer/src/rooms/WalkRoom.js differ
diff --git a/multiplayer/src/schemas.js b/multiplayer/src/schemas.js
index 7e1f72ce3..68f408e79 100644
--- a/multiplayer/src/schemas.js
+++ b/multiplayer/src/schemas.js
@@ -73,6 +73,12 @@ export class WalkState extends Schema {
this.coinName = '';
this.coinSymbol = '';
this.coinImage = '';
+ // Access tier for this instance. '' = the open General world anyone can
+ // enter; 'holders' = a gated world only wallets holding ≥ holderMinUsd of
+ // `coin` can join (enforced in WalkRoom.onAuth). The same coin therefore has
+ // two isolated rooms — General and Holders — kept apart by filterBy.
+ this.tier = '';
+ this.holderMinUsd = 0; // USD floor for the holder world (0 in General)
// Collaborative voxel builds for this coin's world. Keyed by packed grid
// coordinate; the value carries only the block type. Persisted per coin so
// a community's build survives the room emptying and the server restarting.
@@ -85,5 +91,7 @@ defineTypes(WalkState, {
coinName: 'string',
coinSymbol: 'string',
coinImage: 'string',
+ tier: 'string',
+ holderMinUsd: 'float32',
blocks: { map: Block },
});
diff --git a/package-lock.json b/package-lock.json
index dadf95307..b5b387897 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1241,6 +1241,8 @@
"@bonfida/spl-name-service": "^0.1.67",
"@colyseus/core": "^0.16.24",
"@colyseus/monitor": "^0.16.7",
+ "@colyseus/redis-driver": "^0.16.0",
+ "@colyseus/redis-presence": "^0.16.0",
"@colyseus/schema": "^3.0.0",
"@colyseus/ws-transport": "^0.16.5",
"@ethereum-attestation-service/eas-sdk": "0.29.1",
@@ -1248,8 +1250,8 @@
"@pump-fun/pump-sdk": "1.1.0",
"@solana/actions": "0.0.2",
"@solana/pay": "1.0.16",
+ "@upstash/redis": "^1.38.0",
"agent0-sdk": "^1.7.1",
- "colyseus": "^0.16.5",
"ethers": "^6.16.0",
"express": "^4.21.2",
"livepeer": "3.2.4",
@@ -1304,6 +1306,26 @@
"node-os-utils": "^1.2.0"
}
},
+ "multiplayer/node_modules/@colyseus/redis-driver": {
+ "version": "0.16.1",
+ "resolved": "https://registry.npmjs.org/@colyseus/redis-driver/-/redis-driver-0.16.1.tgz",
+ "integrity": "sha512-dFDyyVEBemfdeHrO2fTt86803fV8iMepGi6UHD7feR7vQO9bdN6yXpAyrBWMJrfBs8EFuEEb73gM3mDUjppH/A==",
+ "license": "MIT",
+ "dependencies": {
+ "@colyseus/core": "^0.16.4",
+ "ioredis": "^5.3.2"
+ }
+ },
+ "multiplayer/node_modules/@colyseus/redis-presence": {
+ "version": "0.16.4",
+ "resolved": "https://registry.npmjs.org/@colyseus/redis-presence/-/redis-presence-0.16.4.tgz",
+ "integrity": "sha512-dROj2T6eqxsquGQQuwqWuBjDDNHj33KKyltWiUMP/dFyPYVG6fFZl+IbHDo3rmRB1RdmjwtEYt9/Bz/Bsszvxw==",
+ "license": "MIT",
+ "dependencies": {
+ "@colyseus/core": "^0.16.19",
+ "ioredis": "^5.3.2"
+ }
+ },
"multiplayer/node_modules/@colyseus/timer": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/@colyseus/timer/-/timer-1.0.3.tgz",
@@ -1373,24 +1395,6 @@
"@types/node": "*"
}
},
- "multiplayer/node_modules/colyseus": {
- "version": "0.16.5",
- "resolved": "https://registry.npmjs.org/colyseus/-/colyseus-0.16.5.tgz",
- "integrity": "sha512-Ki3516JZnyJ997/FRgECMUqPLig5LSYOEw54whKfA+fBUVfsTPSzZb/sppOd+MR3LnM59P+c+v2TBEreRgAkYA==",
- "license": "MIT",
- "engines": {
- "node": ">= 20.x"
- },
- "peerDependencies": {
- "@colyseus/auth": "0.16.x",
- "@colyseus/core": "0.16.x",
- "@colyseus/redis-driver": "0.16.x",
- "@colyseus/redis-presence": "0.16.x",
- "@colyseus/schema": "^3.0.0",
- "@colyseus/uwebsockets-transport": "0.16.x",
- "@colyseus/ws-transport": "0.16.x"
- }
- },
"multiplayer/node_modules/nanoid": {
"version": "2.1.11",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-2.1.11.tgz",
diff --git a/public/features.json b/public/features.json
index 3350eb4c6..08d7c89ed 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-05-30T13:43:55.117Z",
+ "generated_at": "2026-05-30T22:23:53.531Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/src/community/town-auth.js b/src/community/town-auth.js
index 71bf08b8e..b92c38771 100644
--- a/src/community/town-auth.js
+++ b/src/community/town-auth.js
@@ -120,6 +120,19 @@ export async function ensureSolanaWallet(session) {
return linked?.address || address;
}
+/**
+ * Ask the server whether the signed-in user holds enough of `mint` to enter its
+ * Holders world, and if so mint a holder pass for the game server.
+ *
+ * Resolves to { eligible, usd, amount, minUsd, wallet, holderPass? } — the pass
+ * is present only when eligible. Rejects with a coded error when the user can't
+ * be checked yet: `auth_required` (not signed in) or `wallet_required` (no
+ * linked Solana wallet) — the gate UI routes on err.code to recover.
+ */
+export function requestHolderPass(mint) {
+ return json(`/holder-pass?token=${encodeURIComponent(mint)}`, { method: 'POST' });
+}
+
/** Post content to a coin world as the signed-in user from their linked wallet. */
export function postAsUser(token, content, walletAddress) {
return json(`/messages?token=${encodeURIComponent(token)}`, {
diff --git a/src/game/coincommunities-ui.js b/src/game/coincommunities-ui.js
index 3454a8991..838742193 100644
--- a/src/game/coincommunities-ui.js
+++ b/src/game/coincommunities-ui.js
@@ -558,17 +558,27 @@ export class CommunityUI {
// OFFICIAL badge, and a "home town" call to action so it reads as the flagship.
_coinCard(c, featured) {
const mc = fmtMc(c.marketCap);
+ const sym = c.symbol ? '$' + c.symbol.toUpperCase().replace(/^\$/, '') : 'this coin';
const liveBadge = featured
? el('span', { class: 'cc-card-official', title: 'Official three.ws town' }, [
el('span', { class: 'cc-card-official-ico', text: '◇' }),
document.createTextNode('OFFICIAL'),
])
: el('span', { class: 'cc-card-live' }, [el('span', { class: 'cc-dot' }), document.createTextNode('LIVE')]);
+ // Every coin has two worlds: the open General room (the card body) and a
+ // gated Holders room. The badge is always visible so the holders' world is
+ // 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`,
+ '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')]);
return el('div', {
class: 'cc-card' + (featured ? ' cc-card-featured' : ''),
- onclick: () => this.h.onEnter(c),
+ onclick: () => this.h.onEnter(c, ''),
}, [
- el('div', { class: 'cc-card-img', style: c.image ? `background-image:url("${c.image}")` : '' }, [liveBadge]),
+ el('div', { class: 'cc-card-img', style: c.image ? `background-image:url("${c.image}")` : '' }, [liveBadge, holdersBadge]),
el('div', { class: 'cc-card-body' }, [
el('div', { class: 'cc-card-name', text: c.name || 'Unnamed coin' }),
el('div', { class: 'cc-card-meta' }, [
@@ -587,12 +597,133 @@ export class CommunityUI {
]));
}
+ // ---------------------------------------------------------------- holder gate
+ // A coin's Holders world is gated: the player must prove they hold ≥ the floor
+ // (default $8) of the coin. This overlay is a thin view over the scene's gate
+ // state machine (coincommunities.js _passHolderGate) — the scene drives us
+ // through setHolderGate(state, data) and we report the player's choice back via
+ // onHolderAction(action): 'signin' | 'wallet' | 'buy' | 'recheck' | 'cancel'.
+ openHolderGate(coin) {
+ if (this._gate) return; // already open — the scene re-uses it across states
+ this._gateBody = el('div', { class: 'cc-gate-body' });
+ const modal = el('div', {
+ class: 'cc-gate-modal', role: 'dialog', 'aria-modal': 'true', 'aria-label': 'Holder verification',
+ }, [
+ el('div', { class: 'cc-gate-head' }, [
+ el('span', { class: 'cc-gate-tag', text: '🔒 Holders only' }),
+ el('button', {
+ type: 'button', class: 'cc-gate-x', 'aria-label': 'Cancel', text: '×',
+ onclick: () => this.h.onHolderAction?.('cancel'),
+ }),
+ ]),
+ this._gateBody,
+ ]);
+ // Backdrop click and Escape both read as "I don't want in" → cancel, which
+ // drops the player back to the lobby (free to enter the open world instead).
+ const overlay = el('div', {
+ class: 'cc-gate-overlay',
+ onclick: (e) => { if (e.target === overlay) this.h.onHolderAction?.('cancel'); },
+ }, [modal]);
+ this._gate = overlay;
+ this._gateKey = (e) => { if (e.key === 'Escape') { e.stopPropagation(); this.h.onHolderAction?.('cancel'); } };
+ document.addEventListener('keydown', this._gateKey, true);
+ document.body.appendChild(overlay);
+ requestAnimationFrame(() => overlay.classList.add('cc-on'));
+ }
+
+ closeHolderGate() {
+ const o = this._gate;
+ if (!o) return;
+ this._gate = null;
+ this._gateBody = null;
+ if (this._gateKey) { document.removeEventListener('keydown', this._gateKey, true); this._gateKey = null; }
+ o.classList.remove('cc-on');
+ const done = () => o.remove();
+ o.addEventListener('transitionend', done, { once: true });
+ setTimeout(done, 280); // fallback if transitionend never fires
+ }
+
+ setHolderGate(state, data = {}) {
+ if (!this._gate) this.openHolderGate(data);
+ const body = this._gateBody;
+ if (!body) return;
+ const sym = data.symbol ? '$' + String(data.symbol).replace(/^\$/, '').toUpperCase() : 'this coin';
+ const round2 = (n) => Math.round((Number(n) || 0) * 100) / 100;
+ const min = '$' + (data.minUsd ? round2(data.minUsd) : 8);
+ const usd = '$' + round2(data.usd);
+ const btn = (label, action, variant = '') => el('button', {
+ type: 'button', class: 'cc-gate-btn' + (variant ? ' ' + variant : ''),
+ onclick: () => this.h.onHolderAction?.(action),
+ }, [label]);
+ const spin = () => el('div', { class: 'cc-gate-spin' }, [el('span', { class: 'cc-spinner cc-spinner-lg' })]);
+ const title = (t) => el('h3', { class: 'cc-gate-title', text: t });
+ const msg = (t) => el('p', { class: 'cc-gate-msg', text: t });
+ const errLine = data.error ? el('p', { class: 'cc-gate-err', text: data.error }) : null;
+ const actions = (...kids) => el('div', { class: 'cc-gate-actions' }, kids.filter(Boolean));
+
+ let nodes;
+ switch (state) {
+ case 'checking':
+ nodes = [spin(), title('Checking your holdings'), msg(`Pricing your ${sym} balance on-chain…`)];
+ break;
+ case 'working':
+ nodes = [spin(), title('One moment'), msg(data.msg || 'Working…')];
+ break;
+ case 'granted':
+ nodes = [el('div', { class: 'cc-gate-check', text: '✓' }), title('You’re in'), msg(`Verified ${usd} of ${sym}. Welcome to the holders’ world.`)];
+ break;
+ case 'short':
+ nodes = [
+ el('div', { class: 'cc-gate-lock', text: '🔒' }),
+ title('Holders only'),
+ msg(`You hold ${usd} of ${sym}. This world is for holders of ${min} or more.`),
+ actions(
+ btn(`Buy ${sym}`, 'buy', 'cc-gate-primary'),
+ btn('I bought — re-check', 'recheck'),
+ btn('Enter the open world instead', 'cancel', 'cc-gate-ghost'),
+ ),
+ ];
+ break;
+ case 'auth':
+ nodes = [
+ el('div', { class: 'cc-gate-lock', text: '𝕏' }),
+ title('Verify you’re a holder'),
+ msg(`Sign in with X so we can check the wallet you hold ${sym} in. Your wallet is read server-side and never shared.`),
+ errLine,
+ actions(btn('Sign in with X', 'signin', 'cc-gate-primary'), btn('Cancel', 'cancel', 'cc-gate-ghost')),
+ ];
+ break;
+ case 'wallet':
+ nodes = [
+ el('div', { class: 'cc-gate-lock', text: '◎' }),
+ title('Link your Solana wallet'),
+ msg(`Connect the wallet that holds ${sym} and sign a message to link it. No transaction, no fee.`),
+ errLine,
+ actions(btn('Connect wallet', 'wallet', 'cc-gate-primary'), btn('Cancel', 'cancel', 'cc-gate-ghost')),
+ ];
+ break;
+ case 'error':
+ default:
+ nodes = [
+ el('div', { class: 'cc-gate-lock', text: '!' }),
+ title('Couldn’t verify'),
+ msg(data.error || 'Something went wrong checking your holdings.'),
+ actions(btn('Try again', 'recheck', 'cc-gate-primary'), btn('Cancel', 'cancel', 'cc-gate-ghost')),
+ ];
+ break;
+ }
+ body.replaceChildren(...nodes.filter(Boolean));
+ }
+
// ---------------------------------------------------------------- HUD
_buildHud() {
this.coinImg = el('img', { class: 'cc-coin-img', alt: '' });
this.coinName = el('div', { class: 'cc-coin-name', text: '' });
this.coinSym = el('span', { class: 'cc-coin-sym', text: '' });
this.onlineCount = el('span', { text: '1 online' });
+ // Marks the gated Holders world so the player always knows which room they're
+ // in and the floor they cleared. Hidden in the open General world.
+ this.tierBadge = el('span', { class: 'cc-tier-badge', hidden: true });
// Buy this coin from inside its own world — the most natural action in a
// pump.fun community. Opens the native on-chain buy modal (lazy chunk).
this.buyBtnLabel = el('span', { class: 'cc-buy-btn-text', text: 'Buy' });
@@ -607,6 +738,7 @@ export class CommunityUI {
el('div', { class: 'cc-coin-sub' }, [
this.coinSym,
el('span', { class: 'cc-online' }, [el('span', { class: 'cc-dot' }), this.onlineCount]),
+ this.tierBadge,
]),
]),
this.buyBtn,
@@ -733,6 +865,9 @@ 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';
+ const holders = coin.tier === 'holders';
+ this.tierBadge.hidden = !holders;
+ this.tierBadge.textContent = holders ? `🔒 Holders · $${coin.holderMinUsd ? Math.round(coin.holderMinUsd * 100) / 100 : 8}+` : '';
this.chatLog.textContent = '';
this._unread = 0;
this.chatUnread.hidden = true;
diff --git a/src/game/coincommunities.css b/src/game/coincommunities.css
index aadb733e2..10b9bc54b 100644
--- a/src/game/coincommunities.css
+++ b/src/game/coincommunities.css
@@ -354,6 +354,83 @@ html, body {
.cc-create-card-ico { width: 36px; height: 36px; font-size: 17px; }
}
+/* Holders world entry — a persistent badge on each coin card, top-right opposite
+ the LIVE/OFFICIAL badge. Always visible so the gated room is discoverable on
+ touch (where the hover CTA never appears). */
+.cc-card-holders {
+ position: absolute; top: 9px; right: 9px; z-index: 2; cursor: pointer; font: inherit;
+ display: inline-flex; align-items: center; gap: 5px;
+ background: rgba(0, 0, 0, 0.6); border: 1px solid var(--cc-edge); border-radius: var(--cc-radius-sm);
+ padding: 3px 9px; color: var(--cc-text);
+ font-size: 10px; font-weight: 700; letter-spacing: 0.1em; text-transform: uppercase;
+ transition: border-color 0.14s ease, background 0.14s ease, color 0.14s ease;
+}
+.cc-card-holders:hover { border-color: var(--cc-edge-hi); background: #fff; color: var(--cc-ink); }
+.cc-card-holders:focus-visible { outline: none; border-color: #fff; box-shadow: 0 0 0 1px #fff; }
+.cc-card-holders-ico { font-size: 10px; line-height: 1; }
+.cc-card-featured .cc-card-holders { top: 12px; right: 12px; }
+
+/* In-world tier badge in the coin banner — present only in the Holders world. */
+.cc-tier-badge {
+ display: inline-flex; align-items: center; gap: 5px;
+ background: #fff; color: var(--cc-ink); border-radius: var(--cc-radius-sm);
+ padding: 2px 8px; font-size: 10px; font-weight: 800; letter-spacing: 0.08em; text-transform: uppercase;
+ white-space: nowrap; box-shadow: var(--cc-glow);
+}
+
+/* Holder gate overlay — mirrors the create modal's chrome + motion. The scene
+ drives its states (checking / working / granted / short / auth / wallet / error)
+ via setHolderGate(); buttons report back through onHolderAction(). */
+.cc-gate-overlay {
+ position: fixed; inset: 0; z-index: 95; display: grid; place-items: center; padding: 20px;
+ background: rgba(4, 4, 5, 0.8); backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px);
+ opacity: 0; transition: opacity 0.2s ease;
+}
+.cc-gate-overlay.cc-on { opacity: 1; }
+.cc-gate-modal {
+ width: min(420px, 100%); background: var(--cc-panel-solid);
+ border: 1px solid var(--cc-edge); border-radius: var(--cc-radius); box-shadow: var(--cc-shadow);
+ padding: 18px 22px 22px;
+ transform: translateY(10px) scale(0.99); transition: transform 0.22s cubic-bezier(0.2, 0.7, 0.2, 1);
+}
+.cc-gate-overlay.cc-on .cc-gate-modal { transform: none; }
+.cc-gate-head { display: flex; align-items: center; justify-content: space-between; gap: 16px; }
+.cc-gate-tag { font-size: 10px; font-weight: 800; letter-spacing: 0.14em; text-transform: uppercase; color: var(--cc-dim); }
+.cc-gate-x {
+ flex: none; width: 30px; height: 30px; border-radius: var(--cc-radius-sm); cursor: pointer;
+ background: var(--cc-bg2); border: 1px solid var(--cc-edge); color: var(--cc-dim); font-size: 19px; line-height: 1;
+ transition: border-color 0.15s ease, color 0.15s ease, background 0.15s ease;
+}
+.cc-gate-x:hover { color: var(--cc-text); border-color: var(--cc-edge-hi); background: var(--cc-bg3); }
+.cc-gate-x:focus-visible { outline: none; border-color: var(--cc-edge-hi); box-shadow: 0 0 0 1px var(--cc-edge-hi); }
+.cc-gate-body { display: flex; flex-direction: column; align-items: center; text-align: center; gap: 8px; padding: 10px 0 2px; }
+.cc-gate-spin { padding: 12px 0 6px; }
+.cc-gate-check, .cc-gate-lock {
+ width: 48px; height: 48px; border-radius: 50%; display: grid; place-items: center;
+ font-size: 22px; line-height: 1; border: 1px solid var(--cc-edge); background: var(--cc-bg2);
+}
+.cc-gate-check { background: #fff; color: var(--cc-ink); border-color: #fff; box-shadow: var(--cc-glow); }
+.cc-gate-title { margin: 4px 0 0; font-size: 18px; font-weight: 700; letter-spacing: 0.01em; }
+.cc-gate-msg { margin: 0; color: var(--cc-dim); font-size: 13px; line-height: 1.5; max-width: 34ch; }
+.cc-gate-err { margin: 2px 0 0; color: var(--cc-text); font-size: 12px; line-height: 1.45; max-width: 34ch; opacity: 0.85; }
+.cc-gate-actions { display: flex; flex-direction: column; gap: 8px; width: 100%; margin-top: 16px; }
+.cc-gate-btn {
+ width: 100%; padding: 11px 14px; border-radius: var(--cc-radius-sm); cursor: pointer; font: inherit;
+ font-weight: 700; font-size: 13px; letter-spacing: 0.03em;
+ background: var(--cc-bg2); border: 1px solid var(--cc-edge); color: var(--cc-text);
+ transition: border-color 0.14s ease, background 0.14s ease, filter 0.12s ease, transform 0.1s ease;
+}
+.cc-gate-btn:hover { border-color: var(--cc-edge-hi); background: var(--cc-bg3); }
+.cc-gate-btn:active { transform: translateY(1px); }
+.cc-gate-btn:focus-visible { outline: none; border-color: #fff; box-shadow: 0 0 0 1px #fff; }
+.cc-gate-primary { background: #fff; color: var(--cc-ink); border-color: #fff; }
+.cc-gate-primary:hover { background: #fff; filter: brightness(0.92); }
+.cc-gate-ghost { background: none; border-color: transparent; color: var(--cc-dim); font-weight: 600; }
+.cc-gate-ghost:hover { background: var(--cc-bg2); color: var(--cc-text); border-color: var(--cc-edge); }
+@media (prefers-reduced-motion: reduce) {
+ .cc-gate-overlay, .cc-gate-modal { transition: none; }
+}
+
/* In-app avatar creator iframe modal (AvatarCreator). Self-contained here so the
builder/photo editor renders correctly on /play without the main-site stylesheet. */
.avatar-creator-overlay {
diff --git a/src/game/coincommunities.js b/src/game/coincommunities.js
index 69f87a953..c309df180 100644
--- a/src/game/coincommunities.js
+++ b/src/game/coincommunities.js
@@ -34,6 +34,7 @@ import {
import { GUEST_SENTINEL, uploadPendingGuestAvatar } from './play-handoff.js';
import { HOME_TOWN, isHomeTown } from './home-town.js';
import { VoiceChat, voiceSupported } from './voice-chat.js';
+import { requestHolderPass, signInWithX, ensureSolanaWallet, getSession } from '../community/town-auth.js';
const WORLD_RADIUS = 58; // a touch inside the server's 60m clamp
const MOVE_SPEED = 4.2;
@@ -182,7 +183,10 @@ export class CoinCommunities {
this._initScene();
this.ui = new CommunityUI({
- onEnter: (coin) => this.enter(coin),
+ onEnter: (coin, tier) => this.enter(coin, { tier }),
+ // Holder gate overlay → the scene's gate state machine resolves on each
+ // action (sign in, link wallet, buy, recheck, cancel).
+ onHolderAction: (action) => { const r = this._holderGateResolve; this._holderGateResolve = null; r?.(action); },
onLeave: () => this.leave(),
onChat: (t) => this._sendChat(t),
onEmote: (n) => this._emote(n),
@@ -224,7 +228,8 @@ export class CoinCommunities {
const p = new URLSearchParams(location.search);
const mint = p.get('coin');
if (mint) {
- this.enter({ mint, name: p.get('name') || '', symbol: p.get('symbol') || '', image: normalizeGatewayURL(p.get('image') || '') });
+ const tier = p.get('tier') === 'holders' ? 'holders' : 'general';
+ this.enter({ mint, name: p.get('name') || '', symbol: p.get('symbol') || '', image: normalizeGatewayURL(p.get('image') || '') }, { tier });
}
}
@@ -515,8 +520,23 @@ export class CoinCommunities {
}
// ---------------------------------------------------------------- enter/leave
- async enter(coin) {
+ async enter(coin, opts = {}) {
if (this.phase !== 'lobby') return;
+ const tier = opts.tier === 'holders' ? 'holders' : 'general';
+
+ // Holder worlds are gated: prove the player holds ≥ the floor of this coin
+ // before we build anything. The gate runs entirely in the lobby so a refusal
+ // leaves them exactly where they were, free to enter the General world
+ // instead. A null result means they cancelled — stay put.
+ let holderPass = '';
+ let holderMinUsd = 0;
+ if (tier === 'holders') {
+ const pass = await this._passHolderGate(coin);
+ if (!pass) return;
+ holderPass = pass.holderPass;
+ holderMinUsd = pass.minUsd;
+ }
+
this.phase = 'loading';
// A bare deep link (/play?coin=<home mint>) carries no name/art; backfill the
// flagship town's identity so its totem, jumbotron, and HUD are never blank.
@@ -530,14 +550,18 @@ export class CoinCommunities {
official: true,
};
}
+ coin = { ...coin, tier, holderMinUsd };
this.coin = coin;
this.ui.enterWorld(coin);
- // Reflect the community in the URL so it can be shared / refreshed into.
+ document.body.classList.toggle('cc-holders', tier === 'holders');
+ // Reflect the community in the URL so it can be shared / refreshed into. A
+ // holder-world link carries &tier=holders so refreshing re-runs the gate.
try {
const q = new URLSearchParams({ coin: coin.mint });
if (coin.name) q.set('name', coin.name);
if (coin.symbol) q.set('symbol', coin.symbol);
if (coin.image) q.set('image', coin.image);
+ if (tier === 'holders') q.set('tier', 'holders');
history.replaceState(null, '', location.pathname + '?' + q.toString());
} catch { /* non-fatal */ }
await loadManifest();
@@ -618,6 +642,8 @@ export class CoinCommunities {
this.net = new CommunityNet({
name, avatar: netAvatar,
coin: { mint: coin.mint, name: coin.name, symbol: coin.symbol, image: coin.image },
+ tier: tier === 'holders' ? 'holders' : '',
+ holderPass, holderMinUsd,
});
if (isGuest) uploadPendingGuestAvatar((publicUrl) => this.net?.setAvatar(publicUrl));
this.net.on('status', ({ status }) => {
@@ -633,6 +659,13 @@ export class CoinCommunities {
this.net.setVoiceActive(true);
}
});
+ // A holder pass can expire (10 min) between minting and a mid-session
+ // reconnect; if the server then refuses the join, drop the player back to
+ // the lobby with a clear reason rather than looping on a dead pass.
+ this.net.on('denied', () => {
+ this.ui.toast('Your holder pass expired — re-enter to verify your holdings.', 'warn');
+ this.leave();
+ });
this.net.on('add', (p, id) => this._onAdd(p, id));
this.net.on('change', (p, id) => this._onChange(p, id));
this.net.on('remove', (id) => this._onRemove(id));
@@ -648,6 +681,73 @@ export class CoinCommunities {
this._initJoystick();
}
+ // Run the holder gate for a coin's Holders world. Drives the overlay through
+ // its states and resolves to the verified pass data ({ holderPass, minUsd, … })
+ // once the player clears the floor, or null if they back out. All the on-chain
+ // truth is computed server-side (api/community/holder-pass); here we only
+ // orchestrate the sign-in / wallet-link / buy steps a player may need first.
+ async _passHolderGate(coin) {
+ const symbol = coin.symbol || '';
+ this.ui.openHolderGate(coin);
+ let skipCheck = false; // set after 'buy' so we re-show the shortfall, not recheck
+ let carryError = ''; // surfaces a failed sign-in/link on the next state
+ let state = 'checking';
+ let data = { symbol };
+ try {
+ for (;;) {
+ if (!skipCheck) {
+ this.ui.setHolderGate('checking', { symbol });
+ try {
+ const res = await requestHolderPass(coin.mint);
+ if (res?.eligible && res.holderPass) {
+ this.ui.setHolderGate('granted', { symbol, usd: res.usd, minUsd: res.minUsd });
+ // Let the "verified" state land for a beat before the world builds.
+ await new Promise((r) => setTimeout(r, 650));
+ this.ui.closeHolderGate();
+ return res;
+ }
+ state = 'short';
+ data = { symbol, usd: res?.usd ?? 0, amount: res?.amount ?? 0, minUsd: res?.minUsd ?? 8 };
+ } catch (err) {
+ if (err?.code === 'auth_required') { state = 'auth'; data = { symbol, error: carryError }; }
+ else if (err?.code === 'wallet_required') { state = 'wallet'; data = { symbol, error: carryError }; }
+ else { state = 'error'; data = { symbol, error: err?.message || 'Could not verify your holdings.' }; }
+ carryError = '';
+ }
+ }
+ skipCheck = false;
+
+ const action = await this._holderGateWait(state, data);
+ if (action === 'cancel') return null;
+ if (action === 'signin') {
+ this.ui.setHolderGate('working', { symbol, msg: 'Opening X sign-in…' });
+ try { await signInWithX(); } catch (e) { carryError = e?.message || 'Sign-in was cancelled.'; }
+ continue;
+ }
+ if (action === 'wallet') {
+ this.ui.setHolderGate('working', { symbol, msg: 'Connecting your wallet…' });
+ try {
+ const session = await getSession();
+ await ensureSolanaWallet(session);
+ } catch (e) { carryError = e?.message || 'Could not link a wallet.'; }
+ continue;
+ }
+ if (action === 'buy') { this._openBuy(coin); skipCheck = true; continue; }
+ // 'recheck' (or any other) → loop and re-run the on-chain check.
+ }
+ } finally {
+ // Guarantee the overlay never lingers if we bailed via return.
+ if (this.phase === 'lobby') this.ui.closeHolderGate();
+ }
+ }
+
+ // Park the gate on a state and resolve when the player picks an action. The UI
+ // buttons fire onHolderAction → resolves this promise.
+ _holderGateWait(state, data) {
+ this.ui.setHolderGate(state, data);
+ return new Promise((resolve) => { this._holderGateResolve = resolve; });
+ }
+
// Stand up spatial voice for this community. Voice starts OFF (no mic access
// until the player opts in); the mic button drives join/mute through here.
_initVoice() {
@@ -770,11 +870,11 @@ export class CoinCommunities {
// Open the native on-chain buy for the current coin. Lazy-loaded so the
// Solana/pump SDKs never weigh down the main /play bundle.
- async _openBuy() {
- if (!this.coin?.mint) return;
+ async _openBuy(coin = this.coin) {
+ if (!coin?.mint) return;
try {
const { openBuyModal } = await import('./coin-buy.js');
- openBuyModal(this.coin);
+ openBuyModal(coin);
} catch (err) {
console.warn('[coincommunities] buy modal failed to load:', err?.message);
this.ui.toast('Couldn’t open the buy panel. Trade on pump.fun instead.', 'warn');
diff --git a/src/game/community-net.js b/src/game/community-net.js
index c694e8e3c..74c537b90 100644
--- a/src/game/community-net.js
+++ b/src/game/community-net.js
@@ -48,6 +48,9 @@ export class CommunityNet {
* @param {string} [opts.avatar] GLB/VRM URL for this player's avatar
* @param {string} [opts.agent] optional three.ws agent id
* @param {object} [opts.coin] { mint, name, symbol, image } — '' mint = lobby
+ * @param {string} [opts.tier] '' (open General world) | 'holders' (gated)
+ * @param {string} [opts.holderPass] signed pass required to join a holder world
+ * @param {number} [opts.holderMinUsd] USD floor the holder world gated on (HUD)
* @param {string} [opts.url] server override
*/
constructor(opts = {}) {
@@ -55,6 +58,9 @@ export class CommunityNet {
this.avatar = opts.avatar || '';
this.agent = opts.agent || '';
this.coin = opts.coin || { mint: '', name: '', symbol: '', image: '' };
+ this.tier = opts.tier === 'holders' ? 'holders' : '';
+ this.holderPass = opts.holderPass || '';
+ this.holderMinUsd = Number(opts.holderMinUsd) || 0;
this.url = opts.url || defaultServerUrl();
this.client = null;
@@ -71,6 +77,7 @@ export class CommunityNet {
remove: new Set(), // (id)
chat: new Set(), // ({id, name, text, ts})
interact: new Set(), // ({from, fromName, action, ts}) — a peer interacted with us
+ denied: new Set(), // (reason) — server refused the join (e.g. holder gate); no retry
voiceSignal: new Set(), // ({from, data}) — relayed WebRTC SDP/ICE from a peer
ping: new Set(), // (ms) — smoothed round-trip latency to the server
blockAdd: new Set(), // (key, type) — a voxel appeared (placed or restored)
@@ -109,9 +116,11 @@ export class CommunityNet {
this.client = new Client(this.url);
const mint = this.coin.mint || '';
const options = {
- // filterBy('coin') isolates each coin into its own instance; the
+ // filterBy('coin','tier') isolates each coin into its own instance and
+ // splits the open General world from the gated Holders world; the
// coin-less lobby ('') groups all lobby players into one world.
coin: mint,
+ tier: this.tier,
coinName: this.coin.name || '',
coinSymbol: this.coin.symbol || '',
coinImage: this.coin.image || '',
@@ -119,6 +128,12 @@ export class CommunityNet {
avatar: this.avatar,
agent: this.agent,
};
+ // Holder worlds require a signed pass the server verifies in onAuth; carry
+ // it (and the floor it gated on, for the seed room's HUD) only for holders.
+ if (this.tier === 'holders') {
+ options.holderPass = this.holderPass;
+ options.holderMinUsd = this.holderMinUsd;
+ }
this.room = await this.client.joinOrCreate(ROOM_NAME, options);
this.sessionId = this.room.sessionId;
@@ -171,8 +186,18 @@ export class CommunityNet {
image: this.room.state.coinImage,
});
} catch (err) {
- console.warn('[community-net] connect failed:', err?.message ?? err);
- this._setStatus('failed', err?.message ?? String(err));
+ const msg = err?.message ?? String(err);
+ // A holder-gate refusal (onAuth threw) is terminal, not a flaky link —
+ // retrying with the same expired/invalid pass just loops. Surface it so
+ // the scene can route the player back to the gate, and stop here.
+ if (/holder_pass/i.test(msg)) {
+ console.warn('[community-net] holder gate denied join:', msg);
+ this._setStatus('denied', msg);
+ this._emit('denied', msg);
+ return;
+ }
+ console.warn('[community-net] connect failed:', msg);
+ this._setStatus('failed', msg);
this._scheduleReconnect();
}
}