Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
Add referral codes, collectibles endpoint, and profile updates
nirholasc9a76a323c79
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 17ae34dd6..3079cabf2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -72,12 +72,15 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Pole Club: every dancer stands on her stage** — Fixed a dancer who sank through her platform instead of standing on it. Avatars exported at centimetre scale (common for Mixamo-rigged characters) had their idle motion collapse, dropping them a metre into the floor. The animation engine now scales each dancer's footing to her own rig, so any avatar you pick stands cleanly at her pole. (`/club`) `[fix]`- **Pole Club: tipping now works with the built-in three.ws wallet** — Tipping a dancer in the Pole Club opens an on-chain payment for $0.001 USDC. On Solana Mobile (Seeker), the payment window only recognized browser extensions like Phantom, so anyone using the three.ws wallet saw a checkout that couldn't be completed — the window opened but the pay button was greyed out. The checkout now recognizes the three.ws wallet (and Backpack and Solflare) the same way the rest of the site does, and names whichever wallet you're using throughout the flow, so tips go through. (`/club`) `[fix]`- **Profiles you can edit — and follow** — Your three.ws profile at three.ws/u/<your-username> is now a real social home. Edit it in place: add a bio, a profile picture and banner image, your location, and a website link — all from an Edit button on your own profile. You can now follow other creators and agents, and they can follow you; every profile shows live follower and following counts you can tap to browse the lists, with one-tap follow buttons throughout. And there's a new Feed at three.ws/feed that gathers the latest avatars, agents, and coin launches from everyone you follow, newest first. Find your profile and Feed links from your account page. (`/feed`) `[feature]`+- **Profiles: your whole on-chain self in one place** — Your profile at three.ws/u/<username> now shows everything you make and own. New Collectibles and Accessories tabs surface the NFTs held across your wallets — 3D NFTs rotate live right in the grid — and the premium avatar items you've bought. Your linked wallets appear as chain-tagged chips with one-tap copy and a block-explorer link, spanning both Solana and EVM. Every avatar now has a Fork button so anyone can save a copy of it (and its agent) to their own account, with a running fork count on each card. And a new Share menu lets you post your profile straight to X or share it through your phone's native share sheet, alongside copy-link. `[feature]`- **Provably-fair vanity grinder now listed in the x402 bazaar** — The provably-fair Solana vanity grinder — which returns a signed, independently-verifiable receipt proving the key was ground fresh and never kept — is now published in the x402 discovery catalog, so paying agents and bazaar crawlers can find and call it directly. (`/vanity/verify`) `[feature, sdk]`+- **Referrals: claim a custom code that's yours** — Your referral code now starts as your name instead of a random string — and you can change it to anything you like. Open Referrals in your dashboard, hit Customize, and pick a code (3–20 letters or numbers); it checks availability as you type and updates your shareable link, QR, and membership card the moment you save. Existing links keep working, codes are matched case-insensitively, and you still earn 5% in USDC on every referred purchase. (`/dashboard/referrals`) `[feature]`- **Regrinding an agent's vanity wallet no longer risks its funds** — The compact "Vanity address" card on an agent's page used to replace a wallet by deleting the old one and creating the new one separately — so if the old wallet held SOL or tokens, they could be left behind. It now uses the same money-safe path as the rest of the platform: any balance is automatically swept to the new vanity address first, and the switch only completes once the funds have moved (and only after the server confirms the new address really matches your pattern). Same one-click experience, but your funds follow the wallet. `[fix, security]`- **Smoother landing page on hover** — The homepage's parallax hero and 3D stack-card glow used to read the page layout on every pointer move, which could make the cursor feel sticky on the first page new visitors see. Those effects now batch their work to one frame at a time, so hover and tilt stay buttery on any device. (`/`) `[improvement]`- **Solana is now the default payment network** — Solana is now the default everywhere you pick a chain — the dashboard's Default payment network setting, x402 merchant settlement, and the monetization payout wallet all default to Solana for every user, with Solana listed first. Base and Polygon remain available if you prefer an EVM chain. (`/dashboard`) `[improvement]`- **Solana reads and the club door survive a degraded RPC provider** — When a Solana node answers with a 200 but an unusable body — an empty payload, an HTML error page, or a quota-exhausted reply — our network layer had one weak spot: if every node was momentarily cooling off at once, it forwarded that garbage response straight through. In the browser that showed up as broken balance and blockhash reads on the marketplace, staking, and payment screens; at the club door it could fail the cover charge with an opaque error even though nothing was charged. The network layer now validates every reply on every path and fails over to a healthy node instead of passing a bad one along, returning a clean, honest error only when every provider is genuinely down. The club door also keeps a recent blockhash on hand and reuses it through a brief blip, so paying to enter and reading on-chain balances stay reliable through provider hiccups. `[fix, infra]`- **Solana stays online even if our paid RPC goes dark** — Everything onchain — paying, minting, balances, name lookups — depends on a Solana RPC node answering. When our primary paid node was throttled or its plan lapsed, some of those reads could error out. The platform now falls through a deeper chain: the paid node first, then several backup providers, then five independent public nodes (each verified live), so a request only fails if every one of them is down at the same moment. The embeddable payment widget and Solana name registration were moved onto the same resilient connection. `[fix, infra]`+- **Studio Lab: six free 3D generators, right in your browser** — The new Lab tab in Studio turns text and parameters into real 3D — no API key, no cost, nothing leaves your machine. Build math-driven parametric solids and supershapes, extrude 3D lettering from any string, turn an SVG icon or logo into a solid model, generate a lithophane relief from a photo, or grow a procedural landscape from a seed — each one previews live and downloads as a real GLB. Plus a Gaussian-splat viewer for the photoreal radiance-field format (.splat / .ply). Powered by three.js and GaussianSplats3D. (`/forge-studio`) `[feature]`- **The $THREE page now shows live market cap, holders & real trades** — Because $THREE has graduated to a DEX, the token page's main panel had broken: it read "100% graduated" but then showed a $0 market cap, no price, a blank holder count, and a "live trades" feed that never filled — even though the header above it showed a real $3.5M market cap. All four are fixed. The bonding-curve panel now reads the live DEX price and market cap for the graduated coin, the holder count comes from our own on-chain holder snapshot (so it shows even when the market-data provider omits it), and the live-trades tape now streams real on-chain swaps from the $THREE pool, refreshed every few seconds with buy/sell side, size, and a link to each transaction. (`/three-token`) `[fix]`- **The $THREE page now spells out why to hold — four real utility pillars** — The $THREE page leads with a clear "Why hold $THREE" section: revenue buybacks (a fixed, live share of platform revenue buys $THREE on the open market), holder rewards (every paid action reflects $THREE back to holders pro-rata), hold-to-access (discounts, higher quotas, and pro perks), and real usage (deploying agents, forging avatars, and trading the marketplace all run on $THREE). Each pillar maps to a mechanism that actually exists on the platform, and the buyback figure is wired to the live commitment. The page's market data also now rides a shared cache, so it stays fast and reliable under heavy traffic. (`/three-token`) `[feature, improvement]`- **The Forge now fills the whole screen** — The Forge — where you turn text or photos into a textured 3D model — used to sit in a narrow column down the middle of the page, leaving big empty margins on wide monitors and a cramped preview. It now stretches edge to edge with comfortable side gutters, so the 3D preview gets far more room to show off your model while the controls stay put on the left. (`/forge`) `[improvement]`diff --git a/api/_lib/referrals.js b/api/_lib/referrals.jsindex bbbc53fb2..4eb287d46 100644--- a/api/_lib/referrals.js+++ b/api/_lib/referrals.js@@ -21,6 +21,185 @@ export function generateReferralCode(length = 8) {return code;}+// ── Custom referral codes ────────────────────────────────────────────────────+//+// Auto-generated codes draw from a restricted, unambiguous alphabet, but a+// user-chosen vanity code (e.g. their name) may legitimately contain any letter+// or digit. Codes are stored and matched in a single canonical case (UPPERCASE)+// so the UNIQUE index on users.referral_code doubles as a case-insensitive+// uniqueness guard and every lookup site can match without per-call lowering.++export const REFERRAL_CODE_MIN_LEN = 3;+export const REFERRAL_CODE_MAX_LEN = 20;++// The canonical, storable shape of a referral code: A–Z and 0–9 only. Vanity+// codes accept the full alphanumeric range; the generator stays restricted so+// auto-minted codes remain easy to read aloud off a membership card.+export const REFERRAL_CODE_RE = new RegExp(`^[A-Z0-9]{${REFERRAL_CODE_MIN_LEN},${REFERRAL_CODE_MAX_LEN}}$`);++// Codes that collide with product surfaces, routes, or the brand. Reserving them+// keeps referral links unambiguous and stops a user from minting a code that+// reads like an official endpoint. Compared case-insensitively (canonical upper).+const RESERVED_REFERRAL_CODES = new Set([+ 'THREE', 'THREEWS', 'THREE3', 'ADMIN', 'ROOT', 'SUPPORT', 'HELP', 'OFFICIAL',+ 'API', 'APP', 'WWW', 'LOGIN', 'REGISTER', 'SIGNUP', 'SIGNIN', 'AUTH', 'OAUTH',+ 'DASHBOARD', 'ACCOUNT', 'SETTINGS', 'BILLING', 'WALLET', 'PAY', 'CHECKOUT',+ 'REFERRAL', 'REFERRALS', 'REF', 'INVITE', 'NULL', 'NONE', 'TEST', 'SYSTEM',+ 'MARKETPLACE', 'FORGE', 'STUDIO', 'AGENT', 'AGENTS', 'CLUB', 'CHANGELOG',+]);++/**+ * Normalize arbitrary user input to a canonical referral code, or null if it+ * can't be one. Trims, uppercases, and validates against the canonical shape —+ * it never strips invalid characters (so "my-code" is rejected, not silently+ * mangled into "MYCODE"); callers surface the rejection to the user.+ *+ * @param {unknown} input+ * @returns {string|null} canonical code, or null when invalid+ */+export function normalizeReferralCode(input) {+ if (input == null) return null;+ const code = String(input).trim().toUpperCase();+ return REFERRAL_CODE_RE.test(code) ? code : null;+}++/** True if the canonical code is reserved for the platform. */+export function isReservedReferralCode(code) {+ return RESERVED_REFERRAL_CODES.has(String(code || '').toUpperCase());+}++/**+ * Derive a canonical referral code candidate from a person's name. Strips+ * everything but letters and digits, uppercases, and clamps to the max length.+ * Returns null if nothing usable (≥ MIN_LEN chars) remains — e.g. a name that's+ * all punctuation or an emoji.+ *+ * @param {string|null|undefined} name+ * @returns {string|null}+ */+export function slugifyReferralName(name) {+ const slug = String(name || '')+ .normalize('NFKD')+ .replace(/[^A-Za-z0-9]/g, '')+ .toUpperCase()+ .slice(0, REFERRAL_CODE_MAX_LEN);+ return slug.length >= REFERRAL_CODE_MIN_LEN ? slug : null;+}++/**+ * Ordered candidate codes for a new account: the user's name first (so the+ * default referral code reads like them), then the name plus a short random+ * suffix to ride out collisions while staying recognizable, then pure random+ * fallbacks. Finite — callers loop until an insert/update succeeds.+ *+ * @param {string|null} name display name or username to seed the default+ * @returns {Generator<string>}+ */+export function* referralCodeCandidates(name) {+ const seen = new Set();+ const offer = function* (code) {+ if (code && !seen.has(code)) { seen.add(code); yield code; }+ };++ const slug = slugifyReferralName(name);+ if (slug && !isReservedReferralCode(slug)) yield* offer(slug);++ if (slug) {+ // Keep room for a 4-char suffix so "ada" → "ADAX7QK" stays under the cap.+ const base = slug.slice(0, REFERRAL_CODE_MAX_LEN - 4);+ for (let i = 0; i < 4; i++) yield* offer(base + generateReferralCode(4));+ }++ for (let i = 0; i < 8; i++) yield* offer(generateReferralCode());+}++// Typed error for referral-code mutations so the endpoint can map a failure to a+// precise HTTP status + machine-readable reason without string-matching.+class ReferralCodeError extends Error {+ constructor(reason, status, message) {+ super(message);+ this.name = 'ReferralCodeError';+ this.reason = reason;+ this.status = status;+ }+}++/**+ * Whether a desired code is available to a given user. Used by the live+ * availability check as the user types in the code editor.+ *+ * @param {string|number} userId+ * @param {unknown} desired raw user input+ * @returns {Promise<{ available: boolean, reason: string, code: string|null }>}+ * reason ∈ 'ok' | 'current' | 'invalid' | 'reserved' | 'taken'+ */+export async function getReferralCodeAvailability(userId, desired) {+ const code = normalizeReferralCode(desired);+ if (!code) return { available: false, reason: 'invalid', code: null };+ if (isReservedReferralCode(code)) return { available: false, reason: 'reserved', code };++ const [holder] = await sql`+ SELECT id FROM users+ WHERE UPPER(referral_code) = ${code} AND deleted_at IS NULL+ LIMIT 1+ `;+ if (!holder) return { available: true, reason: 'ok', code };+ if (String(holder.id) === String(userId)) return { available: true, reason: 'current', code };+ return { available: false, reason: 'taken', code };+}++/**+ * Set the signed-in user's custom referral code. Validates shape, blocks+ * reserved codes, and relies on the UNIQUE index (plus a pre-check) to keep+ * codes globally unique case-insensitively. Idempotent when the user submits+ * the code they already hold.+ *+ * @param {string|number} userId+ * @param {unknown} desired raw user input+ * @returns {Promise<{ referral_code: string, changed: boolean }>}+ * @throws {ReferralCodeError} reason ∈ 'invalid' | 'reserved' | 'not_found' | 'taken'+ */+export async function setReferralCode(userId, desired) {+ const code = normalizeReferralCode(desired);+ if (!code) {+ throw new ReferralCodeError('invalid', 400, `Use ${REFERRAL_CODE_MIN_LEN}–${REFERRAL_CODE_MAX_LEN} letters or numbers (no spaces or symbols).`);+ }+ if (isReservedReferralCode(code)) {+ throw new ReferralCodeError('reserved', 409, 'That code is reserved. Pick another.');+ }++ const [me] = await sql`+ SELECT referral_code FROM users WHERE id = ${userId} AND deleted_at IS NULL+ `;+ if (!me) throw new ReferralCodeError('not_found', 404, 'user not found');++ // No-op when the user re-submits their current code (any case).+ if (me.referral_code && me.referral_code.toUpperCase() === code) {+ return { referral_code: me.referral_code, changed: false };+ }++ const [taken] = await sql`+ SELECT id FROM users+ WHERE UPPER(referral_code) = ${code} AND id <> ${userId} AND deleted_at IS NULL+ LIMIT 1+ `;+ if (taken) throw new ReferralCodeError('taken', 409, 'That code is already taken.');++ try {+ const [row] = await sql`+ UPDATE users SET referral_code = ${code} WHERE id = ${userId}+ RETURNING referral_code+ `;+ return { referral_code: row.referral_code, changed: true };+ } catch (err) {+ // Lost a race to a concurrent claim of the same code.+ if (err && err.code === '23505') {+ throw new ReferralCodeError('taken', 409, 'That code is already taken.');+ }+ throw err;+ }+}+// Every user is a potential referrer, but only the email + SAML signup paths// mint a `referral_code` up front. Privy / SIWS / SIWE sign-ups (and any// pre-existing account) land with a NULL code. This lazily assigns one the@@ -30,11 +209,12 @@ export function generateReferralCode(length = 8) {// @param {string|number} userId// @returns {Promise<string>} the user's referral codeexport async function ensureReferralCode(userId) {- const [existing] = await sql`SELECT referral_code FROM users WHERE id = ${userId}`;+ const [existing] = await sql`SELECT referral_code, display_name, username FROM users WHERE id = ${userId}`;if (existing?.referral_code) return existing.referral_code;- for (let attempt = 0; attempt < 6; attempt++) {- const code = generateReferralCode();+ // Default the code to the member's name (then name+suffix, then random) so the+ // first code they ever see reads like them — they can customize it later.+ for (const code of referralCodeCandidates(existing?.display_name || existing?.username)) {try {const [row] = await sql`UPDATE users SET referral_code = ${code}@@ -46,8 +226,8 @@ export async function ensureReferralCode(userId) {const [now] = await sql`SELECT referral_code FROM users WHERE id = ${userId}`;if (now?.referral_code) return now.referral_code;} catch (err) {- // 23505 = unique_violation: this random code collided with another user's.- // Retry with a fresh code.+ // 23505 = unique_violation: this code collided with another user's.+ // Retry with the next candidate.if (err && err.code === '23505') continue;throw err;}diff --git a/api/auth/[action].js b/api/auth/[action].jsindex de9e9b32f..833a41b97 100644--- a/api/auth/[action].js+++ b/api/auth/[action].js@@ -15,7 +15,7 @@ import { requireCsrf } from '../_lib/csrf.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { parse, loginBody, registerBody, usernameRegisterBody, username as usernameValidator, displayName, email, password, bio as bioValidator, profileLocation, httpUrl } from '../_lib/validate.js';import { sendPasswordResetEmail, sendVerificationEmail } from '../_lib/email.js';-import { generateReferralCode } from '../_lib/referrals.js';+import { referralCodeCandidates, normalizeReferralCode } from '../_lib/referrals.js';import { seedDefaultAgent } from '../_lib/seed-default-agent.js';import { logAudit } from '../_lib/audit.js';import { z } from 'zod';@@ -91,15 +91,13 @@ async function handleLogoutEverywhere(req, res) {// Bounded retry to ride out the rare collision against the unique index on// users.referral_code. The index is the authoritative guard; this loop is the-// UX shield so simultaneous signups don't surface a 500. The generator is a-// CSPRNG over a 32-char alphabet at length 8, so the chance of MAX_TRIES-// consecutive collisions is astronomically low — if we ever exhaust, something-// upstream is wrong (truncated alphabet, broken RNG) and we want to surface it.-const MAX_REFERRAL_CODE_TRIES = 8;-+// UX shield so simultaneous signups don't surface a 500. The first candidate is+// the member's name (so their default referral code reads like them), then a+// name+suffix, then CSPRNG fallbacks — so consecutive collisions are+// astronomically unlikely. If we ever exhaust, something upstream is wrong and+// we want to surface it.async function insertUserWithUniqueReferralCode({ email, passwordHash, displayName, referredById }) {- for (let i = 0; i < MAX_REFERRAL_CODE_TRIES; i += 1) {- const code = generateReferralCode();+ for (const code of referralCodeCandidates(displayName)) {try {const [row] = await sql`insert into users (email, password_hash, display_name, referred_by_id, referral_code)@@ -141,8 +139,9 @@ async function handleRegister(req, res) {}let referred_by_id = null;- if (referralCode) {- const [referrer] = await sql`select id from users where referral_code = ${referralCode}`;+ const normalizedRef = normalizeReferralCode(referralCode);+ if (normalizedRef) {+ const [referrer] = await sql`select id from users where upper(referral_code) = ${normalizedRef} and deleted_at is null limit 1`;if (referrer) {referred_by_id = referrer.id;}diff --git a/api/auth/saml/[action].js b/api/auth/saml/[action].jsindex f3d92df15..fbebcc0c9 100644--- a/api/auth/saml/[action].js+++ b/api/auth/saml/[action].js@@ -17,7 +17,7 @@ import { limits, clientIp } from '../../_lib/rate-limit.js';import { env } from '../../_lib/env.js';import { logAudit } from '../../_lib/audit.js';import { seedDefaultAgent } from '../../_lib/seed-default-agent.js';-import { generateReferralCode } from '../../_lib/referrals.js';+import { referralCodeCandidates } from '../../_lib/referrals.js';import {getSamlInstance,generateSpMetadataXml,@@ -192,13 +192,12 @@ async function findOrCreateUser({ issuer, nameID, email, name }) {}// Bounded retry around the unique referral_code index (mirrors api/auth/[action].js).-// A 23505 on a non-referral constraint means a concurrent ACS won the race for-// this subject/email — re-select and return that user instead of erroring.-const MAX_REFERRAL_CODE_TRIES = 8;-+// The first candidate is the member's name (default referral code reads like+// them), then name+suffix, then random fallbacks. A 23505 on a non-referral+// constraint means a concurrent ACS won the race for this subject/email —+// re-select and return that user instead of erroring.async function insertSamlUser({ email, displayName, issuer, nameID, emailVerified }) {- for (let i = 0; i < MAX_REFERRAL_CODE_TRIES; i += 1) {- const code = generateReferralCode();+ for (const code of referralCodeCandidates(displayName)) {try {const [row] = await sql`insert into users (email, display_name, referral_code, saml_issuer, saml_name_id, email_verified)diff --git a/api/marketplace/buy-asset.js b/api/marketplace/buy-asset.jsindex c2599441c..3afc7d2ec 100644--- a/api/marketplace/buy-asset.js+++ b/api/marketplace/buy-asset.js@@ -29,6 +29,7 @@ import { rpcFallbackFromEnv } from '../_lib/solana/rpc-fallback.js';import { solanaConnection } from '../_lib/solana/connection.js';import { buildGaslessPurchaseTx } from '../_lib/solana/gasless-tx.js';import { insertNotification } from '../_lib/notify.js';+import { normalizeReferralCode } from '../_lib/referrals.js';import { verifyEvmUsdcPayment, evmChainId } from '../_lib/evm-payment-verify.js';const REFERENCE_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;@@ -453,9 +454,9 @@ async function handleEvmAssetConfirm(req, res, pur) {// Resolve the inviting user from a ?ref=<code> query or users.referred_by_id.async function resolveReferrer(req, buyerUserId) {const url = new URL(req.url, 'http://x');- const code = url.searchParams.get('ref');+ const code = normalizeReferralCode(url.searchParams.get('ref'));if (code) {- const [u] = await sql`SELECT id FROM users WHERE referral_code = ${code} LIMIT 1`;+ const [u] = await sql`SELECT id FROM users WHERE UPPER(referral_code) = ${code} AND deleted_at IS NULL LIMIT 1`;if (u && u.id !== buyerUserId) return u.id;}const [me] = await sql`SELECT referred_by_id FROM users WHERE id = ${buyerUserId}`;diff --git a/api/marketplace/purchase.js b/api/marketplace/purchase.jsindex 85cb80395..3f8b9e035 100644--- a/api/marketplace/purchase.js+++ b/api/marketplace/purchase.js@@ -26,6 +26,7 @@ import { MonetizationService } from '../_lib/services/MonetizationService.js';import { solanaConnection } from '../_lib/solana/connection.js';import { buildGaslessPurchaseTx } from '../_lib/solana/gasless-tx.js';import { resolveRecipient } from '../_lib/resolve-recipient.js';+import { normalizeReferralCode } from '../_lib/referrals.js';const SOLANA_RPC = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';@@ -252,9 +253,9 @@ async function handleConfirm(req, res, reference) {// 2. users.referred_by_id — buyer signed up under someone.async function resolveReferrer(req, buyerUserId) {const url = new URL(req.url, 'http://x');- const code = url.searchParams.get('ref');+ const code = normalizeReferralCode(url.searchParams.get('ref'));if (code) {- const [u] = await sql`SELECT id FROM users WHERE referral_code = ${code} LIMIT 1`;+ const [u] = await sql`SELECT id FROM users WHERE UPPER(referral_code) = ${code} AND deleted_at IS NULL LIMIT 1`;if (u && u.id !== buyerUserId) return u.id;}const [me] = await sql`SELECT referred_by_id FROM users WHERE id = ${buyerUserId}`;diff --git a/api/users/[username].js b/api/users/[username].jsindex 607268ed0..3e3bc013c 100644--- a/api/users/[username].js+++ b/api/users/[username].js@@ -34,10 +34,11 @@ export default wrap(async (req, res) => {memoryRows,socialRows,statsRow,+ shopRows,] = await Promise.all([sql`select id, name, slug, description, storage_key, thumbnail_key, tags,- source, size_bytes, version, created_at+ source, size_bytes, version, fork_count, parent_avatar_id, created_atfrom avatarswhere owner_id = ${user.id}and visibility = 'public'@@ -48,7 +49,7 @@ export default wrap(async (req, res) => {sql`select id, name, description, avatar_url, profile_image_url, home_url,wallet_address, chain_id, erc8004_agent_id, x_username,- farcaster_fname, created_at,+ farcaster_fname, created_at, is_published, forks_count, fork_of,meta->>'solana_address' as solana_address,meta->>'sns_domain' as sns_domain,meta->'onchain' as onchain,@@ -146,6 +147,29 @@ export default wrap(async (req, res) => {(select coalesce(sum(view_count), 0)::bigint from widgetswhere user_id = ${user.id} and is_public = true and deleted_at is null) as total_widget_views`,+ // Items for sale: one-time-priced assets the user actively lists. The price+ // of record lives in asset_prices (item_type ∈ avatar|agent|plugin); join+ // each item type to pull a display name + thumbnail. Soft-deleted items are+ // excluded so a delisted asset never renders a dead card.+ sql`+ select ap.item_type, ap.item_id::text as item_id, ap.amount::text as amount,+ ap.currency_mint, ap.chain, ap.mint_decimals, ap.updated_at,+ av.name as avatar_name, av.slug as avatar_slug, av.thumbnail_key,+ ag.name as agent_name, ag.profile_image_url, ag.avatar_url,+ pl.name as plugin_name, pl.identifier as plugin_identifier+ from asset_prices ap+ left join avatars av+ on ap.item_type = 'avatar' and av.id = ap.item_id and av.deleted_at is null+ left join agent_identities ag+ on ap.item_type = 'agent' and ag.id = ap.item_id and ag.deleted_at is null+ left join plugins pl+ on ap.item_type = 'plugin' and pl.id = ap.item_id and pl.deleted_at is null+ where ap.owner_user_id = ${user.id}+ and ap.is_active = true+ and coalesce(av.id, ag.id, pl.id) is not null+ order by ap.updated_at desc+ limit 48+ `.catch(() => []),]);const avatars = avatarRows.map((a) => ({@@ -158,6 +182,8 @@ export default wrap(async (req, res) => {size_bytes: Number(a.size_bytes || 0),source: a.source,version: a.version,+ fork_count: Number(a.fork_count || 0),+ is_fork: Boolean(a.parent_avatar_id),tags: a.tags || [],created_at: a.created_at,}));@@ -180,9 +206,61 @@ export default wrap(async (req, res) => {sns_domain: a.sns_domain? (a.sns_domain.endsWith('.sol') ? a.sns_domain : `${a.sns_domain}.sol`): null,+ // Fork eligibility: only published agents can be forked (the fork endpoint+ // requires is_published). forks_count drives the "N forks" badge; is_fork+ // flags agents that are themselves derived from another.+ is_published: a.is_published === true,+ forks_count: Number(a.forks_count || 0),+ is_fork: Boolean(a.fork_of),created_at: a.created_at,}));+ // Items for sale. avatar/agent carry a thumbnail; plugins don't, so they fall+ // back to a glyph in the UI. Each card deep-links to the item's own page where+ // the existing purchase flow lives (no duplicate checkout here).+ const USDC_MINTS = new Set([+ 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', // USDC Solana mainnet+ '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU', // USDC Solana devnet+ ]);+ const currencyLabel = (mint, chain) => {+ if (!mint || mint === 'native') return chain === 'solana' ? 'SOL' : 'ETH';+ if (USDC_MINTS.has(mint)) return 'USDC';+ return mint.length > 10 ? `${mint.slice(0, 4)}…${mint.slice(-4)}` : mint;+ };+ const shop = shopRows+ .map((r) => {+ const isAvatar = r.item_type === 'avatar';+ const isAgent = r.item_type === 'agent';+ const name = r.avatar_name || r.agent_name || r.plugin_name || 'Item';+ const image = isAvatar+ ? r.thumbnail_key+ ? publicUrl(r.thumbnail_key)+ : null+ : isAgent+ ? r.profile_image_url || r.avatar_url || null+ : null;+ const href = isAvatar+ ? `/avatars/${r.item_id}`+ : isAgent+ ? `/agent/${r.item_id}`+ : r.plugin_identifier+ ? `/plugins#${r.plugin_identifier}`+ : '/plugins';+ const decimals = Number(r.mint_decimals || 0);+ const price = Number(r.amount || 0) / 10 ** decimals;+ return {+ item_type: r.item_type,+ item_id: r.item_id,+ name,+ image,+ href,+ price,+ currency: currencyLabel(r.currency_mint, r.chain),+ chain: r.chain,+ };+ })+ .filter(Boolean);+const widgets = widgetRows.map((w) => ({id: w.id,type: w.type,@@ -271,6 +349,7 @@ export default wrap(async (req, res) => {plugins: statsRow?.plugins_count ?? 0,coins: statsRow?.coins_count ?? 0,memories: statsRow?.memories_count ?? 0,+ shop: shop.length,widget_views: Number(statsRow?.total_widget_views ?? 0),followers: followCounts?.followers ?? 0,following: followCounts?.following ?? 0,@@ -299,5 +378,6 @@ export default wrap(async (req, res) => {plugins,coins,memories,+ shop,});});diff --git a/api/users/[username]/collectibles.js b/api/users/[username]/collectibles.jsnew file mode 100644index 000000000..73763e9d9--- /dev/null+++ b/api/users/[username]/collectibles.js@@ -0,0 +1,282 @@+// GET /api/users/:username/collectibles — a user's on-chain collectibles + wallets.+//+// One lazy endpoint that powers the profile's NFTs, Accessories, and Wallets+// surfaces. It is deliberately split out of /api/users/:username so the main+// profile paints instantly: the NFT lookups here hit billed providers (Helius+// DAS for Solana, Alchemy for EVM) and are slow, so they load after the fold.+//+// Wallets are derived from the user's own custodial address plus every public+// agent's wallet (EVM + Solana). NFTs are aggregated across all Solana/EVM+// wallets, deduped, and capped. Accessories are the premium cosmetics the user's+// wallets have actually purchased over the x402 rail (real ownership, not the+// free base pack).+//+// Cost controls (NFT providers are billed per call):+// • whole response cached by username (10 min) — repeat profile views are free+// • the shared Helius DAS global hourly ceiling gates every cache MISS+// • per-IP rate limit on top+// Public, no auth: the profile it backs is public.++import { sql } from '../../_lib/db.js';+import { cors, json, method, wrap, error, rateLimited } from '../../_lib/http.js';+import { limits, clientIp } from '../../_lib/rate-limit.js';+import { env } from '../../_lib/env.js';+import { cacheGet, cacheSet } from '../../_lib/cache.js';+import { isValidSolanaAddress, isValidEvmAddress } from '../../_lib/validate.js';+import { buildCatalog } from '../../_lib/cosmetics.js';+import { readOwnedCosmetics, normalizeAccountId } from '../../_lib/cosmetics-ownership.js';++const CACHE_TTL_SECONDS = 10 * 60; // 10m — NFT metadata is effectively static+const NFT_CAP = 60; // max NFTs surfaced across all wallets+const MAX_WALLETS_PER_CHAIN = 8; // cap billed upstream calls per request++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: false })) return;+ if (!method(req, res, ['GET'])) return;++ const usernameRaw =+ req.query?.username ||+ new URL(req.url, 'http://x').pathname.split('/').filter(Boolean).slice(-2)[0] ||+ '';+ const username = String(usernameRaw).toLowerCase().replace(/^@/, '').trim();+ if (!username || !/^[a-z0-9_-]{3,30}$/.test(username)) {+ return error(res, 400, 'validation_error', 'invalid username');+ }++ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const [user] = await sql`+ select id, wallet_address+ from users+ where lower(username) = ${username} and deleted_at is null+ limit 1+ `;+ if (!user) return error(res, 404, 'not_found', 'user not found');++ // Serve a warm cache without touching any billed provider.+ const cacheKey = `collectibles:${username}`;+ const cached = await cacheGet(cacheKey).catch(() => null);+ if (cached) {+ res.setHeader('Cache-Control', 'public, s-maxage=300, stale-while-revalidate=900');+ return json(res, 200, cached);+ }++ // Gather every wallet tied to this identity: the user's own custodial wallet+ // plus the wallets of their public agents (EVM + Solana).+ const agentWallets = await sql`+ select wallet_address, chain_id,+ meta->>'solana_address' as solana_address+ from agent_identities+ where user_id = ${user.id}+ and is_public = true+ and deleted_at is null+ `;++ const evm = new Map(); // lowercased addr -> { address, chainId, source }+ const sol = new Map(); // addr -> { address, source }++ const addWallet = (addr, source, chainId = null) => {+ if (!addr) return;+ const a = String(addr).trim();+ if (isValidEvmAddress(a)) {+ const key = a.toLowerCase();+ if (!evm.has(key)) evm.set(key, { address: a, chainId: chainId || 1, source });+ } else if (isValidSolanaAddress(a)) {+ if (!sol.has(a)) sol.set(a, { address: a, source });+ }+ };++ addWallet(user.wallet_address, 'user');+ for (const w of agentWallets) {+ addWallet(w.wallet_address, 'agent', w.chain_id);+ addWallet(w.solana_address, 'agent');+ }++ const wallets = [+ ...[...sol.values()].map((w) => ({+ chain: 'solana',+ address: w.address,+ source: w.source,+ explorer: `https://solscan.io/account/${w.address}`,+ })),+ ...[...evm.values()].map((w) => ({+ chain: 'evm',+ address: w.address,+ chain_id: w.chainId,+ source: w.source,+ explorer: explorerForEvm(w.chainId, w.address),+ })),+ ];++ // Accessories: premium cosmetics any of the user's wallets actually own.+ const accessories = await loadAccessories([...sol.keys(), ...evm.keys()]);++ // NFTs across all wallets. Each cache MISS that reaches a billed provider+ // must pass the shared Helius DAS ceiling — a hard cost cap independent of+ // caching (which can't stop enumeration of distinct usernames).+ let nfts = [];+ const solWallets = [...sol.keys()].slice(0, MAX_WALLETS_PER_CHAIN);+ const evmWallets = [...evm.values()].slice(0, MAX_WALLETS_PER_CHAIN);++ if (solWallets.length || evmWallets.length) {+ const ceiling = await limits.heliusDasGlobal();+ if (ceiling.success) {+ const batches = await Promise.all([+ ...solWallets.map((w) => fetchSolanaNfts(w).catch(() => [])),+ ...evmWallets.map((w) => fetchEvmNfts(w.address, w.chainId).catch(() => [])),+ ]);+ const seen = new Set();+ for (const item of batches.flat()) {+ if (!item || seen.has(item.id)) continue;+ seen.add(item.id);+ nfts.push(item);+ if (nfts.length >= NFT_CAP) break;+ }+ // Models first (they render in 3D on the profile), then the rest.+ nfts.sort((a, b) => (b.model ? 1 : 0) - (a.model ? 1 : 0));+ }+ // ceiling hit → nfts stays []; the tab simply shows its empty state.+ }++ const payload = {+ wallets,+ nfts,+ accessories,+ counts: {+ wallets: wallets.length,+ nfts: nfts.length,+ accessories: accessories.length,+ },+ };++ await cacheSet(cacheKey, payload, CACHE_TTL_SECONDS).catch(() => {});++ res.setHeader('Cache-Control', 'public, s-maxage=300, stale-while-revalidate=900');+ return json(res, 200, payload);+});++function explorerForEvm(chainId, address) {+ const bases = {+ 1: 'https://etherscan.io',+ 8453: 'https://basescan.org',+ 137: 'https://polygonscan.com',+ 10: 'https://optimistic.etherscan.io',+ 42161: 'https://arbiscan.io',+ };+ const base = bases[Number(chainId)] || bases[1];+ return `${base}/address/${address}`;+}++// Premium cosmetics the user's wallets purchased over the x402 rail. The free+// base accessory pack is owned by everyone, so it isn't profile-specific — we+// surface only purchased (premium) items here.+async function loadAccessories(accountIds) {+ const owned = new Set();+ for (const raw of accountIds) {+ const account = normalizeAccountId(raw);+ if (!account) continue;+ const ids = await readOwnedCosmetics(account).catch(() => []);+ for (const id of ids) owned.add(id);+ }+ if (!owned.size) return [];+ return buildCatalog({ ownedIds: [...owned] })+ .filter((c) => c.premium && c.owned)+ .map((c) => ({+ id: c.id,+ name: c.name,+ slot: c.slot,+ rarity: c.rarity,+ previewImage: c.previewImage,+ glbUrl: c.glbUrl || null,+ }));+}++// Solana NFTs via Helius DAS getAssetsByOwner. Non-fungible only.+async function fetchSolanaNfts(wallet) {+ const resp = await fetch(env.SOLANA_RPC_URL, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: 'collectibles',+ method: 'getAssetsByOwner',+ params: {+ ownerAddress: wallet,+ page: 1,+ limit: NFT_CAP,+ displayOptions: {+ showFungible: false,+ showNativeBalance: false,+ showCollectionMetadata: true,+ showUnverifiedCollections: false,+ showZeroBalance: false,+ },+ },+ }),+ });+ if (!resp.ok) throw new Error(`Helius DAS ${resp.status}`);+ const data = await resp.json();+ if (data.error) throw new Error('Helius DAS rpc error');+ const items = data.result?.items || [];+ return items+ .filter((a) => !a.burnt)+ .map((a) => {+ const image =+ a.content?.links?.image ||+ a.content?.files?.find((f) => f.mime?.startsWith('image/'))?.uri ||+ null;+ const model = a.content?.files?.find((f) => f.mime?.startsWith('model/'))?.uri || null;+ return {+ id: a.id,+ chain: 'solana',+ name: a.content?.metadata?.name || a.id,+ collection:+ a.grouping?.find((g) => g.group_key === 'collection')?.collection_metadata?.name ||+ null,+ image,+ model,+ explorer: `https://solscan.io/token/${a.id}`,+ };+ })+ .filter((n) => n.image || n.model);+}++// EVM NFTs via Alchemy getNFTsForOwner. Skipped silently when ALCHEMY_API_KEY+// is absent (no key → no EVM NFTs, never an error).+async function fetchEvmNfts(wallet, chainId) {+ // env has no ALCHEMY getter — read the raw var. No key ⇒ no EVM NFTs (Solana+ // still works), never an error.+ const apiKey = process.env.ALCHEMY_API_KEY;+ if (!apiKey) return [];+ const hosts = {+ 1: 'eth-mainnet',+ 8453: 'base-mainnet',+ 137: 'polygon-mainnet',+ 10: 'opt-mainnet',+ 42161: 'arb-mainnet',+ };+ const host = hosts[Number(chainId)] || 'eth-mainnet';+ const url = `https://${host}.g.alchemy.com/nft/v3/${apiKey}/getNFTsForOwner?owner=${encodeURIComponent(wallet)}&withMetadata=true&pageSize=${NFT_CAP}&excludeFilters[]=SPAM`;+ const resp = await fetch(url);+ if (!resp.ok) throw new Error(`Alchemy ${resp.status}`);+ const data = await resp.json();+ const base = explorerForEvm(chainId, '').replace(/\/address\/$/, '');+ return (data.ownedNfts || [])+ .map((n) => {+ const image = n.image?.cachedUrl || n.image?.originalUrl || n.media?.[0]?.gateway || null;+ const anim = n.raw?.metadata?.animation_url || null;+ const model = anim && /\.(glb|gltf)(\?|$)/i.test(anim) ? anim : null;+ const contract = n.contract?.address;+ return {+ id: `${chainId}:${contract}:${n.tokenId}`,+ chain: 'evm',+ name: n.name || n.contract?.name || `#${n.tokenId}`,+ collection: n.collection?.name || n.contract?.name || null,+ image,+ model,+ explorer: contract ? `${base}/nft/${contract}/${n.tokenId}` : null,+ };+ })+ .filter((n) => n.image || n.model);+}diff --git a/api/users/referral-claim.js b/api/users/referral-claim.jsindex 92bd35202..02bf08974 100644--- a/api/users/referral-claim.js+++ b/api/users/referral-claim.js@@ -22,8 +22,10 @@ import { cors, json, error, method, wrap, rateLimited, readJson } from '../_lib/import { limits, clientIp } from '../_lib/rate-limit.js';import { insertNotification } from '../_lib/notify.js';-// Referral codes use a base32-like alphabet (api/_lib/referrals.js).-const CODE_RE = /^[A-Z2-9]{4,20}$/;+// Canonical referral-code shape (api/_lib/referrals.js REFERRAL_CODE_RE): A–Z+// and 0–9, 3–20 chars. Accepts vanity codes (the member's name), not just the+// restricted alphabet the auto-generator draws from.+const CODE_RE = /^[A-Z0-9]{3,20}$/;// How long after signup a referral can still be attributed. The once-only// `referred_by_id IS NULL` guard does the heavy lifting; this window simply@@ -70,7 +72,7 @@ export default wrap(async (req, res) => {const [referrer] = await sql`SELECT id, display_name, usernameFROM users- WHERE referral_code = ${code} AND id <> ${me.id} AND deleted_at IS NULL+ WHERE UPPER(referral_code) = ${code} AND id <> ${me.id} AND deleted_at IS NULLLIMIT 1`;if (!referrer) return json(res, 200, { status: 'invalid' });diff --git a/api/users/referral-code.js b/api/users/referral-code.jsnew file mode 100644index 000000000..1c824ff69--- /dev/null+++ b/api/users/referral-code.js@@ -0,0 +1,67 @@+// /api/users/referral-code — customize the signed-in user's referral code.+//+// GET ?code=<desired> → live availability check for the code editor:+// { available, reason, code }+// reason ∈ ok | current | invalid | reserved | taken+// PUT { code } → claim the code:+// { referral_code, changed }+//+// Codes default to the member's name at signup (api/_lib/referrals.js); this is+// where they make it their own. Stored uppercase-canonical so the UNIQUE index+// enforces case-insensitive global uniqueness and every ?ref= lookup matches+// without per-call lowering.++import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';+import { requireCsrf } from '../_lib/csrf.js';+import { cors, json, error, method, wrap, rateLimited, readJson } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import {+ getReferralCodeAvailability,+ setReferralCode,+ REFERRAL_CODE_MIN_LEN,+ REFERRAL_CODE_MAX_LEN,+} from '../_lib/referrals.js';++async function resolveAuth(req) {+ const session = await getSessionUser(req);+ if (session) return { userId: session.id, session };+ const bearer = await authenticateBearer(extractBearer(req));+ if (bearer) return { userId: bearer.userId, session: null };+ return null;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,PUT,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET', 'PUT'])) return;++ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const auth = await resolveAuth(req);+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');++ if (req.method === 'GET') {+ const url = new URL(req.url, 'http://localhost');+ const result = await getReferralCodeAvailability(auth.userId, url.searchParams.get('code'));+ return json(res, 200, {+ ...result,+ min_length: REFERRAL_CODE_MIN_LEN,+ max_length: REFERRAL_CODE_MAX_LEN,+ });+ }++ // PUT — a mutation: CSRF only applies to cookie sessions (bearer tokens are+ // not ambient credentials and so aren't CSRF-able).+ if (auth.session && !(await requireCsrf(req, res, auth.userId))) return;++ const body = await readJson(req);+ try {+ const result = await setReferralCode(auth.userId, body?.code);+ return json(res, 200, result);+ } catch (err) {+ if (err && err.name === 'ReferralCodeError') {+ return error(res, err.status, err.reason, err.message);+ }+ throw err;+ }+});diff --git a/data/changelog.json b/data/changelog.jsonindex eb2d2bfb4..c3a67fae9 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,26 @@{"$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-21",+ "title": "Referrals: claim a custom code that's yours",+ "summary": "Your referral code now starts as your name instead of a random string — and you can change it to anything you like. Open Referrals in your dashboard, hit Customize, and pick a code (3–20 letters or numbers); it checks availability as you type and updates your shareable link, QR, and membership card the moment you save. Existing links keep working, codes are matched case-insensitively, and you still earn 5% in USDC on every referred purchase.",+ "tags": ["feature"],+ "link": "/dashboard/referrals"+ },+ {+ "date": "2026-06-21",+ "title": "Profiles: your whole on-chain self in one place",+ "summary": "Your profile at three.ws/u/<username> now shows everything you make and own. New Collectibles and Accessories tabs surface the NFTs held across your wallets — 3D NFTs rotate live right in the grid — and the premium avatar items you've bought. Your linked wallets appear as chain-tagged chips with one-tap copy and a block-explorer link, spanning both Solana and EVM. Every avatar now has a Fork button so anyone can save a copy of it (and its agent) to their own account, with a running fork count on each card. And a new Share menu lets you post your profile straight to X or share it through your phone's native share sheet, alongside copy-link.",+ "tags": ["feature"]+ },+ {+ "date": "2026-06-21",+ "title": "Studio Lab: six free 3D generators, right in your browser",+ "summary": "The new Lab tab in Studio turns text and parameters into real 3D — no API key, no cost, nothing leaves your machine. Build math-driven parametric solids and supershapes, extrude 3D lettering from any string, turn an SVG icon or logo into a solid model, generate a lithophane relief from a photo, or grow a procedural landscape from a seed — each one previews live and downloads as a real GLB. Plus a Gaussian-splat viewer for the photoreal radiance-field format (.splat / .ply). Powered by three.js and GaussianSplats3D.",+ "tags": ["feature"],+ "link": "/forge-studio"+ },{"date": "2026-06-21","title": "Pole Club: every dancer stands on her stage",diff --git a/pages/profile.html b/pages/profile.htmlindex 876fcd21f..9a3161806 100644--- a/pages/profile.html+++ b/pages/profile.html@@ -920,6 +920,246 @@}.up-follow-mini[data-following="true"] { color: rgba(255, 255, 255, 0.55); }.up-follow-mini:hover { border-color: rgba(255, 255, 255, 0.45); }++ /* ── Wallets row ─────────────────────────────────────────────────── */+ .up-wallets {+ display: flex;+ flex-wrap: wrap;+ gap: 0.45rem;+ margin: 0.6rem 0 0;+ }+ .up-wallet-chip {+ display: inline-flex;+ align-items: center;+ gap: 0.4rem;+ background: rgba(255, 255, 255, 0.03);+ border: 1px solid rgba(255, 255, 255, 0.09);+ border-radius: 999px;+ padding: 0.3rem 0.4rem 0.3rem 0.7rem;+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;+ font-size: 0.68rem;+ color: rgba(255, 255, 255, 0.6);+ transition: border-color 0.15s, background 0.15s;+ }+ .up-wallet-chip:hover { border-color: rgba(255, 255, 255, 0.2); }+ .up-wallet-chip .up-chain-dot {+ width: 7px; height: 7px; border-radius: 50%; flex-shrink: 0;+ }+ .up-wallet-chip[data-chain="solana"] .up-chain-dot { background: #14f195; }+ .up-wallet-chip[data-chain="evm"] .up-chain-dot { background: #627eea; }+ .up-wallet-chip a { color: inherit; text-decoration: none; }+ .up-wallet-chip a:hover { color: #fff; }+ .up-wallet-copy, .up-wallet-link {+ background: transparent;+ border: 0;+ color: rgba(255, 255, 255, 0.35);+ cursor: pointer;+ padding: 0.15rem;+ display: inline-flex;+ border-radius: 5px;+ transition: color 0.15s, background 0.15s;+ }+ .up-wallet-copy:hover, .up-wallet-link:hover {+ color: #fff;+ background: rgba(255, 255, 255, 0.08);+ }+ .up-wallet-copy.copied { color: #4ade80; }++ /* ── NFT grid ────────────────────────────────────────────────────── */+ .up-nft-grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));+ gap: 1rem;+ }+ .up-nft-card {+ background: rgba(255, 255, 255, 0.02);+ border: 1px solid rgba(255, 255, 255, 0.07);+ border-radius: 12px;+ overflow: hidden;+ display: flex;+ flex-direction: column;+ text-decoration: none;+ color: inherit;+ transition: border-color 0.15s, transform 0.15s;+ }+ .up-nft-card:hover { border-color: rgba(255, 255, 255, 0.16); transform: translateY(-2px); }+ .up-nft-media {+ aspect-ratio: 1;+ background: radial-gradient(ellipse at center, rgba(255, 215, 0, 0.04), transparent 70%);+ position: relative;+ overflow: hidden;+ }+ .up-nft-media img, .up-nft-media model-viewer {+ width: 100%; height: 100%; object-fit: cover; background: transparent;+ }+ .up-nft-badge {+ position: absolute;+ top: 0.5rem;+ right: 0.5rem;+ font-size: 0.5rem;+ text-transform: uppercase;+ letter-spacing: 0.1em;+ padding: 0.15rem 0.45rem;+ border-radius: 999px;+ background: rgba(0, 0, 0, 0.55);+ backdrop-filter: blur(4px);+ color: #ffd700;+ border: 1px solid rgba(255, 215, 0, 0.3);+ }+ .up-nft-chain {+ position: absolute;+ top: 0.5rem;+ left: 0.5rem;+ width: 9px; height: 9px; border-radius: 50%;+ box-shadow: 0 0 0 3px rgba(0, 0, 0, 0.4);+ }+ .up-nft-chain[data-chain="solana"] { background: #14f195; }+ .up-nft-chain[data-chain="evm"] { background: #627eea; }+ .up-nft-body { padding: 0.6rem 0.7rem 0.7rem; }+ .up-nft-name {+ font-size: 0.78rem;+ color: rgba(255, 255, 255, 0.9);+ margin: 0;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ }+ .up-nft-coll {+ font-size: 0.6rem;+ color: rgba(255, 255, 255, 0.35);+ margin: 0.15rem 0 0;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ }++ /* ── Accessories grid ────────────────────────────────────────────── */+ .up-acc-grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));+ gap: 0.875rem;+ }+ .up-acc-card {+ background: rgba(255, 255, 255, 0.02);+ border: 1px solid rgba(255, 255, 255, 0.07);+ border-radius: 12px;+ overflow: hidden;+ text-align: center;+ }+ .up-acc-thumb {+ aspect-ratio: 1;+ display: flex;+ align-items: center;+ justify-content: center;+ background: radial-gradient(ellipse at center, rgba(154, 140, 255, 0.06), transparent 70%);+ }+ .up-acc-thumb img { width: 100%; height: 100%; object-fit: contain; padding: 0.6rem; box-sizing: border-box; }+ .up-acc-thumb-empty { font-size: 2rem; color: rgba(154, 140, 255, 0.4); }+ .up-acc-body { padding: 0.5rem 0.6rem 0.7rem; }+ .up-acc-name { font-size: 0.74rem; color: rgba(255, 255, 255, 0.85); margin: 0 0 0.3rem; }+ .up-rarity {+ display: inline-block;+ font-size: 0.5rem;+ text-transform: uppercase;+ letter-spacing: 0.08em;+ padding: 0.12rem 0.45rem;+ border-radius: 999px;+ }+ .up-rarity[data-rarity="common"] { background: rgba(255,255,255,0.08); color: rgba(255,255,255,0.6); }+ .up-rarity[data-rarity="rare"] { background: rgba(105,183,255,0.12); color: #69b7ff; }+ .up-rarity[data-rarity="epic"] { background: rgba(186,104,255,0.14); color: #ba68ff; }+ .up-rarity[data-rarity="legendary"] { background: rgba(255,196,0,0.14); color: #ffc400; }++ /* ── Fork button on avatar cards ─────────────────────────────────── */+ .up-card-actions {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 0.5rem;+ padding-top: 0.4rem;+ }+ .up-fork-btn {+ display: inline-flex;+ align-items: center;+ gap: 0.3rem;+ background: transparent;+ border: 1px solid rgba(255, 255, 255, 0.14);+ color: rgba(255, 255, 255, 0.6);+ font-family: inherit;+ font-size: 0.6rem;+ padding: 0.22rem 0.55rem;+ border-radius: 999px;+ cursor: pointer;+ transition: border-color 0.15s, color 0.15s, background 0.15s;+ }+ .up-fork-btn:hover { border-color: rgba(154, 140, 255, 0.5); color: #9a8cff; }+ .up-fork-btn[disabled] { opacity: 0.5; cursor: default; }+ .up-fork-count {+ font-size: 0.55rem;+ font-family: ui-monospace, Menlo, monospace;+ color: rgba(255, 255, 255, 0.3);+ }++ /* ── Share menu ──────────────────────────────────────────────────── */+ .profile-share-wrap { position: relative; }+ .profile-share-menu {+ position: absolute;+ top: calc(100% + 0.4rem);+ right: 0;+ background: var(--bg-0, #0a0a0a);+ border: 1px solid rgba(255, 255, 255, 0.12);+ border-radius: 12px;+ padding: 0.4rem;+ min-width: 200px;+ z-index: 50;+ box-shadow: 0 12px 40px rgba(0, 0, 0, 0.5);+ animation: up-modal-in 0.15s ease both;+ }+ .profile-share-menu[hidden] { display: none; }+ .profile-share-item {+ display: flex;+ align-items: center;+ gap: 0.6rem;+ width: 100%;+ background: transparent;+ border: 0;+ color: rgba(255, 255, 255, 0.85);+ font-family: inherit;+ font-size: 0.8rem;+ padding: 0.55rem 0.6rem;+ border-radius: 8px;+ cursor: pointer;+ text-align: left;+ text-decoration: none;+ transition: background 0.12s;+ }+ .profile-share-item:hover { background: rgba(255, 255, 255, 0.06); }+ .profile-share-item svg { width: 15px; height: 15px; flex-shrink: 0; opacity: 0.75; }++ /* ── Toast ───────────────────────────────────────────────────────── */+ .up-toast {+ position: fixed;+ left: 50%;+ bottom: 2rem;+ transform: translateX(-50%) translateY(1rem);+ background: rgba(20, 20, 20, 0.96);+ border: 1px solid rgba(255, 255, 255, 0.14);+ color: #fff;+ padding: 0.7rem 1.1rem;+ border-radius: 999px;+ font-size: 0.85rem;+ z-index: 10000;+ opacity: 0;+ transition: opacity 0.2s ease, transform 0.2s ease;+ box-shadow: 0 10px 40px rgba(0, 0, 0, 0.5);+ display: flex;+ align-items: center;+ gap: 0.5rem;+ }+ .up-toast.show { opacity: 1; transform: translateX(-50%) translateY(0); }+ .up-toast a { color: #9a8cff; text-decoration: none; }+ .up-toast--ok { border-color: rgba(74, 222, 128, 0.4); }+ .up-toast--err { border-color: rgba(255, 122, 122, 0.5); }</style><link rel="stylesheet" href="/nav.css" /><link rel="stylesheet" href="/mobile.css" />@@ -931,9 +1171,12 @@<header class="profile-page-header"><a href="/" aria-label="Back to three.ws home">← three.ws</a>- <button class="profile-copy-btn" id="copy-profile-btn" aria-label="Copy profile link">- copy link- </button>+ <div class="profile-share-wrap">+ <button class="profile-copy-btn" id="share-profile-btn" aria-label="Share profile" aria-haspopup="true" aria-expanded="false">+ share ↗+ </button>+ <div class="profile-share-menu" id="share-menu" role="menu" hidden></div>+ </div></header><main>@@ -1115,7 +1358,8 @@const slug = segments[1]; // /u/<slug>const root = document.getElementById('profile-root');- const copyBtn = document.getElementById('copy-profile-btn');+ const shareBtn = document.getElementById('share-profile-btn');+ const shareMenu = document.getElementById('share-menu');if (!slug) {root.innerHTML = `<div class="up-error">No profile specified.</div>`;@@ -1168,6 +1412,7 @@plugins = [],coins = [],memories = [],+ shop = [],} = data;// Who's viewing? Drives the owner-only Edit button vs the Follow button.@@ -1435,6 +1680,7 @@['plugins', 'Plugins'],['coins', 'Coins'],['memories', 'Memories'],+ ['shop', 'For Sale'],];if (stats.widget_views > 0) statDefs.push(['widget_views', 'Widget Views']);const statsHtml =@@ -1458,15 +1704,17 @@{ key: 'widgets', label: 'Widgets', count: widgets.length },{ key: 'skills', label: 'Skills', count: skills.length },{ key: 'plugins', label: 'Plugins', count: plugins.length },+ { key: 'shop', label: 'For sale', count: shop.length },{ key: 'coins', label: 'Coins', count: coins.length },{ key: 'memories', label: 'Memories', count: memories.length },];const visibleTabs = tabs.filter((t) => t.count > 0);const defaultTab = visibleTabs[0]?.key || 'avatars';- const tabBar =- visibleTabs.length > 1- ? `<div class="up-tabs" role="tablist">+ // Tab bar is always present (with an id) so the lazily-loaded NFT and+ // Accessories tabs can be appended once /collectibles resolves. It is+ // hidden whenever fewer than two tabs are ultimately visible.+ const tabBar = `<div class="up-tabs" id="up-tab-bar" role="tablist"${visibleTabs.length > 1 ? '' : ' hidden'}>${visibleTabs.map((t) => `@@ -1477,8 +1725,7 @@`,).join('')}- </div>`- : '';+ </div>`;// Banner + profile picture + bio + actionsconst bannerHtml = user.banner_url@@ -1525,6 +1772,7 @@${walletPill}${snsPillSlot}</div>+ <div class="up-wallets" id="up-wallets"></div></div></div><div id="up-walk-hero"></div>@@ -1551,23 +1799,85 @@<section class="up-section" data-section="memories"${defaultTab === 'memories' ? '' : ' hidden'}>${renderMemoriesList(memories)}</section>+ <section class="up-section" data-section="shop"${defaultTab === 'shop' ? '' : ' hidden'}>+ ${renderShopGrid(shop)}+ </section>+ <section class="up-section" data-section="nfts" hidden>+ <div id="up-nfts-body"></div>+ </section>+ <section class="up-section" data-section="accessories" hidden>+ <div id="up-accessories-body"></div>+ </section>`;- // Tab switching- rootEl.querySelectorAll('.up-tab').forEach((btn) => {- btn.addEventListener('click', () => {- const key = btn.dataset.tab;- rootEl.querySelectorAll('.up-tab').forEach((b) => {- const active = b.dataset.tab === key;- b.classList.toggle('up-tab--active', active);- b.setAttribute('aria-selected', active ? 'true' : 'false');- });- rootEl.querySelectorAll('.up-section').forEach((s) => {- s.hidden = s.dataset.section !== key;- });+ // Tab switching — delegated so lazily-added NFT/Accessories tabs work.+ const tabBarEl = rootEl.querySelector('#up-tab-bar');+ function activateTab(key) {+ rootEl.querySelectorAll('.up-tab').forEach((b) => {+ const active = b.dataset.tab === key;+ b.classList.toggle('up-tab--active', active);+ b.setAttribute('aria-selected', active ? 'true' : 'false');});+ rootEl.querySelectorAll('.up-section').forEach((s) => {+ s.hidden = s.dataset.section !== key;+ });+ }+ tabBarEl?.addEventListener('click', (e) => {+ const btn = e.target.closest('.up-tab');+ if (btn) activateTab(btn.dataset.tab);+ });++ // Fork an avatar (clones the GLB + its agent + a fresh wallet into the+ // viewer's namespace). Signed-out viewers are routed to login first.+ rootEl.addEventListener('click', async (e) => {+ const btn = e.target.closest('.up-fork-btn');+ if (!btn) return;+ e.preventDefault();+ if (!viewer) {+ location.href = `/login?return=${encodeURIComponent('/u/' + user.username)}`;+ return;+ }+ const avatarId = btn.dataset.avatar;+ btn.disabled = true;+ const label = btn.querySelector('.up-fork-label');+ const prev = label ? label.textContent : '';+ if (label) label.textContent = 'Forking…';+ try {+ const r = await apiFetch('/api/avatars/fork', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ source_avatar_id: avatarId }),+ });+ const j = await r.json().catch(() => ({}));+ if (!r.ok) throw new Error(j.error_description || 'Fork failed');+ const newId = j.avatar?.id || j.id;+ showToast(+ newId+ ? `Forked. <a href="/avatars/${esc(newId)}">Open your copy →</a>`+ : 'Forked to your account.',+ 'ok',+ );+ // Bump the visible fork count optimistically.+ const countEl = btn.parentElement?.querySelector('.up-fork-count');+ if (countEl) {+ const n = (parseInt(countEl.dataset.count || '0', 10) || 0) + 1;+ countEl.dataset.count = String(n);+ countEl.textContent = `${formatStat(n)} fork${n === 1 ? '' : 's'}`;+ }+ } catch (err) {+ showToast(esc(err.message || 'Could not fork.'), 'err');+ } finally {+ btn.disabled = false;+ if (label) label.textContent = prev || 'Fork';+ }});+ // Lazy-load on-chain collectibles (NFTs, accessories, wallets). Kept+ // out of the main payload because the NFT providers are slow + billed;+ // the profile paints first, these fill in after.+ loadCollectibles(rootEl, user, tabBarEl);+// Follow / unfollowconst followBtn = rootEl.querySelector('#up-follow-btn');if (followBtn) {@@ -1810,6 +2120,153 @@return String(n);}+ // Transient bottom toast. `kind` ∈ {'', 'ok', 'err'}. HTML allowed for the+ // short "open your copy" link — callers escape any interpolated values.+ let toastTimer;+ function showToast(html, kind = '') {+ document.getElementById('up-toast')?.remove();+ clearTimeout(toastTimer);+ const t = document.createElement('div');+ t.id = 'up-toast';+ t.className = `up-toast${kind ? ' up-toast--' + kind : ''}`;+ t.innerHTML = html;+ document.body.appendChild(t);+ requestAnimationFrame(() => t.classList.add('show'));+ toastTimer = setTimeout(() => {+ t.classList.remove('show');+ setTimeout(() => t.remove(), 250);+ }, 5000);+ }++ // ── Collectibles (lazy) ─────────────────────────────────────────────+ // Fetches /api/users/:username/collectibles after the main paint and+ // fills the Wallets row + NFT/Accessories tabs. Failure is silent — the+ // surfaces just stay absent rather than showing a broken state.+ async function loadCollectibles(rootEl, user, tabBarEl) {+ let data;+ try {+ const r = await fetch(+ `/api/users/${encodeURIComponent(user.username)}/collectibles`,+ );+ if (!r.ok) return;+ data = await r.json();+ } catch {+ return;+ }+ const { wallets = [], nfts = [], accessories = [] } = data;++ // Wallets row — chain-tagged chips with copy + explorer.+ const walletsEl = rootEl.querySelector('#up-wallets');+ if (walletsEl && wallets.length) {+ walletsEl.innerHTML = wallets+ .map((w) => {+ const short = `${w.address.slice(0, 4)}…${w.address.slice(-4)}`;+ const label = w.chain === 'solana' ? 'SOL' : 'EVM';+ return `<span class="up-wallet-chip" data-chain="${attr(w.chain)}" title="${attr(w.address)}">+ <span class="up-chain-dot"></span>+ <span class="up-wallet-label">${esc(label)}</span>+ <a href="${attr(w.explorer)}" target="_blank" rel="noopener">${esc(short)}</a>+ <button class="up-wallet-copy" type="button" data-addr="${attr(w.address)}" aria-label="Copy address">+ <svg width="12" height="12" viewBox="0 0 16 16" aria-hidden="true"><path fill="currentColor" d="M10 1H4a2 2 0 0 0-2 2v7h1.5V3a.5.5 0 0 1 .5-.5h6zM12 4H7a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h5a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2"/></svg>+ </button>+ </span>`;+ })+ .join('');+ walletsEl.querySelectorAll('.up-wallet-copy').forEach((b) => {+ b.addEventListener('click', async () => {+ try {+ await navigator.clipboard.writeText(b.dataset.addr);+ b.classList.add('copied');+ setTimeout(() => b.classList.remove('copied'), 1200);+ } catch {}+ });+ });+ }++ // NFTs + Accessories tabs are revealed only when non-empty.+ if (nfts.length) {+ rootEl.querySelector('#up-nfts-body').innerHTML = renderNftGrid(nfts);+ addDeferredTab(tabBarEl, 'nfts', 'Collectibles', nfts.length);+ addStat(rootEl, 'NFTs', nfts.length);+ }+ if (accessories.length) {+ rootEl.querySelector('#up-accessories-body').innerHTML =+ renderAccessoriesGrid(accessories);+ addDeferredTab(tabBarEl, 'accessories', 'Accessories', accessories.length);+ addStat(rootEl, 'Accessories', accessories.length);+ }+ }++ // Append a tab button to the (initially possibly-hidden) tab bar and+ // reveal the bar once it carries more than one tab.+ function addDeferredTab(tabBarEl, key, label, count) {+ if (!tabBarEl || tabBarEl.querySelector(`[data-tab="${key}"]`)) return;+ const btn = document.createElement('button');+ btn.className = 'up-tab';+ btn.setAttribute('role', 'tab');+ btn.dataset.tab = key;+ btn.setAttribute('aria-selected', 'false');+ btn.innerHTML = `${esc(label)} <span class="up-tab-badge">${count}</span>`;+ tabBarEl.appendChild(btn);+ if (tabBarEl.querySelectorAll('.up-tab').length > 1) tabBarEl.hidden = false;+ }++ // Append a read-only stat tile to the strip.+ function addStat(rootEl, label, n) {+ const strip = rootEl.querySelector('.up-stats');+ if (!strip) return;+ const tile = document.createElement('div');+ tile.className = 'up-stat';+ tile.innerHTML = `<span class="up-stat-num">${formatStat(n)}</span><span class="up-stat-label">${esc(label)}</span>`;+ strip.appendChild(tile);+ }++ function renderNftGrid(nfts) {+ if (!nfts.length) return `<p class="up-empty">No collectibles found.</p>`;+ const cards = nfts+ .map((n) => {+ const media = n.model+ ? `<model-viewer src="${attr(n.model)}" alt="${attr(n.name)}" auto-rotate auto-rotate-delay="0" rotation-per-second="20deg" interaction-prompt="none" camera-controls disable-zoom shadow-intensity="0.4" exposure="0.95" environment-image="neutral" loading="lazy"></model-viewer><span class="up-nft-badge">3D</span>`+ : n.image+ ? `<img src="${attr(n.image)}" alt="${attr(n.name)}" loading="lazy" referrerpolicy="no-referrer">`+ : `<div class="up-card-thumb-placeholder">◎</div>`;+ const inner = `+ <div class="up-nft-media">+ <span class="up-nft-chain" data-chain="${attr(n.chain)}" title="${attr(n.chain === 'solana' ? 'Solana' : 'EVM')}"></span>+ ${media}+ </div>+ <div class="up-nft-body">+ <p class="up-nft-name" title="${attr(n.name)}">${esc(n.name)}</p>+ ${n.collection ? `<p class="up-nft-coll">${esc(n.collection)}</p>` : ''}+ </div>`;+ return n.explorer+ ? `<a class="up-nft-card" href="${attr(n.explorer)}" target="_blank" rel="noopener">${inner}</a>`+ : `<div class="up-nft-card">${inner}</div>`;+ })+ .join('');+ return `<div class="up-nft-grid">${cards}</div>`;+ }++ function renderAccessoriesGrid(items) {+ if (!items.length) return `<p class="up-empty">No accessories owned yet.</p>`;+ const cards = items+ .map((a) => {+ const thumb = a.previewImage+ ? `<img src="${attr(a.previewImage)}" alt="${attr(a.name)}" loading="lazy">`+ : `<div class="up-acc-thumb-empty">◈</div>`;+ return `+ <div class="up-acc-card">+ <div class="up-acc-thumb">${thumb}</div>+ <div class="up-acc-body">+ <p class="up-acc-name">${esc(a.name)}</p>+ <span class="up-rarity" data-rarity="${attr(a.rarity || 'common')}">${esc(a.rarity || 'common')}</span>+ </div>+ </div>`;+ })+ .join('');+ return `<div class="up-acc-grid">${cards}</div>`;+ }+function renderAvatarsGrid(avatars) {if (!avatars.length) {return `<p class="up-empty">No public avatars yet.</p>`;@@ -1838,6 +2295,13 @@<div>${tags}</div>${a.size_bytes ? `<span class="up-card-id">${esc(sizeLabel)}</span>` : ''}</div>+ <div class="up-card-actions">+ <button class="up-fork-btn" type="button" data-avatar="${attr(a.id)}" title="Save a copy of this avatar to your account">+ <svg width="11" height="11" viewBox="0 0 16 16" aria-hidden="true"><path fill="currentColor" d="M5 3.25a1.75 1.75 0 1 0-2.5 1.58v6.34A1.75 1.75 0 1 0 5 12.75v-1.06a3 3 0 0 1 3-3h.59a1.75 1.75 0 1 0 0-1.5H8a4.5 4.5 0 0 0-3 1.14V4.83A1.75 1.75 0 0 0 5 3.25"/></svg>+ <span class="up-fork-label">Fork</span>+ </button>+ <span class="up-fork-count" data-count="${a.fork_count || 0}">${a.fork_count ? `${formatStat(a.fork_count)} fork${a.fork_count === 1 ? '' : 's'}` : ''}</span>+ </div></div></article>`;@@ -2025,6 +2489,43 @@return `<div class="up-grid">${cards}</div>`;}+ // Items the user actively lists for sale (asset_prices). Each card deep+ // links to the item's own page, where the existing purchase flow lives —+ // the profile never duplicates checkout.+ function renderShopGrid(shop) {+ if (!shop.length) {+ return `<p class="up-empty">Nothing for sale yet. <a href="/marketplace">Visit the marketplace →</a></p>`;+ }+ const glyphs = { avatar: '◎', agent: '◆', plugin: '◈' };+ const fmtPrice = (n) => {+ if (!Number.isFinite(n)) return '0';+ const s = n.toFixed(n < 1 ? 4 : 2);+ return s.replace(/\.?0+$/, '');+ };+ const cards = shop+ .map((s) => {+ const thumb = s.image+ ? `<img src="${attr(s.image)}" alt="${attr(s.name)}" style="width:100%;height:100%;object-fit:cover" referrerpolicy="no-referrer">`+ : `<div class="up-card-thumb-placeholder">${glyphs[s.item_type] || '◎'}</div>`;+ const priceLabel = `${fmtPrice(s.price)} ${esc(s.currency || '')}`.trim();+ return `+ <a class="up-card" href="${attr(s.href)}" style="text-decoration:none">+ <div class="up-card-thumb">${thumb}</div>+ <div class="up-card-body">+ <span class="up-card-chain">${esc(s.item_type)}</span>+ <span class="up-card-name">${esc(s.name)}</span>+ <div class="up-card-footer">+ <span class="up-card-row-pill">${priceLabel}</span>+ <span class="up-card-edit">Buy →</span>+ </div>+ </div>+ </a>+ `;+ })+ .join('');+ return `<div class="up-grid">${cards}</div>`;+ }+function renderMemoriesList(memories) {if (!memories.length) return `<p class="up-empty">No public memories yet.</p>`;const cards = memories@@ -2064,17 +2565,73 @@return `<div class="up-list up-list-cols-2">${cards}</div>`;}- // Copy profile URL to clipboard- copyBtn.addEventListener('click', async () => {- try {- await navigator.clipboard.writeText(location.href);- copyBtn.textContent = 'copied ✓';- copyBtn.classList.add('copied');- setTimeout(() => {- copyBtn.textContent = 'copy link';- copyBtn.classList.remove('copied');- }, 1800);- } catch {}+ // ── Social share ────────────────────────────────────────────────────+ // Toggle a small menu: native share (where supported), share to X, and+ // copy link. The menu is built lazily off the live document title/URL so+ // it reflects whichever profile finished rendering.+ function buildShareMenu() {+ const url = location.href;+ const title = document.title.replace(/ — three\.ws$/, '');+ const xText = `${title} on three.ws`;+ const xUrl = `https://twitter.com/intent/tweet?text=${encodeURIComponent(xText)}&url=${encodeURIComponent(url)}`;+ const canNativeShare = typeof navigator.share === 'function';+ shareMenu.innerHTML = `+ ${+ canNativeShare+ ? `<button class="profile-share-item" data-share="native" role="menuitem">+ <svg viewBox="0 0 16 16" aria-hidden="true"><path fill="currentColor" d="M11 5.5a2.5 2.5 0 1 0-2.45-3L5.9 4.06a2.5 2.5 0 1 0 0 3.88l2.65 1.56A2.5 2.5 0 1 0 11 7.5a2.49 2.49 0 0 0-1.6.58L6.95 6.56a2.5 2.5 0 0 0 0-1.12L9.4 4.92A2.49 2.49 0 0 0 11 5.5"/></svg>+ Share…+ </button>`+ : ''+ }+ <a class="profile-share-item" href="${attr(xUrl)}" target="_blank" rel="noopener" role="menuitem">+ <svg viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"/></svg>+ Share to X+ </a>+ <button class="profile-share-item" data-share="copy" role="menuitem">+ <svg viewBox="0 0 16 16" aria-hidden="true"><path fill="currentColor" d="M10 1H4a2 2 0 0 0-2 2v7h1.5V3a.5.5 0 0 1 .5-.5h6zM12 4H7a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h5a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2"/></svg>+ <span data-copy-label>Copy link</span>+ </button>+ `;+ shareMenu.querySelector('[data-share="native"]')?.addEventListener('click', async () => {+ closeShareMenu();+ try {+ await navigator.share({ title, url });+ } catch {}+ });+ shareMenu.querySelector('[data-share="copy"]')?.addEventListener('click', async (e) => {+ const lbl = e.currentTarget.querySelector('[data-copy-label]');+ try {+ await navigator.clipboard.writeText(url);+ if (lbl) lbl.textContent = 'Copied ✓';+ setTimeout(() => {+ if (lbl) lbl.textContent = 'Copy link';+ closeShareMenu();+ }, 1100);+ } catch {}+ });+ }+ function openShareMenu() {+ buildShareMenu();+ shareMenu.hidden = false;+ shareBtn.setAttribute('aria-expanded', 'true');+ setTimeout(() => document.addEventListener('click', onDocClick), 0);+ }+ function closeShareMenu() {+ shareMenu.hidden = true;+ shareBtn.setAttribute('aria-expanded', 'false');+ document.removeEventListener('click', onDocClick);+ }+ function onDocClick(e) {+ if (!e.target.closest('.profile-share-wrap')) closeShareMenu();+ }+ shareBtn.addEventListener('click', (e) => {+ e.stopPropagation();+ if (shareMenu.hidden) openShareMenu();+ else closeShareMenu();+ });+ document.addEventListener('keydown', (e) => {+ if (e.key === 'Escape' && !shareMenu.hidden) closeShareMenu();});</script><script src="/brand.js" defer></script>diff --git a/public/changelog.json b/public/changelog.jsonindex 0776124e1..4cfd8d583 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-21T17:29:42.338Z",+ "generated_at": "2026-06-21T18:25:29.194Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -695,6 +695,16 @@"feature"]},+ {+ "date": "2026-06-21",+ "type": "update",+ "title": "Profiles: your whole on-chain self in one place",+ "summary": "Your profile at three.ws/u/<username> now shows everything you make and own. New Collectibles and Accessories tabs surface the NFTs held across your wallets — 3D NFTs rotate live right in the grid — and the premium avatar items you've bought. Your linked wallets appear as chain-tagged chips with one-tap copy and a block-explorer link, spanning both Solana and EVM. Every avatar now has a Fork button so anyone can save a copy of it (and its agent) to their own account, with a running fork count on each card. And a new Share menu lets you post your profile straight to X or share it through your phone's native share sheet, alongside copy-link.",+ "link": null,+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-21","type": "update",@@ -706,6 +716,16 @@"sdk"]},+ {+ "date": "2026-06-21",+ "type": "update",+ "title": "Referrals: claim a custom code that's yours",+ "summary": "Your referral code now starts as your name instead of a random string — and you can change it to anything you like. Open Referrals in your dashboard, hit Customize, and pick a code (3–20 letters or numbers); it checks availability as you type and updates your shareable link, QR, and membership card the moment you save. Existing links keep working, codes are matched case-insensitively, and you still earn 5% in USDC on every referred purchase.",+ "link": "/dashboard/referrals",+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-21","type": "update",@@ -759,6 +779,16 @@"infra"]},+ {+ "date": "2026-06-21",+ "type": "update",+ "title": "Studio Lab: six free 3D generators, right in your browser",+ "summary": "The new Lab tab in Studio turns text and parameters into real 3D — no API key, no cost, nothing leaves your machine. Build math-driven parametric solids and supershapes, extrude 3D lettering from any string, turn an SVG icon or logo into a solid model, generate a lithophane relief from a photo, or grow a procedural landscape from a seed — each one previews live and downloads as a real GLB. Plus a Gaussian-splat viewer for the photoreal radiance-field format (.splat / .ply). Powered by three.js and GaussianSplats3D.",+ "link": "/forge-studio",+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-21","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 8c0e30e70..feddd8f15 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -534,6 +534,14 @@<category>feature</category><description>Your three.ws profile at three.ws/u/<your-username> is now a real social home. Edit it in place: add a bio, a profile picture and banner image, your location, and a website link — all from an Edit button on your own profile. You can now follow other creators and agents, and they can follow you; every profile shows live follower and following counts you can tap to browse the lists, with one-tap follow buttons throughout. And there's a new Feed at three.ws/feed that gathers the latest avatars, agents, and coin launches from everyone you follow, newest first. Find your profile and Feed links from your account page.</description></item>+ <item>+ <title>Profiles: your whole on-chain self in one place</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-21:Profiles: your whole on-chain self in one place</guid>+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Your profile at three.ws/u/<username> now shows everything you make and own. New Collectibles and Accessories tabs surface the NFTs held across your wallets — 3D NFTs rotate live right in the grid — and the premium avatar items you've bought. Your linked wallets appear as chain-tagged chips with one-tap copy and a block-explorer link, spanning both Solana and EVM. Every avatar now has a Fork button so anyone can save a copy of it (and its agent) to their own account, with a running fork count on each card. And a new Share menu lets you post your profile straight to X or share it through your phone's native share sheet, alongside copy-link.</description>+ </item><item><title>Provably-fair vanity grinder now listed in the x402 bazaar</title><link>https://three.ws/vanity/verify</link>@@ -542,6 +550,14 @@<category>feature</category><description>The provably-fair Solana vanity grinder — which returns a signed, independently-verifiable receipt proving the key was ground fresh and never kept — is now published in the x402 discovery catalog, so paying agents and bazaar crawlers can find and call it directly.</description></item>+ <item>+ <title>Referrals: claim a custom code that's yours</title>+ <link>https://three.ws/dashboard/referrals</link>+ <guid isPermaLink="false">2026-06-21:Referrals: claim a custom code that's yours</guid>+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Your referral code now starts as your name instead of a random string — and you can change it to anything you like. Open Referrals in your dashboard, hit Customize, and pick a code (3–20 letters or numbers); it checks availability as you type and updates your shareable link, QR, and membership card the moment you save. Existing links keep working, codes are matched case-insensitively, and you still earn 5% in USDC on every referred purchase.</description>+ </item><item><title>Regrinding an agent's vanity wallet no longer risks its funds</title><link>https://three.ws/changelog</link>@@ -582,6 +598,14 @@<category>fix</category><description>Everything onchain — paying, minting, balances, name lookups — depends on a Solana RPC node answering. When our primary paid node was throttled or its plan lapsed, some of those reads could error out. The platform now falls through a deeper chain: the paid node first, then several backup providers, then five independent public nodes (each verified live), so a request only fails if every one of them is down at the same moment. The embeddable payment widget and Solana name registration were moved onto the same resilient connection.</description></item>+ <item>+ <title>Studio Lab: six free 3D generators, right in your browser</title>+ <link>https://three.ws/forge-studio</link>+ <guid isPermaLink="false">2026-06-21:Studio Lab: six free 3D generators, right in your browser</guid>+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>The new Lab tab in Studio turns text and parameters into real 3D — no API key, no cost, nothing leaves your machine. Build math-driven parametric solids and supershapes, extrude 3D lettering from any string, turn an SVG icon or logo into a solid model, generate a lithophane relief from a photo, or grow a procedural landscape from a seed — each one previews live and downloads as a real GLB. Plus a Gaussian-splat viewer for the photoreal radiance-field format (.splat / .ply). Powered by three.js and GaussianSplats3D.</description>+ </item><item><title>The $THREE page now shows live market cap, holders & real trades</title><link>https://three.ws/three-token</link>diff --git a/public/features.json b/public/features.jsonindex 88c8bf954..233778015 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-21T17:29:42.288Z",+ "generated_at": "2026-06-21T18:25:29.182Z","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.jsindex 177c8a80a..b6859cb98 100644--- a/public/referral-capture.js+++ b/public/referral-capture.js@@ -10,7 +10,11 @@*/(function () {var KEY = 'tw:ref';- var CODE_RE = /^[A-Z2-9]{4,20}$/;+ // Canonical referral-code shape: A–Z and 0–9, 3–20 chars. Vanity codes (the+ // member's name) may use any letter or digit; the auto-generator stays on a+ // restricted alphabet but matching must accept the full range. Mirrors+ // REFERRAL_CODE_RE in api/_lib/referrals.js.+ var CODE_RE = /^[A-Z0-9]{3,20}$/;// A captured code older than this is stale — drop it rather than attribute a// signup to a link the user clicked weeks ago.var MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;diff --git a/src/dashboard-next/pages/referrals.js b/src/dashboard-next/pages/referrals.jsindex 880054e53..be51bf44f 100644--- a/src/dashboard-next/pages/referrals.js+++ b/src/dashboard-next/pages/referrals.js@@ -6,11 +6,19 @@// pulled from /api/users/referrals — no placeholders.import { mountShell } from '../shell.js';-import { requireUser, get, esc } from '../api.js';+import { requireUser, get, put, esc } from '../api.js';import { renderQRToSVG, renderQRToCanvas } from '../../erc8004/qr.js';const MONO = `'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace`;+// Canonical referral-code shape — mirrors REFERRAL_CODE_RE in+// api/_lib/referrals.js. The server is authoritative; this gates the editor's+// Save button and pre-filters obviously-invalid input before the availability+// check fires.+const CODE_MIN = 3;+const CODE_MAX = 20;+const CODE_RE = new RegExp(`^[A-Z0-9]{${CODE_MIN},${CODE_MAX}}$`);+// 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;@@ -185,6 +193,33 @@ function injectStyles() {.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}+ /* ── referral code editor ─────────────────────────────────────────────── */+ .ref-codebox{margin-top:12px;border:1px solid var(--nxt-stroke);border-radius:var(--nxt-radius-sm,12px);+ background:rgba(255,255,255,.015);padding:14px 16px}+ .ref-code-display{display:flex;align-items:center;justify-content:space-between;gap:14px;flex-wrap:wrap}+ .ref-code-meta{min-width:0}+ .ref-code-label{font-size:11px;color:var(--nxt-ink-fade);text-transform:uppercase;letter-spacing:.06em;margin-bottom:5px}+ .ref-code-value{font-family:${MONO};font-size:19px;font-weight:700;color:var(--nxt-ink);letter-spacing:.02em;+ word-break:break-all}+ .ref-code-cta{display:flex;gap:8px;flex:0 0 auto}+ .ref-code-inputwrap{display:flex;align-items:center;gap:0;border:1px solid var(--nxt-stroke-strong);+ border-radius:10px;background:rgba(255,255,255,.04);overflow:hidden;+ transition:border-color .14s ease,box-shadow .14s ease}+ .ref-code-inputwrap:focus-within{border-color:rgba(167,139,250,.6);box-shadow:0 0 0 3px rgba(167,139,250,.18)}+ .ref-code-prefix{padding:0 4px 0 12px;color:var(--nxt-ink-fade);font-family:${MONO};font-size:13px;white-space:nowrap;user-select:none}+ .ref-code-input{flex:1;min-width:80px;background:transparent;border:0;outline:none;color:var(--nxt-ink);+ font-family:${MONO};font-size:15px;font-weight:600;letter-spacing:.04em;padding:11px 8px 11px 0;text-transform:uppercase}+ .ref-code-status{flex:0 0 auto;display:grid;place-items:center;width:34px;height:100%;align-self:stretch}+ .ref-code-status.good{color:#86efac}+ .ref-code-status.bad{color:#fca5a5}+ .ref-code-status.checking{color:var(--nxt-ink-fade)}+ .ref-code-hint{margin-top:8px;font-size:12.5px;color:var(--nxt-ink-dim);line-height:1.45;min-height:1.2em}+ .ref-code-hint.good{color:#86efac}+ .ref-code-hint.bad{color:#fca5a5}+ .ref-code-actions{display:flex;gap:8px;margin-top:12px}+ .ref-spin{animation:ref-spin .7s linear infinite;transform-origin:center}+ @keyframes ref-spin{to{transform:rotate(360deg)}}+ @media (prefers-reduced-motion: reduce){.ref-spin{animation:none}}.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}@@ -454,8 +489,8 @@ function renderCard(host, card) {<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 class="ref-codebox" data-codebox>${codeBoxCollapsed(card)}</div></div><div class="ref-tiles" style="margin-top:18px">@@ -529,8 +564,8 @@ function wireCard(host, card, refUrl) {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(); });+ wireCodeEditor(host, card);host.querySelector('[data-action="download"]').addEventListener('click', () => exportCardPNG(card, refUrl));host.querySelector('[data-action="share"]').addEventListener('click', async () => {@@ -547,6 +582,159 @@ function wireCard(host, card, refUrl) {});}+// ── referral code editor ──────────────────────────────────────────────────────+//+// The code defaults to the member's name at signup; here they make it their own.+// Collapsed: shows the current code with Copy + Customize. Expanded: an inline+// editor with a live, debounced availability check against /api/users/referral-code.++const CHECK_ICON = '<svg viewBox="0 0 16 16" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M13 4.5 6.5 11 3 7.5"/></svg>';+const SPINNER = '<svg viewBox="0 0 16 16" width="14" height="14" class="ref-spin" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M8 1.5a6.5 6.5 0 1 0 6.5 6.5" opacity="0.9"/></svg>';+const WARN_ICON = '<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M8 5v3.5M8 11h.01"/><circle cx="8" cy="8" r="6.5"/></svg>';++function codeBoxCollapsed(card) {+ return `+ <div class="ref-code-display">+ <div class="ref-code-meta">+ <div class="ref-code-label">Your referral code</div>+ <div class="ref-code-value" data-code-value>${esc(card.referral_code)}</div>+ </div>+ <div class="ref-code-cta">+ <button class="dn-btn" data-action="copy-code" type="button">Copy</button>+ <button class="dn-btn primary" data-action="edit-code" type="button">Customize</button>+ </div>+ </div>`;+}++function codeBoxEditing(card) {+ return `+ <label class="ref-code-label" for="ref-code-input">Customize your referral code</label>+ <div class="ref-code-inputwrap">+ <span class="ref-code-prefix">?ref=</span>+ <input id="ref-code-input" class="ref-code-input" data-code-input type="text"+ value="${esc(card.referral_code)}" maxlength="${CODE_MAX}"+ autocomplete="off" autocapitalize="characters" autocorrect="off" spellcheck="false"+ aria-label="Referral code" aria-describedby="ref-code-hint" />+ <span class="ref-code-status" data-code-status aria-hidden="true"></span>+ </div>+ <div class="ref-code-hint" id="ref-code-hint" data-code-hint>${CODE_MIN}–${CODE_MAX} letters or numbers. This becomes your shareable link.</div>+ <div class="ref-code-actions">+ <button class="dn-btn primary" data-action="save-code" type="button" disabled>Save code</button>+ <button class="dn-btn" data-action="cancel-code" type="button">Cancel</button>+ </div>`;+}++function wireCodeEditor(host, card) {+ const box = host.querySelector('[data-codebox]');+ if (!box) return;++ function showCollapsed() {+ box.innerHTML = codeBoxCollapsed(card);+ box.querySelector('[data-action="copy-code"]').addEventListener('click', () => copyToClipboard(card.referral_code));+ box.querySelector('[data-action="edit-code"]').addEventListener('click', showEditing);+ }++ function showEditing() {+ box.innerHTML = codeBoxEditing(card);+ const input = box.querySelector('[data-code-input]');+ const statusEl = box.querySelector('[data-code-status]');+ const hintEl = box.querySelector('[data-code-hint]');+ const saveBtn = box.querySelector('[data-action="save-code"]');+ const current = card.referral_code.toUpperCase();+ let token = 0; // guards against out-of-order availability responses+ let ok = false;++ const setState = (cls, statusHtml, hintText, canSave) => {+ statusEl.className = `ref-code-status ${cls}`;+ statusEl.innerHTML = statusHtml;+ hintEl.className = `ref-code-hint ${cls === 'good' ? 'good' : cls === 'bad' ? 'bad' : ''}`;+ hintEl.textContent = hintText;+ ok = !!canSave;+ saveBtn.disabled = !canSave;+ };++ const evaluate = () => {+ const value = input.value;+ const myToken = ++token;+ if (value === current) {+ setState('', '', 'This is your current code.', false);+ return;+ }+ if (!CODE_RE.test(value)) {+ setState('', '', `${CODE_MIN}–${CODE_MAX} letters or numbers — no spaces or symbols.`, false);+ return;+ }+ setState('checking', SPINNER, 'Checking availability…', false);+ get(`/api/users/referral-code?code=${encodeURIComponent(value)}`)+ .then((r) => {+ if (myToken !== token) return; // a newer keystroke superseded this+ if (r.available) {+ setState('good', CHECK_ICON, r.reason === 'current' ? 'This is your current code.' : 'Available — yours to claim.', r.reason !== 'current');+ } else if (r.reason === 'reserved') {+ setState('bad', WARN_ICON, 'That code is reserved. Pick another.', false);+ } else if (r.reason === 'taken') {+ setState('bad', WARN_ICON, 'Already taken. Try a variation.', false);+ } else {+ setState('bad', WARN_ICON, `${CODE_MIN}–${CODE_MAX} letters or numbers.`, false);+ }+ })+ .catch(() => {+ if (myToken !== token) return;+ setState('', '', 'Couldn’t check availability — try again.', false);+ });+ };++ let debounce;+ input.addEventListener('input', () => {+ // Live-sanitize to the canonical alphabet so the field only ever holds+ // what can actually be saved.+ const caret = input.selectionStart;+ const cleaned = input.value.replace(/[^A-Za-z0-9]/g, '').toUpperCase().slice(0, CODE_MAX);+ if (cleaned !== input.value) {+ input.value = cleaned;+ if (caret != null) input.setSelectionRange(caret - 1, caret - 1);+ }+ clearTimeout(debounce);+ debounce = setTimeout(evaluate, 280);+ });+ input.addEventListener('keydown', (e) => {+ if (e.key === 'Enter') { e.preventDefault(); if (ok) save(); }+ else if (e.key === 'Escape') { e.preventDefault(); showCollapsed(); }+ });++ async function save() {+ if (!ok) return;+ const desired = input.value;+ saveBtn.disabled = true;+ setState('checking', SPINNER, 'Saving…', false);+ try {+ const r = await put('/api/users/referral-code', { code: desired });+ card.referral_code = r.referral_code;+ toast('Referral code updated');+ // Re-render the whole card so the link, QR, and PNG export all pick up+ // the new code.+ renderCard(host, card);+ } catch (err) {+ const reason = err?.code;+ const msg = reason === 'taken' ? 'Already taken. Try a variation.'+ : reason === 'reserved' ? 'That code is reserved. Pick another.'+ : err?.message || 'Couldn’t save — try again.';+ setState('bad', WARN_ICON, msg, false);+ saveBtn.disabled = false;+ }+ }++ box.querySelector('[data-action="save-code"]').addEventListener('click', save);+ box.querySelector('[data-action="cancel-code"]').addEventListener('click', showCollapsed);++ input.focus();+ input.setSelectionRange(input.value.length, input.value.length);+ evaluate();+ }++ showCollapsed();+}+// ── referred-users table ──────────────────────────────────────────────────────const PEOPLE_ICON = '<svg width="34" height="34" viewBox="0 0 24 24" fill="none" stroke="#a78bfa" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"><path d="M16 19v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 19v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>';diff --git a/tests/referral-codes.test.js b/tests/referral-codes.test.jsnew file mode 100644index 000000000..5a6118adc--- /dev/null+++ b/tests/referral-codes.test.js@@ -0,0 +1,100 @@+/**+ * Custom referral codes — pure-helper unit tests.+ *+ * Covers the case-insensitive normalization, name → default-code slugging, the+ * candidate generator (name-first, then suffixed, then random), reserved-code+ * blocking, and the canonical-shape regex. These helpers gate every referral+ * lookup and the customize-your-code editor, so they're worth pinning down+ * without a database.+ */++import { describe, it, expect } from 'vitest';+import {+ normalizeReferralCode,+ slugifyReferralName,+ isReservedReferralCode,+ referralCodeCandidates,+ REFERRAL_CODE_RE,+ REFERRAL_CODE_MIN_LEN,+ REFERRAL_CODE_MAX_LEN,+} from '../api/_lib/referrals.js';++describe('normalizeReferralCode', () => {+ it('uppercases and trims valid codes', () => {+ expect(normalizeReferralCode(' catherine ')).toBe('CATHERINE');+ expect(normalizeReferralCode('Ada99')).toBe('ADA99');+ });++ it('rejects codes with spaces, symbols, or hyphens (no silent mangling)', () => {+ expect(normalizeReferralCode('my-code')).toBeNull();+ expect(normalizeReferralCode('hi there')).toBeNull();+ expect(normalizeReferralCode('coin$')).toBeNull();+ });++ it('enforces length bounds', () => {+ expect(normalizeReferralCode('ab')).toBeNull(); // too short+ expect(normalizeReferralCode('a'.repeat(REFERRAL_CODE_MAX_LEN + 1))).toBeNull();+ expect(normalizeReferralCode('a'.repeat(REFERRAL_CODE_MIN_LEN))).toBe('AAA');+ });++ it('handles nullish input', () => {+ expect(normalizeReferralCode(null)).toBeNull();+ expect(normalizeReferralCode(undefined)).toBeNull();+ expect(normalizeReferralCode('')).toBeNull();+ });+});++describe('slugifyReferralName', () => {+ it('derives a canonical code from a person name', () => {+ expect(slugifyReferralName('Catherine Maerial')).toBe('CATHERINEMAERIAL');+ expect(slugifyReferralName('María José')).toBe('MARIAJOSE'); // accent-folded+ });++ it('clamps to the max length', () => {+ const slug = slugifyReferralName('a'.repeat(40));+ expect(slug.length).toBe(REFERRAL_CODE_MAX_LEN);+ });++ it('returns null when nothing usable remains', () => {+ expect(slugifyReferralName('!!')).toBeNull();+ expect(slugifyReferralName('')).toBeNull();+ expect(slugifyReferralName(null)).toBeNull();+ });+});++describe('isReservedReferralCode', () => {+ it('blocks platform/route codes case-insensitively', () => {+ expect(isReservedReferralCode('admin')).toBe(true);+ expect(isReservedReferralCode('ADMIN')).toBe(true);+ expect(isReservedReferralCode('three')).toBe(true);+ expect(isReservedReferralCode('catherine')).toBe(false);+ });+});++describe('referralCodeCandidates', () => {+ it('offers the name slug first', () => {+ const first = referralCodeCandidates('Ada Lovelace').next().value;+ expect(first).toBe('ADALOVELACE');+ });++ it('falls back to suffixed then random when the name is unusable', () => {+ const codes = [...referralCodeCandidates('!!')];+ expect(codes.length).toBeGreaterThan(0);+ for (const c of codes) expect(REFERRAL_CODE_RE.test(c)).toBe(true);+ });++ it('never offers a reserved name slug as the bare default', () => {+ const codes = [...referralCodeCandidates('admin')];+ expect(codes).not.toContain('ADMIN');+ for (const c of codes) expect(REFERRAL_CODE_RE.test(c)).toBe(true);+ });++ it('yields only unique, in-bounds candidates', () => {+ const codes = [...referralCodeCandidates('Bo')]; // short name → mostly random+ expect(new Set(codes).size).toBe(codes.length);+ for (const c of codes) {+ expect(c.length).toBeLessThanOrEqual(REFERRAL_CODE_MAX_LEN);+ expect(c.length).toBeGreaterThanOrEqual(REFERRAL_CODE_MIN_LEN);+ }+ });+});diff --git a/vercel.json b/vercel.jsonindex c3bd3abe4..3e1ebef91 100644--- a/vercel.json+++ b/vercel.json@@ -2572,6 +2572,10 @@"src": "/api/users/([^/]+)/follows","dest": "/api/users/[username]/follows?username=$1"},+ {+ "src": "/api/users/([^/]+)/collectibles",+ "dest": "/api/users/[username]/collectibles?username=$1"+ },{"src": "/api/users/([^/]+)","dest": "/api/users/[username]?username=$1"