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.

Add $THREE holder tiers + club cover-pass; referral membership card

nirholas239030f69642
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 09298066a..58d49d87b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -27,6 +27,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Pump Live: real token art, live market caps, and a feed that heals itself** — The Pump Live showcase (three.ws/pump-live) — where a 3D agent reacts to brand-new pump.fun launches in real time — is now fully wired. Every new coin appears with its real artwork and a live USD market cap, instead of a generic avatar and a rough estimate. A new stats bar tracks tokens launched, initial-buy volume, and time since the last launch as events stream in. Before the first launch arrives you get a tidy loading skeleton instead of a blank panel; if the upstream stream drops, the feed reconnects on its own with a backoff and, if it stays down, shows a clear message with a Retry button. Token images are resolved and served through three.ws, so they always load cleanly and never trip browser security errors, and the page keeps streaming even on devices that can't run the 3D view. (`/pump-live`) `[improvement, fix]`
- **Pump Visualizer’s Trending view fixed — spheres now sized by real market cap** — The Trending mode of the 3D Pump Visualizer (three.ws/pump-visualizer) now renders correctly: every coin appears as a sphere sized by its real USD market cap, textured with its actual logo, with a full detail panel showing market cap, all-time-high, replies, age, and socials. Previously Trending failed to load because the market data it relied on wasn’t reaching the scene. Click a sphere to inspect it, or double-click to open the full 3D coin page. The live Firehose and Migrations modes are unchanged. (`/pump-visualizer`) `[fix, improvement]`
- **Rate and vouch for Solana agents from their passport** — Every Solana agent passport already showed its on-chain reputation — now you can add to it. A new "Rate this agent" panel lets anyone with a Solana wallet (Phantom or Solflare) leave a 1–5 score, with an optional public note, written on-chain as a signed attestation — no account needed. You can also back your rating with a SOL stake (from 0.001 SOL) sent to the agent's owner for an economically-weighted vouch. Submitting is guarded the obvious ways: you can't rate your own agent, scores are limited to 1–5, the minimum stake is enforced, and re-rating asks you to confirm before it updates your previous score. The moment your transaction confirms, the passport re-reads the chain on demand instead of waiting for the next indexing pass, so your rating shows up in the reputation summary within seconds. (`/agent-passport.html`) `[feature]`
+- **Refer friends with a 3D membership card** — Your account now has a Referrals page with a 3D, flippable membership card — your member number, referral count, and score on the front, a scannable QR for your invite link on the back. Tilt it with your cursor, flip it over, then share it: post to X or Telegram, copy your link, or download the card as an image. Anyone who signs up through your link is tied to you for life, and you earn 5% in USDC on everything they buy on three.ws. Sign-ups now carry your referral code through every login method — email and wallet alike — so credit always lands where it's due. (`/dashboard/referrals`) `[feature]`
- **Register an existing agent on-chain in one click** — Any agent you already built can now be given an ERC-8004 on-chain identity straight from its profile — no re-entering its name, 3D model, voice, or skills. The new "Register on-chain" control reuses everything the agent already has, automatically assembles and pins a full agent manifest (its persona, voice, installed skills, and memory mode), links that manifest to the on-chain agent card, and mints the identity on the network you pick. Re-running it on the same network is a safe no-op, and your profile shows a live on-chain badge with explorer and agent-card links the moment it's done. (`/agents`) `[feature]`
- **Registered agents now carry an on-chain "Validated" badge** — When an agent is registered on-chain, three.ws now automatically runs its 3D model through the platform's glTF validator and records a signed validation attestation on the ERC-8004 ValidationRegistry — so an agent that advertises validation actually carries proof of it. A green "Validated" badge appears on the agent profile, readable by anyone without a wallet, and links straight to the full validation report and the on-chain record. The check is independent of the file's byte-identity (sha256), so both are surfaced on their own: a model that passes schema validation still shows its exact byte fingerprint. If a model has problems, the badge shows "Validation failed" with the specific reason — the agent is still registered, just unvalidated — and owners can re-validate after updating their model to refresh the badge. Validation is best-effort and never blocks or reverts a registration. (`/marketplace`) `[feature, security]`
- **Save any avatar as your own — forks with their own wallet** — Saving someone else's avatar now works like forking on GitHub: it mints a brand-new avatar in your account with its own copy of the model, linked back to the original with a "Forked from" credit and a fork counter on the source. You never share one avatar between two people — your copy is yours to edit, deploy, or launch, and the original owner's stays untouched. Every saved or forked avatar's agent also gets its own custodial wallet (EVM + Solana) the moment it lands, assigned to you alone — create it, copy the addresses, or manage it right from the avatar page, the editor, and the gallery picker. One person can hold a copy of another's avatar, but no two people ever control the same agent wallet. (`/gallery`) `[feature]`
diff --git a/api/_lib/club/cover-pass.js b/api/_lib/club/cover-pass.js
new file mode 100644
index 000000000..beeb6cab1
--- /dev/null
+++ b/api/_lib/club/cover-pass.js
@@ -0,0 +1,113 @@
+// Shared club-door pass issuer.
+//
+// Both cover-charge rails issue the SAME entry pass once payment settles:
+// - USDC via x402 → api/x402/club-cover.js
+// - $THREE on Solana → api/club/cover-three.js
+//
+// The bouncer logic is identical regardless of which coin paid: look the payer
+// up against the ban list, count their prior settled club activity to assign a
+// door tier, and mint a time-boxed pass the /club door consumes to drop the
+// rope. Keeping it here means the two endpoints can never drift on who gets in.
+
+import { randomUUID } from 'node:crypto';
+import { sql } from '../db.js';
+
+// How long an entry pass is good for. A wallet that paid the cover re-enters
+// for the rest of the night without paying again.
+export const PASS_TTL_SEC = 60 * 60 * 6; // 6 hours
+
+// Normalize a wallet for ban/activity lookups. Lowercased so a Base 0x address
+// matches regardless of EIP-55 checksum casing; base58 Solana addresses are
+// case-sensitive but never collide across the lowercase fold in practice.
+export function normalizeWallet(w) {
+ return String(w || '').trim().toLowerCase();
+}
+
+/**
+ * Look the payer's wallet up against the ban list. Fails OPEN: a missing table
+ * or a transient DB error must not lock the whole club out, so any error
+ * resolves to "not banned". Returns the matching row or null.
+ */
+export async function findBan(wallet) {
+ if (!wallet) return null;
+ try {
+ const rows = await sql`select wallet, reason from club_bans where wallet = ${wallet} limit 1`;
+ return rows?.[0] ?? null;
+ } catch (err) {
+ console.warn('[club-cover] ban lookup failed (fail-open)', err?.message || err);
+ return null;
+ }
+}
+
+/**
+ * Count this wallet's prior settled club tips to assign a door tier. Pure read
+ * of the existing club_tips ledger. Fails soft to 0 visits / newcomer.
+ */
+export async function visitsFor(wallet) {
+ if (!wallet) return 0;
+ try {
+ const rows = await sql`select count(*)::int as n from club_tips where lower(payer) = ${wallet}`;
+ return rows?.[0]?.n ?? 0;
+ } catch (err) {
+ console.warn('[club-cover] visit count failed (soft 0)', err?.message || err);
+ return 0;
+ }
+}
+
+export function tierFor(visits) {
+ if (visits >= 10) return 'vip';
+ if (visits >= 1) return 'regular';
+ return 'newcomer';
+}
+
+/**
+ * Run the bouncer over a paid wallet and return its entry pass. The payment is
+ * assumed already settled on-chain by the caller — this only decides admission
+ * and tier. A banned wallet gets `admitted:false` and no usable pass (the cover
+ * already settled; there are no refunds for being on the list).
+ *
+ * @param {{ payer: string|null, network?: string|null, amountAtomics?: string|null, asset?: string|null }} p
+ * @returns {Promise<object>} the pass object the /club door consumes.
+ */
+export async function issueCoverPass({ payer, network = null, amountAtomics = null, asset = null }) {
+ const wallet = normalizeWallet(payer || '');
+ const now = new Date();
+
+ const ban = await findBan(wallet);
+ if (ban) {
+ return {
+ ok: true,
+ admitted: false,
+ banned: true,
+ reason: ban.reason || 'Not on the list tonight.',
+ tier: 'banned',
+ visits: 0,
+ passId: randomUUID(),
+ issuedAt: now.toISOString(),
+ expiresAt: now.toISOString(),
+ payer: payer ?? null,
+ network,
+ amountAtomics,
+ asset,
+ };
+ }
+
+ const visits = await visitsFor(wallet);
+ const expires = new Date(now.getTime() + PASS_TTL_SEC * 1000);
+
+ return {
+ ok: true,
+ admitted: true,
+ banned: false,
+ reason: null,
+ tier: tierFor(visits),
+ visits,
+ passId: randomUUID(),
+ issuedAt: now.toISOString(),
+ expiresAt: expires.toISOString(),
+ payer: payer ?? null,
+ network,
+ amountAtomics,
+ asset,
+ };
+}
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index 7c7b7990c..161a222a7 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -257,6 +257,15 @@ export const limits = {
// human iterating on a prompt routinely exceeds 12/h; this lane lets them.
mcp3dGenerateFree: (key) =>
getLimiter('mcp3d:generate:free', { limit: 60, window: '1 h' }).limit(key),
+ // Holder perk (Lever 2): $THREE tiers raise the free-generation ceiling by their
+ // rate multiplier. Same per-key counter + prefix as the base free lane — the tier
+ // only lifts the threshold, so a holder iterating heavily isn't throttled at 60/h.
+ // `multiplier` comes from a verified tier pass (pure HMAC, no RPC on the hot path).
+ mcp3dGenerateFreeTiered: (key, multiplier = 1) =>
+ getLimiter('mcp3d:generate:free', {
+ limit: Math.max(60, Math.round(60 * (Number(multiplier) || 1))),
+ window: '1 h',
+ }).limit(key),
// Status polling is the highest-frequency call in the generation flow (every
// active job polls every few seconds, plus the /forge health pill). It only
// guards against pathological poll floods, so it is enforced per instance
diff --git a/api/_lib/three-tier.js b/api/_lib/three-tier.js
new file mode 100644
index 000000000..58c20c2e4
--- /dev/null
+++ b/api/_lib/three-tier.js
@@ -0,0 +1,227 @@
+// $THREE holder tiers — the hold-to-access lever.
+//
+// HOLD (don't spend) $THREE to unlock platform-wide perks: a fee discount on
+// pay-per-use compute, higher free quotas (rate-limit multiplier), private/branded
+// worlds, priority routing, and early access. Holding removes float and rewards
+// bag size without depleting it — the deflation-free status lever.
+//
+// A tier is resolved from the USD VALUE a wallet currently holds of $THREE (priced
+// live), generalizing the per-coin holder-pass (api/_lib/holder-pass.js) to the
+// whole platform. This module is the single source of truth for the thresholds,
+// the perk curve, and the (signed) tier pass the multiplayer server verifies.
+//
+// Reads degrade gracefully: a wallet that can't be priced resolves to the free
+// Member tier rather than throwing — a balance hiccup must never block a charge.
+
+import crypto from 'node:crypto';
+import { getBalances } from './balances.js';
+import { getTokenPriceUsd } from './token/price.js';
+import { TOKEN_MINT } from './token/config.js';
+
+// ── Tier ladder ─────────────────────────────────────────────────────────────────
+// Ordered low→high. `minUsd` is the USD value of $THREE held to reach the tier.
+// `discountBps` is the fee discount on fixed-price compute. `rateMultiplier`
+// scales free quotas. Thresholds/curve are tunable knobs (see plan) — starting
+// points chosen so the entry tier is reachable and the top tier is aspirational.
+export const TIERS = Object.freeze([
+ Object.freeze({
+ level: 0,
+ id: 'member',
+ label: 'Member',
+ minUsd: 0,
+ discountBps: 0,
+ rateMultiplier: 1,
+ perks: Object.freeze(['Everything free-forever: create, discover, embed, social, basic worlds']),
+ }),
+ Object.freeze({
+ level: 1,
+ id: 'bronze',
+ label: 'Bronze',
+ minUsd: 25,
+ discountBps: 500, // 5% off compute
+ rateMultiplier: 2,
+ perks: Object.freeze(['5% off all $THREE compute', '2× free generation quota', 'Bronze profile badge']),
+ }),
+ Object.freeze({
+ level: 2,
+ id: 'silver',
+ label: 'Silver',
+ minUsd: 100,
+ discountBps: 1000, // 10%
+ rateMultiplier: 3,
+ perks: Object.freeze([
+ '10% off all $THREE compute',
+ '3× free generation quota',
+ 'Private worlds',
+ 'Priority MCP routing',
+ ]),
+ }),
+ Object.freeze({
+ level: 3,
+ id: 'gold',
+ label: 'Gold',
+ minUsd: 500,
+ discountBps: 2000, // 20%
+ rateMultiplier: 5,
+ perks: Object.freeze([
+ '20% off all $THREE compute',
+ '5× free generation quota',
+ 'Branded worlds + custom environments',
+ 'Early access to drops',
+ ]),
+ }),
+ Object.freeze({
+ level: 4,
+ id: 'genesis',
+ label: 'Genesis',
+ minUsd: 2500,
+ discountBps: 3000, // 30%
+ rateMultiplier: 10,
+ perks: Object.freeze([
+ '30% off all $THREE compute',
+ '10× free generation quota',
+ 'First dibs on rare names + collectibles',
+ 'Genesis-only cosmetics',
+ ]),
+ }),
+]);
+
+/** Resolve the tier for a given USD value held. Always returns a tier (Member floor). */
+export function tierForUsd(usdHeld) {
+ const usd = Number(usdHeld) || 0;
+ let resolved = TIERS[0];
+ for (const t of TIERS) if (usd >= t.minUsd) resolved = t;
+ return resolved;
+}
+
+/** The next tier up from a given one, or null at the top. */
+export function nextTier(tier) {
+ return TIERS.find((t) => t.level === tier.level + 1) || null;
+}
+
+function isSolanaAddress(s) {
+ return typeof s === 'string' && /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(s);
+}
+
+/**
+ * Read the USD value of $THREE a wallet holds. Never throws — returns 0 on any
+ * failure so callers degrade to the free Member tier rather than erroring.
+ * @returns {Promise<{ usd: number, amount: number, priceUsd: number }>}
+ */
+export async function holderUsd(walletAddress) {
+ if (!isSolanaAddress(walletAddress)) return { usd: 0, amount: 0, priceUsd: 0 };
+ try {
+ const balances = await getBalances({ chain: 'solana', address: walletAddress });
+ const entry = (balances?.tokens ?? []).find((t) => t.mint === TOKEN_MINT);
+ const amount = entry?.amount || 0;
+ if (amount <= 0) return { usd: 0, amount: 0, priceUsd: 0 };
+ // Prefer the price the balance read already resolved; fall back to the
+ // dedicated $THREE price feed so the tier is correct even if the portfolio
+ // pricer skipped this mint.
+ let priceUsd = entry?.price > 0 ? entry.price : 0;
+ if (!(priceUsd > 0)) {
+ const p = await getTokenPriceUsd();
+ priceUsd = p?.priceUsd || 0;
+ }
+ const usd = entry?.usd > 0 ? entry.usd : amount * priceUsd;
+ return { usd, amount, priceUsd };
+ } catch {
+ return { usd: 0, amount: 0, priceUsd: 0 };
+ }
+}
+
+/**
+ * Resolve a session user's $THREE tier from their linked wallet. Never throws.
+ * @returns {Promise<{ tier: object, usd: number, amount: number, priceUsd: number, next: object|null }>}
+ */
+export async function resolveUserTier(user) {
+ const wallet = user?.wallet_address || null;
+ const { usd, amount, priceUsd } = await holderUsd(wallet);
+ const tier = tierForUsd(usd);
+ return { tier, usd, amount, priceUsd, next: nextTier(tier) };
+}
+
+/** Fee discount (bps) for a user's current tier. Never throws → 0 on failure. */
+export async function holderDiscountBps(user) {
+ try {
+ const { tier } = await resolveUserTier(user);
+ return tier.discountBps;
+ } catch {
+ return 0;
+ }
+}
+
+// ── Signed tier pass ─────────────────────────────────────────────────────────────
+// Generalizes the holder-pass HMAC (byte-compatible construction) so the
+// multiplayer/Colyseus server can gate private/branded worlds on a tier without a
+// Solana RPC or price feed of its own. Format: b64url(JSON(payload)).b64url(HMAC).
+
+const PASS_TTL_S = 10 * 60;
+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 (process.env.NODE_ENV === 'production') {
+ throw new Error(
+ '[three-tier] HOLDER_PASS_SECRET is required in production — refusing to mint tier passes with the dev secret.',
+ );
+ }
+ if (!_warned) {
+ _warned = true;
+ console.warn('[three-tier] HOLDER_PASS_SECRET not set — using insecure dev secret.');
+ }
+ 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 resolved tier into a signed pass. The level + USD are signed so a game
+ * server can gate (e.g. "Silver+ worlds") and display the real tier without
+ * trusting a client value.
+ * @param {{ wallet: string, level: number, tierId: string, usd: number }} claims
+ */
+export function signTierPass({ wallet, level, tierId, usd }) {
+ const now = Math.floor(Date.now() / 1000);
+ const payload = {
+ kind: 'three-tier',
+ wallet,
+ level: Math.max(0, Number(level) || 0),
+ tierId,
+ usd: Math.round((Number(usd) || 0) * 100) / 100,
+ iat: now,
+ exp: now + PASS_TTL_S,
+ };
+ const body = b64url(JSON.stringify(payload));
+ return `${body}.${hmac(body)}`;
+}
+
+/**
+ * Verify a tier pass (signature + expiry). Returns the payload or null. Mirrors
+ * the multiplayer verifier; safe to use server-side to re-check a presented pass.
+ */
+export function verifyTierPass(token) {
+ if (typeof token !== 'string' || !token.includes('.')) return null;
+ const [body, sig] = token.split('.');
+ if (!body || !sig) return null;
+ const expected = hmac(body);
+ const a = Buffer.from(sig);
+ const b = Buffer.from(expected);
+ if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) return null;
+ let payload;
+ try {
+ payload = JSON.parse(Buffer.from(body.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'));
+ } catch {
+ return null;
+ }
+ if (!payload.exp || payload.exp < Math.floor(Date.now() / 1000)) return null;
+ if (payload.kind !== 'three-tier') return null;
+ return payload;
+}
diff --git a/api/forge.js b/api/forge.js
index 241813e7a..cd350d51a 100644
--- a/api/forge.js
+++ b/api/forge.js
@@ -61,6 +61,20 @@ import {
} from './_lib/forge-store.js';
import { constantTimeEquals } from './_lib/crypto.js';
import { env as _env } from './_lib/env.js';
+import { verifyTierPass, TIERS } from './_lib/three-tier.js';
+
+// Holder perk (Lever 2): a presented, verified $THREE tier pass lifts the free
+// generation ceiling by that tier's multiplier. The pass is pure-HMAC verifiable
+// (no RPC/price feed), so this adds zero latency to the anonymous free lane. An
+// absent or invalid pass simply leaves the multiplier at 1 (the base 60/h).
+function freeLaneMultiplier(req, body) {
+ const token = req.headers?.['x-three-tier-pass'] || body?.tier_pass || null;
+ if (!token) return 1;
+ const payload = verifyTierPass(token);
+ if (!payload) return 1;
+ const tier = TIERS.find((t) => t.level === payload.level);
+ return tier?.rateMultiplier || 1;
+}
// Returns true when the request carries the internal cron seed token, meaning
// the call comes from forge-seed-cron (server→server). These bypass the per-IP
@@ -401,7 +415,9 @@ async function startJob(req, res) {
const isFreeLane = BACKENDS[backendId]?.free === true;
if (!isInternalSeedRequest(req)) {
- const rl = isFreeLane ? await limits.mcp3dGenerateFree(ip) : await limits.mcp3dGenerate(ip);
+ const rl = isFreeLane
+ ? await limits.mcp3dGenerateFreeTiered(ip, freeLaneMultiplier(req, body))
+ : await limits.mcp3dGenerate(ip);
if (!rl.success) {
return rateLimited(res, rl, 'Generation limit reached. Try again shortly.');
}
diff --git a/api/three/[action].js b/api/three/[action].js
index 2b67b0218..e330d51e5 100644
--- a/api/three/[action].js
+++ b/api/three/[action].js
@@ -1,8 +1,10 @@
// $THREE pay-per-use rail — the canonical HTTP surface every paid compute action
// charges through. One endpoint, one currency.
//
-// GET /api/three/catalog — public price list (display)
+// GET /api/three/catalog — public price list (display)
// POST /api/three/charge — issue a $THREE quote, or settle a paid one (auth)
+// GET /api/three/tier — the signed-in holder's $THREE tier + perks (auth)
+// POST /api/three/tier-pass — mint a signed tier pass for world gating (auth)
//
// The charge → settle handshake reuses api/_lib/pricing/charge-three.js, which
// wraps the token rail (quote → on-chain verify → settle). No action burns; every
@@ -20,7 +22,7 @@ import { limits, clientIp } from '../_lib/rate-limit.js';
import { parse } from '../_lib/validate.js';
import { publicCatalog } from '../_lib/pricing/catalog.js';
import { requireThreePayment } from '../_lib/pricing/charge-three.js';
-import { holderDiscountBps } from '../_lib/three-tier.js';
+import { holderDiscountBps, resolveUserTier, signTierPass, TIERS } from '../_lib/three-tier.js';
const SOLANA_ADDRESS = z.string().regex(/^[1-9A-HJ-NP-Za-km-z]{32,44}$/, 'invalid Solana address');
@@ -91,11 +93,63 @@ async function handleCharge(req, res) {
return json(res, result.paid ? 200 : 201, result);
}
+// ── GET /api/three/tier ────────────────────────────────────────────────────────
+
+async function handleTier(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+ const user = await getSessionUser(req, res);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const { tier, usd, amount, priceUsd, next } = await resolveUserTier(user);
+ return json(res, 200, {
+ tier: { level: tier.level, id: tier.id, label: tier.label, discount_bps: tier.discountBps, perks: tier.perks },
+ held_usd: usd,
+ held_amount: amount,
+ price_usd: priceUsd,
+ next: next
+ ? { id: next.id, label: next.label, min_usd: next.minUsd, usd_to_go: Math.max(0, next.minUsd - usd) }
+ : null,
+ // The full ladder so the UI can render thresholds and what each tier unlocks.
+ ladder: TIERS.map((t) => ({
+ level: t.level,
+ id: t.id,
+ label: t.label,
+ min_usd: t.minUsd,
+ discount_bps: t.discountBps,
+ rate_multiplier: t.rateMultiplier,
+ perks: t.perks,
+ })),
+ });
+}
+
+// ── POST /api/three/tier-pass ─────────────────────────────────────────────────────
+
+async function handleTierPass(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+ const user = await getSessionUser(req, res);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+ if (!user.wallet_address) {
+ return error(res, 403, 'wallet_required', 'link a Solana wallet to mint a tier pass');
+ }
+
+ const { tier, usd } = await resolveUserTier(user);
+ const pass = signTierPass({ wallet: user.wallet_address, level: tier.level, tierId: tier.id, usd });
+ return json(res, 201, {
+ pass,
+ tier: { level: tier.level, id: tier.id, label: tier.label },
+ held_usd: usd,
+ });
+}
+
// ── dispatcher ────────────────────────────────────────────────────────────────────
const DISPATCH = {
catalog: handleCatalog,
charge: handleCharge,
+ tier: handleTier,
+ 'tier-pass': handleTierPass,
};
export default wrap(async (req, res) => {
diff --git a/api/x402/club-cover.js b/api/x402/club-cover.js
index 9de49378e..38c0a5675 100644
--- a/api/x402/club-cover.js
+++ b/api/x402/club-cover.js
@@ -16,14 +16,14 @@ import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';
import { buildBazaarSchema } from '../_lib/x402-spec.js';
import { installAccessControl } from '../_lib/x402/access-control.js';
import { withService } from '../_lib/x402/bazaar-helpers.js';
-import { sql } from '../_lib/db.js';
import { priceFor } from '../_lib/x402-prices.js';
+import { issueCoverPass, PASS_TTL_SEC } from '../_lib/club/cover-pass.js';
const ROUTE = '/api/x402/club-cover';
-// How long an entry pass is good for. A wallet that paid the cover can re-enter
-// (and re-trigger this endpoint for free via SIWX) for the rest of the night.
-const PASS_TTL_SEC = 60 * 60 * 6; // 6 hours
+// PASS_TTL_SEC + the bouncer (ban/tier/pass) live in ../_lib/club/cover-pass.js
+// so the USDC door here and the $THREE door (api/club/cover-three.js) issue an
+// identical pass.
const DESCRIPTION =
'three.ws Pole Club — pay the cover charge to get past the door. Pay ' +
diff --git a/data/changelog.json b/data/changelog.json
index 5ad1d6210..919dd1126 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,13 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-06-15",
+ "title": "Refer friends with a 3D membership card",
+ "summary": "Your account now has a Referrals page with a 3D, flippable membership card — your member number, referral count, and score on the front, a scannable QR for your invite link on the back. Tilt it with your cursor, flip it over, then share it: post to X or Telegram, copy your link, or download the card as an image. Anyone who signs up through your link is tied to you for life, and you earn 5% in USDC on everything they buy on three.ws. Sign-ups now carry your referral code through every login method — email and wallet alike — so credit always lands where it's due.",
+ "tags": ["feature"],
+ "link": "/dashboard/referrals"
+ },
{
"date": "2026-06-15",
"title": "Camera AR on /irl now turns on",
diff --git a/multiplayer/src/holder-pass.js b/multiplayer/src/holder-pass.js
index 46ebf9eb6..2d25c4879 100644
--- a/multiplayer/src/holder-pass.js
+++ b/multiplayer/src/holder-pass.js
@@ -92,3 +92,38 @@ export function verifyHolderPass(token) {
if (payload.amount != null && (typeof payload.amount !== 'number' || !Number.isFinite(payload.amount) || payload.amount < 0)) return null;
return payload;
}
+
+/**
+ * Verify a $THREE tier pass and return its payload, or null. Byte-for-byte
+ * compatible with signTierPass() in api/_lib/three-tier.js, so the game server can
+ * gate private/branded worlds on a holder's tier LEVEL without touching Solana RPC
+ * or a price feed — the same trust model as holder passes.
+ * @param {unknown} token
+ * @returns {{ kind:'three-tier', wallet:string, level:number, tierId:string, usd:number, iat:number, exp:number } | null}
+ */
+export function verifyTierPass(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.kind !== 'three-tier') return null;
+ if (typeof payload.exp !== 'number' || payload.exp * 1000 < Date.now()) return null;
+ const now = Date.now() / 1000;
+ if (typeof payload.iat !== 'number' || payload.iat > now + 60) return null;
+ if (payload.exp - payload.iat > 15 * 60) return null;
+ if (typeof payload.wallet !== 'string' || !payload.wallet) return null;
+ if (typeof payload.level !== 'number' || !Number.isInteger(payload.level) || payload.level < 0) return null;
+ if (typeof payload.tierId !== 'string' || !payload.tierId) return null;
+ if (typeof payload.usd !== 'number' || !Number.isFinite(payload.usd) || payload.usd < 0) return null;
+ return payload;
+}
diff --git a/pages/agent-detail.html b/pages/agent-detail.html
index d900eff64..333003dc2 100644
--- a/pages/agent-detail.html
+++ b/pages/agent-detail.html
@@ -224,6 +224,7 @@
style="width: 80%; height: 48px; margin-top: 8px; display: none"
></div>
<div class="ad-hero-trust" id="ad-trust-pills"></div>
+ <avatar-actions id="ad-avatar-actions" mode="fork" style="display:none;margin:10px 0"></avatar-actions>
<div class="ad-hero-actions">
<a
id="ad-see-3d"
diff --git a/pages/mocap-studio.html b/pages/mocap-studio.html
index 5c8bf82a5..3a91a21da 100644
--- a/pages/mocap-studio.html
+++ b/pages/mocap-studio.html
@@ -542,6 +542,7 @@
<button class="btn btn-ghost" id="load-avatar" style="flex-shrink:0;">Load</button>
</div>
<div class="avatar-info" id="avatar-info">no avatar loaded</div>
+ <avatar-actions id="mc-actions" mode="wallet" style="display:none;margin-top:10px"></avatar-actions>
</div>
<div class="card" style="flex:1;">
@@ -568,6 +569,7 @@
<div id="footer-container"></div>
<script src="/footer.js"></script>
+ <script type="module" src="/avatar-actions.js"></script>
<script type="module" src="/src/mocap-studio.js"></script>
<script src="/brand.js" defer></script>
</body>
diff --git a/public/avatar-actions.js b/public/avatar-actions.js
index b8d598250..bd1096d41 100644
--- a/public/avatar-actions.js
+++ b/public/avatar-actions.js
@@ -145,6 +145,12 @@ class AvatarActions extends HTMLElement {
} catch {
/* render whatever we have */
}
+ // A bad / non-existent id (e.g. a default mannequin stand-in) never resolves
+ // an avatar — stay invisible rather than showing a stuck "Loading…".
+ if (!this._avatar) {
+ this.shadowRoot.innerHTML = '';
+ return;
+ }
this._render();
}
diff --git a/public/changelog.json b/public/changelog.json
index 7bb1fb32c..21d2d1893 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-15T20:11:46.076Z",
+ "generated_at": "2026-06-15T20:22:29.540Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -222,6 +222,16 @@
"feature"
]
},
+ {
+ "date": "2026-06-15",
+ "type": "update",
+ "title": "Refer friends with a 3D membership card",
+ "summary": "Your account now has a Referrals page with a 3D, flippable membership card — your member number, referral count, and score on the front, a scannable QR for your invite link on the back. Tilt it with your cursor, flip it over, then share it: post to X or Telegram, copy your link, or download the card as an image. Anyone who signs up through your link is tied to you for life, and you earn 5% in USDC on everything they buy on three.ws. Sign-ups now carry your referral code through every login method — email and wallet alike — so credit always lands where it's due.",
+ "link": "/dashboard/referrals",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-15",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 7f5e4b0e7..224772022 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -174,6 +174,14 @@
<category>feature</category>
<description>Every Solana agent passport already showed its on-chain reputation — now you can add to it. A new &quot;Rate this agent&quot; panel lets anyone with a Solana wallet (Phantom or Solflare) leave a 1–5 score, with an optional public note, written on-chain as a signed attestation — no account needed. You can also back your rating with a SOL stake (from 0.001 SOL) sent to the agent's owner for an economically-weighted vouch. Submitting is guarded the obvious ways: you can't rate your own agent, scores are limited to 1–5, the minimum stake is enforced, and re-rating asks you to confirm before it updates your previous score. The moment your transaction confirms, the passport re-reads the chain on demand instead of waiting for the next indexing pass, so your rating shows up in the reputation summary within seconds.</description>
</item>
+ <item>
+ <title>Refer friends with a 3D membership card</title>
+ <link>https://three.ws/dashboard/referrals</link>
+ <guid isPermaLink="false">2026-06-15:Refer friends with a 3D membership card</guid>
+ <pubDate>Mon, 15 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Your account now has a Referrals page with a 3D, flippable membership card — your member number, referral count, and score on the front, a scannable QR for your invite link on the back. Tilt it with your cursor, flip it over, then share it: post to X or Telegram, copy your link, or download the card as an image. Anyone who signs up through your link is tied to you for life, and you earn 5% in USDC on everything they buy on three.ws. Sign-ups now carry your referral code through every login method — email and wallet alike — so credit always lands where it's due.</description>
+ </item>
<item>
<title>Register an existing agent on-chain in one click</title>
<link>https://three.ws/agents</link>
diff --git a/public/club/venue/tour.glb b/public/club/venue/tour.glb
new file mode 100644
index 000000000..07c27693d
Binary files /dev/null and b/public/club/venue/tour.glb differ
diff --git a/public/features.json b/public/features.json
index 9313b0941..6ac782040 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-15T20:11:46.063Z",
+ "generated_at": "2026-06-15T20:22:29.518Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/public/referral-capture.js b/public/referral-capture.js
index 0d214467f..177c8a80a 100644
--- a/public/referral-capture.js
+++ b/public/referral-capture.js
@@ -22,7 +22,7 @@
if (!raw) return null;
var code = raw.trim().toUpperCase();
return CODE_RE.test(code) ? code : null;
- } catch (e) {
+ } catch {
return null;
}
}
@@ -41,7 +41,7 @@
}
}
}
- } catch (e) {
+ } catch {
/* private mode / disabled storage — referral capture is best-effort */
}
})();
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index 214e6cc98..d86babd6b 100644
--- a/public/sitemap/index.html
+++ b/public/sitemap/index.html
@@ -56,6 +56,20 @@
.sm-brand img { width: 24px; height: 24px; border-radius: 5px; }
.sm-brand:hover { text-decoration: none; }
</style>
+
+ <meta property="og:type" content="website">
+ <meta property="og:site_name" content="three.ws">
+ <meta property="og:title" content="Sitemap · three.ws">
+ <meta property="og:description" content="Human-readable index of every page on three.ws.">
+ <meta property="og:url" content="https://three.ws/sitemap">
+ <meta property="og:image" content="https://three.ws/og-image.png">
+ <meta property="og:image:width" content="1200">
+ <meta property="og:image:height" content="630">
+ <meta name="twitter:card" content="summary_large_image">
+ <meta name="twitter:title" content="Sitemap · three.ws">
+ <meta name="twitter:description" content="Human-readable index of every page on three.ws.">
+ <meta name="twitter:image" content="https://three.ws/og-image.png">
+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Sitemap","description":"Human-readable index of every page on three.ws.","url":"https://three.ws/sitemap","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>
</head>
<body>
<header class="sm-topbar">
diff --git a/scripts/build-club-entrance-venue.mjs b/scripts/build-club-entrance-venue.mjs
index 5778dfec0..129e8fe1f 100644
--- a/scripts/build-club-entrance-venue.mjs
+++ b/scripts/build-club-entrance-venue.mjs
@@ -40,14 +40,31 @@ const MAX_TEXTURE = 2048;
const TARGETS = [
{ src: 'alleyway.glb', out: 'alleyway.glb' },
{ src: 'space_smugglers_club_house_-_dark_version.glb', out: 'space-smugglers-clubhouse.glb' },
+ // Gallery corridor you walk through before reaching the club door.
+ { src: 'tour.glb', out: 'tour.glb' },
];
const mb = (n) => (n / 1024 / 1024).toFixed(2);
+// Drop meshes the artist flagged as junk (`xxx`, `DO NOT RENDER`) — e.g. the
+// tour's giant ground disc that otherwise inflates the footprint and breaks the
+// runtime's floor/axis normalisation.
+function stripJunkMeshes(doc) {
+ const junk = /xxx|do not render/i;
+ let removed = 0;
+ for (const mesh of doc.getRoot().listMeshes()) {
+ if (junk.test(mesh.getName() || '')) { mesh.dispose(); removed++; }
+ }
+ return removed;
+}
+
async function compress(io, srcPath, outPath) {
const before = statSync(srcPath).size;
const doc = await io.read(srcPath);
+ const stripped = stripJunkMeshes(doc);
+ if (stripped) console.log(` stripped ${stripped} junk mesh(es)`);
+
await doc.transform(
weld(),
prune(),
diff --git a/src/a-me.js b/src/a-me.js
index b766ba9ff..bd864300f 100644
--- a/src/a-me.js
+++ b/src/a-me.js
@@ -241,7 +241,9 @@ function renderAgentCards(host, agents, avatars) {
${pumpMint ? `<span class="ame-tag pump">pump.fun</span>` : ''}
${created ? `<span class="ame-meta-text">${esc(created)}</span>` : ''}
</div>
- ${wallet ? `<div class="ame-wallet">${esc(truncAddr(wallet, 8, 6))}</div>` : ''}
+ ${wallet
+ ? `<div class="ame-wallet">${esc(truncAddr(wallet, 8, 6))}</div>`
+ : `<button class="ame-btn small" data-action="create-wallet" data-agent-id="${esc(a.id)}">Create wallet</button>`}
</div>
</div>
@@ -273,6 +275,7 @@ function renderAgentCards(host, agents, avatars) {
const action = btn.dataset.action;
if (action === 'share') handleShare(btn.dataset.avatarId, btn.dataset.name);
else if (action === 'embed') handleEmbed(btn.dataset.avatarId);
+ else if (action === 'create-wallet') handleCreateWallet(btn);
else if (action === 'toggle-skills') togglePanel(btn.dataset.agentId, 'skills', agents);
else if (action === 'toggle-memory') togglePanel(btn.dataset.agentId, 'memory', agents);
else if (action === 'toggle-actions') togglePanel(btn.dataset.agentId, 'actions', agents);
@@ -489,6 +492,39 @@ function renderPanel(panel, type, data, agentId) {
// ── Share / Embed actions ────────────────────────────────────────────────────
+async function handleCreateWallet(btn) {
+ const agentId = btn.dataset.agentId;
+ if (!agentId || btn.disabled) return;
+ btn.disabled = true;
+ const label = btn.textContent;
+ btn.textContent = 'Creating…';
+ try {
+ let token = null;
+ try {
+ const cr = await fetch('/api/csrf-token', { credentials: 'include' });
+ if (cr.ok) token = (await cr.json()).token || null;
+ } catch { /* token optional — endpoint still rejects without it */ }
+ const r = await fetch(`/api/agents/${encodeURIComponent(agentId)}/wallet/provision`, {
+ method: 'POST',
+ credentials: 'include',
+ headers: token ? { 'x-csrf-token': token } : {},
+ });
+ const d = await r.json().catch(() => ({}));
+ if (!r.ok) throw new Error(d.message || d.error || `provision failed (${r.status})`);
+ btn.replaceWith(
+ Object.assign(document.createElement('div'), {
+ className: 'ame-wallet',
+ textContent: truncAddr(d.wallet_address, 8, 6),
+ }),
+ );
+ toast('Agent wallet created');
+ } catch (e) {
+ btn.disabled = false;
+ btn.textContent = label;
+ toast(e.message || 'Could not create wallet');
+ }
+}
+
function handleShare(avatarId, name) {
const link = `${location.origin}/agents/${encodeURIComponent(avatarId)}`;
navigator.clipboard.writeText(link).then(() => {
diff --git a/src/agent-detail.js b/src/agent-detail.js
index 0ad97b7cf..289a0c3c2 100644
--- a/src/agent-detail.js
+++ b/src/agent-detail.js
@@ -389,6 +389,21 @@ function render(agent) {
};
$('ad-name').textContent = agent.name;
+ // Let visitors save this agent's avatar as their own fork (its wallet is
+ // already managed in the holdings panel below, so fork-only here).
+ const fork = $('ad-avatar-actions');
+ if (fork && agent.avatar_id) {
+ if (!customElements.get('avatar-actions') && !document.querySelector('script[data-avatar-actions]')) {
+ const s = document.createElement('script');
+ s.type = 'module';
+ s.src = '/avatar-actions.js';
+ s.dataset.avatarActions = '1';
+ document.head.appendChild(s);
+ }
+ fork.setAttribute('avatar-id', agent.avatar_id);
+ fork.style.display = 'block';
+ }
+
// "See in 3D" drops this agent's avatar into the live $three world. Every
// agent has one — its own GLB if attached, the base mannequin otherwise — so
// the button is always live. Marketplace enrichment upgrades the href to a
@@ -1657,6 +1672,7 @@ function normalize(rec, avatar) {
return {
id: rec.id,
+ avatar_id: rec.avatar_id || avatar?.id || null,
name: rec.name || 'Unnamed agent',
assetKind: rec.is_registered ? 'Core Asset' : 'Off-chain',
// "Active" is a liveness signal, NOT an on-chain one. An agent is live as
diff --git a/src/club-entrance.js b/src/club-entrance.js
index d9e85b5ab..bcddb673c 100644
--- a/src/club-entrance.js
+++ b/src/club-entrance.js
@@ -1,21 +1,22 @@
// /club entrance — walk up to the club as your own 3D avatar.
//
-// You don't drop onto the pole floor. You spawn outside in the alley as a
-// third-person avatar and you're in control: move (WASD / arrows / touch
-// joystick), look around (drag), and walk up to the neon door at the end of
-// the alley. Step into range and a prompt appears — press E, tap, or click the
-// door — and only then does the cover-charge card (src/club-gate.js) ask you
-// to pay. Pay the cover and your avatar walks through the Space Smugglers club
-// house interior while the anthem plays (wired in src/club.js), and the room
-// with the poles opens up around you (src/club.js, booting behind it all).
+// You don't drop onto the pole floor. You spawn as a third-person avatar and
+// you're in control: move (WASD / arrows / touch joystick) and look around
+// (drag). First you walk through a gallery tour; reach the end and you step
+// out into the alley, where you walk up to the neon door. Step into range and a
+// prompt appears — press E, tap, or click the door — and only then does the
+// cover-charge card (src/club-gate.js) ask you to pay. Pay the cover and your
+// avatar walks through the Space Smugglers club house interior while the anthem
+// plays (wired in src/club.js), and the room with the poles opens up around you
+// (src/club.js, booting behind it all).
//
// Everything renders into one full-screen canvas (#club-door-canvas) layered
-// above the pole stage and below the cover card. Two ~1.6 MB Meshopt+WebP
-// environments (built by scripts/build-club-entrance-venue.mjs) plus the
-// shared avatar GLB; the interior is prefetched while you walk so the
-// transition never stalls. Already paid tonight? The door is gone on load and
-// we skip the whole thing. Any load failure degrades silently — the cover card
-// and the room behind it still work.
+// above the pole stage and below the cover card. Three Meshopt+WebP
+// environments (built by scripts/build-club-entrance-venue.mjs) plus the shared
+// avatar GLB; the alley and interior are prefetched while you walk so each
+// transition never stalls. Already paid tonight? The whole approach is skipped
+// on load. Any load failure degrades silently — the cover card and the room
+// behind it still work.
import {
AmbientLight,
@@ -42,6 +43,7 @@ import { gltfLoader } from './loaders/gltf.js';
import { AnimationManager } from './animation-manager.js';
import { log } from './shared/log.js';
+const TOUR_URL = '/club/venue/tour.glb';
const ALLEYWAY_URL = '/club/venue/alleyway.glb';
const CLUBHOUSE_URL = '/club/venue/space-smugglers-clubhouse.glb';
const AVATAR_URL = '/avatars/default.glb';
@@ -136,25 +138,40 @@ async function start(canvasEl) {
const loader = gltfLoader(renderer);
- // Land in the alley + the avatar first; prefetch the interior so the
- // walk-through after the cover settles never waits on a download.
- const [alleyGltf, avatarGltf, manifest] = await Promise.all([
- loader.loadAsync(ALLEYWAY_URL),
+ // Walk the gallery tour + the avatar first; prefetch the alley and the
+ // interior so each transition lands without waiting on a download.
+ const [tourGltf, avatarGltf, manifest] = await Promise.all([
+ loader.loadAsync(TOUR_URL),
loader.loadAsync(AVATAR_URL),
fetch(MANIFEST_URL, { cache: 'force-cache' }).then((r) => (r.ok ? r.json() : [])).catch(() => []),
]);
const clubhousePromise = loader.loadAsync(CLUBHOUSE_URL);
+ let alleyGltf = null;
+ loader.loadAsync(ALLEYWAY_URL)
+ .then((g) => { alleyGltf = g; })
+ .catch((err) => { log.warn('[club-entrance] alley load failed', err); alleyGltf = 'error'; });
// ── Environment ──────────────────────────────────────────────────────────
- let env = mountEnvironment(scene, alleyGltf.scene);
- // Anchor the entrance to the alley's modelled door so the prompt and the
- // neon frame land on the real doorway, not a guessed end of the footprint.
- let doorAnchor = findDoorAnchor(env.root);
- let path = walkPath(env.box, doorAnchor);
- // Seal the doorway: a dark plane just inside it so the lit interior never
- // reads from the alley — the club stays hidden until you pay and walk in.
- let occluder = doorAnchor ? buildDoorOccluder(doorAnchor, path.dir) : null;
- if (occluder) scene.add(occluder);
+ // `cover` flags the venue whose door opens the cover card (the alley); the
+ // tour's exit just advances you to the alley. Door-anchoring + the sealing
+ // occluder only apply to the alley — the tour exits down its long axis.
+ let currentCover = false;
+ let env = null, doorAnchor = null, path = null, occluder = null;
+ mountApproach(tourGltf.scene, { cover: false, useDoorAnchor: false });
+
+ function mountApproach(root, { cover, useDoorAnchor }) {
+ if (occluder) { scene.remove(occluder); disposeObject(occluder); occluder = null; }
+ if (env) { disposeObject(env.root); scene.remove(env.root); }
+ env = mountEnvironment(scene, root);
+ // Anchor to the modelled door so the prompt + neon frame land on the real
+ // doorway; the tour skips this and exits down its longest dimension.
+ doorAnchor = useDoorAnchor ? findDoorAnchor(env.root) : null;
+ path = walkPath(env.box, doorAnchor);
+ // Seal the doorway so the lit interior never reads from outside.
+ occluder = doorAnchor ? buildDoorOccluder(doorAnchor, path.dir) : null;
+ if (occluder) scene.add(occluder);
+ currentCover = cover;
+ }
// ── Avatar ─────────────────────────────────────────────────────────────
const avatar = avatarGltf.scene;
@@ -291,12 +308,26 @@ async function start(canvasEl) {
const promptEl = document.getElementById('club-door-prompt');
const hintEl = document.getElementById('club-controls-hint');
promptEl?.addEventListener('click', tryEnter);
- if (hintEl) hintEl.textContent = isTouch
- ? 'Drag to move and look · walk to the door to enter'
- : 'WASD / arrows to move · drag to look · press E at the door';
+ setHint();
showHint(true);
showJoystick(isTouch);
+ // Hint + prompt copy depend on the venue: the tour says "walk to the end",
+ // the alley says "enter".
+ function setHint() {
+ if (!hintEl) return;
+ const tail = currentCover ? 'press E at the door' : 'walk to the end of the gallery';
+ const tailTouch = currentCover ? 'walk to the door to enter' : 'walk to the end of the gallery';
+ hintEl.textContent = isTouch
+ ? `Drag to move and look · ${tailTouch}`
+ : `WASD / arrows to move · drag to look · ${tail}`;
+ }
+ function setPromptLabel() {
+ if (!promptEl) return;
+ promptEl.innerHTML = `${currentCover ? 'Enter the club' : 'Continue'} <kbd>E</kbd>`;
+ promptEl.setAttribute('aria-label', currentCover ? 'Enter the club' : 'Continue into the alley');
+ }
+
let nearDoor = false;
function tryEnter() {
if (!inputEnabled || !nearDoor) return;
@@ -304,8 +335,18 @@ async function start(canvasEl) {
showPrompt(false);
showHint(false);
showJoystick(false);
- // Hand off to the cover-charge card.
- window.dispatchEvent(new CustomEvent('club:enter-door'));
+ if (currentCover) {
+ // Hand off to the cover-charge card.
+ window.dispatchEvent(new CustomEvent('club:enter-door'));
+ } else {
+ // End of the gallery — walk on into the alley.
+ advanceApproach();
+ }
+ }
+
+ function advanceApproach() {
+ nearDoor = false;
+ setPhase('toAlleyOut');
}
// Backed out of the cover card without paying — resume walking the alley.
@@ -317,7 +358,7 @@ async function start(canvasEl) {
});
// ── State + render loop ──────────────────────────────────────────────────
- let phase = 'alley'; // alley → leaving → swapping → entering → walking → arriving → done
+ let phase = 'tour'; // tour → toAlleyOut → toAlleyIn → alley → leaving → swapping → entering → walking → arriving → done
let phaseStart = performance.now();
let raf = 0;
let last = performance.now();
@@ -350,15 +391,49 @@ async function start(canvasEl) {
key.position.set(rig.position.x, 5, rig.position.z + 1);
key.target.position.copy(rig.position).setY(1);
- if (phase === 'alley') {
+ if (phase === 'tour' || phase === 'alley') {
const d = Math.hypot(rig.position.x - path.door.x, rig.position.z - path.door.z);
const inRange = d < DOOR_RANGE;
- if (inRange !== nearDoor) { nearDoor = inRange; showPrompt(inRange && inputEnabled); }
+ if (inRange !== nearDoor) {
+ nearDoor = inRange;
+ if (inRange) setPromptLabel();
+ showPrompt(inRange && inputEnabled);
+ }
doorGlow.intensity = inRange ? 3.2 : 1.4;
doorMarker.pulse(now / 1000, inRange);
}
switch (phase) {
+ case 'toAlleyOut': {
+ // Fade the tour out, swap in the alley, then fade back in.
+ const k = Math.min(1, elapsed / 0.6);
+ canvasEl.style.opacity = String(1 - k);
+ if (k >= 1 && alleyGltf) {
+ if (alleyGltf === 'error') {
+ // Alley never loaded — skip straight to the cover card.
+ setPhase('alley');
+ window.dispatchEvent(new CustomEvent('club:enter-door'));
+ } else {
+ mountApproach(alleyGltf.scene, { cover: true, useDoorAnchor: true });
+ placeSpawn();
+ setHint();
+ setPhase('toAlleyIn');
+ }
+ }
+ break;
+ }
+ case 'toAlleyIn': {
+ const k = Math.min(1, elapsed / 0.5);
+ canvasEl.style.opacity = String(k);
+ if (k >= 1) {
+ setPhase('alley');
+ inputEnabled = true;
+ nearDoor = false;
+ showHint(true);
+ showJoystick(isTouch);
+ }
+ break;
+ }
case 'leaving': {
const k = Math.min(1, elapsed / LEAVE);
canvasEl.style.opacity = String(1 - k);
diff --git a/src/create.js b/src/create.js
index f40d16d0e..0e38104e6 100644
--- a/src/create.js
+++ b/src/create.js
@@ -63,8 +63,30 @@ function markVideoAvatarUnavailable() {
}
async function handleFork(avatarId) {
- showSaveOverlay('Loading avatar…');
+ showSaveOverlay('Saving avatar…');
try {
+ // Canonical, GitHub-style fork for signed-in users: the server copies the
+ // model into the caller's namespace, mints a new owned avatar with a
+ // "Forked from" link, and provisions its agent wallet. No client download.
+ const forkRes = await fetch('/api/avatars/fork', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ source_avatar_id: avatarId }),
+ });
+ if (forkRes.ok) {
+ const { avatar } = await forkRes.json();
+ window.location.href = `/avatars/${encodeURIComponent(avatar.id)}`;
+ return;
+ }
+ // Only auth failures fall through to the guest remix flow; surface real errors.
+ if (forkRes.status !== 401 && forkRes.status !== 403) {
+ const d = await forkRes.json().catch(() => ({}));
+ throw new Error(d.message || d.error || 'Could not save this avatar.');
+ }
+
+ // Not signed in → stage a guest copy so they can sign up at review and own it.
+ updateSaveOverlay('Loading avatar…');
const metaRes = await fetch(`/api/avatars/${encodeURIComponent(avatarId)}`);
if (!metaRes.ok) throw new Error('Could not load the original avatar.');
const { avatar } = await metaRes.json();
diff --git a/src/dashboard-next/pages/referrals.js b/src/dashboard-next/pages/referrals.js
new file mode 100644
index 000000000..be3193228
--- /dev/null
+++ b/src/dashboard-next/pages/referrals.js
@@ -0,0 +1,519 @@
+// dashboard-next — Referrals.
+//
+// A 3D, flippable membership card (the centrepiece) plus the referral link,
+// share actions, and live referral stats. Front shows the member's standing;
+// back shows a scannable QR for the referral link. Every number is real,
+// pulled from /api/users/referrals — no placeholders.
+
+import { mountShell } from '../shell.js';
+import { requireUser, get, esc } from '../api.js';
+import { renderQRToSVG, renderQRToCanvas } from '../../erc8004/qr.js';
+
+const MONO = `'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace`;
+
+// Referral commission paid to the referrer on each purchase. Mirrors the
+// server default (REFERRAL_COMMISSION_BPS in api/_lib/purchase-confirm.js).
+const REFERRAL_PCT = 5;
+
+// ── small utilities ─────────────────────────────────────────────────────────
+
+function toast(msg) {
+ let el = document.getElementById('dn-toast');
+ if (!el) {
+ el = document.createElement('div');
+ el.id = 'dn-toast';
+ el.style.cssText = `
+ position:fixed;left:50%;bottom:32px;transform:translateX(-50%) translateY(20px);
+ background:rgba(20,21,28,0.95);border:1px solid var(--nxt-stroke-strong);
+ color:var(--nxt-ink);padding:9px 16px;border-radius:999px;font-size:13px;
+ z-index:9999;opacity:0;transition:opacity .18s, transform .18s;
+ backdrop-filter:blur(20px);-webkit-backdrop-filter:blur(20px);
+ box-shadow:0 8px 24px rgba(0,0,0,0.4);pointer-events:none;`;
+ document.body.appendChild(el);
+ }
+ el.textContent = msg;
+ requestAnimationFrame(() => {
+ el.style.opacity = '1';
+ el.style.transform = 'translateX(-50%) translateY(0)';
+ });
+ clearTimeout(el._t);
+ el._t = setTimeout(() => {
+ el.style.opacity = '0';
+ el.style.transform = 'translateX(-50%) translateY(20px)';
+ }, 1600);
+}
+
+async function copyToClipboard(text) {
+ try {
+ await navigator.clipboard.writeText(text);
+ toast('Copied');
+ return true;
+ } catch {
+ const t = document.createElement('textarea');
+ t.value = text;
+ t.style.position = 'fixed';
+ t.style.opacity = '0';
+ document.body.appendChild(t);
+ t.select();
+ let ok = false;
+ try { ok = document.execCommand('copy'); } catch { ok = false; }
+ document.body.removeChild(t);
+ toast(ok ? 'Copied' : 'Copy failed');
+ return ok;
+ }
+}
+
+function fmtInt(n) {
+ return Number(n || 0).toLocaleString('en-US');
+}
+
+function fmtUsd(n) {
+ return Number(n || 0).toLocaleString('en-US', { style: 'currency', currency: 'USD' });
+}
+
+/** "06/27" — two years out, the card's notional validity. */
+function expLabel(memberSince) {
+ const base = memberSince ? new Date(memberSince) : new Date();
+ const exp = new Date(base.getTime());
+ exp.setFullYear(exp.getFullYear() + 2);
+ const mm = String(exp.getMonth() + 1).padStart(2, '0');
+ const yy = String(exp.getFullYear()).slice(-2);
+ return `${mm}/${yy}`;
+}
+
+function memberSinceLabel(memberSince) {
+ if (!memberSince) return '—';
+ const d = new Date(memberSince);
+ if (Number.isNaN(d.getTime())) return '—';
+ return d.toLocaleDateString('en-US', { month: 'short', year: 'numeric' });
+}
+
+// ── styles (scoped, injected once) ──────────────────────────────────────────
+
+function injectStyles() {
+ if (document.getElementById('ref-card-styles')) return;
+ const s = document.createElement('style');
+ s.id = 'ref-card-styles';
+ s.textContent = `
+ .ref-wrap{max-width:980px}
+ .ref-stage{display:flex;gap:18px;align-items:center;justify-content:center;flex-wrap:wrap}
+ .ref-perspective{perspective:1400px;width:100%;max-width:460px;flex:1 1 360px;min-width:300px}
+ .ref-card{
+ position:relative;width:100%;aspect-ratio:1.74/1;
+ transform-style:preserve-3d;transition:transform .7s cubic-bezier(.22,.61,.36,1);
+ will-change:transform;cursor:grab;
+ }
+ .ref-card:active{cursor:grabbing}
+ .ref-face{
+ position:absolute;inset:0;border-radius:20px;overflow:hidden;
+ -webkit-backface-visibility:hidden;backface-visibility:hidden;
+ box-shadow:0 26px 60px -22px rgba(60,30,140,0.7), 0 2px 0 rgba(255,255,255,0.06) inset;
+ border:1px solid rgba(167,139,250,0.28);
+ padding:clamp(16px,4.4%,22px);display:flex;flex-direction:column;color:#fff;
+ }
+ .ref-face.front{
+ background:
+ radial-gradient(120% 140% at 88% 6%, rgba(167,139,250,0.42), transparent 52%),
+ radial-gradient(90% 120% at 0% 100%, rgba(86,52,170,0.5), transparent 60%),
+ linear-gradient(135deg,#181230 0%,#241a4d 52%,#3a2680 100%);
+ }
+ .ref-face.back{
+ transform:rotateY(180deg);
+ background:
+ radial-gradient(120% 130% at 12% 8%, rgba(167,139,250,0.34), transparent 55%),
+ linear-gradient(150deg,#15102a 0%,#221a44 60%,#2f2160 100%);
+ }
+ .ref-sheen{position:absolute;inset:0;pointer-events:none;
+ background:linear-gradient(105deg,transparent 38%,rgba(255,255,255,0.10) 48%,transparent 58%);
+ mix-blend-mode:screen;opacity:.7}
+ .ref-row{display:flex;align-items:center;justify-content:space-between;gap:10px}
+ .ref-brand{display:flex;align-items:center;gap:8px;font-weight:700;letter-spacing:-0.01em;font-size:15px}
+ .ref-brand img{width:20px;height:20px;border-radius:5px;display:block}
+ .ref-chip{width:30px;height:22px;border-radius:5px;
+ background:linear-gradient(135deg,#e8d9a0,#b8932f);position:relative;opacity:.9;flex-shrink:0}
+ .ref-chip::before,.ref-chip::after{content:"";position:absolute;left:18%;right:18%;height:1px;background:rgba(0,0,0,.32)}
+ .ref-chip::before{top:38%}.ref-chip::after{top:62%}
+ .ref-qr{background:#fff;border-radius:9px;padding:6px;line-height:0;box-shadow:0 4px 14px rgba(0,0,0,.3)}
+ .ref-qr svg{display:block;width:100%;height:100%}
+ .ref-scan{font-size:11px;color:rgba(255,255,255,.62);letter-spacing:.02em}
+ .ref-scan b{display:block;color:rgba(255,255,255,.92);font-size:12px;font-weight:600;letter-spacing:0}
+ .ref-divider{height:1px;background:linear-gradient(90deg,transparent,rgba(255,255,255,.18),transparent);margin:auto 0 0}
+ .ref-stats{display:flex;gap:12px;justify-content:space-between}
+ .ref-stat-k{font-size:9.5px;letter-spacing:.14em;text-transform:uppercase;color:rgba(255,255,255,.5);margin-bottom:3px}
+ .ref-stat-v{font-size:19px;font-weight:700;font-family:${MONO};line-height:1}
+ .ref-stat-v.accent{color:#c4b5fd}
+ .ref-meta{display:flex;align-items:center;justify-content:space-between;gap:8px;
+ font-family:${MONO};font-size:10.5px;color:rgba(255,255,255,.5)}
+ .ref-meta b{color:rgba(255,255,255,.82);font-weight:600}
+ .ref-name{font-size:clamp(20px,5.5%,26px);font-weight:700;letter-spacing:-0.01em;line-height:1}
+ .ref-strip{display:flex;align-items:center;gap:8px;background:rgba(255,255,255,.06);
+ border:1px solid rgba(255,255,255,.1);border-radius:10px;padding:9px 12px;font-size:12px;color:rgba(255,255,255,.86)}
+ .ref-strip svg{flex-shrink:0}
+ .ref-rail{display:flex;flex-direction:column;gap:10px;flex:0 0 auto}
+ .ref-rail-btn{width:44px;height:44px;border-radius:50%;display:grid;place-items:center;
+ background:rgba(255,255,255,.05);border:1px solid var(--nxt-stroke-strong);color:var(--nxt-ink);
+ cursor:pointer;transition:transform .14s ease,background .14s ease,border-color .14s ease,box-shadow .14s ease;position:relative}
+ .ref-rail-btn:hover{background:rgba(167,139,250,.16);border-color:rgba(167,139,250,.5);transform:translateY(-1px)}
+ .ref-rail-btn:active{transform:translateY(0) scale(.95)}
+ .ref-rail-btn:focus-visible{outline:none;box-shadow:0 0 0 3px rgba(167,139,250,.4)}
+ .ref-rail-btn svg{width:18px;height:18px}
+ .ref-rail-btn[data-active="true"]{background:rgba(167,139,250,.22);border-color:rgba(167,139,250,.6)}
+ .ref-tip{position:absolute;right:54px;top:50%;transform:translateY(-50%) translateX(4px);
+ background:rgba(20,21,28,.96);border:1px solid var(--nxt-stroke-strong);color:var(--nxt-ink);
+ font-size:12px;padding:5px 9px;border-radius:7px;white-space:nowrap;opacity:0;pointer-events:none;
+ transition:opacity .14s ease,transform .14s ease;box-shadow:0 6px 18px rgba(0,0,0,.4)}
+ .ref-rail-btn:hover .ref-tip,.ref-rail-btn:focus-visible .ref-tip{opacity:1;transform:translateY(-50%) translateX(0)}
+ .ref-linkbar{display:flex;gap:8px;align-items:stretch;flex-wrap:wrap}
+ .ref-linkbar input{flex:1;min-width:200px;background:rgba(255,255,255,.04);border:1px solid var(--nxt-stroke-strong);
+ border-radius:9px;padding:11px 13px;color:var(--nxt-ink);font-family:${MONO};font-size:13px}
+ .ref-tiles{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:12px}
+ .ref-tile{border:1px solid var(--nxt-stroke);border-radius:var(--nxt-radius-sm,12px);padding:14px 16px;background:rgba(255,255,255,.015)}
+ .ref-tile-k{font-size:11.5px;color:var(--nxt-ink-fade);text-transform:uppercase;letter-spacing:.05em;margin-bottom:6px}
+ .ref-tile-v{font-size:24px;font-weight:700;letter-spacing:-0.01em;font-family:${MONO}}
+ .ref-tile-v small{font-size:13px;color:var(--nxt-ink-fade);font-weight:500;font-family:inherit}
+ .ref-steps{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:14px}
+ .ref-step{display:flex;gap:12px;align-items:flex-start}
+ .ref-step-n{flex:0 0 auto;width:26px;height:26px;border-radius:50%;display:grid;place-items:center;
+ background:rgba(167,139,250,.16);border:1px solid rgba(167,139,250,.4);color:#c4b5fd;font-size:12.5px;font-weight:700;font-family:${MONO}}
+ .ref-step h4{margin:0 0 3px;font-size:13.5px;color:var(--nxt-ink)}
+ .ref-step p{margin:0;font-size:12.5px;color:var(--nxt-ink-dim);line-height:1.45}
+ .ref-card-skel{width:100%;aspect-ratio:1.74/1;border-radius:20px;
+ background:linear-gradient(135deg,#1a1336,#2a1f52);border:1px solid var(--nxt-stroke);
+ position:relative;overflow:hidden}
+ .ref-card-skel::after{content:"";position:absolute;inset:0;
+ background:linear-gradient(90deg,transparent,rgba(255,255,255,.07),transparent);
+ transform:translateX(-100%);animation:ref-shim 1.4s infinite}
+ @keyframes ref-shim{100%{transform:translateX(100%)}}
+ @media (prefers-reduced-motion: reduce){
+ .ref-card{transition:none}
+ .ref-card-skel::after{animation:none}
+ }
+ @media (max-width:560px){
+ .ref-stage{flex-direction:column-reverse}
+ .ref-rail{flex-direction:row;flex-wrap:wrap;justify-content:center}
+ .ref-tip{display:none}
+ }
+ `;
+ document.head.appendChild(s);
+}
+
+// ── card faces ───────────────────────────────────────────────────────────────
+
+function frontFace(card, refUrl) {
+ const qr = renderQRToSVG(refUrl, { scale: 3, margin: 1, dark: '#1a1336', light: '#ffffff' });
+ return `
+ <div class="ref-face front" data-face="front">
+ <div class="ref-sheen"></div>
+ <div class="ref-row">
+ <div class="ref-brand"><img src="/favicon.ico" alt="" />three.ws</div>
+ <div class="ref-chip" aria-hidden="true"></div>
+ </div>
+ <div class="ref-row" style="margin-top:14px;align-items:flex-start;gap:14px">
+ <div class="ref-qr" style="width:64px;height:64px">${qr}</div>
+ <div class="ref-scan" style="margin-top:6px"><b>Scan to join</b>three.ws referral</div>
+ </div>
+ <div class="ref-divider" style="margin-top:14px"></div>
+ <div class="ref-stats" style="margin-top:12px">
+ <div><div class="ref-stat-k">Position</div><div class="ref-stat-v accent">#${fmtInt(card.position)}</div></div>
+ <div><div class="ref-stat-k">Referrals</div><div class="ref-stat-v">${fmtInt(card.referred_users_count)}</div></div>
+ <div><div class="ref-stat-k">Score</div><div class="ref-stat-v">${fmtInt(card.score)}</div></div>
+ </div>
+ <div class="ref-meta" style="margin-top:10px">
+ <span>EXP <b>${esc(expLabel(card.member_since))}</b> &nbsp; Member since ${esc(memberSinceLabel(card.member_since))}</span>
+ <span>#${String(card.position).padStart(6, '0')}</span>
+ </div>
+ <div class="ref-name" style="margin-top:10px">${esc(card.display_name || 'Member')}</div>
+ </div>`;
+}
+
+function backFace(card, refUrl) {
+ const qr = renderQRToSVG(refUrl, { scale: 4, margin: 1, dark: '#1a1336', light: '#ffffff' });
+ const shortUrl = refUrl.replace(/^https?:\/\//, '');
+ return `
+ <div class="ref-face back" data-face="back">
+ <div class="ref-sheen"></div>
+ <div style="display:flex;gap:16px;align-items:center;flex:1">
+ <div class="ref-qr" style="width:108px;height:108px;flex:0 0 auto">${qr}</div>
+ <div>
+ <div class="ref-scan"><b style="font-size:14px">Scan to join</b></div>
+ <div style="font-family:${MONO};font-size:11px;color:rgba(255,255,255,.6);margin-top:4px;word-break:break-all">${esc(shortUrl)}</div>
+ </div>
+ </div>
+ <div class="ref-strip" style="margin-top:12px">
+ <svg width="16" height="16" viewBox="0 0 20 20" fill="none" stroke="#c4b5fd" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><circle cx="10" cy="10" r="7"/><path d="M10 6.5v7M7.8 8.2h3a1.4 1.4 0 010 2.8H8.2a1.4 1.4 0 000 2.8h3"/></svg>
+ Earn <b style="color:#fff">${REFERRAL_PCT}%</b> on every referral purchase — paid in USDC
+ </div>
+ <div class="ref-stats" style="margin-top:12px">
+ <div><div class="ref-stat-k">Position</div><div class="ref-stat-v accent">#${fmtInt(card.position)}</div></div>
+ <div><div class="ref-stat-k">Score</div><div class="ref-stat-v">${fmtInt(card.score)}</div></div>
+ <div><div class="ref-stat-k">Referrals</div><div class="ref-stat-v">${fmtInt(card.referred_users_count)}</div></div>
+ </div>
+ <div class="ref-divider" style="margin-top:12px"></div>
+ <div class="ref-row" style="margin-top:10px;color:rgba(255,255,255,.5);font-size:11px">
+ <div class="ref-brand" style="font-size:13px;opacity:.85"><img src="/favicon.ico" alt="" />three.ws</div>
+ <span>© ${new Date().getFullYear()} three.ws</span>
+ </div>
+ </div>`;
+}
+
+// ── icons for the action rail ─────────────────────────────────────────────────
+
+const ICONS = {
+ flip: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M4 8a6 6 0 019.7-3.2L16 7M16 3v4h-4"/><path d="M16 12a6 6 0 01-9.7 3.2L4 13M4 17v-4h4"/></svg>',
+ x: '<svg viewBox="0 0 20 20" fill="currentColor"><path d="M14.9 3H17l-4.6 5.3L18 17h-4.3l-3.4-4.4L6.4 17H4.3l5-5.7L3.5 3h4.4l3 4 3.9-4z"/></svg>',
+ tg: '<svg viewBox="0 0 20 20" fill="currentColor"><path d="M17.6 3.3 2.9 9c-1 .4-1 1 0 1.3l3.7 1.1 1.4 4.5c.2.5.1.7.6.7.4 0 .6-.2.8-.4l1.8-1.8 3.8 2.8c.7.4 1.2.2 1.4-.6l2.5-11.8c.3-1-.4-1.5-1.3-1.1zM7.8 11.8l8-5c.4-.2.7 0 .4.3l-6.7 6-.3 2.6-1.4-3.9z"/></svg>',
+ copy: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><rect x="7" y="7" width="9" height="9" rx="2"/><path d="M13 7V5a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2"/></svg>',
+ dl: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M10 3v9M6.5 8.5 10 12l3.5-3.5"/><path d="M4 14v1.5A1.5 1.5 0 005.5 17h9a1.5 1.5 0 001.5-1.5V14"/></svg>',
+ share: '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><circle cx="15" cy="5" r="2.2"/><circle cx="5" cy="10" r="2.2"/><circle cx="15" cy="15" r="2.2"/><path d="M6.9 8.9l6.2-3M6.9 11.1l6.2 3"/></svg>',
+};
+
+// ── PNG export — draw the front face to a canvas for a shareable image ────────
+
+function exportCardPNG(card, refUrl) {
+ const W = 1100, H = Math.round(W / 1.74), P = 56;
+ const canvas = document.createElement('canvas');
+ canvas.width = W; canvas.height = H;
+ const ctx = canvas.getContext('2d');
+
+ // Background gradient + radial sheen.
+ const g = ctx.createLinearGradient(0, 0, W, H);
+ g.addColorStop(0, '#181230'); g.addColorStop(0.52, '#241a4d'); g.addColorStop(1, '#3a2680');
+ roundRect(ctx, 0, 0, W, H, 40); ctx.fillStyle = g; ctx.fill();
+ const rg = ctx.createRadialGradient(W * 0.88, H * 0.06, 0, W * 0.88, H * 0.06, W * 0.6);
+ rg.addColorStop(0, 'rgba(167,139,250,0.4)'); rg.addColorStop(1, 'rgba(167,139,250,0)');
+ ctx.fillStyle = rg; ctx.fillRect(0, 0, W, H);
+
+ ctx.fillStyle = '#ffffff';
+ ctx.textBaseline = 'alphabetic';
+
+ // Brand wordmark.
+ ctx.font = '700 34px Inter, system-ui, sans-serif';
+ ctx.fillText('three.ws', P, P + 30);
+
+ // QR (small) top area.
+ const qrCanvas = renderQRToCanvas(refUrl, { scale: 4, margin: 1 });
+ const qrSize = 150;
+ ctx.save();
+ roundRect(ctx, P, P + 60, qrSize, qrSize, 14); ctx.fillStyle = '#fff'; ctx.fill();
+ ctx.drawImage(qrCanvas, P + 8, P + 68, qrSize - 16, qrSize - 16);
+ ctx.restore();
+ ctx.fillStyle = 'rgba(255,255,255,0.92)';
+ ctx.font = '600 24px Inter, system-ui, sans-serif';
+ ctx.fillText('Scan to join', P + qrSize + 28, P + 110);
+ ctx.fillStyle = 'rgba(255,255,255,0.55)';
+ ctx.font = '400 18px Inter, system-ui, sans-serif';
+ ctx.fillText('three.ws referral', P + qrSize + 28, P + 138);
+
+ // Divider.
+ const dy = P + 250;
+ ctx.fillStyle = 'rgba(255,255,255,0.16)';
+ ctx.fillRect(P, dy, W - P * 2, 1.5);
+
+ // Stats row.
+ const stats = [
+ ['POSITION', `#${fmtInt(card.position)}`, '#c4b5fd'],
+ ['REFERRALS', fmtInt(card.referred_users_count), '#ffffff'],
+ ['SCORE', fmtInt(card.score), '#ffffff'],
+ ];
+ stats.forEach((st, i) => {
+ const x = P + i * ((W - P * 2) / 3);
+ ctx.fillStyle = 'rgba(255,255,255,0.5)';
+ ctx.font = '600 16px Inter, system-ui, sans-serif';
+ ctx.fillText(st[0], x, dy + 40);
+ ctx.fillStyle = st[2];
+ ctx.font = `700 40px ${'ui-monospace, Menlo, monospace'}`;
+ ctx.fillText(st[1], x, dy + 86);
+ });
+
+ // Member meta + name.
+ ctx.fillStyle = 'rgba(255,255,255,0.55)';
+ ctx.font = '400 18px ui-monospace, Menlo, monospace';
+ ctx.fillText(`EXP ${expLabel(card.member_since)} Member since ${memberSinceLabel(card.member_since)}`, P, H - P - 44);
+ ctx.textAlign = 'right';
+ ctx.fillText(`#${String(card.position).padStart(6, '0')}`, W - P, H - P - 44);
+ ctx.textAlign = 'left';
+ ctx.fillStyle = '#ffffff';
+ ctx.font = '700 40px Inter, system-ui, sans-serif';
+ ctx.fillText(card.display_name || 'Member', P, H - P);
+
+ canvas.toBlob((blob) => {
+ if (!blob) { toast('Export failed'); return; }
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = `three-ws-membership-${card.referral_code}.png`;
+ document.body.appendChild(a); a.click(); a.remove();
+ URL.revokeObjectURL(url);
+ toast('Card downloaded');
+ }, 'image/png');
+}
+
+function roundRect(ctx, x, y, w, h, r) {
+ ctx.beginPath();
+ ctx.moveTo(x + r, y);
+ ctx.arcTo(x + w, y, x + w, y + h, r);
+ ctx.arcTo(x + w, y + h, x, y + h, r);
+ ctx.arcTo(x, y + h, x, y, r);
+ ctx.arcTo(x, y, x + w, y, r);
+ ctx.closePath();
+}
+
+// ── render ────────────────────────────────────────────────────────────────────
+
+function renderCard(host, card) {
+ const refUrl = `${location.origin}/register?ref=${encodeURIComponent(card.referral_code)}`;
+ const shareText = `Join me on three.ws — build, deploy, and monetize 3D AI agents.`;
+ const xUrl = `https://twitter.com/intent/tweet?text=${encodeURIComponent(shareText)}&url=${encodeURIComponent(refUrl)}`;
+ const tgUrl = `https://t.me/share/url?url=${encodeURIComponent(refUrl)}&text=${encodeURIComponent(shareText)}`;
+
+ host.innerHTML = `
+ <div class="ref-stage">
+ <div class="ref-perspective">
+ <div class="ref-card" data-card role="img"
+ aria-label="three.ws membership card — position ${fmtInt(card.position)}, ${fmtInt(card.referred_users_count)} referrals, score ${fmtInt(card.score)}">
+ ${frontFace(card, refUrl)}
+ ${backFace(card, refUrl)}
+ </div>
+ </div>
+ <div class="ref-rail" role="toolbar" aria-label="Card actions">
+ <button class="ref-rail-btn" data-action="flip" aria-label="Flip card">${ICONS.flip}<span class="ref-tip">Flip card</span></button>
+ <a class="ref-rail-btn" data-action="x" href="${esc(xUrl)}" target="_blank" rel="noopener" aria-label="Share on X">${ICONS.x}<span class="ref-tip">Share on X</span></a>
+ <a class="ref-rail-btn" data-action="tg" href="${esc(tgUrl)}" target="_blank" rel="noopener" aria-label="Share on Telegram">${ICONS.tg}<span class="ref-tip">Telegram</span></a>
+ <button class="ref-rail-btn" data-action="copy" aria-label="Copy referral link">${ICONS.copy}<span class="ref-tip">Copy link</span></button>
+ <button class="ref-rail-btn" data-action="download" aria-label="Download card image">${ICONS.dl}<span class="ref-tip">Download</span></button>
+ <button class="ref-rail-btn" data-action="share" aria-label="Share">${ICONS.share}<span class="ref-tip">Share</span></button>
+ </div>
+ </div>
+
+ <div style="margin-top:22px">
+ <div class="dn-panel-title" style="margin-bottom:8px">Your referral link</div>
+ <div class="ref-linkbar">
+ <input type="text" readonly value="${esc(refUrl)}" data-link aria-label="Referral link" />
+ <button class="dn-btn primary" data-action="copy-link" style="padding:0 18px">Copy link</button>
+ <button class="dn-btn" data-action="copy-code" style="padding:0 16px">Copy code · ${esc(card.referral_code)}</button>
+ </div>
+ </div>
+
+ <div class="ref-tiles" style="margin-top:18px">
+ <div class="ref-tile"><div class="ref-tile-k">Member position</div><div class="ref-tile-v">#${fmtInt(card.position)} <small>of ${fmtInt(card.total_members)}</small></div></div>
+ <div class="ref-tile"><div class="ref-tile-k">Referrals</div><div class="ref-tile-v">${fmtInt(card.referred_users_count)}</div></div>
+ <div class="ref-tile"><div class="ref-tile-k">Referral earnings</div><div class="ref-tile-v">${fmtUsd(card.referral_earnings_usd)}</div></div>
+ <div class="ref-tile"><div class="ref-tile-k">Score</div><div class="ref-tile-v">${fmtInt(card.score)}</div></div>
+ </div>
+
+ <section class="dn-panel" style="margin-top:20px">
+ <div class="dn-panel-title" style="margin-bottom:14px">How referrals work</div>
+ <div class="ref-steps">
+ <div class="ref-step"><div class="ref-step-n">1</div><div><h4>Share your link</h4><p>Send your referral link or QR. Anyone who signs up through it is linked to you for life.</p></div></div>
+ <div class="ref-step"><div class="ref-step-n">2</div><div><h4>They build &amp; spend</h4><p>When your referrals buy assets, skills, or services on three.ws, you earn automatically.</p></div></div>
+ <div class="ref-step"><div class="ref-step-n">3</div><div><h4>You earn ${REFERRAL_PCT}%</h4><p>You collect ${REFERRAL_PCT}% of every referred purchase in USDC, paid straight to your account.</p></div></div>
+ </div>
+ </section>
+ `;
+
+ wireCard(host, card, refUrl);
+}
+
+function wireCard(host, card, refUrl) {
+ const cardEl = host.querySelector('[data-card]');
+ const flipBtn = host.querySelector('[data-action="flip"]');
+
+ const state = { flipped: false, rx: 0, ry: 0 };
+ const reduce = window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches;
+
+ const apply = () => {
+ const baseY = state.flipped ? 180 : 0;
+ cardEl.style.transform = `rotateX(${state.rx}deg) rotateY(${baseY + state.ry}deg)`;
+ };
+ apply();
+
+ const flip = () => {
+ state.flipped = !state.flipped;
+ flipBtn.setAttribute('data-active', String(state.flipped));
+ const tip = flipBtn.querySelector('.ref-tip');
+ if (tip) tip.textContent = state.flipped ? 'Show front' : 'Flip card';
+ apply();
+ };
+ flipBtn.addEventListener('click', flip);
+ // Tapping the card flips it too — but not when the user is dragging to tilt.
+ cardEl.addEventListener('click', (e) => {
+ if (cardEl._dragged) { cardEl._dragged = false; return; }
+ if (e.target.closest('a')) return;
+ flip();
+ });
+
+ if (!reduce) {
+ const onMove = (e) => {
+ const r = cardEl.getBoundingClientRect();
+ const px = (e.clientX - r.left) / r.width - 0.5;
+ const py = (e.clientY - r.top) / r.height - 0.5;
+ state.ry = px * 10;
+ state.rx = -py * 10;
+ cardEl._dragged = true;
+ apply();
+ };
+ cardEl.addEventListener('pointermove', onMove);
+ cardEl.addEventListener('pointerleave', () => {
+ state.rx = 0; state.ry = 0; apply();
+ setTimeout(() => { cardEl._dragged = false; }, 0);
+ });
+ }
+
+ const copyLink = () => copyToClipboard(refUrl);
+ host.querySelector('[data-action="copy"]').addEventListener('click', copyLink);
+ host.querySelector('[data-action="copy-link"]').addEventListener('click', copyLink);
+ host.querySelector('[data-action="copy-code"]').addEventListener('click', () => copyToClipboard(card.referral_code));
+ host.querySelector('[data-link]').addEventListener('click', (e) => { e.currentTarget.select(); });
+ host.querySelector('[data-action="download"]').addEventListener('click', () => exportCardPNG(card, refUrl));
+
+ host.querySelector('[data-action="share"]').addEventListener('click', async () => {
+ const data = {
+ title: 'three.ws',
+ text: 'Join me on three.ws — build, deploy, and monetize 3D AI agents.',
+ url: refUrl,
+ };
+ if (navigator.share) {
+ try { await navigator.share(data); } catch { /* user cancelled */ }
+ } else {
+ await copyToClipboard(refUrl);
+ }
+ });
+}
+
+function renderError(host, message) {
+ host.innerHTML = `
+ <div class="dn-empty" style="padding:40px 24px">
+ <h3>Couldn't load your card</h3>
+ <p>${esc(message || 'Try again in a moment.')}</p>
+ <button class="dn-btn primary" data-action="retry">Retry</button>
+ </div>`;
+ host.querySelector('[data-action="retry"]').addEventListener('click', () => boot(host));
+}
+
+async function boot(host) {
+ host.innerHTML = `<div class="ref-stage"><div class="ref-perspective"><div class="ref-card-skel"></div></div></div>`;
+ try {
+ const card = await get('/api/users/referrals');
+ if (!card || !card.referral_code) {
+ renderError(host, 'No referral code yet — refresh to mint one.');
+ return;
+ }
+ renderCard(host, card);
+ } catch (err) {
+ renderError(host, err?.message);
+ }
+}
+
+(async function main() {
+ injectStyles();
+ const root = await mountShell();
+ await requireUser();
+
+ root.innerHTML = `
+ <h1 class="dn-h1">Referrals</h1>
+ <p class="dn-h1-sub">Your three.ws membership card. Share it, earn ${REFERRAL_PCT}% on every referral.</p>
+ <div class="ref-wrap" data-slot="card"></div>
+ `;
+
+ boot(root.querySelector('[data-slot="card"]'));
+})();
diff --git a/src/mocap-studio.js b/src/mocap-studio.js
index 85b50241b..35df15cb8 100644
--- a/src/mocap-studio.js
+++ b/src/mocap-studio.js
@@ -153,6 +153,13 @@ async function bootAvatar() {
async function applyLoadedAvatar(modelUrl, meta) {
await viewer.load(modelUrl, '', new Map());
state.avatar = meta;
+ // If this is a real saved avatar (UUID id), surface its agent-wallet panel.
+ // Non-UUID stand-ins (e.g. the default mannequin) self-hide in the component.
+ const actions = $('#mc-actions');
+ if (actions && meta?.id) {
+ actions.style.display = 'block';
+ actions.setAttribute('avatar-id', meta.id);
+ }
if (state.idle) state.idle.dispose();
if (!viewer._afterAnimateHooks) viewer._afterAnimateHooks = [];
if (state._idleHook) {
diff --git a/tests/three-tier.test.js b/tests/three-tier.test.js
new file mode 100644
index 000000000..60e804e2a
--- /dev/null
+++ b/tests/three-tier.test.js
@@ -0,0 +1,121 @@
+// Unit tests for the $THREE holder-tier lever (api/_lib/three-tier.js).
+// Balance/price reads are mocked: these prove the tier ladder, the discount curve,
+// graceful degradation to Member, and the signed tier-pass round-trip.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const getBalances = vi.fn();
+const getTokenPriceUsd = vi.fn();
+vi.mock('../api/_lib/balances.js', () => ({ getBalances: (...a) => getBalances(...a) }));
+vi.mock('../api/_lib/token/price.js', () => ({ getTokenPriceUsd: (...a) => getTokenPriceUsd(...a) }));
+
+import {
+ TIERS,
+ tierForUsd,
+ nextTier,
+ holderUsd,
+ resolveUserTier,
+ holderDiscountBps,
+ signTierPass,
+ verifyTierPass,
+} from '../api/_lib/three-tier.js';
+import { TOKEN_MINT } from '../api/_lib/token/config.js';
+
+const WALLET = 'So11111111111111111111111111111111111111112';
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('tier ladder', () => {
+ it('ladder is ordered and starts at a free Member tier', () => {
+ expect(TIERS[0].id).toBe('member');
+ expect(TIERS[0].minUsd).toBe(0);
+ expect(TIERS[0].discountBps).toBe(0);
+ for (let i = 1; i < TIERS.length; i++) {
+ expect(TIERS[i].minUsd).toBeGreaterThan(TIERS[i - 1].minUsd);
+ expect(TIERS[i].discountBps).toBeGreaterThanOrEqual(TIERS[i - 1].discountBps);
+ }
+ });
+
+ it('tierForUsd resolves the highest tier at or below the held value', () => {
+ expect(tierForUsd(0).id).toBe('member');
+ expect(tierForUsd(24).id).toBe('member');
+ expect(tierForUsd(25).id).toBe('bronze');
+ expect(tierForUsd(150).id).toBe('silver');
+ expect(tierForUsd(999).id).toBe('gold');
+ expect(tierForUsd(100000).id).toBe('genesis');
+ });
+
+ it('nextTier points up the ladder and is null at the top', () => {
+ expect(nextTier(TIERS[0]).id).toBe('bronze');
+ expect(nextTier(TIERS[TIERS.length - 1])).toBeNull();
+ });
+});
+
+describe('holderUsd', () => {
+ it('returns 0 for a non-Solana address without any RPC call', async () => {
+ const r = await holderUsd('not-a-wallet');
+ expect(r.usd).toBe(0);
+ expect(getBalances).not.toHaveBeenCalled();
+ });
+
+ it('uses the balance entry usd when present', async () => {
+ getBalances.mockResolvedValue({ tokens: [{ mint: TOKEN_MINT, amount: 1000, usd: 120, price: 0.12 }] });
+ const r = await holderUsd(WALLET);
+ expect(r.usd).toBe(120);
+ expect(r.amount).toBe(1000);
+ });
+
+ it('falls back to the $THREE price feed when the entry has no usd', async () => {
+ getBalances.mockResolvedValue({ tokens: [{ mint: TOKEN_MINT, amount: 1000 }] });
+ getTokenPriceUsd.mockResolvedValue({ priceUsd: 0.2 });
+ const r = await holderUsd(WALLET);
+ expect(r.usd).toBeCloseTo(200);
+ });
+
+ it('degrades to 0 on a balance read failure (never throws)', async () => {
+ getBalances.mockRejectedValue(new Error('rpc down'));
+ const r = await holderUsd(WALLET);
+ expect(r.usd).toBe(0);
+ });
+});
+
+describe('resolveUserTier + holderDiscountBps', () => {
+ it('maps held value to the right tier and discount', async () => {
+ getBalances.mockResolvedValue({ tokens: [{ mint: TOKEN_MINT, amount: 5000, usd: 600, price: 0.12 }] });
+ const { tier, usd } = await resolveUserTier({ wallet_address: WALLET });
+ expect(tier.id).toBe('gold');
+ expect(usd).toBe(600);
+ expect(await holderDiscountBps({ wallet_address: WALLET })).toBe(2000);
+ });
+
+ it('a wallet-less user is Member with no discount', async () => {
+ const { tier } = await resolveUserTier({});
+ expect(tier.id).toBe('member');
+ expect(await holderDiscountBps({})).toBe(0);
+ expect(getBalances).not.toHaveBeenCalled();
+ });
+});
+
+describe('signed tier pass', () => {
+ it('round-trips a valid pass', () => {
+ const pass = signTierPass({ wallet: WALLET, level: 3, tierId: 'gold', usd: 600 });
+ const payload = verifyTierPass(pass);
+ expect(payload).toBeTruthy();
+ expect(payload.level).toBe(3);
+ expect(payload.tierId).toBe('gold');
+ expect(payload.kind).toBe('three-tier');
+ });
+
+ it('rejects a tampered pass', () => {
+ const pass = signTierPass({ wallet: WALLET, level: 4, tierId: 'genesis', usd: 3000 });
+ const [body, sig] = pass.split('.');
+ expect(verifyTierPass(`${body}.${sig.slice(0, -2)}ZZ`)).toBeNull();
+ });
+
+ it('rejects a malformed token', () => {
+ expect(verifyTierPass('garbage')).toBeNull();
+ expect(verifyTierPass('')).toBeNull();
+ });
+});
diff --git a/vercel.json b/vercel.json
index 125084d00..1463be50a 100644
--- a/vercel.json
+++ b/vercel.json
@@ -1095,6 +1095,10 @@
"src": "/dashboard/account/?",
"dest": "/dashboard-next/account.html"
},
+ {
+ "src": "/dashboard/referrals/?",
+ "dest": "/dashboard-next/referrals.html"
+ },
{
"src": "/dashboard/settings/?",
"dest": "/dashboard-next/settings.html"
@@ -1996,6 +2000,14 @@
"src": "/api/users/by-subdomain",
"dest": "/api/users/by-subdomain.js"
},
+ {
+ "src": "/api/users/referrals",
+ "dest": "/api/users/referrals.js"
+ },
+ {
+ "src": "/api/users/referral-claim",
+ "dest": "/api/users/referral-claim.js"
+ },
{
"src": "/api/threews/subdomain",
"dest": "/api/threews/subdomain.js"