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
THREE access client, gate, forge pay, coincommunities, nav badge, and changelog updates
nirholasd54aa4e3f242
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e77bc933c..43116e3a9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,8 +6,10 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr## 2026-06-18+- **Connect a wallet and your $THREE tier is recognized — no account needed** — You no longer need a three.ws account to be seen as a $THREE holder. Connect your Solana wallet and the site reads your tier straight from your on-chain holdings: the holder chip in the top bar shows your live tier (◆ Bronze, Silver, Gold…) and holder features like High-quality generation on Forge unlock from the connected wallet alone. When a feature needs proof the wallet is yours, you approve a single free signature that moves no funds. Switch or disconnect a wallet and your tier updates instantly, no reload. Signed-in accounts keep working exactly as before. (`/forge`) `[improvement]`- **Holding $THREE now unlocks a premium feature** — $THREE gets its first hard utility: High-quality 3D generation on Forge — the 200k-polygon, PBR-textured tier — is now reserved for $THREE holders. Reach the Bronze holder tier (the entry tier) by holding $THREE and the High tier unlocks automatically, with no payment step. Draft and Standard generation stay free forever, and bring-your-own-key generation is unaffected. Sign in, link your Solana wallet, and the economy page shows your live holder tier and exactly what it unlocks. (`/three`) `[feature]`- **Pay $THREE per High generation — no holding required** — Don't hold $THREE yet but want a High-quality model? You can now pay in $THREE for a single High generation instead. Pick High in Forge, choose "Pay" on the holder panel, and a clean payment flow prices it in $THREE, takes one wallet approval, verifies it on-chain, and runs your generation automatically. The platform now genuinely accepts $THREE for compute. One payment buys exactly one High generation, and if a generation fails before it runs your payment stays usable — you're never charged for a model you didn't get. Draft and Standard remain free, and holders still generate High straight away. (`/forge`) `[feature]`+- **The disco dance floor in coin worlds works again** — Every coin world has a disco pad beside the totem that pulses to a shared beat and crossfades dancers in lockstep. A wiring gap meant the world tried to listen for a beat the connection didn't know about, which threw an error the moment you entered and left the pad dark. The beat is now delivered properly: step onto the pad, hit Dance, and you and everyone else standing on it move to the same animation on the same beat, with the floor and lights pulsing in time. (`/play`) `[fix]`- **Your $THREE holder tier now shows across the site** — Holding $THREE is now visible everywhere you are. A holder chip in the top bar shows your live tier (◆ Bronze, Silver, Gold…) on every page and links to the full tier breakdown. On Forge, choosing the High quality tier now shows a clear, designed panel instead of a silent block: holders see an "Unlocked" badge and generate straight away, while everyone else gets a "Get $THREE" path, the exact reason (sign in, link a wallet, or hold more), and a one-tap switch back to free Draft or Standard — no dead ends and no raw errors. (`/forge`) `[feature, improvement]`## 2026-06-17diff --git a/data/changelog.json b/data/changelog.jsonindex e2d34d67e..4c5937682 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,24 @@{"$comment": "Curated changelog entries for three.ws \u2014 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-18",+ "title": "Connect a wallet and your $THREE tier is recognized — no account needed",+ "summary": "You no longer need a three.ws account to be seen as a $THREE holder. Connect your Solana wallet and the site reads your tier straight from your on-chain holdings: the holder chip in the top bar shows your live tier (◆ Bronze, Silver, Gold…) and holder features like High-quality generation on Forge unlock from the connected wallet alone. When a feature needs proof the wallet is yours, you approve a single free signature that moves no funds. Switch or disconnect a wallet and your tier updates instantly, no reload. Signed-in accounts keep working exactly as before.",+ "tags": [+ "improvement"+ ],+ "link": "/forge"+ },+ {+ "date": "2026-06-18",+ "title": "The disco dance floor in coin worlds works again",+ "summary": "Every coin world has a disco pad beside the totem that pulses to a shared beat and crossfades dancers in lockstep. A wiring gap meant the world tried to listen for a beat the connection didn't know about, which threw an error the moment you entered and left the pad dark. The beat is now delivered properly: step onto the pad, hit Dance, and you and everyone else standing on it move to the same animation on the same beat, with the floor and lights pulsing in time.",+ "tags": [+ "fix"+ ],+ "link": "/play"+ },{"date": "2026-06-18","title": "Pay $THREE per High generation — no holding required",diff --git a/public/changelog.json b/public/changelog.jsonindex ed6edd7e7..bf3ad509c 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,11 +1,21 @@{- "generated_at": "2026-06-18T01:05:47.110Z",+ "generated_at": "2026-06-18T01:18:31.096Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws","url": "https://three.ws"},"entries": [+ {+ "date": "2026-06-18",+ "type": "update",+ "title": "Connect a wallet and your $THREE tier is recognized — no account needed",+ "summary": "You no longer need a three.ws account to be seen as a $THREE holder. Connect your Solana wallet and the site reads your tier straight from your on-chain holdings: the holder chip in the top bar shows your live tier (◆ Bronze, Silver, Gold…) and holder features like High-quality generation on Forge unlock from the connected wallet alone. When a feature needs proof the wallet is yours, you approve a single free signature that moves no funds. Switch or disconnect a wallet and your tier updates instantly, no reload. Signed-in accounts keep working exactly as before.",+ "link": "/forge",+ "tags": [+ "improvement"+ ]+ },{"date": "2026-06-18","type": "update",@@ -26,6 +36,16 @@"feature"]},+ {+ "date": "2026-06-18",+ "type": "update",+ "title": "The disco dance floor in coin worlds works again",+ "summary": "Every coin world has a disco pad beside the totem that pulses to a shared beat and crossfades dancers in lockstep. A wiring gap meant the world tried to listen for a beat the connection didn't know about, which threw an error the moment you entered and left the pad dark. The beat is now delivered properly: step onto the pad, hit Dance, and you and everyone else standing on it move to the same animation on the same beat, with the floor and lights pulsing in time.",+ "link": "/play",+ "tags": [+ "fix"+ ]+ },{"date": "2026-06-18","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 9d61bca06..863ae334e 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -6,6 +6,14 @@<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/><description>What's new on three.ws — features, improvements, and releases, newest first.</description><language>en</language>+ <item>+ <title>Connect a wallet and your $THREE tier is recognized — no account needed</title>+ <link>https://three.ws/forge</link>+ <guid isPermaLink="false">2026-06-18:Connect a wallet and your $THREE tier is recognized — no account needed</guid>+ <pubDate>Thu, 18 Jun 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>You no longer need a three.ws account to be seen as a $THREE holder. Connect your Solana wallet and the site reads your tier straight from your on-chain holdings: the holder chip in the top bar shows your live tier (◆ Bronze, Silver, Gold…) and holder features like High-quality generation on Forge unlock from the connected wallet alone. When a feature needs proof the wallet is yours, you approve a single free signature that moves no funds. Switch or disconnect a wallet and your tier updates instantly, no reload. Signed-in accounts keep working exactly as before.</description>+ </item><item><title>Holding $THREE now unlocks a premium feature</title><link>https://three.ws/three</link>@@ -22,6 +30,14 @@<category>feature</category><description>Don't hold $THREE yet but want a High-quality model? You can now pay in $THREE for a single High generation instead. Pick High in Forge, choose "Pay" on the holder panel, and a clean payment flow prices it in $THREE, takes one wallet approval, verifies it on-chain, and runs your generation automatically. The platform now genuinely accepts $THREE for compute. One payment buys exactly one High generation, and if a generation fails before it runs your payment stays usable — you're never charged for a model you didn't get. Draft and Standard remain free, and holders still generate High straight away.</description></item>+ <item>+ <title>The disco dance floor in coin worlds works again</title>+ <link>https://three.ws/play</link>+ <guid isPermaLink="false">2026-06-18:The disco dance floor in coin worlds works again</guid>+ <pubDate>Thu, 18 Jun 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>Every coin world has a disco pad beside the totem that pulses to a shared beat and crossfades dancers in lockstep. A wiring gap meant the world tried to listen for a beat the connection didn't know about, which threw an error the moment you entered and left the pad dark. The beat is now delivered properly: step onto the pad, hit Dance, and you and everyone else standing on it move to the same animation on the same beat, with the floor and lights pulsing in time.</description>+ </item><item><title>Your $THREE holder tier now shows across the site</title><link>https://three.ws/forge</link>diff --git a/public/features.json b/public/features.jsonindex 63c81904c..050c89326 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-18T01:05:47.072Z",+ "generated_at": "2026-06-18T01:18:31.072Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/src/forge-pay.js b/src/forge-pay.jsindex fd57f35ac..04f84e430 100644--- a/src/forge-pay.js+++ b/src/forge-pay.js@@ -27,7 +27,7 @@ let _stylesInjected = false;function escapeHtml(s) {return String(s ?? '').replace(/[&<>"']/g,- (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]),+ (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],);}@@ -74,9 +74,16 @@ function classifyError(err) {};}if (/reject|denied|cancel|declin|user.*reject/i.test(msg)) {- return { title: 'Payment cancelled', detail: 'You dismissed the wallet request — no $THREE was spent.', cta: { label: 'Try again', retry: true } };+ return {+ title: 'Payment cancelled',+ detail: 'You dismissed the wallet request — no $THREE was spent.',+ cta: { label: 'Try again', retry: true },+ };}- if (code === 'insufficient_funds' || /insufficient|0x1\b|not enough|debit|exceeds.*balance/i.test(msg)) {+ if (+ code === 'insufficient_funds' ||+ /insufficient|0x1\b|not enough|debit|exceeds.*balance/i.test(msg)+ ) {return {title: 'Not enough $THREE',detail: "Your wallet doesn't hold enough $THREE for this generation.",@@ -84,15 +91,26 @@ function classifyError(err) {};}if (code === 'price_unavailable') {- return { title: 'Price feed unavailable', detail: 'We couldn’t price $THREE just now. Try again in a moment.', cta: { label: 'Try again', retry: true } };+ return {+ title: 'Price feed unavailable',+ detail: 'We couldn’t price $THREE just now. Try again in a moment.',+ cta: { label: 'Try again', retry: true },+ };}if (code === 'already_settled') {- return { title: 'Already paid', detail: 'This payment already settled — retry your generation.', cta: { label: 'Try again', retry: true } };+ return {+ title: 'Already paid',+ detail: 'This payment already settled — retry your generation.',+ cta: { label: 'Try again', retry: true },+ };}// Settlement / verification or any other transient failure.return {title: 'Payment didn’t go through',- detail: msg && msg.length < 160 ? msg : 'Something interrupted the payment. Try again — no $THREE is spent unless it settles.',+ detail:+ msg && msg.length < 160+ ? msg+ : 'Something interrupted the payment. Try again — no $THREE is spent unless it settles.',cta: { label: 'Try again', retry: true },};}@@ -164,9 +182,13 @@ export function payForHighGeneration({ usd }) {);}if (info.cta?.retry) {- buttons.push(`<button type="button" class="fpay-btn fpay-btn--primary" data-fpay-retry>${escapeHtml(info.cta.label)}</button>`);+ buttons.push(+ `<button type="button" class="fpay-btn fpay-btn--primary" data-fpay-retry>${escapeHtml(info.cta.label)}</button>`,+ );}- buttons.push(`<button type="button" class="fpay-btn fpay-btn--ghost" data-fpay-cancel>Close</button>`);+ buttons.push(+ `<button type="button" class="fpay-btn fpay-btn--ghost" data-fpay-cancel>Close</button>`,+ );actionsEl.innerHTML = buttons.join('');actionsEl.querySelector('[data-fpay-retry]')?.addEventListener('click', startPayment);actionsEl.querySelector('[data-fpay-cancel]').addEventListener('click', close);@@ -181,10 +203,13 @@ export function payForHighGeneration({ usd }) {usd,refType: 'forge',refId,- onStatus: (phase) => showStatus(PHASE_COPY[phase] || 'Working…', { busy: true }),+ onStatus: (phase) =>+ showStatus(PHASE_COPY[phase] || 'Working…', { busy: true }),});if (!result?.ok || !result.payment_id) {- throw Object.assign(new Error('Payment could not be verified.'), { code: 'verification_failed' });+ throw Object.assign(new Error('Payment could not be verified.'), {+ code: 'verification_failed',+ });}settled = true;statusEl.className = 'fpay-status fpay-status--ok';diff --git a/src/forge.js b/src/forge.jsindex 6cb6cb22f..776f38b59 100644--- a/src/forge.js+++ b/src/forge.js@@ -2,7 +2,7 @@import { skeletonHTML, errorStateHTML, ensureStateKitStyles } from './shared/state-kit.js';import { showSharePanel } from './shared/share.js';import { stampGlbAttribution } from './shared/glb-attribution.js';-import { primeTierPass, attachTierPass, getAccess, onGate } from './three-access.js';+import { primeTierPass, attachTierPass, getTierPass, getAccess, onGate } from './three-access.js';import { renderLock, lockStateFromAccess } from './three-lock.js';import { payForHighGeneration } from './forge-pay.js';ensureStateKitStyles();@@ -541,6 +541,10 @@ function selectEngine(btn, silent) {updateByokRow();updateAspectVisibility();if (!silent) updateEstimate();+ // The engine decides whether High is $THREE-gated (platform) or exempt (BYOK), so+ // re-evaluate the lock whenever the engine changes under High. Reuses the cached+ // access verdict — no extra round-trip, no loading flash.+ if (selectedTier === 'high') reflectHighAccess('high', { silent: true });}// Show the key field only for BYOK engines, with provider-specific hint + link.@@ -581,6 +585,15 @@ let _accessHost = null;let highLocked = false; // true → High is selected but the holder isn't eligiblelet _highAccess = null; // last resolved forge.high access payload (for the gate modal)+// The only combination the server actually $THREE-gates: High tier on a PLATFORM-keyed+// backend. BYOK engines run on the caller's own vendor key, so the server exempts BYOK+// High (key-gated, not hold-gated) — and so must the client, or a non-holder with their+// own Meshy/Tripo/Rodin key would be wrongly blocked from High. Draft/Standard are never+// gated. Every client gate check keys on this, so the lock can never engage outside it.+function highTierNeedsPass() {+ return selectedTier === 'high' && !selectedEngine.byok;+}+function accessHost() {if (_accessHost || !els.tier) return _accessHost;const host = document.createElement('div');@@ -596,7 +609,7 @@ function accessHost() {// not mid-job (setBusy owns the busy label).function applyHighGate() {if (!els.generate || els.generate.dataset.busy === '1') return;- const locked = selectedTier === 'high' && highLocked;+ const locked = highTierNeedsPass() && highLocked;els.generate.disabled = locked;els.generate.classList.toggle('is-gated', locked);if (els.generateLabel) {@@ -604,7 +617,7 @@ function applyHighGate() {}}-async function reflectHighAccess(tierId) {+async function reflectHighAccess(tierId, { silent = false } = {}) {const host = accessHost();if (!host) return;if (tierId !== 'high') {@@ -616,13 +629,29 @@ async function reflectHighAccess(tierId) {applyHighGate();return;}- // High is selected — the full in-place lock panel takes over, so the small- // persistent hint stands down to avoid stacking two "holder feature" notes.+ // High on a BYOK engine is server-exempt (the caller's own vendor key pays), so it's+ // never $THREE-gated here either: clear any lock, drop the holder note, and let the+ // BYOK key flow take over. This is the path that keeps BYOK High byte-for-byte free.+ if (!highTierNeedsPass()) {+ highLocked = false;+ renderLock(host, { clear: true });+ if (els.holderNote) els.holderNote.hidden = true;+ applyHighGate();+ return;+ }+ // Platform-keyed High — the real $THREE gate. The in-place lock panel takes over, so+ // the small persistent hint stands down to avoid stacking two "holder feature" notes.if (els.holderNote) els.holderNote.hidden = true;- renderLock(host, { loading: true });- const data = await getAccess('forge.high');- if (selectedTier !== 'high') return; // user moved on while we fetched- const access = data?.access || null;+ // Re-evaluating after an engine switch (silent) reuses the last resolved verdict so+ // the panel doesn't flash a loading state for a check we already made.+ let access = silent && _highAccess ? _highAccess : null;+ if (!access) {+ renderLock(host, { loading: true });+ const data = await getAccess('forge.high');+ // User moved off High, or switched to a BYOK engine, while we fetched.+ if (!highTierNeedsPass()) return;+ access = data?.access || null;+ }if (!access) {// Access read failed — show a retry, but don't lock (fail open; the server// enforces and a real holder isn't trapped behind a transient hiccup).@@ -1164,6 +1193,14 @@ async function startJob({ prompt, imageUrls, skipValidation, payment }) {body.ref_id = payment.refId;}+ // Platform-keyed High is the $THREE-gated combination — mint/refresh the holder's tier+ // pass and AWAIT it so forgeHeaders attaches a fresh, RPC-free proof on this very+ // request. An eligible holder then clears the server gate even if a live on-chain read+ // would hiccup, and even when they submit faster than the background primeTierPass()+ // could finish. No-op for anonymous callers (no linked wallet → no pass), for the free+ // tiers, and for BYOK High (server-exempt — no pass needed).+ if (highTierNeedsPass()) await getTierPass();+const res = await fetch('/api/forge', {method: 'POST',headers: forgeHeaders({ 'content-type': 'application/json' }),@@ -1998,10 +2035,11 @@ function collectComposerCfg() {}function submit() {- // High is a $THREE holder perk. The Generate button is disabled when locked,- // but a keyboard submit (⌘↵) can still reach here — open the upsell (with the- // working Pay-per-use path) instead of firing a request the server will gate.- if (selectedTier === 'high' && highLocked) {+ // Platform-keyed High is a $THREE holder perk. The Generate button is disabled+ // when locked, but a keyboard submit (⌘↵) can still reach here — open the upsell+ // (with the working Pay-per-use path) instead of firing a request the server will+ // gate. BYOK High is exempt, so highTierNeedsPass() lets it through untouched.+ if (highTierNeedsPass() && highLocked) {if (_highAccess) onGate(_highAccess, gateOpts());else reflectHighAccess('high');return;@@ -2165,10 +2203,22 @@ els.refineLocally?.addEventListener('click', () => {// Refine — re-run the same prompt/views one quality tier higher. Bumping the// tier syncs the selector (and the tier's default engine), then replays the// stored job, so the higher-fidelity model lands in the same viewer.-els.refine?.addEventListener('click', () => {+els.refine?.addEventListener('click', async () => {const next = nextTierAfter(currentResultTier);if (!next || !lastJob) return;selectTier(next);+ // Refining into platform-keyed High runs the same $THREE pre-flight as selecting+ // it: resolve the holder's eligibility first and open the upsell instead of firing+ // a job the server would 402. BYOK High is exempt (highTierNeedsPass() is false);+ // a transient access failure leaves highLocked false so the request proceeds and+ // the server stays the authority.+ if (highTierNeedsPass()) {+ await reflectHighAccess('high', { silent: true });+ if (highLocked) {+ if (_highAccess) onGate(_highAccess, gateOpts());+ return;+ }+ }run(lastJob);});diff --git a/src/game/coincommunities.js b/src/game/coincommunities.jsindex 26637f6fc..9fe726b81 100644--- a/src/game/coincommunities.js+++ b/src/game/coincommunities.js@@ -939,7 +939,7 @@ export class CoinCommunities {});// Durability flag for this world's build — drives the HUD "Saved" badge.this.net.on('persistent', (durable) => { if (this.net?.status === 'online') this.buildHud.setPersistent(durable); });- this.net.on('floor:beat', (msg) => this._onFloorBeat(msg));+ this.net.on('floorBeat', (msg) => this._onFloorBeat(msg));// Game systems (economy + activities). The server streams this player's own// pack/purse/skills here; PlaySystems renders the HUD, ponds, and cast visual,diff --git a/src/game/community-net.js b/src/game/community-net.jsindex addfa3e98..9577127a7 100644--- a/src/game/community-net.js+++ b/src/game/community-net.js@@ -155,6 +155,7 @@ export class CommunityNet {objectReject: new Set(), // ({reason}) — server refused a spawn (world/player full)reaction: new Set(), // ({id, emoji}) — a player sent a floating reactiontag: new Set(), // ({event, itId, leaderboard}) — tag mini-game state (R08)+ floorBeat: new Set(), // ({clip}) — disco-pad beat tick (R06): pulses the floor + aligns standing dancers};this.ping = null; // smoothed RTT in ms, null until the first echothis._pingSentAt = 0; // perf-clock stamp of the last move awaiting an echo@@ -289,6 +290,11 @@ export class CommunityNet {// Broadcast reactions (R04): floating emoji that rise above the sender's avatar.this.room.onMessage('reaction', (msg) => this._emit('reaction', msg || {}));this.room.onMessage('tag', (msg) => this._emit('tag', msg || {})); // R08 tag mini-game+ // Dance floor (R06): the room broadcasts a beat every 4s so every client+ // pulses the disco pad and crossfades standing dancers to the same clip in+ // lockstep. The server message keeps its colon namespace; we normalize it to+ // a camelCase event like the other namespaced messages above.+ this.room.onMessage('floor:beat', (msg) => this._emit('floorBeat', msg || {}));const $ = getStateCallbacks(this.room);const $state = $(this.room.state);diff --git a/src/nav-tier-badge.js b/src/nav-tier-badge.jsindex 352e6be6f..99f3126e5 100644--- a/src/nav-tier-badge.js+++ b/src/nav-tier-badge.js@@ -1,28 +1,15 @@// Global nav holder chip. Loaded by the shared header (public/nav.js → the stable// /nav-tier-badge.js bundle) right after the nav markup mounts, this hydrates the-// nav's #nav-tier-badge slot with the signed-in holder's $THREE tier ("◆ Silver")-// via the shared access helper. One getAccess() call does it; the helper hides the-// chip for anonymous visitors and non-holders, and the chip links to /three#tiers.+// nav's #nav-tier-badge slot with the holder's $THREE tier ("◆ Silver") via the+// shared access helper. One mountTierBadge() call does it; the helper hides the chip+// for anonymous visitors and non-holders, shows it for a signed-in account OR a+// connected wallet, and links to /three#tiers.//-// A wallet:changed event (dispatched by src/wallet.js when a wallet connects or-// disconnects) re-hydrates the chip so a freshly-connected holder sees their tier-// without a reload — the only live coupling, kept lightweight.+// mountTierBadge re-hydrates itself on wallet:changed (it binds its own listener and+// keys the access cache by wallet), so a freshly-connected holder sees their tier —+// and a disconnect clears it — without a reload. No extra wiring needed here.-import { mountTierBadge, getAccess } from './three-access.js';+import { mountTierBadge } from './three-access.js';-const SLOT_ID = 'nav-tier-badge';--function hydrate() {- const slot = document.getElementById(SLOT_ID);- if (slot) mountTierBadge(slot);-}--hydrate();--// Re-read on wallet change. getAccess() is short-cached, so force a fresh read to-// refresh the matrix the badge reads, then re-mount; failures degrade silently.-if (typeof window !== 'undefined') {- window.addEventListener('wallet:changed', () => {- getAccess(undefined, { fresh: true }).finally(hydrate);- });-}+const slot = document.getElementById('nav-tier-badge');+if (slot) mountTierBadge(slot);diff --git a/src/three-access.js b/src/three-access.jsindex e8a1039cc..fdd550142 100644--- a/src/three-access.js+++ b/src/three-access.js@@ -2,16 +2,23 @@//// One module any page imports to make the hold-to-access lever real in the UI:// • getAccess(feature?) — GET /api/three/access (the gated-feature matrix or-// a single feature), short-cached.-// • getTierPass() — POST /api/three/tier-pass, cached until ~1 min before+// a single feature), short-cached. Reads the connected+// wallet (?wallet=) when one is connected, else the session.+// • getTierPass(opts?) — mint/reuse the tier pass, cached until ~1 min before// expiry; the portable, RPC-free proof of holder tier.+// A connected wallet mints by signing a fresh message+// ({ interactive:true } only — never a surprise popup);+// a session user mints silently. The portable, RPC-free+// proof of holder tier.// • tierPassHeader() — the cached pass string for the x-three-tier-pass// header (sync; null when none), so a gated request can// attach an eligible holder's entitlement with no await.// • attachTierPass(h) — adds that header to a headers object when a pass is// cached; no-op + returns it unchanged otherwise.// • primeTierPass() — fetch the pass in the background (fire-and-forget).-// • mountTierBadge(el) — render the signed-in holder's tier chip (Bronze+).+// • mountTierBadge(el) — render the holder's tier chip (Bronze+), for a+// signed-in account OR a connected wallet; re-renders+// itself on wallet:changed.// • onGate(payload) — open the upsell from a 402 three_hold_required body// (the intent-named entry; showThreeGate is the impl).// • showThreeGate(gate) — the upsell modal: Get $THREE + what you hold vs. need.@@ -20,13 +27,52 @@// Everything degrades to a safe locked/anonymous state on any network failure —// the UI never throws and the server stays the only authority on eligibility.+import { getConnectedWallet, getConnectedWalletAddress } from './wallet.js';+const ACCESS_TTL_MS = 30_000;-let _matrix = { at: 0, data: null };-let _tierPass = null; // { pass, tier, exp(ms) }+// The matrix cache is keyed by identity (the connected wallet, or null for the+// session) so a wallet connect/disconnect/switch never serves the previous+// identity's access.+let _matrix = { at: 0, data: null, wallet: undefined };+let _tierPass = null; // { pass, tier, exp(ms), wallet } — wallet is the identity it was minted for (null = session)+let _tierPassInFlight = null; // de-dupe concurrent mints onto one network/signature round-triplet _stylesInjected = false;const ECONOMY_URL = '/three';+// The connected Solana wallet address (Phantom on web, the Seeker TWA wallet on+// mobile), or null when none is connected — in which case every read falls back to+// the session identity. Seeded on import and kept current by the wallet:changed+// listener below. Reading is best-effort: a wallet module hiccup degrades to session.+function readConnectedWallet() {+ try {+ return getConnectedWalletAddress() || null;+ } catch {+ return null;+ }+}+let _walletAddr = readConnectedWallet();++// A wallet connect/disconnect/switch changes who the caller is, so the cached access+// matrix and tier pass are now for the wrong identity. Drop both and re-track the+// address so the next read reflects the wallet in hand. Registered at import time —+// before any mountTierBadge() call — so it always runs ahead of the per-badge+// re-render listeners those mounts add: they then read an already-invalidated cache+// and fetch fresh for the new identity.+if (typeof window !== 'undefined' && typeof window.addEventListener === 'function') {+ window.addEventListener('wallet:changed', (e) => {+ const next =+ e?.detail && Object.prototype.hasOwnProperty.call(e.detail, 'address')+ ? e.detail.address || null+ : readConnectedWallet();+ if (next === _walletAddr) return;+ _walletAddr = next;+ _matrix = { at: 0, data: null, wallet: undefined };+ _tierPass = null;+ _tierPassInFlight = null;+ });+}+function escapeHtml(s) {return String(s ?? '').replace(/[&<>"']/g,@@ -34,6 +80,22 @@ function escapeHtml(s) {);}+// The canonical message a connected wallet signs to mint a tier pass without an+// account. MUST stay byte-identical to the server validator (checkTierPassMessage in+// api/three/[action].js — it requires the 'three.ws' domain, the wallet, and a fresh+// `Issued At:`) and to tests/three-tier-public.test.js: the server reconstructs and+// verifies the signature over these exact bytes, so any drift breaks every mint.+function buildTierPassMessage(wallet, issuedAt) {+ return [+ 'three.ws — verify wallet to unlock $THREE holder perks.',+ '',+ `Wallet: ${wallet}`,+ `Issued At: ${issuedAt}`,+ '',+ 'Signing is free and does not move funds.',+ ].join('\n');+}+// base64url → JSON (the tier-pass payload is the part before the first '.').function decodePassExpMs(pass) {try {@@ -56,17 +118,28 @@ function decodePassExpMs(pass) {* Feature shape: { signed_in, wallet_linked, tier, access:{…} }*/export async function getAccess(feature, { fresh = false } = {}) {- if (!fresh && !feature && _matrix.data && Date.now() - _matrix.at < ACCESS_TTL_MS) {+ const wallet = _walletAddr;+ if (+ !fresh &&+ !feature &&+ _matrix.data &&+ _matrix.wallet === wallet &&+ Date.now() - _matrix.at < ACCESS_TTL_MS+ ) {return _matrix.data;}- const url = feature- ? `/api/three/access?feature=${encodeURIComponent(feature)}`- : '/api/three/access';+ // A connected wallet reads its own on-chain tier via ?wallet=; with no wallet the+ // request carries only the session cookie and the server reads the linked account.+ const params = new URLSearchParams();+ if (feature) params.set('feature', feature);+ if (wallet) params.set('wallet', wallet);+ const qs = params.toString();+ const url = qs ? `/api/three/access?${qs}` : '/api/three/access';try {const r = await fetch(url, { credentials: 'include' });if (!r.ok) return null;const data = await r.json();- if (!feature) _matrix = { at: Date.now(), data };+ if (!feature) _matrix = { at: Date.now(), data, wallet };return data;} catch {return null;@@ -75,23 +148,83 @@ export async function getAccess(feature, { fresh = false } = {}) {/*** Mint (or reuse) the signed $THREE tier pass. Cached until ~1 min before expiry.- * Returns null when the user is anonymous / has no linked wallet (401/403) or on- * any failure — the caller simply proceeds with no pass attached.+ * Split by identity:+ * • A connected wallet mints via the signature path — sign a fresh, domain-bound+ * message and POST { wallet, message, signature }. The wallet popup only fires on+ * an INTERACTIVE call (a user gesture); a background `primeTierPass()` for a+ * connected wallet returns the cached pass or null, never a surprise prompt.+ * • No connected wallet → the session POST (silent), unchanged for signed-in users.+ * Concurrent mints de-dupe onto one in-flight promise. Returns null when the caller+ * is anonymous / has no linked wallet (the endpoint 401/403s) or on any failure —+ * the caller simply proceeds with no pass attached.+ * @param {{ interactive?: boolean }} [opts]*/-export async function getTierPass() {+export async function getTierPass({ interactive = false } = {}) {const now = Date.now();- if (_tierPass && _tierPass.exp - 60_000 > now) return _tierPass;+ const wallet = _walletAddr;++ // Serve a still-valid pass, but only if it was minted for the identity in hand+ // (a wallet change clears it — this is the belt-and-suspenders check).+ if (_tierPass && _tierPass.wallet === wallet && _tierPass.exp - 60_000 > now) {+ return _tierPass;+ }++ // A connected wallet must sign to mint — do that only on an interactive call so a+ // background prime never pops the wallet's signature dialog.+ if (wallet && !interactive) return null;++ // De-dupe concurrent mints (e.g. an interactive Generate click racing a prime).+ if (_tierPassInFlight) return _tierPassInFlight;+ _tierPassInFlight = (wallet ? mintWalletTierPass(wallet) : mintSessionTierPass()).finally(() => {+ _tierPassInFlight = null;+ });+ return _tierPassInFlight;+}++// Mint a pass for a connected wallet by signing the canonical message. Never throws;+// degrades to null on a declined signature, a disconnect mid-flight, or a rejected+// POST. Only adopts the result as the live cache when the connected identity hasn't+// changed mid-mint, so a wallet switch can't leave a stale pass on the header.+async function mintWalletTierPass(wallet) {+ try {+ const provider = getConnectedWallet();+ if (!provider?.signMessage) return null;+ const message = buildTierPassMessage(wallet, new Date().toISOString());+ const encoded = new TextEncoder().encode(message);+ const signed = await provider.signMessage(encoded, 'utf8');+ const sigBytes = signed?.signature ?? signed;+ const bs58 = (await import('bs58')).default;+ const signature = bs58.encode(sigBytes);+ const r = await fetch('/api/three/tier-pass', {+ method: 'POST',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ wallet, message, signature }),+ });+ if (!r.ok) return null;+ const data = await r.json().catch(() => null);+ if (!data?.pass) return null;+ const expMs = decodePassExpMs(data.pass) || Date.now() + 9 * 60_000;+ const entry = { pass: data.pass, tier: data.tier || null, exp: expMs, wallet };+ if (_walletAddr === wallet) _tierPass = entry;+ return entry;+ } catch {+ return null;+ }+}++// Mint a pass for the signed-in session (no body → getSessionUser server-side). The+// original v1 path, kept byte-for-byte so signed-in users are unaffected.+async function mintSessionTierPass() {try {const r = await fetch('/api/three/tier-pass', { method: 'POST', credentials: 'include' });- if (!r.ok) {- _tierPass = null;- return null;- }- const data = await r.json();+ if (!r.ok) return null;+ const data = await r.json().catch(() => null);if (!data?.pass) return null;- const expMs = decodePassExpMs(data.pass) || now + 9 * 60_000;- _tierPass = { pass: data.pass, tier: data.tier || null, exp: expMs };- return _tierPass;+ const expMs = decodePassExpMs(data.pass) || Date.now() + 9 * 60_000;+ const entry = { pass: data.pass, tier: data.tier || null, exp: expMs, wallet: null };+ if (_walletAddr === null) _tierPass = entry;+ return entry;} catch {return null;}@@ -115,23 +248,47 @@ export function attachTierPass(headers = {}) {return headers;}-/** Fetch the pass in the background so it's ready when a gated request fires. */+/**+ * Fetch the pass in the background so it's ready when a gated request fires. Always+ * non-interactive: a signed-in session mints silently, while a connected wallet is+ * left for the next interactive getTierPass({ interactive:true }) so priming never+ * pops the wallet's signature dialog.+ */export function primeTierPass() {getTierPass();}// ── Tier badge ─────────────────────────────────────────────────────────────────-/** Render the signed-in user's tier chip into `target`. Hides it for anonymous users. */+// Bind the wallet:changed re-render once per element so repeat mounts don't stack+// listeners. WeakSet lets a removed element be GC'd without leaking.+const _badgeBound = typeof WeakSet !== 'undefined' ? new WeakSet() : null;++/**+ * Render the holder's tier chip into `target` — for a signed-in account OR a+ * connected wallet. Hides it for anonymous visitors and non-holders. Re-renders+ * itself on wallet:changed so a freshly-connected holder sees their tier (and a+ * disconnect clears it) without a reload.+ */export async function mountTierBadge(target) {const el = typeof target === 'string' ? document.querySelector(target) : target;if (!el) return;injectStyles();+ // The module-level wallet:changed listener has already invalidated the matrix by+ // the time this per-element listener fires, so the re-mount's getAccess() fetches+ // fresh for the new identity.+ if (_badgeBound && typeof window !== 'undefined' && !_badgeBound.has(el)) {+ _badgeBound.add(el);+ window.addEventListener('wallet:changed', () => {+ mountTierBadge(el);+ });+ }const data = await getAccess();- // Show the chip only for an actual holder (Bronze+). Anonymous visitors and- // signed-in non-holders (Member, level 0) hold no $THREE, so the green holder- // chip would read as a false signal — they get the upsell on /three instead.- if (!data || !data.signed_in || !data.tier || (Number(data.tier.level) || 0) < 1) {+ // Show the chip for any real holder (Bronze+) — whether the tier was resolved from+ // a signed-in account or a connected wallet's on-chain holdings, the tier is real.+ // Anonymous visitors and non-holders (Member, level 0) hold no $THREE, so the green+ // holder chip would read as a false signal — they get the upsell on /three instead.+ if (!data || !data.tier || (Number(data.tier.level) || 0) < 1) {el.hidden = true;el.innerHTML = '';return;diff --git a/src/three-gate.js b/src/three-gate.jsindex b1d6ffcf7..51e66fe7c 100644--- a/src/three-gate.js+++ b/src/three-gate.js@@ -73,7 +73,9 @@ async function acquireThree() {(typeof window !== 'undefined' && (window.solana || window.phantom?.solana)) || null;if (provider && (provider.isPhantom || provider.isThreeWs)) {try {- const resp = provider.publicKey ? { publicKey: provider.publicKey } : await provider.connect();+ const resp = provider.publicKey+ ? { publicKey: provider.publicKey }+ : await provider.connect();const wallet = resp?.publicKey?.toString?.();if (wallet) {const mod = await import('./swap-jupiter.js').catch(() => null);@@ -248,8 +250,10 @@ class ThreeGate extends HTMLElement {const tone = tierTone(required.id);const heldUsd = Number(held.usd) || 0;const reqMin = Number(required.min_usd) || 0;- const pct = reqMin > 0 ? Math.max(0, Math.min(100, Math.round((heldUsd / reqMin) * 100))) : 100;- const pay = access.pay_per_use && access.pay_per_use.usd != null ? access.pay_per_use : null;+ const pct =+ reqMin > 0 ? Math.max(0, Math.min(100, Math.round((heldUsd / reqMin) * 100))) : 100;+ const pay =+ access.pay_per_use && access.pay_per_use.usd != null ? access.pay_per_use : null;const secondary =reason === 'sign_in'diff --git a/src/three/access.css b/src/three/access.cssnew file mode 100644index 000000000..c65d88799--- /dev/null+++ b/src/three/access.css@@ -0,0 +1,343 @@+/* src/three/access.css+ *+ * Shared visual language for the $THREE hold-to-unlock surfaces:+ * • tg- — the gate modal (src/three/gate-modal.js, prompt 02)+ * • ta- — the /three access panel (prompt 04)+ *+ * Every rule is scoped under a root (.tg-gate / .ta-panel) so nothing leaks into+ * global CSS — and so the gate's classes win on specificity over any bare,+ * single-class `tg-*` rules another module may have injected globally. Token refs+ * carry literal fallbacks (the economy palette in src/three-economy.js) so the+ * surfaces render correctly on pages that don't load the design tokens.+ */++/* ── Gate modal (tg-) ─────────────────────────────────────────────────────── */++.tg-gate {+ --tg-ink: var(--ink, #f6f6f8);+ --tg-muted: var(--muted, #9a9aa4);+ --tg-muted-2: var(--muted-2, #80808b);+ --tg-line: var(--line-2, #23232c);+ --tg-surface: rgba(255, 255, 255, 0.03);+ --tg-green: var(--green, #6ee7a8);+ --tg-ease: cubic-bezier(0.22, 1, 0.36, 1);+ --tg-accent: var(--tg-green);+ --tg-accent-ink: #06120c;+ font-family: Inter, system-ui, -apple-system, BlinkMacSystemFont, sans-serif;+ color: var(--tg-ink);+}+.tg-gate[data-tone='gold'] {+ --tg-accent: var(--gold, #f5c451);+ --tg-accent-ink: #1a1304;+}+.tg-gate[data-tone='silver'] {+ --tg-accent: var(--silver, #cfd6e4);+ --tg-accent-ink: #0b0b0f;+}++/* Header / lead copy */+.tg-gate .tg-eyebrow {+ margin: 0 0 0.4rem;+ display: flex;+ align-items: center;+ gap: 0.35rem;+ font-size: 11px;+ font-weight: 700;+ letter-spacing: 0.07em;+ text-transform: uppercase;+ color: var(--tg-accent);+}+.tg-gate .tg-eyebrow::before {+ content: '◆';+ font-size: 11px;+ filter: drop-shadow(0 0 8px color-mix(in srgb, var(--tg-accent) 60%, transparent));+}+.tg-gate .tg-feature {+ margin: 0 0 0.85rem;+ font-size: 16px;+ font-weight: 750;+ letter-spacing: -0.01em;+ line-height: 1.3;+ color: var(--tg-ink);+}+.tg-gate .tg-lead {+ margin: 0 0 0.7rem;+ font-size: 13.5px;+ line-height: 1.55;+ color: var(--tg-muted);+}+.tg-gate .tg-lead strong {+ color: var(--tg-ink);+ font-weight: 650;+}++/* Tier chips: held → required */+.tg-gate .tg-tiers {+ display: flex;+ align-items: stretch;+ gap: 0.5rem;+ margin: 0.2rem 0 0.85rem;+}+.tg-gate .tg-chip {+ flex: 1 1 0;+ min-width: 0;+ display: flex;+ flex-direction: column;+ gap: 3px;+ padding: 0.6rem 0.7rem;+ border: 1px solid var(--tg-line);+ border-radius: 11px;+ background: var(--tg-surface);+}+.tg-gate .tg-chip--req {+ border-color: var(--tg-accent);+ background: color-mix(in srgb, var(--tg-accent) 7%, transparent);+}+.tg-gate .tg-chip-k {+ font-size: 10px;+ font-weight: 700;+ letter-spacing: 0.08em;+ text-transform: uppercase;+ color: var(--tg-muted-2);+}+.tg-gate .tg-chip-v {+ font-size: 13px;+ font-weight: 650;+ color: var(--tg-ink);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.tg-gate .tg-chip--req .tg-chip-v {+ color: var(--tg-accent);+}+.tg-gate .tg-arrow {+ flex: 0 0 auto;+ align-self: center;+ font-size: 14px;+ color: var(--tg-muted-2);+}++/* Progress toward the required threshold */+.tg-gate .tg-prog {+ margin: 0 0 0.55rem;+}+.tg-gate .tg-prog-track {+ display: block;+ height: 7px;+ border-radius: 99px;+ background: rgba(255, 255, 255, 0.07);+ overflow: hidden;+}+.tg-gate .tg-prog-fill {+ display: block;+ height: 100%;+ min-width: 2%;+ border-radius: 99px;+ background: var(--tg-accent);+ box-shadow: 0 0 10px -1px var(--tg-accent);+ transition: width 0.5s var(--tg-ease);+}+.tg-gate .tg-gap {+ margin: 0 0 0.7rem;+ font-size: 13px;+ font-weight: 600;+ text-align: center;+ color: var(--tg-ink);+}+.tg-gate .tg-gap strong {+ color: var(--tg-accent);+}++/* The honest reason it's gated */+.tg-gate .tg-why {+ margin: 0.15rem 0 0.6rem;+ font-size: 12.5px;+ line-height: 1.5;+ font-style: italic;+ color: var(--tg-muted);+}++/* Pay-per-use tertiary line */+.tg-gate .tg-pay {+ margin: 0.2rem 0 0.4rem;+ font-size: 12.5px;+ color: var(--tg-muted);+}+.tg-gate .tg-pay strong {+ color: var(--tg-ink);+ font-weight: 650;+}+.tg-gate .tg-pay-btn {+ margin: 0.2rem 0 0.4rem;+ padding: 0.15rem 0;+ background: none;+ border: none;+ font: 600 12.5px/1.4 inherit;+ color: var(--tg-muted);+ cursor: pointer;+ text-decoration: underline;+ text-underline-offset: 3px;+ transition: color 0.15s;+}+.tg-gate .tg-pay-btn strong {+ color: var(--tg-accent);+}+.tg-gate .tg-pay-btn:hover {+ color: var(--tg-ink);+}+.tg-gate .tg-pay-btn:disabled {+ opacity: 0.5;+ cursor: not-allowed;+}++/* aria-live recheck status */+.tg-gate .tg-status {+ margin: 0.55rem 0 0;+ min-height: 1.1em;+ display: flex;+ align-items: center;+ gap: 0.4rem;+ font-size: 12px;+ line-height: 1.4;+ color: var(--tg-muted);+}+.tg-gate .tg-status:empty {+ margin: 0;+ min-height: 0;+}+.tg-gate .tg-status[data-kind='warn'] {+ color: var(--gold, #f5c451);+}+.tg-gate .tg-status[data-kind='err'] {+ color: #ff8a8a;+}+.tg-gate .tg-status[data-kind='ok'] {+ color: var(--tg-green);+}++/* Actions */+.tg-gate-actions {+ display: flex;+ flex-direction: column;+ gap: 0.55rem;+ width: 100%;+}+.tg-gate .tg-act-row {+ display: flex;+ gap: 0.55rem;+}+.tg-gate .tg-act-row > * {+ flex: 1 1 0;+}+.tg-gate .tg-btn {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ gap: 0.45rem;+ padding: 0.72rem 1rem;+ border: 1px solid var(--tg-line);+ border-radius: 11px;+ background: transparent;+ color: var(--tg-ink);+ font: 650 13.5px/1 Inter, system-ui, sans-serif;+ text-decoration: none;+ white-space: nowrap;+ cursor: pointer;+ transition:+ transform 0.16s var(--tg-ease),+ background 0.16s,+ border-color 0.16s,+ color 0.16s,+ filter 0.16s,+ opacity 0.16s;+}+.tg-gate .tg-btn:hover {+ transform: translateY(-1px);+}+.tg-gate .tg-btn:active {+ transform: translateY(0);+}+.tg-gate .tg-btn--primary {+ background: var(--tg-accent);+ border-color: var(--tg-accent);+ color: var(--tg-accent-ink);+ font-weight: 750;+}+.tg-gate .tg-btn--primary:hover {+ filter: brightness(1.07);+}+.tg-gate .tg-btn--secondary {+ background: rgba(255, 255, 255, 0.04);+ color: var(--tg-ink);+}+.tg-gate .tg-btn--secondary:hover {+ background: rgba(255, 255, 255, 0.07);+ border-color: #3a3a44;+}+.tg-gate .tg-btn--ghost {+ background: transparent;+ color: var(--tg-muted);+}+.tg-gate .tg-btn--ghost:hover {+ color: var(--tg-ink);+ border-color: #3a3a44;+}+.tg-gate .tg-btn:disabled,+.tg-gate .tg-btn--disabled {+ opacity: 0.5;+ cursor: not-allowed;+ transform: none;+ pointer-events: none;+}+.tg-gate :where(.tg-btn, .tg-pay-btn, a):focus-visible {+ outline: 2px solid var(--tg-accent);+ outline-offset: 2px;+}++/* Recheck spinner glyph (real async — driven by the await, no fake timer) */+.tg-gate .tg-spin {+ width: 13px;+ height: 13px;+ flex: 0 0 auto;+ border-radius: 50%;+ border: 2px solid currentColor;+ border-top-color: transparent;+ animation: tg-spin 0.7s linear infinite;+}+@keyframes tg-spin {+ to {+ transform: rotate(360deg);+ }+}++/* Responsive: stack chips + actions on the narrowest screens (320px) */+@media (max-width: 380px) {+ .tg-gate .tg-tiers {+ flex-direction: column;+ }+ .tg-gate .tg-arrow {+ transform: rotate(90deg);+ }+ .tg-gate .tg-act-row {+ flex-direction: column;+ }+}++@media (prefers-reduced-motion: reduce) {+ .tg-gate .tg-btn,+ .tg-gate .tg-prog-fill {+ transition: none;+ }+ .tg-gate .tg-btn:hover {+ transform: none;+ }+ .tg-gate .tg-spin {+ animation: none;+ }+}++/* ── /three access panel (ta-) — populated by prompt 04 ───────────────────── */+/* The personal access panel reuses the same dark palette + tier chips. Its+ rules belong here, scoped under .ta-panel, so the gate and the panel share one+ stylesheet. (Intentionally left for prompt 04 to fill in.) */diff --git a/src/three/access.js b/src/three/access.jsnew file mode 100644index 000000000..aa7a0fa8b--- /dev/null+++ b/src/three/access.js@@ -0,0 +1,280 @@+// $THREE client access SDK — the single module every gated surface imports.+//+// It is the browser's view of the hold-to-access lever: it wraps the two server+// reads that decide entitlement, owns their caching + invalidation, and exposes one+// high-level call that either lets the user through (with a signed tier pass) or+// shows the gate.+//+// GET /api/three/access — the tier + per-feature entitlement matrix (auth+// optional; anonymous callers get the Member view).+// POST /api/three/tier-pass — mints a short-lived, HMAC-signed pass bound to the+// holder's wallet; a gated endpoint trusts it even+// when a live RPC read would hiccup.+//+// Public API:+// • fetchAccess({ feature, fresh }) — the entitlements snapshot (full or single+// feature). Never throws — Member fallback.+// • getTierPass({ force }) — mint/reuse the bearer pass; null when there+// is none to hold (anonymous / no wallet).+// • ensureFeatureAccess(feature, …) — the gate: proceed (with a pass) or open the+// modal and resolve on cancel / recheck.+// • subscribeAccess(cb) / refreshAccess() — react to wallet/auth/balance changes.+//+// Resilience contract: every network path is caught and degrades to a safe locked /+// anonymous state. Nothing here throws to the caller, and the server stays the only+// authority on eligibility — a pass is a hint, never a grant.++const ACCESS_URL = '/api/three/access';+const TIER_PASS_URL = '/api/three/tier-pass';++// Memoize the full matrix for ~30s; a per-feature read is derived from it when fresh.+const ACCESS_TTL_MS = 30_000;+// Re-mint a pass once it's within 90s of expiry so an in-flight gated request never+// rides a credential that expires mid-handshake.+const PASS_RENEW_BEFORE_MS = 90_000;+// Useful lifetime to assume when a pass payload's `exp` can't be decoded.+const PASS_FALLBACK_TTL_MS = 8 * 60_000;++const hasWindow = typeof window !== 'undefined';++let _matrix = { at: 0, data: null }; // cached full /access snapshot+let _pass = null; // { pass, tier, held_usd, exp(ms) } | null (memory only — bearer credential)+let _passReason = null; // 'sign_in' | 'link_wallet' | null — why the last mint returned no pass+const _subs = new Set(); // change subscribers++// ── helpers ─────────────────────────────────────────────────────────────────────++// Throwing JSON fetch (mirrors src/three-economy.js). Callers that must never throw+// wrap this; the access/tier-pass endpoints read the session cookie, so include it.+async function getJSON(path, opts = {}) {+ const r = await fetch(path, { credentials: 'include', ...opts });+ if (!r.ok) {+ const body = await r.json().catch(() => ({}));+ const err = new Error(body.error_description || body.error || `${r.status}`);+ err.status = r.status;+ err.code = body.error || null;+ throw err;+ }+ return r.json();+}++// base64url(json) → the pass payload's `exp` (unix seconds) in ms, or 0 if undecodable.+// The pass format is `<b64url(payload)>.<b64url(sig)>`; we only read the payload.+function decodePassExpMs(pass) {+ try {+ let b = String(pass).split('.')[0].replace(/-/g, '+').replace(/_/g, '/');+ while (b.length % 4) b += '=';+ const payload = JSON.parse(atob(b));+ const exp = Number(payload.exp) || 0;+ return exp > 0 ? exp * 1000 : 0;+ } catch {+ return 0;+ }+}++// A Member-shaped payload so a caller always has a safe locked state to render after+// a network failure. `_error` flags the degraded read for a richer UI; the shape+// otherwise matches a real signed-out response.+function memberFallback(feature) {+ const tier = { level: 0, id: 'member', label: 'Member', held_usd: 0 };+ const base = { signed_in: false, wallet_linked: false, tier, _error: true };+ if (!feature) return { ...base, features: [] };+ return {+ ...base,+ access: {+ feature,+ label: 'Holder feature',+ why: '',+ eligible: false,+ required: null,+ held: { level: 0, id: 'member', label: 'Member', min_usd: 0, usd: 0 },+ reason: 'error',+ pay_per_use: null,+ },+ };+}++// Carve a single-feature payload out of a cached full matrix, so a per-feature read+// is free when the matrix is already warm. Null when the feature isn't in the matrix.+function deriveFeature(matrix, feature) {+ if (!matrix || !Array.isArray(matrix.features)) return null;+ const access = matrix.features.find((f) => f && f.feature === feature);+ if (!access) return null;+ return {+ signed_in: matrix.signed_in,+ wallet_linked: matrix.wallet_linked,+ tier: matrix.tier,+ access,+ };+}++function passIsFresh(entry, now = Date.now()) {+ return Boolean(entry && entry.pass && entry.exp - PASS_RENEW_BEFORE_MS > now);+}++function notify() {+ for (const cb of _subs) {+ try {+ cb();+ } catch {+ /* a subscriber throwing must not break the others */+ }+ }+}++// ── reads ─────────────────────────────────────────────────────────────────────────++/**+ * The entitlements snapshot. With `feature`, returns the single-feature shape+ * ({ ..., access }); without, the full matrix ({ ..., features }). Both always carry+ * { signed_in, wallet_linked, tier }. The full matrix is memoized for ~30s and a+ * per-feature read is served from it when warm. Never throws — returns a+ * Member-shaped fallback (`_error: true`) on any network failure.+ * @param {{ feature?: string, fresh?: boolean }} [opts]+ */+export async function fetchAccess({ feature, fresh = false } = {}) {+ const now = Date.now();+ if (!fresh && _matrix.data && now - _matrix.at < ACCESS_TTL_MS) {+ if (!feature) return _matrix.data;+ const derived = deriveFeature(_matrix.data, feature);+ if (derived) return derived;+ }+ try {+ const url = feature ? `${ACCESS_URL}?feature=${encodeURIComponent(feature)}` : ACCESS_URL;+ const data = await getJSON(url);+ if (!feature && data && Array.isArray(data.features)) _matrix = { at: Date.now(), data };+ return data;+ } catch {+ return memberFallback(feature);+ }+}++/**+ * Mint (or reuse) the signed tier pass a holder attaches to gated calls. Cached in+ * memory only (never localStorage — it is a bearer credential) and re-minted once it+ * is within 90s of expiry. `force` bypasses the cache.+ * @param {{ force?: boolean }} [opts]+ * @returns {Promise<{ pass: string, tier: object|null, held_usd: number|null, exp: number }|null>}+ * null when the user is signed out (401) / has no linked wallet (403) / the mint+ * fails. The reason for a null is readable via {@link tierPassReason}.+ */+export async function getTierPass({ force = false } = {}) {+ const now = Date.now();+ if (!force && passIsFresh(_pass, now)) {+ _passReason = null;+ return _pass;+ }+ try {+ const r = await fetch(TIER_PASS_URL, { method: 'POST', credentials: 'include' });+ if (r.status === 201) {+ const data = await r.json().catch(() => null);+ const pass = data && typeof data.pass === 'string' ? data.pass : null;+ if (!pass) {+ _pass = null;+ _passReason = null;+ return null;+ }+ _pass = {+ pass,+ tier: data.tier || null,+ held_usd: data.held_usd ?? null,+ exp: decodePassExpMs(pass) || now + PASS_FALLBACK_TTL_MS,+ };+ _passReason = null;+ return _pass;+ }+ // 401 → sign in; 403 → link a wallet. Either way there is no pass to hold.+ _pass = null;+ _passReason = r.status === 401 ? 'sign_in' : r.status === 403 ? 'link_wallet' : null;+ return null;+ } catch {+ // Transient network error: keep any existing cache for the next attempt, but+ // don't hand back a stale credential this call.+ _passReason = null;+ return null;+ }+}++/** Why the last {@link getTierPass} returned null — 'sign_in' | 'link_wallet' | null. */+export function tierPassReason() {+ return _passReason;+}++// ── the gate ────────────────────────────────────────────────────────────────────++// One attempt at the gate: read the feature's access fresh, and if eligible, mint the+// pass (when the feature needs one). Returns the same shape the modal's recheck expects.+async function attempt(feature, needsPass) {+ const snapshot = await fetchAccess({ feature, fresh: true });+ const access = snapshot && snapshot.access ? snapshot.access : null;+ if (access && access.eligible) {+ if (!needsPass) return { ok: true, pass: null, access, snapshot };+ const pass = await getTierPass();+ // Eligible but the mint hiccupped (transient): fail OPEN — let the server be the+ // final authority rather than trapping a real holder behind a network blip.+ return { ok: true, pass: pass ? pass.pass : null, access, snapshot };+ }+ return { ok: false, reason: (access && access.reason) || 'insufficient_tier', access, snapshot };+}++/**+ * The high-level gate. Resolves { ok:true, pass } when the user may proceed (minting a+ * pass when `needsPass`), or opens the gate modal and resolves { ok:false, reason }+ * when they cancel. If, inside the modal, the user signs in / acquires $THREE and+ * Rechecks into eligibility, it re-resolves { ok:true, pass } and proceeds.+ * @param {string} feature a gated feature id (e.g. 'forge.high').+ * @param {{ trigger?: Element, needsPass?: boolean }} [opts] `trigger` is the element+ * that opened the gate (focus returns to it on close). `needsPass` (default true)+ * controls whether a pass is minted + returned on success.+ * @returns {Promise<{ ok: true, pass: string|null } | { ok: false, reason: string }>}+ */+export async function ensureFeatureAccess(feature, { trigger, needsPass = true } = {}) {+ const first = await attempt(feature, needsPass);+ if (first.ok) return { ok: true, pass: first.pass };++ let mod;+ try {+ mod = await import('./gate-modal.js');+ } catch {+ // The modal chunk failed to load — fail closed but never throw to the caller.+ return { ok: false, reason: first.reason };+ }+ const outcome = await mod.openGateModal({+ feature,+ trigger,+ snapshot: first.snapshot,+ recheck: () => attempt(feature, needsPass),+ });+ if (outcome && outcome.ok) return { ok: true, pass: outcome.pass ?? null };+ return { ok: false, reason: (outcome && outcome.reason) || first.reason || 'cancelled' };+}++// ── change notification ───────────────────────────────────────────────────────────++/**+ * Subscribe to access changes (wallet connect/disconnect, sign-in, manual refresh).+ * @param {() => void} cb+ * @returns {() => void} unsubscribe+ */+export function subscribeAccess(cb) {+ if (typeof cb !== 'function') return () => {};+ _subs.add(cb);+ return () => _subs.delete(cb);+}++/**+ * Drop the cached snapshot + pass and notify subscribers. Call after a known balance+ * or auth change so the next read re-resolves against the server.+ */+export function refreshAccess() {+ _matrix = { at: 0, data: null };+ _pass = null;+ _passReason = null;+ notify();+}++// A wallet connect/disconnect changes who the caller is, so every cached answer is now+// for the wrong identity. Drop them and notify — the one live coupling, kept light.+if (hasWindow && typeof window.addEventListener === 'function') {+ window.addEventListener('wallet:changed', refreshAccess);+}diff --git a/src/three/gate-modal.js b/src/three/gate-modal.jsnew file mode 100644index 000000000..166ea0c99--- /dev/null+++ b/src/three/gate-modal.js@@ -0,0 +1,330 @@+// The $THREE access gate — the modal src/three/access.js opens when a caller is not+// yet entitled to a gated feature. It is honest and actionable: it shows what the+// user holds vs. what the feature needs, gives a real path to fix it (sign in, link a+// wallet, or get $THREE), and lets them Recheck in place so acquiring access proceeds+// the original action without a reload.+//+// Contract with access.js:+// openGateModal({ feature, trigger, snapshot, recheck }) → Promise<+// { ok:true, pass:string|null } | { ok:false, reason:string }>+// • snapshot — the single-feature /api/three/access payload that failed the gate.+// • recheck — async () => the same attempt() result access.js uses internally:+// { ok:true, pass } when newly eligible, or { ok:false, reason, snapshot }.+// • trigger — the element that opened the gate; focus returns to it on close.+//+// Resolves { ok:true, pass } when a Recheck lands the user in eligibility, else+// { ok:false, reason } on cancel. The server stays the authority — this only shapes+// the path back to eligibility, it never grants it.++const ECONOMY_URL = '/three'; // the $THREE economy page — where you get $THREE / see tiers++let _active = null; // the single live instance: { overlay, resolve, restoreFocus, onKey }+let _stylesInjected = false;++const esc = (s) =>+ String(s ?? '').replace(+ /[&<>"']/g,+ (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],+ );++const fmtUsd = (n) => {+ const v = Number(n);+ if (!Number.isFinite(v) || v <= 0) return '';+ return v.toLocaleString('en-US', { style: 'currency', currency: 'USD', maximumFractionDigits: v < 1 ? 2 : 0 });+};++// Reason → the user-facing framing of why they're locked + which action leads out.+// `held`/`required` come from the access payload; `feature` is its holder-readable label.+function describe(access) {+ const reason = access?.reason || 'insufficient_tier';+ const held = access?.held || { label: 'Member', level: 0, usd: 0 };+ const required = access?.required || null;+ const reqLabel = required?.label || 'a higher tier';+ const heldUsd = fmtUsd(held.usd);++ if (reason === 'sign_in') {+ return {+ title: 'Sign in to unlock',+ body: `Sign in with your Solana wallet so we can read your $THREE and check your tier.`,+ primary: 'signin',+ primaryLabel: 'Sign in',+ };+ }+ if (reason === 'link_wallet') {+ return {+ title: 'Link a Solana wallet',+ body: `You're signed in, but no Solana wallet is linked yet. Connect one so we can read your $THREE.`,+ primary: 'signin',+ primaryLabel: 'Link a wallet',+ };+ }+ if (reason === 'error') {+ return {+ title: "Couldn't check your tier",+ body: `We couldn't read your $THREE just now. Recheck in a moment — or get $THREE to unlock this.`,+ primary: 'get',+ primaryLabel: 'Get $THREE',+ };+ }+ // insufficient_tier — a real holder under the bar.+ return {+ title: `Hold ${esc(reqLabel)} to unlock`,+ body: `You hold <strong>${esc(held.label)}</strong>${heldUsd ? ` (≈ ${esc(heldUsd)})` : ''}. Reach <strong>${esc(reqLabel)}</strong> to unlock this.`,+ primary: 'get',+ primaryLabel: 'Get $THREE',+ };+}++// The modal's inner markup, rebuilt on every (re)check so held-vs-required stays live.+function bodyHTML(snapshot) {+ const access = snapshot?.access || {};+ const d = describe(access);+ const featureLabel = access.label || 'This is a $THREE holder feature.';+ const why = access.why ? `<p class="tga-why">${esc(access.why)}</p>` : '';+ // Pay-per-use is shown as honest context, not a button — paying is the caller's own+ // flow, so we never render a control here that wouldn't do anything.+ const ppu =+ access.pay_per_use && Number(access.pay_per_use.usd) > 0+ ? `<p class="tga-ppu">No $THREE yet? This action can also be paid per use — about ${esc(fmtUsd(access.pay_per_use.usd))} each — at checkout.</p>`+ : '';++ const primaryBtn =+ d.primary === 'signin'+ ? `<button class="tga-btn tga-btn--primary" data-act="signin" type="button">${esc(d.primaryLabel)}</button>`+ : `<a class="tga-btn tga-btn--primary" data-act="get" href="${ECONOMY_URL}" target="_blank" rel="noopener">${esc(d.primaryLabel)}</a>`;++ return `+ <button class="tga-x" data-act="close" type="button" aria-label="Close">✕</button>+ <div class="tga-mark" aria-hidden="true">◆</div>+ <h2 class="tga-title" id="tga-title">${d.title}</h2>+ <p class="tga-feature">${esc(featureLabel)}</p>+ <p class="tga-body" id="tga-desc">${d.body}</p>+ ${why}+ <div class="tga-actions">+ ${primaryBtn}+ <button class="tga-btn tga-btn--ghost" data-act="recheck" type="button">Recheck access</button>+ </div>+ <a class="tga-tiers" href="${ECONOMY_URL}#tiers" target="_blank" rel="noopener">See holder tiers →</a>+ ${ppu}+ <p class="tga-note" id="tga-note" role="status" aria-live="polite"></p>+ <p class="tga-foot">$THREE is the only coin on three.ws. Draft & Standard generation stay free, forever.</p>`;+}++function focusable(root) {+ return [...root.querySelectorAll('button:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])')].filter(+ (el) => el.offsetParent !== null || el === document.activeElement,+ );+}++function setNote(overlay, text, tone = 'info') {+ const note = overlay.querySelector('#tga-note');+ if (!note) return;+ note.textContent = text || '';+ note.dataset.tone = tone;+}++function setBusy(overlay, act, busy, busyLabel) {+ const btn = overlay.querySelector(`[data-act="${act}"]`);+ if (!btn) return null;+ if (busy) {+ btn._label = btn.textContent;+ btn.textContent = busyLabel || btn.textContent;+ btn.setAttribute('aria-busy', 'true');+ btn.disabled = true;+ } else {+ if (btn._label) btn.textContent = btn._label;+ btn.removeAttribute('aria-busy');+ btn.disabled = false;+ }+ return btn;+}++/**+ * Open the gate. See the module header for the full contract.+ * @returns {Promise<{ ok:true, pass:string|null } | { ok:false, reason:string }>}+ */+export function openGateModal({ feature, trigger, snapshot, recheck } = {}) {+ if (typeof document === 'undefined') return Promise.resolve({ ok: false, reason: 'no_dom' });+ injectStyles();+ closeActive({ ok: false, reason: 'superseded' }); // never stack two gates++ let current = snapshot; // updated by each recheck so the copy stays accurate+ const restoreFocus = trigger && typeof trigger.focus === 'function' ? trigger : null;++ return new Promise((resolve) => {+ const overlay = document.createElement('div');+ overlay.className = 'tga-overlay';+ overlay.innerHTML = `<div class="tga-modal" role="dialog" aria-modal="true" aria-labelledby="tga-title" aria-describedby="tga-desc">${bodyHTML(current)}</div>`;+ document.body.appendChild(overlay);+ const modal = overlay.querySelector('.tga-modal');++ const finish = (outcome) => {+ if (_active !== inst) return;+ _active = null;+ document.removeEventListener('keydown', onKey, true);+ overlay.classList.remove('tga-in');+ const remove = () => overlay.remove();+ overlay.addEventListener('transitionend', remove, { once: true });+ setTimeout(remove, 260); // fallback when transitions are disabled+ if (restoreFocus && document.contains(restoreFocus)) {+ try {+ restoreFocus.focus();+ } catch {+ /* element may have been detached — nothing to restore */+ }+ }+ resolve(outcome);+ };++ const onKey = (e) => {+ if (e.key === 'Escape') {+ e.stopPropagation();+ finish({ ok: false, reason: 'cancelled' });+ } else if (e.key === 'Tab') {+ const items = focusable(modal);+ if (!items.length) return;+ const first = items[0];+ const last = items[items.length - 1];+ if (e.shiftKey && document.activeElement === first) {+ e.preventDefault();+ last.focus();+ } else if (!e.shiftKey && document.activeElement === last) {+ e.preventDefault();+ first.focus();+ }+ }+ };++ // Re-resolve eligibility in place; proceed on success, refresh the copy otherwise.+ const doRecheck = async () => {+ setNote(overlay, 'Checking your access…');+ setBusy(overlay, 'recheck', true, 'Checking…');+ let res;+ try {+ res = typeof recheck === 'function' ? await recheck() : { ok: false };+ } catch {+ res = { ok: false };+ }+ if (_active !== inst) return; // closed mid-flight+ if (res && res.ok) {+ finish({ ok: true, pass: res.pass ?? null });+ return;+ }+ if (res && res.snapshot) {+ current = res.snapshot;+ modal.innerHTML = bodyHTML(current);+ wire();+ }+ setBusy(overlay, 'recheck', false);+ setNote(overlay, 'Not unlocked yet — get $THREE, then Recheck.', 'warn');+ };++ // Real auth: SIWS connects a Solana wallet and signs in (or links one to the+ // session). On success the wallet:changed event busts access.js's cache; we then+ // recheck to proceed the original action.+ const doSignIn = async () => {+ setNote(overlay, '');+ setBusy(overlay, 'signin', true, 'Signing in…');+ try {+ const { signInWithWallet } = await import('../wallet-auth.js');+ await signInWithWallet();+ } catch {+ if (_active !== inst) return;+ setBusy(overlay, 'signin', false);+ setNote(overlay, 'Sign-in was cancelled or failed. Try again.', 'warn');+ return;+ }+ if (_active !== inst) return;+ await doRecheck();+ };++ const onClick = (e) => {+ const actEl = e.target.closest('[data-act]');+ if (!actEl) {+ if (e.target === overlay) finish({ ok: false, reason: 'cancelled' });+ return;+ }+ const act = actEl.dataset.act;+ if (act === 'close') finish({ ok: false, reason: 'cancelled' });+ else if (act === 'recheck') doRecheck();+ else if (act === 'signin') {+ e.preventDefault();+ doSignIn();+ }+ // 'get' is a real <a> → let it navigate (opens /three in a new tab).+ };++ // (Re)bind the delegated click handler after each innerHTML rebuild.+ const wire = () => {+ modal.onclick = onClick;+ };+ wire();++ const inst = { overlay, finish };+ _active = inst;+ document.addEventListener('keydown', onKey, true);+ requestAnimationFrame(() => {+ overlay.classList.add('tga-in');+ const primary = modal.querySelector('.tga-btn--primary') || modal.querySelector('[data-act="close"]');+ if (primary) primary.focus();+ });+ });+}++/** Close any open gate immediately, resolving its promise with `outcome`. */+export function closeActive(outcome = { ok: false, reason: 'cancelled' }) {+ if (_active && typeof _active.finish === 'function') _active.finish(outcome);+}++// ── styles ────────────────────────────────────────────────────────────────────────++function injectStyles() {+ if (_stylesInjected || typeof document === 'undefined') return;+ _stylesInjected = true;+ const css = `+ .tga-overlay{position:fixed;inset:0;z-index:2147483000;display:flex;align-items:center;justify-content:center;+ padding:20px;background:rgba(4,4,7,.68);backdrop-filter:blur(7px);opacity:0;transition:opacity .2s ease;}+ .tga-overlay.tga-in{opacity:1;}+ .tga-modal{position:relative;width:min(440px,100%);background:linear-gradient(180deg,#0e0e13,#0a0a0e);+ border:1px solid #23232c;border-radius:20px;padding:34px 30px 26px;text-align:center;color:#f6f6f8;+ font-family:Inter,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;+ box-shadow:0 30px 80px -30px rgba(0,0,0,.8);+ transform:translateY(10px) scale(.985);transition:transform .24s cubic-bezier(.22,1,.36,1);}+ .tga-overlay.tga-in .tga-modal{transform:none;}+ .tga-x{position:absolute;top:12px;right:12px;width:32px;height:32px;border-radius:9px;border:1px solid #23232c;+ background:transparent;color:#9a9aa4;cursor:pointer;font-size:13px;transition:.15s cubic-bezier(.22,1,.36,1);}+ .tga-x:hover{color:#f6f6f8;border-color:#34343f;}+ .tga-mark{font-size:34px;color:#6ee7a8;filter:drop-shadow(0 0 14px rgba(110,231,168,.5));margin-bottom:8px;}+ .tga-title{font-size:22px;font-weight:820;letter-spacing:-.02em;margin:2px 0 8px;}+ .tga-feature{font-size:14.5px;color:#c9c9d2;margin:0 0 10px;line-height:1.45;}+ .tga-body{font-size:13.5px;color:#9a9aa4;margin:0 0 8px;line-height:1.5;}+ .tga-body strong{color:#f6f6f8;}+ .tga-why{font-size:12.5px;color:#80808b;margin:0 0 16px;line-height:1.5;font-style:italic;}+ .tga-actions{display:flex;flex-direction:column;gap:9px;margin:10px 0 6px;}+ .tga-btn{display:inline-flex;align-items:center;justify-content:center;font:700 14px/1 Inter,system-ui,sans-serif;+ padding:12px 18px;border-radius:12px;text-decoration:none;cursor:pointer;border:1px solid #2a2a33;+ transition:.16s cubic-bezier(.22,1,.36,1);}+ .tga-btn[aria-busy="true"],.tga-btn:disabled{opacity:.62;cursor:default;}+ .tga-btn--primary{background:#6ee7a8;color:#06120c;border-color:#6ee7a8;}+ .tga-btn--primary:not(:disabled):hover{background:#8af0c0;transform:translateY(-1px);}+ .tga-btn--ghost{background:#0e0e13;color:#f6f6f8;}+ .tga-btn--ghost:not(:disabled):hover{border-color:#3a3a44;transform:translateY(-1px);}+ .tga-tiers{display:inline-block;margin:8px 0 0;font:600 12.5px/1 Inter,system-ui,sans-serif;color:#6ee7a8;+ text-decoration:none;}+ .tga-tiers:hover{text-decoration:underline;}+ .tga-ppu{font-size:12px;color:#9a9aa4;margin:14px 0 0;line-height:1.5;}+ .tga-note{font-size:12.5px;margin:12px 0 0;line-height:1.45;min-height:0;}+ .tga-note[data-tone="warn"]{color:#f0c886;}+ .tga-note[data-tone="info"]{color:#80808b;}+ .tga-foot{font-size:11px;color:#6a6a74;margin:14px 0 0;line-height:1.5;}+ :where(.tga-btn,.tga-tiers,.tga-x):focus-visible{outline:2px solid #6ee7a8;outline-offset:2px;border-radius:9px;}+ @media (prefers-reduced-motion: reduce){+ .tga-overlay,.tga-modal,.tga-btn,.tga-x{transition:none;}+ .tga-modal{transform:none;}+ .tga-btn--primary:hover,.tga-btn--ghost:hover{transform:none;}+ }`;+ const el = document.createElement('style');+ el.id = 'tga-styles';+ el.textContent = css;+ document.head.appendChild(el);+}diff --git a/tests/three-access-client.test.js b/tests/three-access-client.test.jsnew file mode 100644index 000000000..88357182f--- /dev/null+++ b/tests/three-access-client.test.js@@ -0,0 +1,197 @@+// @vitest-environment jsdom+//+// Unit tests for the connected-wallet wiring in the v1 client helper+// (src/three-access.js). They prove the four contract points added when a Phantom /+// Seeker wallet is connected without a three.ws account:+// • getAccess() reads the wallet's on-chain tier via ?wallet=, and falls back to+// the session (no ?wallet=) when none is connected;+// • getTierPass({ interactive }) mints through the signature path — signing the+// canonical, server-validated message — only on an interactive call, never in a+// background prime, and de-dupes concurrent mints onto one signature;+// • the session path still mints silently (no wallet, no body);+// • mountTierBadge renders for a connected-wallet holder even when signed_in:false.+//+// src/wallet.js is mocked so we drive the connected identity + provider directly; the+// live endpoint + signature verifier are covered by tests/three-tier-public.test.js.++import { describe, it, expect, beforeEach, vi } from 'vitest';++// Mutable, hoisted so the vi.mock factory can read the current identity each call.+const state = vi.hoisted(() => ({ addr: null, provider: null }));++vi.mock('../src/wallet.js', () => ({+ getConnectedWalletAddress: () => state.addr,+ getConnectedWallet: () => state.provider,+}));++const WALLET = 'So11111111111111111111111111111111111111112';++// A pass string shaped like the server's: `<base64url(payload)>.<sig>`, payload.exp+// in unix seconds, far enough out to read as fresh (cached until ~1 min before exp).+function makePass(secondsOut = 600) {+ const exp = Math.floor(Date.now() / 1000) + secondsOut;+ const payload = btoa(JSON.stringify({ exp }))+ .replace(/\+/g, '-')+ .replace(/\//g, '_')+ .replace(/=+$/, '');+ return `${payload}.signature`;+}++const PASS = makePass();++function jsonRes(body, { ok = true, status = 200 } = {}) {+ return { ok, status, json: async () => body };+}++// Fresh module instance per test so the in-memory caches don't leak across cases.+async function loadModule() {+ vi.resetModules();+ return import('../src/three-access.js');+}++beforeEach(() => {+ state.addr = null;+ state.provider = null;+ global.fetch = vi.fn();+ document.body.innerHTML = '';+});++describe('getAccess — identity-aware', () => {+ it('appends ?wallet= for a connected wallet (alongside &feature=)', async () => {+ state.addr = WALLET;+ const matrix = { signed_in: false, wallet_linked: true, tier: { level: 1, id: 'bronze', label: 'Bronze', held_usd: 30 } };+ global.fetch = vi.fn(async () => jsonRes(matrix));+ const { getAccess } = await loadModule();++ const data = await getAccess('forge.high');+ const url = String(global.fetch.mock.calls[0][0]);+ expect(url).toContain('feature=forge.high');+ expect(url).toContain(`wallet=${WALLET}`);+ expect(data).toBe(matrix);+ });++ it('omits ?wallet= when no wallet is connected (session fallback)', async () => {+ const matrix = { signed_in: true, wallet_linked: true, tier: { level: 0, id: 'member', label: 'Member', held_usd: 0 } };+ global.fetch = vi.fn(async () => jsonRes(matrix));+ const { getAccess } = await loadModule();++ await getAccess();+ const url = String(global.fetch.mock.calls[0][0]);+ expect(url).not.toContain('wallet=');+ });++ it('re-keys the matrix cache on wallet:changed', async () => {+ const matrix = { signed_in: false, wallet_linked: true, tier: { level: 1, id: 'bronze', label: 'Bronze', held_usd: 30 } };+ global.fetch = vi.fn(async () => jsonRes(matrix));+ const { getAccess } = await loadModule();++ await getAccess(); // session read, cached+ expect(global.fetch).toHaveBeenCalledTimes(1);+ await getAccess(); // served from the 30s cache+ expect(global.fetch).toHaveBeenCalledTimes(1);++ state.addr = WALLET;+ window.dispatchEvent(new CustomEvent('wallet:changed', { detail: { address: WALLET } }));+ await getAccess(); // identity changed → cache invalidated → fresh fetch with ?wallet=+ expect(global.fetch).toHaveBeenCalledTimes(2);+ expect(String(global.fetch.mock.calls[1][0])).toContain(`wallet=${WALLET}`);+ });+});++describe('getTierPass — signature path for a connected wallet', () => {+ it('mints by signing the canonical message on an interactive call', async () => {+ state.addr = WALLET;+ state.provider = { signMessage: vi.fn(async () => ({ signature: new Uint8Array(64) })) };+ global.fetch = vi.fn(async (url, opts) => {+ expect(String(url)).toContain('/api/three/tier-pass');+ expect(opts.method).toBe('POST');+ const body = JSON.parse(opts.body);+ expect(body.wallet).toBe(WALLET);+ expect(body.message).toContain('three.ws');+ expect(body.message).toContain(`Wallet: ${WALLET}`);+ expect(body.message).toContain('Issued At:');+ expect(typeof body.signature).toBe('string');+ return jsonRes({ pass: PASS, tier: { level: 3, id: 'gold', label: 'Gold' } }, { status: 201 });+ });+ const { getTierPass, tierPassHeader } = await loadModule();++ const pass = await getTierPass({ interactive: true });+ expect(pass.pass).toBe(PASS);+ expect(pass.wallet).toBe(WALLET);+ expect(state.provider.signMessage).toHaveBeenCalledOnce();+ expect(tierPassHeader()).toBe(PASS);+ });++ it('never prompts the wallet on a background (non-interactive) call', async () => {+ state.addr = WALLET;+ state.provider = { signMessage: vi.fn() };+ const { getTierPass } = await loadModule();++ const pass = await getTierPass(); // primeTierPass() path+ expect(pass).toBeNull();+ expect(state.provider.signMessage).not.toHaveBeenCalled();+ expect(global.fetch).not.toHaveBeenCalled();+ });++ it('de-dupes concurrent interactive mints onto one signature', async () => {+ state.addr = WALLET;+ let resolveSig;+ state.provider = {+ signMessage: vi.fn(() => new Promise((r) => { resolveSig = r; })),+ };+ global.fetch = vi.fn(async () => jsonRes({ pass: PASS, tier: { level: 3, id: 'gold', label: 'Gold' } }, { status: 201 }));+ const { getTierPass } = await loadModule();++ const a = getTierPass({ interactive: true });+ const b = getTierPass({ interactive: true });+ resolveSig({ signature: new Uint8Array(64) });+ const [ra, rb] = await Promise.all([a, b]);+ expect(ra).toBe(rb);+ expect(state.provider.signMessage).toHaveBeenCalledOnce();+ expect(global.fetch).toHaveBeenCalledTimes(1);+ });++ it('keeps the silent session path for a signed-in user (no wallet, no body)', async () => {+ global.fetch = vi.fn(async (url, opts) => {+ expect(String(url)).toContain('/api/three/tier-pass');+ expect(opts.method).toBe('POST');+ expect(opts.body).toBeUndefined();+ return jsonRes({ pass: PASS, tier: { level: 2, id: 'silver', label: 'Silver' } }, { status: 201 });+ });+ const { getTierPass } = await loadModule();++ const pass = await getTierPass(); // background prime works silently for a session+ expect(pass.pass).toBe(PASS);+ expect(pass.wallet).toBeNull();+ });+});++describe('mountTierBadge — connected-wallet holder', () => {+ it('renders the chip for a connected wallet even when signed_in:false', async () => {+ state.addr = WALLET;+ global.fetch = vi.fn(async () =>+ jsonRes({ signed_in: false, wallet_linked: true, tier: { level: 2, id: 'silver', label: 'Silver', held_usd: 300 } }),+ );+ document.body.innerHTML = '<div id="badge"></div>';+ const { mountTierBadge } = await loadModule();++ await mountTierBadge('#badge');+ const el = document.getElementById('badge');+ expect(el.hidden).toBe(false);+ expect(el.innerHTML).toContain('Silver');+ expect(el.innerHTML).toContain('tg-tier-silver');+ });++ it('hides the chip for a non-holder (Member, level 0)', async () => {+ global.fetch = vi.fn(async () =>+ jsonRes({ signed_in: true, wallet_linked: false, tier: { level: 0, id: 'member', label: 'Member', held_usd: 0 } }),+ );+ document.body.innerHTML = '<div id="badge"></div>';+ const { mountTierBadge } = await loadModule();++ await mountTierBadge('#badge');+ const el = document.getElementById('badge');+ expect(el.hidden).toBe(true);+ expect(el.innerHTML).toBe('');+ });+});diff --git a/tests/three/access.test.js b/tests/three/access.test.jsnew file mode 100644index 000000000..5d6a9424e--- /dev/null+++ b/tests/three/access.test.js@@ -0,0 +1,275 @@+// @vitest-environment jsdom+//+// Unit tests for the client access SDK (src/three/access.js) — the single module+// every gated surface imports. Against a mocked fetch + a real jsdom DOM (the gate+// modal mounts for real), these prove: the 30s matrix cache + per-feature derivation+// + `fresh` bypass, the Member-shaped fallback that means fetchAccess never throws,+// the tier-pass mint/cache/90s-renewal + the 401→sign_in / 403→link_wallet reason+// map, the high-level gate (eligible → pass; eligible-but-mint-fails → fail-open;+// not-eligible → opens the modal and resolves on cancel; Recheck into eligibility →+// proceeds), subscribe/refresh, and that a wallet:changed event busts the cache.++import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';++const ACCESS_RE = /\/api\/three\/access/;+const PASS_RE = /\/api\/three\/tier-pass/;++// Mutable per-test responses the fetch mock serves; reset in beforeEach.+let accessState;+let passState;++const TIER = { level: 0, id: 'member', label: 'Member', held_usd: 0 };++function res(status, body) {+ return { ok: status >= 200 && status < 300, status, json: async () => body };+}++// A locked single-feature payload with a chosen reason — the real server shape.+function locked(reason = 'sign_in', extra = {}) {+ return {+ signed_in: reason !== 'sign_in',+ wallet_linked: reason === 'insufficient_tier',+ tier: TIER,+ access: {+ feature: 'forge.high',+ label: 'High-quality generation (200k poly + PBR)',+ why: 'The High tier spends real GPU budget — holders fund it by holding.',+ eligible: false,+ required: { level: 1, id: 'bronze', label: 'Bronze', min_usd: 25 },+ held: { level: 0, id: 'member', label: 'Member', min_usd: 0, usd: 0 },+ reason,+ pay_per_use: { action: 'forge.high', usd: 0.5 },+ ...extra,+ },+ };+}++function eligible() {+ const d = locked('insufficient_tier');+ d.signed_in = true;+ d.wallet_linked = true;+ d.tier = { level: 1, id: 'bronze', label: 'Bronze', held_usd: 40 };+ d.access.eligible = true;+ d.access.reason = 'eligible';+ d.access.held = { level: 1, id: 'bronze', label: 'Bronze', min_usd: 25, usd: 40 };+ return d;+}++function matrix(features) {+ return { signed_in: true, wallet_linked: true, tier: { level: 1, id: 'bronze', label: 'Bronze', held_usd: 40 }, features };+}++// A real `<b64url(payload)>.<b64url(sig)>` pass whose exp is `secs` from now.+function makePass(secs) {+ const b64 = (o) => btoa(JSON.stringify(o)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');+ return `${b64({ wallet: 'THREEsynthetic1111', exp: Math.floor(Date.now() / 1000) + secs })}.${b64({ sig: 'x' })}`;+}++function installFetch() {+ global.fetch = vi.fn(async (url) => {+ const u = String(url);+ if (ACCESS_RE.test(u)) return res(accessState.status, accessState.body);+ if (PASS_RE.test(u)) return res(passState.status, passState.body);+ return res(404, { error: 'not_found' });+ });+ return global.fetch;+}++// Each test gets a pristine module (module-level caches/singletons reset).+async function freshModule() {+ vi.resetModules();+ return import('../../src/three/access.js');+}++beforeEach(() => {+ accessState = { status: 200, body: locked('sign_in') };+ passState = { status: 201, body: { pass: makePass(600), tier: { level: 1, id: 'bronze', label: 'Bronze' }, held_usd: 40 } };+ installFetch();+});++afterEach(() => {+ document.querySelectorAll('.tga-overlay').forEach((el) => el.remove());+ vi.restoreAllMocks();+});++describe('fetchAccess — cache, derivation, fallback', () => {+ it('returns the full matrix and memoizes it within the TTL', async () => {+ const { fetchAccess } = await freshModule();+ accessState.body = matrix([eligible().access]);+ const a = await fetchAccess();+ const b = await fetchAccess();+ expect(a).toEqual(b);+ expect(global.fetch).toHaveBeenCalledTimes(1);+ });++ it('derives a single feature from the warm matrix without a second request', async () => {+ const { fetchAccess } = await freshModule();+ accessState.body = matrix([eligible().access]);+ await fetchAccess(); // warms the matrix+ const f = await fetchAccess({ feature: 'forge.high' });+ expect(global.fetch).toHaveBeenCalledTimes(1);+ expect(f.access.feature).toBe('forge.high');+ expect(f.tier.id).toBe('bronze');+ expect(f.signed_in).toBe(true);+ });++ it('fresh:true bypasses the cache', async () => {+ const { fetchAccess } = await freshModule();+ accessState.body = matrix([eligible().access]);+ await fetchAccess();+ await fetchAccess({ fresh: true });+ expect(global.fetch).toHaveBeenCalledTimes(2);+ });++ it('never throws — returns a Member-shaped fallback on a network failure', async () => {+ const { fetchAccess } = await freshModule();+ global.fetch.mockRejectedValueOnce(new Error('offline'));+ const a = await fetchAccess({ feature: 'forge.high' });+ expect(a.signed_in).toBe(false);+ expect(a.wallet_linked).toBe(false);+ expect(a.tier.id).toBe('member');+ expect(a._error).toBe(true);+ expect(a.access.eligible).toBe(false);+ });++ it('signed-out shape matches the acceptance contract', async () => {+ const { fetchAccess } = await freshModule();+ accessState.body = { signed_in: false, wallet_linked: false, tier: TIER, access: locked('sign_in').access };+ const a = await fetchAccess({ feature: 'forge.high' });+ expect(a.signed_in).toBe(false);+ expect(a.wallet_linked).toBe(false);+ expect(a.tier.id).toBe('member');+ });+});++describe('getTierPass — mint, cache, renewal, reason map', () => {+ it('mints a pass (201) and caches it across calls', async () => {+ const { getTierPass } = await freshModule();+ const p1 = await getTierPass();+ const p2 = await getTierPass();+ expect(p1.pass).toBe(passState.body.pass);+ expect(p1.held_usd).toBe(40);+ expect(p1.tier.id).toBe('bronze');+ expect(p2).toBe(p1);+ expect(global.fetch).toHaveBeenCalledTimes(1);+ });++ it('re-mints when the cached pass is within 90s of expiry', async () => {+ const { getTierPass } = await freshModule();+ passState.body = { ...passState.body, pass: makePass(60) }; // inside the 90s renew window+ await getTierPass();+ await getTierPass();+ expect(global.fetch).toHaveBeenCalledTimes(2);+ });++ it('force:true bypasses a fresh cache', async () => {+ const { getTierPass } = await freshModule();+ await getTierPass();+ await getTierPass({ force: true });+ expect(global.fetch).toHaveBeenCalledTimes(2);+ });++ it('401 → null with reason sign_in', async () => {+ const { getTierPass, tierPassReason } = await freshModule();+ passState = { status: 401, body: { error: 'unauthorized' } };+ expect(await getTierPass()).toBeNull();+ expect(tierPassReason()).toBe('sign_in');+ });++ it('403 → null with reason link_wallet', async () => {+ const { getTierPass, tierPassReason } = await freshModule();+ passState = { status: 403, body: { error: 'wallet_required' } };+ expect(await getTierPass()).toBeNull();+ expect(tierPassReason()).toBe('link_wallet');+ });++ it('a network failure returns null without throwing', async () => {+ const { getTierPass } = await freshModule();+ global.fetch.mockRejectedValueOnce(new Error('offline'));+ expect(await getTierPass()).toBeNull();+ });+});++describe('ensureFeatureAccess — the gate', () => {+ it('eligible → { ok:true, pass } and mints a pass', async () => {+ const { ensureFeatureAccess } = await freshModule();+ accessState.body = eligible();+ const out = await ensureFeatureAccess('forge.high');+ expect(out.ok).toBe(true);+ expect(out.pass).toBe(passState.body.pass);+ expect(global.fetch).toHaveBeenCalledWith('/api/three/tier-pass', expect.objectContaining({ method: 'POST' }));+ });++ it('eligible with needsPass:false → { ok:true } and mints no pass', async () => {+ const { ensureFeatureAccess } = await freshModule();+ accessState.body = eligible();+ const out = await ensureFeatureAccess('forge.high', { needsPass: false });+ expect(out).toEqual({ ok: true, pass: null });+ expect(global.fetch).toHaveBeenCalledTimes(1); // access only, no tier-pass+ });++ it('eligible but the pass mint fails → fails OPEN with { ok:true, pass:null }', async () => {+ const { ensureFeatureAccess } = await freshModule();+ accessState.body = eligible();+ passState = { status: 401, body: { error: 'unauthorized' } };+ const out = await ensureFeatureAccess('forge.high');+ expect(out).toEqual({ ok: true, pass: null });+ });++ it('not eligible → opens the gate modal and does not throw', async () => {+ const { ensureFeatureAccess } = await freshModule();+ accessState.body = locked('sign_in');+ const p = ensureFeatureAccess('forge.high');+ await vi.waitFor(() => expect(document.querySelector('.tga-overlay')).toBeTruthy());+ expect(document.querySelector('.tga-title')).toBeTruthy();+ // Cancel via the close button → resolves { ok:false }.+ document.querySelector('[data-act="close"]').click();+ const out = await p;+ expect(out.ok).toBe(false);+ expect(out.reason).toBe('cancelled');+ });++ it('Recheck into eligibility proceeds the original action', async () => {+ const { ensureFeatureAccess } = await freshModule();+ accessState.body = locked('insufficient_tier');+ const p = ensureFeatureAccess('forge.high');+ await vi.waitFor(() => expect(document.querySelector('.tga-overlay')).toBeTruthy());+ // User acquires $THREE in another tab: the next read is eligible + a pass mints.+ accessState.body = eligible();+ document.querySelector('[data-act="recheck"]').click();+ const out = await p;+ expect(out.ok).toBe(true);+ expect(out.pass).toBe(passState.body.pass);+ });+});++describe('subscribeAccess / refreshAccess / wallet:changed', () => {+ it('notifies subscribers on refreshAccess and stops after unsubscribe', async () => {+ const { subscribeAccess, refreshAccess } = await freshModule();+ const cb = vi.fn();+ const off = subscribeAccess(cb);+ refreshAccess();+ expect(cb).toHaveBeenCalledTimes(1);+ off();+ refreshAccess();+ expect(cb).toHaveBeenCalledTimes(1);+ });++ it('refreshAccess busts the matrix cache', async () => {+ const { fetchAccess, refreshAccess } = await freshModule();+ accessState.body = matrix([eligible().access]);+ await fetchAccess();+ refreshAccess();+ await fetchAccess();+ expect(global.fetch).toHaveBeenCalledTimes(2);+ });++ it('a wallet:changed event busts the cache', async () => {+ const { fetchAccess } = await freshModule();+ accessState.body = matrix([eligible().access]);+ await fetchAccess();+ window.dispatchEvent(new CustomEvent('wallet:changed', { detail: { address: null } }));+ await fetchAccess();+ expect(global.fetch).toHaveBeenCalledTimes(2);+ });+});diff --git a/vercel.json b/vercel.jsonindex c29b3eaba..561fd7754 100644--- a/vercel.json+++ b/vercel.json@@ -164,7 +164,7 @@},"api/sniper/stream.js": {"includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",- "maxDuration": 90+ "maxDuration": 300},"api/sniper/history.js": {"maxDuration": 20