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 token gating, forge high payment, nav tier badge, access controls, and changelog updates
nirholas14f3b0b780f4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a5dabd6a2..e77bc933c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,12 @@Public history for [three.ws](https://three.ws), newest first. New pages come from `added` dates in data/pages.json; everything else is curated in data/changelog.json. Also available as [JSON](https://three.ws/changelog.json) and [RSS](https://three.ws/changelog.xml), live at [three.ws/changelog](https://three.ws/changelog).+## 2026-06-18++- **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]`+- **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-17- **Animation Gallery** (`/animations`) — Browse and preview public animations authored by the three.ws community. Apply any clip to your avatar in the Animation Studio.@@ -99,6 +105,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **The IBM demo's 3D agent is now a clean, bare avatar** — The 3D agent on the IBM × three.ws x402 demo page is now simply an avatar on a transparent background — the chat box, on-canvas controls, and name plate are gone. It still comes alive and reacts the moment your on-chain payment settles; it just no longer carries the extra interface around it. (`/ibm/x402-demo`) `[improvement]`- **The IBM page became a live showcase — five three.ws demos in one place** — The IBM page at three.ws/ibm/x402-demo is now a live showcase: five real, unmocked three.ws demos you can try in sequence. Pay a tenth of a cent over x402 and watch it settle on-chain; meet a 3D AI agent that pays for its own data and celebrates the moment your payment clears; then Forge (turn text into a 3D model), Play (a shared 3D world), and IRL (an agent in augmented reality) each run full-size right on the page, with a one-tap full-screen. Everything still loads from three.ws with no build step. (`/ibm/x402-demo`) `[feature]`- **The Oracle's proof pages — wins, backtest, and live activity — load again** — The conviction Oracle's evidence views had stopped responding: the Wins gallery, the accuracy Backtest, and the global Activity feed were all erroring instead of returning data, and the live activity feed failed on every request. The cause was in how those queries were assembled — optional filters (time window, tier, agent) weren't being stitched into the database query correctly, so the database rejected them. All three views now build their filters cleanly and return the Oracle's track record, hit-rate, and real-time agent actions as intended. (`/oracle`) `[fix]`+- **The Play world embed on the IBM demo is now transparent** — The embedded Coin Communities world on the IBM × three.ws x402 demo no longer sits in its own black box. Open it with a transparent background and the world composites straight onto the host page — the lobby and 3D scene render without the opaque dark fill behind them, so the embed blends into the demo instead of cutting a hard rectangle out of it. Regular Play at three.ws/play is unchanged. (`/ibm/x402-demo`) `[improvement]`- **The Pole Club now has a real soundtrack** — Walk into the Pole Club and music starts playing the moment you interact — a full-length club anthem that rolls straight into a second track and then loops back to the top, so the room is never silent. The soundtrack streams (no heavy decode) and runs through the same room acoustics as everything else: muffled like it's heard through the door while you're outside, then opening up to full clarity the instant you're admitted. A tipped dancer's track and the walk-in anthem duck the music underneath them, and the Audio toggle in the top bar silences it all. (`/club`) `[feature, improvement]`- **The sniper now runs as an always-on service — armed strategies fire in real time** — An armed sniper strategy now has a live engine behind it. The sniper runs as a dedicated always-on worker that holds the pump.fun launch feed open continuously and acts the moment a launch matches your rules — not on a slow timer. It starts in a safe simulate mode (real scoring, zero spend) and going live is a deliberate, gated step that needs a funded agent wallet, so nothing trades real money by accident. If the launch feed ever drops, the worker reconnects on its own and pages the operators, and a public health check at /api/sniper/status reports whether it's live, reconnecting, or down — so 'is the sniper actually working right now?' is always answerable. Every safety limit you set — daily budget, per-trade size, max open positions, mandatory stop-loss, price-impact cutoff — is enforced by the running service exactly as configured. (`/dashboard/sniper`) `[infra, feature]`- **Try x402 live — pay a tenth of a cent to call a real API from your own wallet** — There's now a live, self-contained x402 demo you can try in a browser. Pay $0.001 USDC from your own wallet — MetaMask on Base or Phantom on Solana — and call a real three.ws data API. The page reads the live HTTP 402 price the server quotes, runs the paid call once your wallet signs a gasless authorization, and shows the response next to an on-chain transaction receipt you can open on Basescan or Solscan. Nothing is mocked and there's no account or backend. The same eight-line embed it runs on — one script tag from three.ws plus any button carrying a data-x402-endpoint — is copy-pasteable into any site, so a developer can add a working pay-per-call paywall in minutes. Built with IBM as the public face of the partnership and designed to host cleanly on a strict-CSP enterprise page. (`/ibm/x402-demo`) `[feature, sdk]`diff --git a/api/_lib/forge-high-payment.js b/api/_lib/forge-high-payment.jsnew file mode 100644index 000000000..b4119bf9a--- /dev/null+++ b/api/_lib/forge-high-payment.js@@ -0,0 +1,157 @@+// Pay-per-use proof for Forge High — the consumption lever of Token Utility.+//+// A non-holder pays $THREE per High generation instead of holding. The payment+// runs through the existing token rail (api/_lib/token: quote → settle), which+// records a settled `consumption` row in token_payments bound to ref_type:'forge'+// and the client nonce as ref_id. The client then retries POST /api/forge for+// High with { payment_id, ref_id }, and this module is the server's authority on+// whether that proof satisfies the holder gate.+//+// Two-phase, so a generation that fails before it is dispatched never costs the+// user their payment:+// • assertForgePayment() — read-only validation at the gate: the payment is a+// settled `consumption` for forge.high, ref-bound, correctly priced, recent,+// and not already redeemed. Satisfies the gate; consumes nothing.+// • redeemForgePayment() — the atomic single-use claim, taken immediately+// before the provider dispatch. The PRIMARY KEY on payment_id makes it+// race-safe: exactly one caller can claim a given payment.+// • releaseForgePayment() — undo the claim when dispatch fails, so the settled+// payment is reusable on retry. Never called after a successful dispatch.+//+// Security model: forge has no login, so authorization rests on the (payment_id,+// ref_id) pair. payment_id is a server-minted UUID returned only to the settling+// client; ref_id is the client nonce recorded on the payment at quote time. An+// attacker would need both, and each pair buys exactly one generation.++import { sql } from './db.js';+import { priceForAction } from './pricing/catalog.js';++// How long after settlement a payment may be redeemed. Generous — a paid+// generation is normally redeemed seconds after settling, but a failed dispatch+// (released claim) may be retried later, and a holder may pay, get distracted,+// and come back. A settled payment older than this is treated as stale rather+// than letting an indefinitely-old proof unlock a generation.+const REDEMPTION_WINDOW_MS = 24 * 60 * 60 * 1000;++// Catalog action this proof unlocks, and the ref_type the client tags the quote+// with. Both are matched exactly so a `consumption` payment for some other action+// (voice clone, MCP-3D) can never be redeemed as a Forge High generation.+const FORGE_HIGH_ACTION = 'forge.high';+const FORGE_REF_TYPE = 'forge';+const CONSUMPTION_PURPOSE = 'consumption';++function payErr(message, status, code, extra = {}) {+ return Object.assign(new Error(message), { status, code, ...extra });+}++// Direct lookup of one settled payment by id — lighter than listPayments (which+// pulls in the on-chain settle/verify module) and all this path needs. numeric+// columns come back as strings from the driver; callers coerce what they compare.+async function lookupPayment(paymentId) {+ const [row] = await sql`+ select id, purpose, usd, ref_type, ref_id, confirmed_at, created_at+ from token_payments+ where id = ${paymentId}+ limit 1+ `;+ return row || null;+}++async function isRedeemed(paymentId) {+ const [row] = await sql`+ select payment_id from forge_high_redemptions where payment_id = ${paymentId} limit 1+ `;+ return Boolean(row);+}++/**+ * Validate that a settled $THREE payment proves entitlement to one Forge High+ * generation. Read-only: satisfies the gate without consuming the payment.+ *+ * @param {object} params+ * @param {string} params.paymentId token_payments.id returned by settle+ * @param {string} params.refId the client nonce the payment was bound to+ * @param {number} [params.discountBps] holder fee discount (bps) when a tier pass+ * also rides along, so the expected price+ * matches what the client was quoted+ * @returns {Promise<{ ok: true, payment: { id, usd, settledAt } }>}+ * @throws 402 payment_invalid | 409 payment_already_used | 400 bad_request+ */+export async function assertForgePayment({ paymentId, refId, discountBps = 0 }) {+ if (!paymentId || !refId) {+ throw payErr('payment_id and ref_id are required', 400, 'bad_request');+ }++ const payment = await lookupPayment(paymentId);+ if (!payment) {+ throw payErr('No settled $THREE payment found for this generation.', 402, 'payment_invalid');+ }+ if (payment.purpose !== CONSUMPTION_PURPOSE || payment.ref_type !== FORGE_REF_TYPE) {+ throw payErr('This payment is not a Forge generation payment.', 402, 'payment_invalid');+ }+ if (payment.ref_id !== refId) {+ throw payErr('This payment does not match this generation.', 402, 'payment_invalid');+ }++ // Price must equal the catalog price for forge.high (holder discount applied+ // when a pass rides along), so an underpaid `consumption` quote can't be+ // redeemed as a High generation.+ const expectedUsd = Number(priceForAction(FORGE_HIGH_ACTION, { discountBps }).usd);+ const paidUsd = Number(payment.usd);+ if (!(Math.abs(paidUsd - expectedUsd) < 0.005)) {+ throw payErr(+ `This payment ($${paidUsd.toFixed(2)}) does not cover a High generation ($${expectedUsd.toFixed(2)}).`,+ 402,+ 'payment_invalid',+ );+ }++ const settledAt = payment.confirmed_at || payment.created_at;+ const ageMs = Date.now() - new Date(settledAt).getTime();+ if (!(ageMs >= 0) || ageMs > REDEMPTION_WINDOW_MS) {+ throw payErr('This payment has expired — pay again to generate.', 402, 'payment_expired');+ }++ if (await isRedeemed(paymentId)) {+ throw payErr(+ 'This payment has already been used for a generation.',+ 409,+ 'payment_already_used',+ );+ }++ return { ok: true, payment: { id: payment.id, usd: paidUsd, settledAt } };+}++/**+ * Atomically claim a validated payment for one generation. Race-safe via the+ * payment_id PRIMARY KEY: a concurrent claim of the same payment inserts nothing+ * and returns { redeemed: false }. Call immediately before dispatch.+ *+ * @param {object} params+ * @param {string} params.paymentId+ * @param {string} params.refId+ * @param {string} [params.jobId] forge job/creation handle, when known+ * @param {string|Date} [params.settledAt]+ * @returns {Promise<{ redeemed: boolean }>}+ */+export async function redeemForgePayment({ paymentId, refId, jobId = null, settledAt = null }) {+ const rows = await sql`+ insert into forge_high_redemptions (payment_id, ref_id, job_id, settled_at)+ values (${paymentId}, ${refId}, ${jobId}, ${settledAt})+ on conflict (payment_id) do nothing+ returning payment_id+ `;+ return { redeemed: rows.length > 0 };+}++/**+ * Release a claim so the settled payment is reusable on retry. Called only when a+ * generation fails before a model is delivered — never after a successful+ * dispatch, so a delivered generation can never be repeated.+ * @param {object} params+ * @param {string} params.paymentId+ */+export async function releaseForgePayment({ paymentId }) {+ await sql`delete from forge_high_redemptions where payment_id = ${paymentId}`;+}diff --git a/api/_lib/migrations/2026-06-18-forge-high-redemptions.sql b/api/_lib/migrations/2026-06-18-forge-high-redemptions.sqlnew file mode 100644index 000000000..47b46737b--- /dev/null+++ b/api/_lib/migrations/2026-06-18-forge-high-redemptions.sql@@ -0,0 +1,40 @@+-- Migration: forge_high_redemptions — single-use ledger for pay-per-use Forge High.+-- Apply: node scripts/apply-migrations.mjs --apply --file 2026-06-18-forge-high-redemptions.sql+-- Idempotent.+--+-- Token Utility — the consumption lever. A non-holder can pay $THREE per High+-- generation instead of holding (api/_lib/token quote → settle records the+-- payment in token_payments). This table binds ONE settled `consumption` payment+-- to ONE High generation: the PRIMARY KEY on payment_id is the source of truth+-- for "one payment = one generation". A second redemption of the same payment_id+-- violates it and is surfaced as payment_already_used.+--+-- The row is written only when a generation is actually dispatched. If the+-- generation fails before dispatch (validation, moderation, rate limit) or the+-- provider call itself throws, the claim is released (row deleted) so the settled+-- payment stays reusable on retry — the user never loses a payment to a failure+-- that produced no model. Both timestamps are kept for audit/reconciliation.+--+-- No secrets are stored: payment_id references the public token_payments ledger.++begin;++create table if not exists forge_high_redemptions (+ -- The settled consumption payment redeemed (one row per payment, ever).+ payment_id uuid primary key references token_payments(id) on delete cascade,+ -- The client nonce the payment was quoted/settled against (token_payments.ref_id).+ -- Re-checked at redemption so possession of payment_id alone can't redeem.+ ref_id text not null,+ -- The forge job/creation the redemption funded (audit link; null for sync lanes+ -- that complete inside the request before a handle exists).+ job_id text,+ -- When the underlying payment settled on-chain (copied from token_payments) and+ -- when it was redeemed here — both kept so a redemption is fully reconcilable.+ settled_at timestamptz,+ redeemed_at timestamptz not null default now()+);++create index if not exists forge_high_redemptions_redeemed+ on forge_high_redemptions (redeemed_at desc);++commit;diff --git a/api/_lib/require-three.js b/api/_lib/require-three.jsnew file mode 100644index 000000000..d0aaa5237--- /dev/null+++ b/api/_lib/require-three.js@@ -0,0 +1,197 @@+// Server enforcement for the $THREE hold-to-access lever.+//+// The keystone that turns the `three-access.js` registry from a read into an+// actual gate: one helper any Vercel function calls to require a minimum holder+// tier for a feature, with a hold-OR-pay 402 when the caller falls short.+//+// Semantics mirror cors()/method() in http.js — on a BLOCKED request it writes+// the response itself and returns `{ ok: false }`; on an ALLOWED request it+// writes nothing and returns `{ ok: true, access, level, wallet }`:+//+// const gate = await requireFeatureAccess(req, res, 'forge.high', { body });+// if (!gate.ok) return; // 402 three_hold_required already sent+//+// Resolution is pass-first: a signed tier pass is pure-HMAC (no RPC), so a holder+// presenting one is never wrongly blocked during a price/RPC outage. It then+// falls back to the session user's on-chain tier, then anonymous Member. Every+// failure degrades to Member (a normal 402), never a 500.++import { json, error } from './http.js';+import { verifyTierPass, resolveUserTier } from './three-tier.js';+import { accessFromTierLevel, gatedFeature, requiredTierFor } from './three-access.js';+import { catalogEntry } from './pricing/catalog.js';+import { getSessionUser } from './auth.js';+import { TOKEN_MINT, publicConfig } from './token/config.js';++// The "how to acquire $THREE" block the 402 surfaces so a non-holder can act+// without leaving the error. Mint is the platform config; the swap/pump URLs are+// derived from the canonical mint. Symbol drops a leading "$" for clean URLs/copy.+function acquireBlock() {+ let symbol = 'THREE';+ try {+ symbol = String(publicConfig().symbol || 'THREE').replace(/^\$/, '') || 'THREE';+ } catch {+ symbol = 'THREE';+ }+ return {+ mint: TOKEN_MINT,+ symbol,+ swap_url: `https://jup.ag/swap/SOL-${TOKEN_MINT}`,+ pump_url: `https://pump.fun/coin/${TOKEN_MINT}`,+ };+}++// Resolve the caller's verified holder level for gating. Pass-first (pure HMAC,+// never depends on a live RPC), then the session user's on-chain tier, then+// anonymous Member (level 0). Never throws.+async function resolveCaller(req, res, body) {+ // 1. Signed tier pass — header or parsed body. Pure HMAC, no RPC.+ const token = req.headers?.['x-three-tier-pass'] || body?.tier_pass || null;+ if (token) {+ const payload = verifyTierPass(token);+ if (payload) {+ return {+ level: Math.max(0, Number(payload.level) || 0),+ wallet: payload.wallet || null,+ usd: null,+ source: 'pass',+ hasUser: false,+ hasWallet: Boolean(payload.wallet),+ };+ }+ }++ // 2. Session user → on-chain tier (degrades to Member on any failure).+ let user = null;+ try {+ user = await getSessionUser(req, res);+ } catch {+ user = null;+ }+ if (user?.wallet_address) {+ try {+ const { tier, usd } = await resolveUserTier(user);+ return {+ level: tier.level,+ wallet: user.wallet_address,+ usd: Math.round((Number(usd) || 0) * 100) / 100,+ source: 'onchain',+ hasUser: true,+ hasWallet: true,+ };+ } catch {+ return {+ level: 0,+ wallet: user.wallet_address,+ usd: 0,+ source: 'onchain',+ hasUser: true,+ hasWallet: true,+ };+ }+ }++ // 3. Anonymous / signed-in without a linked wallet.+ return {+ level: 0,+ wallet: null,+ usd: 0,+ source: 'anon',+ hasUser: Boolean(user),+ hasWallet: false,+ };+}++// access.reason upgraded with auth context: a presented (but short) pass is an+// insufficient-tier case; otherwise no user → sign in, user without a wallet →+// link a wallet, else under the threshold.+function reasonFor(caller) {+ if (caller.source === 'pass') return 'insufficient_tier';+ if (!caller.hasUser) return 'sign_in';+ if (!caller.hasWallet) return 'link_wallet';+ return 'insufficient_tier';+}++/**+ * Require a minimum $THREE holder tier for a feature.+ * @param {object} req+ * @param {object} res+ * @param {string} featureId a key of GATED_FEATURES (three-access.js)+ * @param {object} [opts]+ * @param {boolean} [opts.allowPayPerUse=true] include the pay-per-use action in+ * the 402 so a non-holder can pay once in $THREE instead of holding.+ * @param {object|null} [opts.body] a pre-parsed request body (so the helper can+ * read body.tier_pass without re-reading the stream).+ * @returns {Promise<{ ok: true, access, level, wallet } | { ok: false }>}+ */+export async function requireFeatureAccess(req, res, featureId, opts = {}) {+ const { allowPayPerUse = true, body = null } = opts;++ // A typo'd featureId is a clean 404, not a 500.+ try {+ gatedFeature(featureId);+ } catch (err) {+ error(res, 404, 'unknown_feature', err?.message || `unknown gated feature: ${featureId}`);+ return { ok: false };+ }++ const caller = await resolveCaller(req, res, body);+ const access = accessFromTierLevel(caller.level, featureId);++ if (access.eligible) {+ return { ok: true, access, level: caller.level, wallet: caller.wallet };+ }++ // Blocked → structured 402 with everything the UI needs to recover. Build the+ // `required` tier explicitly (level/id/label from the access view + the USD+ // threshold from the tier ladder) so the payload carries `min_usd` regardless+ // of the access registry's display shape.+ const requiredMinUsd = Number(requiredTierFor(featureId).minUsd) || 0;+ const required = {+ level: access.required.level,+ id: access.required.id,+ label: access.required.label,+ min_usd: requiredMinUsd,+ };+ // Only the on-chain path carries a USD value; the pass path proved the level+ // without a price (and a passing holder never reaches here anyway).+ const heldUsd = caller.source === 'onchain' ? Number(caller.usd) || 0 : 0;+ const usdToGo = Math.max(0, Math.round((requiredMinUsd - heldUsd) * 100) / 100);++ let payPerUse = null;+ if (allowPayPerUse && access.pay_per_use) {+ let usd = null;+ try {+ const p = Number(catalogEntry(access.pay_per_use).usd);+ usd = p >= 0 ? p : null;+ } catch {+ usd = null; // a missing/variable price never fails the 402+ }+ payPerUse = { action: access.pay_per_use, usd };+ }++ const held = {+ level: access.held.level,+ id: access.held.id,+ label: access.held.label,+ usd: heldUsd,+ };+ const message = payPerUse+ ? `${access.label} requires holding $THREE (${required.label}+) — or pay per use.`+ : `${access.label} requires holding $THREE (${required.label}+).`;++ json(res, 402, {+ error: 'three_hold_required',+ message,+ feature: featureId,+ label: access.label,+ why: access.why,+ reason: reasonFor(caller),+ held,+ required,+ usd_to_go: usdToGo,+ acquire: acquireBlock(),+ pay_per_use: payPerUse,+ });+ return { ok: false };+}diff --git a/api/_lib/three-access.js b/api/_lib/three-access.jsnew file mode 100644index 000000000..15e291781--- /dev/null+++ b/api/_lib/three-access.js@@ -0,0 +1,188 @@+// $THREE holder access registry — the hold-to-access lever's source of truth.+//+// A small, pure registry mapping a featureId → the minimum holder tier required+// to use it, plus holder-readable copy. It generalizes the per-skill $THREE gate+// (three-gate.js) and the per-coin world gate into one platform-wide table so the+// access endpoint, the gated endpoints, and the UI all agree on what each feature+// costs in *tier* terms.+//+// Two resolvers, by what the caller already knows:+// • resolveAccess(user, featureId) — reads the user's on-chain tier (async).+// • accessFromTierLevel(level, feature) — a pure level check for callers that+// already hold a verified level (e.g. a signed tier pass), no I/O, no latency.+//+// Enforcement note: the authoritative entitlement carrier for *gating* a request+// is the signed tier pass (three-tier.js → verifyTierPass), which is pure-HMAC+// and never depends on a live RPC. resolveAccess() is for display/affordances and+// degrades a holder to Member on a price/RPC hiccup — so a transient outage can+// under-state a holder in the UI, but the pass path still lets them through.++import { TIERS, resolveUserTier } from './three-tier.js';++/** The TIERS entry for a level, clamped to a real tier (Member floor). */+function tierByLevel(level) {+ const n = Math.max(0, Number(level) || 0);+ let resolved = TIERS[0];+ for (const t of TIERS) if (t.level <= n) resolved = t;+ return resolved;+}++// featureId → { minLevel, enforced, label, why, payPerUse }.+// minLevel — the TIERS level a wallet must reach (1 = Bronze, …, 4 = Genesis).+// enforced — true when the gate is WIRED and live in the product right now+// (a request for it is actually checked); false when the perk is+// registered/planned but not yet enforced anywhere. The UI uses this+// to mark a feature "Live" vs "Planned" so /three only ever promises+// what it actually delivers — never an aspirational, unwired claim.+// label — holder-readable feature name.+// why — one line on why holding gates it (real cost / scarcity / status).+// payPerUse — catalog action id a non-holder may pay instead, or null when the+// feature is hold-only. The price is attached by the caller from the+// pricing catalog so this module stays dependency-free.+//+// Enforced today: only `forge.high` — the High-tier Forge gate in api/forge.js. The+// rest are planned. As each gate ships, flip its `enforced` to true (and add a test);+// nothing else changes — the access endpoint and /three pick it up automatically.+export const GATED_FEATURES = Object.freeze({+ 'forge.high': Object.freeze({+ minLevel: 1,+ enforced: true, // gated in api/forge.js (High + platform backend) — see forge-high-gate.test.js+ label: 'High-quality generation (200k poly + PBR)',+ why: 'The High tier spends real GPU/vendor budget — holders fund it by holding, not draining.',+ payPerUse: 'forge.high',+ }),+ 'worlds.private': Object.freeze({+ minLevel: 2,+ enforced: false,+ label: 'Private, invite-only worlds',+ why: 'A persistent private space is a held perk, not a per-call cost.',+ payPerUse: null,+ }),+ 'worlds.branded': Object.freeze({+ minLevel: 3,+ enforced: false,+ label: 'Branded worlds + custom environments',+ why: 'Custom-branded environments are a Gold-tier status perk.',+ payPerUse: null,+ }),+ 'mcp.priority': Object.freeze({+ minLevel: 2,+ enforced: false,+ label: 'Priority MCP routing',+ why: 'Holders skip the shared queue on the MCP compute lanes.',+ payPerUse: null,+ }),+ 'drops.early': Object.freeze({+ minLevel: 3,+ enforced: false,+ label: 'Early access to drops',+ why: 'Early windows on scarce drops reward the largest holders.',+ payPerUse: null,+ }),+ 'names.first_dibs': Object.freeze({+ minLevel: 4,+ enforced: false,+ label: 'First dibs on rare *.threews.sol names',+ why: 'Genesis holders get the first window on the rarest names.',+ payPerUse: 'name.auction',+ }),+});++/** Look up a gated feature. Throws a typed 404 for an unknown id. */+export function gatedFeature(featureId) {+ const f = GATED_FEATURES[featureId];+ if (!f) {+ const err = new Error(`unknown gated feature: ${featureId}`);+ err.status = 404;+ err.code = 'unknown_feature';+ throw err;+ }+ return f;+}++/** The minimum TIERS entry required for a feature. */+export function requiredTierFor(featureId) {+ return tierByLevel(gatedFeature(featureId).minLevel);+}++/** Every registered gated-feature id. */+export function listGatedFeatures() {+ return Object.keys(GATED_FEATURES);+}++function publicTier(t) {+ // min_usd lets a client render a "held → required" progress bar and the 402+ // hold-or-pay path (require-three.js) compute usd_to_go without re-deriving the+ // ladder thresholds.+ return { level: t.level, id: t.id, label: t.label, min_usd: t.minUsd };+}++function reasonFor({ eligible, user, hasWallet }) {+ if (eligible) return 'eligible';+ if (!user) return 'sign_in';+ if (!hasWallet) return 'link_wallet';+ return 'insufficient_tier';+}++/**+ * Pure tier-level eligibility check — for callers that already hold a verified+ * level (e.g. a presented tier pass). No network, no DB.+ * @param {number} level the holder's verified tier level (0 = Member)+ * @param {string} featureId+ */+export function accessFromTierLevel(level, featureId) {+ const f = gatedFeature(featureId);+ const required = tierByLevel(f.minLevel);+ const held = tierByLevel(level);+ const eligible = held.level >= f.minLevel;+ return {+ feature: featureId,+ label: f.label,+ why: f.why,+ enforced: f.enforced,+ eligible,+ required: publicTier(required),+ held: publicTier(held),+ pay_per_use: f.payPerUse,+ reason: eligible ? 'eligible' : 'insufficient_tier',+ };+}++/**+ * Resolve a session user's access to a gated feature from their on-chain $THREE+ * holdings. Never throws — degrades to the Member floor on any failure.+ * @param {object|null} user session user ({ wallet_address, ... }) or null+ * @param {string} featureId+ * @returns {Promise<{ feature, label, why, enforced, eligible, required, held, pay_per_use, reason }>}+ */+export async function resolveAccess(user, featureId) {+ const f = gatedFeature(featureId);+ const required = tierByLevel(f.minLevel);+ const hasWallet = Boolean(user?.wallet_address);++ let held = TIERS[0];+ let usd = 0;+ if (hasWallet) {+ try {+ const r = await resolveUserTier(user);+ held = r.tier;+ usd = r.usd;+ } catch {+ held = TIERS[0];+ usd = 0;+ }+ }++ const eligible = held.level >= f.minLevel;+ return {+ feature: featureId,+ label: f.label,+ why: f.why,+ enforced: f.enforced,+ eligible,+ required: publicTier(required),+ held: { ...publicTier(held), usd: Math.round((Number(usd) || 0) * 100) / 100 },+ pay_per_use: f.payPerUse,+ reason: reasonFor({ eligible, user, hasWallet }),+ };+}diff --git a/api/forge.js b/api/forge.jsindex 9ce865630..694396a85 100644--- a/api/forge.js+++ b/api/forge.js@@ -62,6 +62,13 @@ import {import { constantTimeEquals } from './_lib/crypto.js';import { env as _env } from './_lib/env.js';import { verifyTierPass, TIERS } from './_lib/three-tier.js';+import { requireFeatureAccess } from './_lib/require-three.js';+import { priceForAction } from './_lib/pricing/catalog.js';+import {+ assertForgePayment,+ redeemForgePayment,+ releaseForgePayment,+} from './_lib/forge-high-payment.js';// Holder perk (Lever 2): a presented, verified $THREE tier pass lifts the free// generation ceiling by that tier's multiplier. The pass is pure-HMAC verifiable@@ -398,6 +405,12 @@ async function startJob(req, res) {// last-resort fallback when Replicate is down).let nvidiaTried = false;+ // Pay-per-use (Token Utility — consumption lever): set to { paymentId, refId,+ // settledAt, redeemed? } once a non-holder's settled $THREE payment is accepted+ // in lieu of holding. The payment is validated at the gate, claimed atomically+ // just before dispatch, and released if the generation fails before delivery.+ let paidHigh = null;+// The geometry path is BYOK-only — no free model does native text→geometry.// So when the caller didn't explicitly pick a backend and has no key for the// default geometry engine, transparently serve the free image lane (NVIDIA@@ -413,6 +426,50 @@ async function startJob(req, res) {}}+ // $THREE hold-to-access gate (Token Utility v1) — the High tier (200k poly ++ // PBR) spends real GPU/vendor budget on a PLATFORM-keyed backend, so it's the+ // first real $THREE-gated feature: reserved for holders (Bronze+, $25 hold) or+ // a presented tier pass, otherwise a hold-or-pay 402. BYOK backends are exempt+ // (the caller pays their own vendor key — key-gated, not hold-gated). Draft and+ // Standard are never gated, and internal cron seed jobs bypass it entirely.+ // requireFeatureAccess writes the 402 (three_hold_required) itself and returns+ // { ok:false }; on a holder it writes nothing and lets the job proceed.+ if (tier.id === 'high' && BACKENDS[backendId]?.byok === false && !isInternalSeedRequest(req)) {+ // Consumption lever: a non-holder may present a settled $THREE payment+ // (payment_id + the client nonce it was bound to) to satisfy the gate per+ // generation instead of holding. Validate it read-only here; the single-use+ // claim is taken atomically just before dispatch (see paidHigh below). A+ // missing/invalid proof falls through to the normal hold-or-pay 402.+ const paymentId = typeof body?.payment_id === 'string' ? body.payment_id.trim() : '';+ const refId = typeof body?.ref_id === 'string' ? body.ref_id.trim() : '';+ if (paymentId && refId) {+ try {+ const proof = await assertForgePayment({ paymentId, refId });+ paidHigh = { paymentId, refId, settledAt: proof.payment.settledAt };+ } catch (err) {+ // A presented-but-invalid proof is a designed, recoverable state: the+ // client can pay again (pay_per_use) or hold. Carry the price so the UI+ // can re-offer Pay without another round-trip.+ let usd = null;+ try {+ usd = Number(priceForAction('forge.high').usd) || null;+ } catch {+ usd = null;+ }+ return json(res, err.status || 402, {+ error: err.code || 'payment_invalid',+ feature: 'forge.high',+ get_three_url: '/three',+ pay_per_use: usd ? { action: 'forge.high', usd } : null,+ message: err.message || 'That $THREE payment could not be verified.',+ });+ }+ } else {+ const gate = await requireFeatureAccess(req, res, 'forge.high', { body });+ if (!gate.ok) return; // 402 three_hold_required already sent+ }+ }+const isFreeLane = BACKENDS[backendId]?.free === true;if (!isInternalSeedRequest(req)) {const rl = isFreeLane@@ -519,6 +576,30 @@ async function startJob(req, res) {}try {+ // Pay-per-use: claim the settled $THREE payment now — immediately before any+ // provider work, so every cheap failure above (rate limit, moderation, bad+ // input) left the payment reusable. The atomic claim (payment_id PRIMARY KEY)+ // is the single-use source of truth: a concurrent retry of the same payment+ // loses the race and is told the payment is already used. If anything below+ // fails before a model is delivered, the finally releases the claim.+ if (paidHigh && !paidHigh.redeemed) {+ const claim = await redeemForgePayment({+ paymentId: paidHigh.paymentId,+ refId: paidHigh.refId,+ settledAt: paidHigh.settledAt,+ });+ if (!claim.redeemed) {+ return json(res, 409, {+ error: 'payment_already_used',+ feature: 'forge.high',+ get_three_url: '/three',+ message:+ 'This payment has already been used for a generation. Pay again to generate another High model.',+ });+ }+ paidHigh.redeemed = true;+ }+// ── Sketch path (TripoSG-scribble, self-host) ───────────────────────────// The drawing + prompt go straight to the TripoSG worker's scribble// pipeline. Geometry only — no synthesized intermediate view, no textures;@@ -977,6 +1058,14 @@ async function startJob(req, res) {error: 'generation_failed',message: err?.message || 'The generator could not start this job.',});+ } finally {+ // A claimed pay-per-use payment that did NOT deliver a model — any non-2xx+ // exit (validation 4xx, unconfigured 5xx, provider failure) — is released so+ // the settled $THREE payment stays reusable on retry. A successful job (200)+ // keeps the claim, so one payment can never buy a second generation.+ if (paidHigh?.redeemed && res.statusCode >= 400) {+ await releaseForgePayment({ paymentId: paidHigh.paymentId }).catch(() => {});+ }}}diff --git a/api/three/[action].js b/api/three/[action].jsindex 9a8c27335..5131d17bc 100644--- a/api/three/[action].js+++ b/api/three/[action].js@@ -22,9 +22,19 @@ import { getSessionUser } from '../_lib/auth.js';import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { parse } from '../_lib/validate.js';-import { publicCatalog } from '../_lib/pricing/catalog.js';+import { publicCatalog, catalogEntry } from '../_lib/pricing/catalog.js';import { requireThreePayment } from '../_lib/pricing/charge-three.js';-import { holderDiscountBps, resolveUserTier, signTierPass, TIERS } from '../_lib/three-tier.js';+import {+ holderDiscountBps,+ resolveUserTier,+ signTierPass,+ tierForUsd,+ nextTier,+ holderUsd,+ TIERS,+} from '../_lib/three-tier.js';+import { accessFromTierLevel, listGatedFeatures } from '../_lib/three-access.js';+import { verifySiwsSignature } from '../_lib/siws.js';import { creatorEarnings, economyStats, listRewardsDistributions } from '../_lib/token/index.js';import { priceName, isValidLabel, RARITY_TIERS } from '../_lib/pricing/name-rarity.js';import { quoteTokenForUsd } from '../_lib/token/price.js';@@ -48,6 +58,70 @@ const solscan = (addr) => (addr ? `https://solscan.io/account/${addr}` : null);const SOLANA_ADDRESS = z.string().regex(/^[1-9A-HJ-NP-Za-km-z]{32,44}$/, 'invalid Solana address');+// Build the full /tier response from a resolved tier. Shared by the authed+// (session user) path and the public (?wallet=) path so both return one shape.+function tierPayload({ tier, usd, amount, priceUsd, next, wallet = null, source }) {+ return {+ tier: {+ level: tier.level,+ id: tier.id,+ label: tier.label,+ discount_bps: tier.discountBps,+ perks: tier.perks,+ },+ held_usd: usd,+ held_amount: amount,+ price_usd: priceUsd,+ ...(wallet ? { wallet } : {}),+ ...(source ? { source } : {}),+ next: next+ ? { id: next.id, label: next.label, min_usd: next.minUsd, usd_to_go: Math.max(0, next.minUsd - usd) }+ : null,+ // The full ladder so the UI can render thresholds and what each tier unlocks.+ ladder: TIERS.map((t) => ({+ level: t.level,+ id: t.id,+ label: t.label,+ min_usd: t.minUsd,+ discount_bps: t.discountBps,+ rate_multiplier: t.rateMultiplier,+ perks: t.perks,+ })),+ };+}++// Resolve a tier publicly from a raw wallet's on-chain $THREE (no auth). Never+// throws — holderUsd() degrades to zero held → Member tier on any RPC/price hiccup.+async function resolveWalletTier(wallet) {+ const { usd, amount, priceUsd } = await holderUsd(wallet);+ const tier = tierForUsd(usd);+ return { tier, usd, amount, priceUsd, next: nextTier(tier) };+}++// The canonical message a wallet signs to mint a tier pass without an account.+// Kept byte-identical to the client builder (src/three/holder.js). We validate+// it server-side: it must name our domain, bind to the wallet, and be fresh —+// which blocks replay of an old capture and minting a pass for someone else's bag.+const TIER_PASS_MESSAGE_MAX = 1000;+const TIER_PASS_FRESH_MS = 5 * 60 * 1000; // accept signatures issued in the last 5 min+const TIER_PASS_SKEW_MS = 60 * 1000; // tolerate up to 60s of client clock skew ahead++/** Returns an error code string when the signed message is unacceptable, else null. */+function checkTierPassMessage(message, wallet) {+ if (typeof message !== 'string' || message.length === 0 || message.length > TIER_PASS_MESSAGE_MAX) {+ return 'malformed_message';+ }+ if (!message.includes('three.ws')) return 'malformed_message';+ if (!message.includes(wallet)) return 'wallet_mismatch';+ const m = /Issued At:\s*([^\n]+)/.exec(message);+ if (!m) return 'malformed_message';+ const ts = Date.parse(m[1].trim());+ if (!Number.isFinite(ts)) return 'malformed_message';+ const age = Date.now() - ts;+ if (age > TIER_PASS_FRESH_MS || age < -TIER_PASS_SKEW_MS) return 'stale_message';+ return null;+}+// ── GET /api/three/catalog ─────────────────────────────────────────────────────async function handleCatalog(req, res) {@@ -120,29 +194,29 @@ async function handleCharge(req, res) {async function handleTier(req, res) {if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;if (!method(req, res, ['GET'])) return;++ // Public path: ?wallet=<addr> resolves a connected wallet's tier with no+ // account — the common case (a visitor connects Phantom but isn't signed in).+ const walletParam = (new URL(req.url, 'http://x').searchParams.get('wallet') || '').trim();+ if (walletParam) {+ const valid = SOLANA_ADDRESS.safeParse(walletParam);+ if (!valid.success) {+ return error(res, 400, 'invalid_wallet', 'wallet must be a valid Solana address');+ }+ const rl = await limits.tokenPriceIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);+ const resolved = await resolveWalletTier(walletParam);+ return json(res, 200, tierPayload({ ...resolved, wallet: walletParam, source: 'wallet' }), {+ 'cache-control': 'public, max-age=20, s-maxage=20, stale-while-revalidate=60',+ });+ }++ // Authed path: the signed-in user's linked wallet (also carries the discount).const user = await getSessionUser(req, res);- if (!user) return error(res, 401, 'unauthorized', 'sign in required');+ if (!user) return error(res, 401, 'unauthorized', 'sign in or pass ?wallet= to read a tier');- const { tier, usd, amount, priceUsd, next } = await resolveUserTier(user);- return json(res, 200, {- tier: { level: tier.level, id: tier.id, label: tier.label, discount_bps: tier.discountBps, perks: tier.perks },- held_usd: usd,- held_amount: amount,- price_usd: priceUsd,- next: next- ? { id: next.id, label: next.label, min_usd: next.minUsd, usd_to_go: Math.max(0, next.minUsd - usd) }- : null,- // The full ladder so the UI can render thresholds and what each tier unlocks.- ladder: TIERS.map((t) => ({- level: t.level,- id: t.id,- label: t.label,- min_usd: t.minUsd,- discount_bps: t.discountBps,- rate_multiplier: t.rateMultiplier,- perks: t.perks,- })),- });+ const resolved = await resolveUserTier(user);+ return json(res, 200, tierPayload({ ...resolved, source: 'session' }));}// ── POST /api/three/tier-pass ─────────────────────────────────────────────────────@@ -150,8 +224,54 @@ async function handleTier(req, res) {async function handleTierPass(req, res) {if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;if (!method(req, res, ['POST'])) return;++ const body = (await readJson(req).catch(() => ({}))) || {};++ // ── Signature path (no account): a connected wallet proves ownership by signing+ // a fresh, domain-bound message. The tier is resolved from real on-chain holdings+ // of that wallet, so the pass can only ever reflect what the wallet actually holds.+ if (body.wallet || body.signature || body.message) {+ const valid = SOLANA_ADDRESS.safeParse(String(body.wallet || ''));+ if (!valid.success) {+ return error(res, 400, 'invalid_wallet', 'wallet must be a valid Solana address');+ }+ const wallet = valid.data;+ // Key the limiter by wallet so one wallet can't grind passes; tokenQuote is the+ // existing "issue a signed artifact" bucket.+ const rl = await limits.tokenQuote(wallet);+ if (!rl.success) return rateLimited(res, rl);++ const msgErr = checkTierPassMessage(body.message, wallet);+ if (msgErr) {+ return error(+ res,+ 401,+ msgErr,+ msgErr === 'stale_message'+ ? 'signed message is expired — sign again'+ : 'signed message is malformed or not bound to this wallet',+ );+ }+ let ok = false;+ try {+ ok = verifySiwsSignature(String(body.message), String(body.signature || ''), wallet);+ } catch {+ ok = false;+ }+ if (!ok) return error(res, 401, 'bad_signature', 'signature does not match the wallet');++ const { tier, usd } = await resolveWalletTier(wallet);+ const pass = signTierPass({ wallet, level: tier.level, tierId: tier.id, usd });+ return json(res, 201, {+ pass,+ tier: { level: tier.level, id: tier.id, label: tier.label },+ held_usd: usd,+ });+ }++ // ── Session path: a signed-in user with a linked wallet.const user = await getSessionUser(req, res);- if (!user) return error(res, 401, 'unauthorized', 'sign in required');+ if (!user) return error(res, 401, 'unauthorized', 'sign in, or POST { wallet, message, signature }');if (!user.wallet_address) {return error(res, 403, 'wallet_required', 'link a Solana wallet to mint a tier pass');}@@ -275,6 +395,107 @@ async function handleStats(req, res) {});}+// ── GET /api/three/access ──────────────────────────────────────────────────────+// The hold-to-access read the UI consumes. Resolves the caller's $THREE tier ONCE+// and answers, per gated feature, whether they're entitled — plus the exact reason+// (sign in / link wallet / hold more) and the pay-per-use price when a non-holder+// can pay instead. Auth is OPTIONAL: anonymous callers get the Member view so the+// page can render the locked state and a "Get $THREE" path without forcing sign-in.++async function handleAccess(req, res) {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;+ const rl = await limits.tokenPriceIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const url = new URL(req.url, 'http://x');+ const walletParam = (url.searchParams.get('wallet') || '').trim();+ if (walletParam && !SOLANA_ADDRESS.safeParse(walletParam).success) {+ return error(res, 400, 'invalid_wallet', 'wallet must be a valid Solana address');+ }++ const user = await getSessionUser(req, res);+ // Identity precedence: an explicit ?wallet= (a connected, account-less visitor)+ // wins over the session's linked wallet so the page reflects the wallet in hand.+ const walletMode = Boolean(walletParam);+ const hasWallet = walletMode || Boolean(user?.wallet_address);++ // One tier resolution for the whole request; every feature check below is then a+ // pure level comparison (no extra on-chain reads). Degrades to Member on failure.+ let tier = TIERS[0];+ let usd = 0;+ if (hasWallet) {+ try {+ const r = walletMode ? await resolveWalletTier(walletParam) : await resolveUserTier(user);+ tier = r.tier;+ usd = r.usd;+ } catch {+ tier = TIERS[0];+ usd = 0;+ }+ }+ const heldUsd = Math.round((Number(usd) || 0) * 100) / 100;++ // Attach the catalog price to a pay-per-use action (null for variable-price ones).+ const payInfo = (actionId) => {+ if (!actionId) return null;+ let priceUsd = null;+ try {+ priceUsd = catalogEntry(actionId).usd ?? null;+ } catch {+ priceUsd = null;+ }+ return { action: actionId, usd: priceUsd };+ };+ // Turn a pure level-check into the full UI payload: real held USD + the precise+ // reason for the lock (the pure check only knows eligible/insufficient).+ const decorate = (a) => ({+ ...a,+ held: { ...a.held, usd: heldUsd },+ // In wallet mode the wallet is in hand, so a lock is always "hold more" —+ // never "sign in" / "link a wallet" (those are session-only prompts).+ reason: a.eligible+ ? 'eligible'+ : walletMode+ ? 'insufficient_tier'+ : !user+ ? 'sign_in'+ : !hasWallet+ ? 'link_wallet'+ : 'insufficient_tier',+ pay_per_use: payInfo(a.pay_per_use),+ });++ const tierSummary = { level: tier.level, id: tier.id, label: tier.label, held_usd: heldUsd };+ const feature = url.searchParams.get('feature');++ if (feature) {+ let access;+ try {+ access = accessFromTierLevel(tier.level, feature);+ } catch (e) {+ if (e.code === 'unknown_feature') {+ return error(res, 404, 'unknown_feature', `unknown gated feature: ${feature}`);+ }+ throw e;+ }+ return json(res, 200, {+ signed_in: Boolean(user),+ wallet_linked: hasWallet,+ tier: tierSummary,+ access: decorate(access),+ });+ }++ const features = listGatedFeatures().map((id) => decorate(accessFromTierLevel(tier.level, id)));+ return json(res, 200, {+ signed_in: Boolean(user),+ wallet_linked: hasWallet,+ tier: tierSummary,+ features,+ });+}+// ── dispatcher ────────────────────────────────────────────────────────────────────const DISPATCH = {@@ -282,6 +503,7 @@ const DISPATCH = {charge: handleCharge,tier: handleTier,'tier-pass': handleTierPass,+ access: handleAccess,earnings: handleEarnings,'name-quote': handleNameQuote,stats: handleStats,diff --git a/data/changelog.json b/data/changelog.jsonindex 36dc0995c..e2d34d67e 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,43 @@{"$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": "Pay $THREE per High generation — no holding required",+ "summary": "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.",+ "tags": [+ "feature"+ ],+ "link": "/forge"+ },+ {+ "date": "2026-06-18",+ "title": "Your $THREE holder tier now shows across the site",+ "summary": "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.",+ "tags": [+ "feature",+ "improvement"+ ],+ "link": "/forge"+ },+ {+ "date": "2026-06-18",+ "title": "Holding $THREE now unlocks a premium feature",+ "summary": "$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.",+ "tags": [+ "feature"+ ],+ "link": "/three"+ },+ {+ "date": "2026-06-17",+ "title": "The Play world embed on the IBM demo is now transparent",+ "summary": "The embedded Coin Communities world on the IBM × three.ws x402 demo no longer sits in its own black box. Open it with a transparent background and the world composites straight onto the host page — the lobby and 3D scene render without the opaque dark fill behind them, so the embed blends into the demo instead of cutting a hard rectangle out of it. Regular Play at three.ws/play is unchanged.",+ "tags": [+ "improvement"+ ],+ "link": "/ibm/x402-demo"+ },{"date": "2026-06-17","title": "The IBM demo's 3D agent is now a clean, bare avatar",diff --git a/pages/animations.html b/pages/animations.htmlindex 0b9aaccb9..2abdb11cd 100644--- a/pages/animations.html+++ b/pages/animations.html@@ -413,7 +413,9 @@.ag-hero h1 { font-size: 28px; }}</style>- </head>++ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Animation Gallery","description":"Browse and preview public animations authored by the three.ws community. Apply any clip to your avatar in the Animation Studio.","url":"https://three.ws/animations","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>+</head><body class="ag-page"><header><div id="nav-container"></div>diff --git a/pages/collection.html b/pages/collection.htmlindex 218a178f1..c49a112a5 100644--- a/pages/collection.html+++ b/pages/collection.html@@ -113,7 +113,22 @@.col-stats{gap:20px;flex-wrap:wrap;}}</style>- </head>++ <link rel="canonical" href="https://three.ws/collection">+ <meta property="og:type" content="website">+ <meta property="og:site_name" content="three.ws">+ <meta property="og:title" content="My Collection · three.ws">+ <meta property="og:description" content="View all the skills and subscriptions you've unlocked on three.ws.">+ <meta property="og:url" content="https://three.ws/collection">+ <meta property="og:image" content="https://three.ws/og-image.png">+ <meta property="og:image:width" content="1200">+ <meta property="og:image:height" content="630">+ <meta name="twitter:card" content="summary_large_image">+ <meta name="twitter:title" content="My Collection · three.ws">+ <meta name="twitter:description" content="View all the skills and subscriptions you've unlocked on three.ws.">+ <meta name="twitter:image" content="https://three.ws/og-image.png">+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"My Collection","description":"View all the skills and subscriptions you've unlocked on three.ws.","url":"https://three.ws/collection","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>+</head><body><header><div id="nav-container"></div></header><script src="/nav.js"></script>diff --git a/pages/forge.html b/pages/forge.htmlindex 811521bea..d1466dc88 100644--- a/pages/forge.html+++ b/pages/forge.html@@ -259,6 +259,17 @@0 0 0 4px var(--accent-soft),0 8px 28px -8px rgba(255, 255, 255, 0.15);}+ /* Gated (High needs $THREE): readable "locked perk" state, not a faded+ dead button — the lock panel above explains, this stays legible. */+ #generate.is-gated,+ #generate.is-gated:hover {+ opacity: 1;+ cursor: not-allowed;+ background: var(--surface-2);+ color: var(--muted);+ border: 1px solid rgba(245, 196, 81, 0.4);+ box-shadow: none;+ }.gen-kbd {font-family: var(--font-mono);font-size: 0.72em;@@ -440,6 +451,96 @@}/* forge.js hides the #aspect control itself when the mode makes itirrelevant — collapse the labeled row with it, no orphan label. */+ /* High is a $THREE holder perk — a small lock pill on the button makes+ the premium nature legible before the user selects it (a quality+ signal, not a nag). Gold while locked, green once the viewer holds+ $THREE. forge.js (applyHighAffordances) flips data-state from the+ live /api/three/access read. */+ #tier button[data-tier='high'] {+ display: inline-flex;+ align-items: center;+ gap: 0.4rem;+ }+ .tier-lock {+ display: inline-flex;+ align-items: center;+ gap: 0.22rem;+ font-family: var(--font-mono);+ font-size: 0.68em;+ line-height: 1;+ padding: 0.18em 0.42em;+ border-radius: 999px;+ color: #f0d488;+ background: rgba(245, 196, 81, 0.12);+ border: 1px solid rgba(245, 196, 81, 0.32);+ transition:+ color 0.15s,+ background 0.15s,+ border-color 0.15s;+ }+ .tier-lock-ico {+ width: 0.92em;+ height: 0.92em;+ }+ .tier-lock[data-state='unlocked'] {+ color: #6ee7a8;+ background: rgba(110, 231, 168, 0.13);+ border-color: rgba(110, 231, 168, 0.34);+ }+ #tier button[data-tier='high']:hover .tier-lock,+ #tier button[data-tier='high']:focus-visible .tier-lock {+ border-color: rgba(245, 196, 81, 0.55);+ }+ #tier button[data-tier='high']:hover .tier-lock[data-state='unlocked'],+ #tier button[data-tier='high']:focus-visible .tier-lock[data-state='unlocked'] {+ border-color: rgba(110, 231, 168, 0.55);+ }+ #tier button[data-tier='high'][aria-pressed='true'] .tier-lock {+ background: rgba(245, 196, 81, 0.2);+ }+ #tier button[data-tier='high'][aria-pressed='true'] .tier-lock[data-state='unlocked'] {+ background: rgba(110, 231, 168, 0.2);+ }+ /* Inline holder note under the Quality row — links to /three. forge.js+ hides it while High is selected (the full in-place lock panel takes+ over) and swaps the copy once the viewer is a holder. */+ .fq-holder-note {+ display: flex;+ align-items: center;+ gap: 0.4rem;+ margin: 0.1rem 0 0;+ font-size: var(--text-xs);+ line-height: 1.5;+ color: var(--ink-dim);+ }+ .fq-holder-note a {+ color: var(--accent);+ text-decoration: none;+ font-weight: 500;+ white-space: nowrap;+ transition: opacity 0.15s;+ }+ .fq-holder-note a:hover {+ text-decoration: underline;+ opacity: 0.85;+ }+ .fq-holder-note a:focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: 2px;+ border-radius: 2px;+ }+ .fq-holder-note .fq-holder-ico {+ color: #f5c451;+ font-size: 0.9em;+ }+ .fq-holder-note[data-state='unlocked'] .fq-holder-ico {+ color: #6ee7a8;+ }+ @media (prefers-reduced-motion: reduce) {+ .tier-lock {+ transition: none;+ }+ }.fq-row:has(> .aspect.is-hidden) {display: none;}@@ -2463,11 +2564,25 @@<button type="button" data-tier="standard" aria-pressed="true">Standard</button>- <button type="button" data-tier="high" aria-pressed="false">- High+ <button+ type="button"+ data-tier="high"+ data-access="locked"+ aria-pressed="false"+ aria-label="High quality — $THREE holder feature"+ >+ <span class="tier-name">High</span>+ <span class="tier-lock" data-state="locked" title="High quality is a $THREE holder feature">+ <svg class="tier-lock-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="5" y="11" width="14" height="9" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></svg>+ <span class="tier-lock-txt">$THREE</span>+ </span></button></div></div>+ <p class="fq-holder-note" id="fq-holder-note" data-state="locked">+ <span class="fq-holder-ico" aria-hidden="true">◆</span> High quality is a+ <a href="/three">$THREE holder</a> feature — hold to unlock, or pay per generation.+ </p><div class="fq-row"><span class="fq-label" id="engine-label">Engine</span><divdiff --git a/pages/irl-privacy.html b/pages/irl-privacy.htmlindex 66910d2be..9c1a542ea 100644--- a/pages/irl-privacy.html+++ b/pages/irl-privacy.html@@ -236,6 +236,8 @@.ip-card, .ip-card:hover, .ip-btn, .ip-btn:active { transition: none; transform: none; }}</style>++ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"How location works on IRL","description":"Placed agents are private by location: they appear only to people physically standing near them, never on a map or a list. What's shared, what isn't, and how your camera, motion, and location are used.","url":"https://three.ws/irl-privacy","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script></head><body><div id="nav-container"></div>diff --git a/pages/marketplace-analytics.html b/pages/marketplace-analytics.htmlindex 919edeb90..0cc6bf835 100644--- a/pages/marketplace-analytics.html+++ b/pages/marketplace-analytics.html@@ -87,7 +87,22 @@.stats-grid{grid-template-columns:1fr;}}</style>- </head>++ <link rel="canonical" href="https://three.ws/marketplace/analytics">+ <meta property="og:type" content="website">+ <meta property="og:site_name" content="three.ws">+ <meta property="og:title" content="Marketplace Analytics · three.ws">+ <meta property="og:description" content="Real-time stats on the three.ws skill marketplace: top skills, top agents, and sales volume.">+ <meta property="og:url" content="https://three.ws/marketplace/analytics">+ <meta property="og:image" content="https://three.ws/og-image.png">+ <meta property="og:image:width" content="1200">+ <meta property="og:image:height" content="630">+ <meta name="twitter:card" content="summary_large_image">+ <meta name="twitter:title" content="Marketplace Analytics · three.ws">+ <meta name="twitter:description" content="Real-time stats on the three.ws skill marketplace: top skills, top agents, and sales volume.">+ <meta name="twitter:image" content="https://three.ws/og-image.png">+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Marketplace Analytics","description":"Real-time stats on the three.ws skill marketplace: top skills, top agents, and sales volume.","url":"https://three.ws/marketplace/analytics","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>+</head><body><header><div id="nav-container"></div></header><script src="/nav.js"></script>diff --git a/pages/play.html b/pages/play.htmlindex 5850bef68..08a3859cb 100644--- a/pages/play.html+++ b/pages/play.html@@ -2,6 +2,7 @@<html lang="en"><head><script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <script>/* embed bg — ?bg=transparent composites the world onto the host page (e.g. the IBM x402 showcase) instead of a black box. Set before first paint so there is no dark flash. */(function(){try{if(new URLSearchParams(location.search).get('bg')==='transparent')document.documentElement.setAttribute('data-bg','transparent');}catch(e){}})();</script><meta charset="utf-8" /><title>Play · Coin Communities — three.ws</title><metadiff --git a/pages/pose.html b/pages/pose.htmlindex 20a5e02bf..c7b4b2aac 100644--- a/pages/pose.html+++ b/pages/pose.html@@ -1622,7 +1622,10 @@}}</style>- </head>++ <link rel="canonical" href="https://three.ws/pose">+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Animation Studio","description":"Pose any three.ws avatar or the built-in mannequin with FK/IK, keyframe a timeline, and preview the motion live. Export an animated GLB or clip JSON, save animations to your account, play them back across the platform, and sell them for USDC.","url":"https://three.ws/pose","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>+</head><body><header><div id="nav-container"></div></header><script src="/nav.js"></script>diff --git a/public/changelog.json b/public/changelog.jsonindex dc3c940ae..ed6edd7e7 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,11 +1,42 @@{- "generated_at": "2026-06-17T23:26:29.150Z",+ "generated_at": "2026-06-18T01:05:47.110Z","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": "Holding $THREE now unlocks a premium feature",+ "summary": "$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.",+ "link": "/three",+ "tags": [+ "feature"+ ]+ },+ {+ "date": "2026-06-18",+ "type": "update",+ "title": "Pay $THREE per High generation — no holding required",+ "summary": "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.",+ "link": "/forge",+ "tags": [+ "feature"+ ]+ },+ {+ "date": "2026-06-18",+ "type": "update",+ "title": "Your $THREE holder tier now shows across the site",+ "summary": "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.",+ "link": "/forge",+ "tags": [+ "feature",+ "improvement"+ ]+ },{"date": "2026-06-17","type": "launch",@@ -966,6 +997,16 @@"fix"]},+ {+ "date": "2026-06-17",+ "type": "update",+ "title": "The Play world embed on the IBM demo is now transparent",+ "summary": "The embedded Coin Communities world on the IBM × three.ws x402 demo no longer sits in its own black box. Open it with a transparent background and the world composites straight onto the host page — the lobby and 3D scene render without the opaque dark fill behind them, so the embed blends into the demo instead of cutting a hard rectangle out of it. Regular Play at three.ws/play is unchanged.",+ "link": "/ibm/x402-demo",+ "tags": [+ "improvement"+ ]+ },{"date": "2026-06-17","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 5cf37830f..9d61bca06 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -6,6 +6,30 @@<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>Holding $THREE now unlocks a premium feature</title>+ <link>https://three.ws/three</link>+ <guid isPermaLink="false">2026-06-18:Holding $THREE now unlocks a premium feature</guid>+ <pubDate>Thu, 18 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>$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.</description>+ </item>+ <item>+ <title>Pay $THREE per High generation — no holding required</title>+ <link>https://three.ws/forge</link>+ <guid isPermaLink="false">2026-06-18:Pay $THREE per High generation — no holding required</guid>+ <pubDate>Thu, 18 Jun 2026 12:00:00 GMT</pubDate>+ <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>Your $THREE holder tier now shows across the site</title>+ <link>https://three.ws/forge</link>+ <guid isPermaLink="false">2026-06-18:Your $THREE holder tier now shows across the site</guid>+ <pubDate>Thu, 18 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>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.</description>+ </item><item><title>Animation Gallery</title><link>https://three.ws/animations</link>@@ -750,6 +774,14 @@<category>fix</category><description>The conviction Oracle's evidence views had stopped responding: the Wins gallery, the accuracy Backtest, and the global Activity feed were all erroring instead of returning data, and the live activity feed failed on every request. The cause was in how those queries were assembled — optional filters (time window, tier, agent) weren't being stitched into the database query correctly, so the database rejected them. All three views now build their filters cleanly and return the Oracle's track record, hit-rate, and real-time agent actions as intended.</description></item>+ <item>+ <title>The Play world embed on the IBM demo is now transparent</title>+ <link>https://three.ws/ibm/x402-demo</link>+ <guid isPermaLink="false">2026-06-17:The Play world embed on the IBM demo is now transparent</guid>+ <pubDate>Wed, 17 Jun 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>The embedded Coin Communities world on the IBM × three.ws x402 demo no longer sits in its own black box. Open it with a transparent background and the world composites straight onto the host page — the lobby and 3D scene render without the opaque dark fill behind them, so the embed blends into the demo instead of cutting a hard rectangle out of it. Regular Play at three.ws/play is unchanged.</description>+ </item><item><title>The Pole Club now has a real soundtrack</title><link>https://three.ws/club</link>diff --git a/public/features.json b/public/features.jsonindex 1b6b81eee..63c81904c 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-17T23:26:29.134Z",+ "generated_at": "2026-06-18T01:05:47.072Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/public/nav-data.js b/public/nav-data.jsindex d726435f6..bd804303d 100644--- a/public/nav-data.js+++ b/public/nav-data.js@@ -76,6 +76,12 @@ export const NAV_GROUPS = [href: '/what-is',desc: 'Plain-English intro + real use-cases — start here',},+ {+ title: 'The $THREE Economy',+ href: '/three',+ badge: 'New',+ desc: 'Holder tiers, live pricing & rewards — and what holding $THREE unlocks',+ },{ title: 'Agents Index', href: '/agents', desc: 'Browse every registered agent' },{ title: 'Marketplace', href: '/marketplace', desc: 'Buy, sell & remix agents' },{ title: 'Avatar Gallery', href: '/gallery', desc: 'Every public 3D avatar' },diff --git a/public/nav.css b/public/nav.cssindex 9fd5b64c9..6a457dddf 100644--- a/public/nav.css+++ b/public/nav.css@@ -89,6 +89,17 @@.nav-end .console:hover { border-color: var(--nv-text); background: rgba(255,255,255,0.04); }.nav-end [hidden] { display: none; }+/* $THREE holder tier chip. The chip's own look (pill, tier colours) is injected+ by src/three-access.js (.tg-badge / .tg-tier-*), but `.nav-end a` would override+ its colour + padding at higher specificity — so restate the tier palette here,+ scoped above `.nav-end a`, to let the chip read true. */+.nav-end .nav-tier-badge:not([hidden]) { display: inline-flex; align-items: center; margin: 0 2px; }+.nav-end .nav-tier-badge a { padding: 5px 11px; font-weight: 600; color: #6ee7a8; }+.nav-end .nav-tier-badge a:hover { color: #8af0c0; }+.nav-end .nav-tier-badge a.tg-tier-silver { color: #cfd6e4; }+.nav-end .nav-tier-badge a.tg-tier-gold,+.nav-end .nav-tier-badge a.tg-tier-genesis { color: #f5c451; }+/* Global search button — opens the Cmd-K command palette */.nav-search-btn {display: inline-flex; align-items: center; gap: 6px;diff --git a/public/nav.html b/public/nav.htmlindex aaa1fecd5..0e9b01778 100644--- a/public/nav.html+++ b/public/nav.html@@ -82,6 +82,9 @@<path d="M10 2v2M10 16v2M2 10h2M16 10h2M4.2 4.2l1.4 1.4M14.4 14.4l1.4 1.4M4.2 15.8l1.4-1.4M14.4 5.6l1.4-1.4" /></svg></button>+ <!-- $THREE holder tier chip — hydrated by /nav-tier-badge.js (mountTierBadge).+ Stays hidden for anonymous visitors and non-holders. -->+ <span class="nav-tier-badge" id="nav-tier-badge" hidden></span><buttontype="button"class="nav-notif-btn"diff --git a/public/nav.js b/public/nav.jsindex 9c6addae6..95d2c7c54 100644--- a/public/nav.js+++ b/public/nav.js@@ -53,6 +53,17 @@ function loadNotificationsInbox() {document.head.appendChild(s);}+// Load the $THREE holder tier chip. Must run after nav HTML is injected because+// the module mounts onto #nav-tier-badge in nav.html. Self-hides for anonymous+// visitors and non-holders, so it's safe to load unconditionally.+function loadHolderBadge() {+ if (document.querySelector('script[src="/nav-tier-badge.js"]')) return;+ const s = document.createElement('script');+ s.type = 'module';+ s.src = '/nav-tier-badge.js';+ document.head.appendChild(s);+}+// Load the site-wide feature-discovery layer (public/feature-discovery.js):// "New" badges, "have you tried…" prompts and contextual cross-links. Loaded// after the glossary so it can reuse that tooltip primitive. Self-mounting +@@ -98,6 +109,7 @@ function boot() {renderMenus(navContainer, navData);initNav(navContainer);loadNotificationsInbox();+ loadHolderBadge();}).catch((err) => console.error('nav: failed to load shared navigation', err));}diff --git a/src/forge-pay.js b/src/forge-pay.jsnew file mode 100644index 000000000..fd57f35ac--- /dev/null+++ b/src/forge-pay.js@@ -0,0 +1,283 @@+// Pay-per-use for Forge High — the client flow that lets a non-holder pay $THREE+// for one High generation instead of holding. Drives the server-authoritative+// quote → sign → settle rail (src/token-pay.js → /api/token/quote|settle) behind+// a designed status modal, then hands the settled { paymentId, refId } back so the+// caller can retry the generation with the proof attached.+//+// One entry point:+//+// import { payForHighGeneration } from './forge-pay.js';+// const r = await payForHighGeneration({ usd: 0.5 });+// if (r.ok) run({ ...cfg, payment: { paymentId: r.paymentId, refId: r.refId } });+//+// Every state is designed: the confirm step, the live phases (pricing → approve →+// confirming → verifying), and the recoverable errors — no wallet, sign-in needed,+// payment cancelled, not enough $THREE (→ Get $THREE), and settlement failure+// (Retry). The modal never throws; it resolves { ok:false } on cancel/error and+// { ok:true, paymentId, refId } on a verified on-chain payment.++import { payWithToken } from './token-pay.js';++const ECONOMY_URL = '/three';+const SIGN_IN_URL = '/login';+const WALLET_URL = 'https://phantom.app/';++let _stylesInjected = false;++function escapeHtml(s) {+ return String(s ?? '').replace(+ /[&<>"']/g,+ (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]),+ );+}++// A fresh client nonce per payment — recorded as token_payments.ref_id at quote+// time and presented again (with the payment_id) when the generation redeems it,+// so possession of the payment_id alone can't unlock a generation.+function clientNonce() {+ const id =+ (typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID()) ||+ `${Date.now()}-${Math.random().toString(16).slice(2)}`;+ return `forge-high-${id}`;+}++function usdLabel(usd) {+ return `$${(Number(usd) || 0).toFixed(2)}`;+}++// Map a payWithToken phase to holder-readable status copy.+const PHASE_COPY = {+ quoting: 'Pricing in $THREE…',+ awaiting_signature: 'Approve the payment in your wallet…',+ confirming: 'Confirming on Solana…',+ settling: 'Verifying your payment…',+};++// Classify a thrown error into a designed, recoverable state. Returns+// { title, detail, cta } where cta is { label, href } | { label, retry:true } | null.+function classifyError(err) {+ const code = err?.code || '';+ const msg = String(err?.message || '');++ if (code === 'no_wallet' || code === 'not_connected' || code === 'no_pubkey') {+ return {+ title: 'No Solana wallet',+ detail: 'Connect a Solana wallet (Phantom) to pay in $THREE, then try again.',+ cta: { label: 'Get Phantom', href: WALLET_URL, external: true },+ };+ }+ if (code === 'unauthorized') {+ return {+ title: 'Sign in to pay',+ detail: 'Sign in to three.ws first so we can issue your $THREE payment quote.',+ cta: { label: 'Sign in', href: SIGN_IN_URL },+ };+ }+ 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 } };+ }+ 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.",+ cta: { label: 'Get $THREE', href: ECONOMY_URL },+ };+ }+ 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 } };+ }+ if (code === 'already_settled') {+ 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.',+ cta: { label: 'Try again', retry: true },+ };+}++/**+ * Run the pay-per-use flow for one Forge High generation.+ * @param {{ usd: number }} params+ * @returns {Promise<{ ok: true, paymentId: string, refId: string } | { ok: false, cancelled?: boolean }>}+ */+export function payForHighGeneration({ usd }) {+ injectStyles();+ return new Promise((resolve) => {+ const refId = clientNonce();+ let settled = false;++ const overlay = document.createElement('div');+ overlay.className = 'fpay-overlay';+ overlay.innerHTML = renderShell(usd);+ document.body.appendChild(overlay);++ const modal = overlay.querySelector('.fpay-modal');+ const statusEl = overlay.querySelector('.fpay-status');+ const actionsEl = overlay.querySelector('.fpay-actions');++ const cleanup = () => {+ if (overlay._onKey) document.removeEventListener('keydown', overlay._onKey);+ overlay.classList.remove('fpay-in');+ const remove = () => overlay.remove();+ overlay.addEventListener('transitionend', remove, { once: true });+ setTimeout(remove, 260);+ };+ const finish = (result) => {+ if (overlay._done) return;+ overlay._done = true;+ cleanup();+ resolve(result);+ };+ const close = () => finish({ ok: false, cancelled: true });++ // ── State renderers ────────────────────────────────────────────────────+ function showStatus(text, { busy = false } = {}) {+ statusEl.className = 'fpay-status' + (busy ? ' fpay-status--busy' : '');+ statusEl.innerHTML = busy+ ? `<span class="fpay-spinner" aria-hidden="true"></span><span>${escapeHtml(text)}</span>`+ : escapeHtml(text);+ }++ function showConfirm() {+ showStatus('One High-quality generation (200k poly + PBR), paid in $THREE.');+ actionsEl.innerHTML =+ `<button type="button" class="fpay-btn fpay-btn--primary" data-fpay-pay>Pay ${usdLabel(usd)}</button>` ++ `<button type="button" class="fpay-btn fpay-btn--ghost" data-fpay-cancel>Cancel</button>`;+ actionsEl.querySelector('[data-fpay-pay]').addEventListener('click', startPayment);+ actionsEl.querySelector('[data-fpay-cancel]').addEventListener('click', close);+ actionsEl.querySelector('[data-fpay-pay]').focus();+ }++ function showError(err) {+ const info = classifyError(err);+ statusEl.className = 'fpay-status fpay-status--err';+ statusEl.innerHTML =+ `<strong class="fpay-err-title">${escapeHtml(info.title)}</strong>` ++ `<span class="fpay-err-detail">${escapeHtml(info.detail)}</span>`;+ const buttons = [];+ if (info.cta?.href) {+ const ext = info.cta.external ? ' target="_blank" rel="noopener"' : '';+ buttons.push(+ `<a class="fpay-btn fpay-btn--primary" href="${escapeHtml(info.cta.href)}"${ext}>${escapeHtml(info.cta.label)}</a>`,+ );+ }+ 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--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);+ }++ async function startPayment() {+ actionsEl.innerHTML = '';+ showStatus(PHASE_COPY.quoting, { busy: true });+ try {+ const result = await payWithToken({+ purpose: 'consumption',+ usd,+ refType: 'forge',+ refId,+ 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' });+ }+ settled = true;+ statusEl.className = 'fpay-status fpay-status--ok';+ statusEl.innerHTML = `<span class="fpay-check" aria-hidden="true">✓</span> Payment confirmed — starting your generation…`;+ actionsEl.innerHTML = '';+ setTimeout(() => finish({ ok: true, paymentId: result.payment_id, refId }), 850);+ } catch (err) {+ if (settled) return; // already resolved+ showError(err);+ }+ }++ // ── Mount ────────────────────────────────────────────────────────────────+ overlay.addEventListener('click', (e) => {+ if (e.target === overlay) close();+ });+ overlay.querySelector('[data-fpay-x]').addEventListener('click', close);+ const onKey = (e) => {+ if (e.key === 'Escape') close();+ };+ overlay._onKey = onKey;+ document.addEventListener('keydown', onKey);+ requestAnimationFrame(() => {+ overlay.classList.add('fpay-in');+ (modal || overlay).focus?.();+ });+ showConfirm();+ });+}++function renderShell(usd) {+ return (+ `<div class="fpay-modal" role="dialog" aria-modal="true" aria-labelledby="fpay-title">` ++ `<button class="fpay-x" data-fpay-x type="button" aria-label="Close">✕</button>` ++ `<div class="fpay-badge" aria-hidden="true">◆</div>` ++ `<h2 class="fpay-title" id="fpay-title">Pay ${usdLabel(usd)} in $THREE</h2>` ++ `<div class="fpay-price"><span class="fpay-price-amt">${usdLabel(usd)}</span><span class="fpay-price-unit">in $THREE · one High generation</span></div>` ++ `<div class="fpay-status" role="status" aria-live="polite"></div>` ++ `<div class="fpay-actions"></div>` ++ `<p class="fpay-foot">$THREE is the only coin on three.ws. Draft & Standard generation stay free.</p>` ++ `</div>`+ );+}++function injectStyles() {+ if (_stylesInjected || typeof document === 'undefined') return;+ _stylesInjected = true;+ const css = `+ .fpay-overlay{position:fixed;inset:0;z-index:2147483100;display:flex;align-items:center;justify-content:center;+ padding:20px;background:rgba(4,4,7,.66);backdrop-filter:blur(7px);-webkit-backdrop-filter:blur(7px);+ opacity:0;transition:opacity .2s ease;font-family:Inter,system-ui,sans-serif;}+ .fpay-overlay.fpay-in{opacity:1;}+ .fpay-modal{position:relative;width:min(420px,100%);background:linear-gradient(180deg,#0e0e13,#0a0a0e);+ border:1px solid #23232c;border-radius:20px;padding:30px 28px 22px;text-align:center;color:#f6f6f8;+ 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);}+ .fpay-overlay.fpay-in .fpay-modal{transform:none;}+ .fpay-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;}+ .fpay-x:hover{color:#f6f6f8;border-color:#34343f;}+ .fpay-badge{font-size:30px;color:#6ee7a8;filter:drop-shadow(0 0 14px rgba(110,231,168,.5));margin-bottom:6px;}+ .fpay-title{font-size:20px;font-weight:820;letter-spacing:-.02em;margin:2px 0 12px;}+ .fpay-price{display:flex;flex-direction:column;align-items:center;gap:2px;margin:0 0 16px;padding:13px;+ background:rgba(110,231,168,.07);border:1px solid rgba(110,231,168,.2);border-radius:12px;}+ .fpay-price-amt{font-size:26px;font-weight:800;color:#6ee7a8;line-height:1;}+ .fpay-price-unit{font-size:12px;color:#9a9aa4;}+ .fpay-status{font-size:13.5px;color:#b6b6c0;line-height:1.5;min-height:20px;margin:0 0 16px;+ display:flex;align-items:center;justify-content:center;gap:9px;flex-wrap:wrap;}+ .fpay-status--busy{color:#d6d6de;}+ .fpay-status--ok{color:#6ee7a8;font-weight:600;}+ .fpay-status--err{flex-direction:column;gap:3px;}+ .fpay-err-title{font-size:14px;font-weight:700;color:#f0c2c2;}+ .fpay-err-detail{font-size:12.5px;color:#a6a6b0;}+ .fpay-check{color:#6ee7a8;font-weight:800;}+ .fpay-spinner{width:15px;height:15px;border-radius:50%;border:2px solid rgba(110,231,168,.25);+ border-top-color:#6ee7a8;animation:fpay-spin .7s linear infinite;flex-shrink:0;}+ .fpay-actions{display:flex;flex-direction:column;gap:9px;min-height:1px;}+ .fpay-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;+ background:#13131a;color:#f1f1f4;transition:transform .15s cubic-bezier(.22,1,.36,1),background .15s ease,border-color .15s ease;}+ .fpay-btn--primary{background:#6ee7a8;color:#06120c;border-color:#6ee7a8;}+ .fpay-btn--primary:hover{background:#8af0c0;transform:translateY(-1px);}+ .fpay-btn--ghost:hover{border-color:#3a3a44;background:#181820;transform:translateY(-1px);}+ .fpay-foot{font-size:11px;color:#6a6a74;margin:16px 0 0;line-height:1.5;}+ .fpay-btn:focus-visible,.fpay-x:focus-visible{outline:2px solid #6ee7a8;outline-offset:2px;}+ @keyframes fpay-spin{to{transform:rotate(360deg)}}+ @media (prefers-reduced-motion: reduce){+ .fpay-overlay,.fpay-modal,.fpay-btn{transition:none;}+ .fpay-modal{transform:none;}+ .fpay-spinner{animation-duration:1.4s;}+ }`;+ const el = document.createElement('style');+ el.id = 'fpay-styles';+ el.textContent = css;+ document.head.appendChild(el);+}diff --git a/src/forge.js b/src/forge.jsindex 2ba264bfe..6cb6cb22f 100644--- a/src/forge.js+++ b/src/forge.js@@ -2,6 +2,9 @@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 { renderLock, lockStateFromAccess } from './three-lock.js';+import { payForHighGeneration } from './forge-pay.js';ensureStateKitStyles();//// Drives /api/forge. Three paths share one polling loop:@@ -89,6 +92,9 @@ const els = {creationsCount: document.getElementById('creations-count'),// Quality tier + generation engine + BYOK key.tier: document.getElementById('tier'),+ // Persistent inline hint under the Quality row — advertises that High is a+ // $THREE holder feature (toggled locked/unlocked by the live access read).+ holderNote: document.getElementById('fq-holder-note'),engine: document.getElementById('engine'),byokRow: document.getElementById('byok-row'),byokLabel: document.getElementById('byok-label'),@@ -321,8 +327,13 @@ function stopElapsed() {}function setBusy(busy) {+ els.generate.dataset.busy = busy ? '1' : '0';els.generate.disabled = busy;els.generateLabel.textContent = busy ? 'Forging…' : 'Generate';+ // When returning to idle, re-assert the High-tier $THREE gate (if active) so a+ // finished/cancelled job doesn't leave the Generate button enabled for a tier+ // the user can't use.+ if (!busy) applyHighGate();}function sleep(ms) {@@ -556,6 +567,139 @@ function selectTier(tierId) {// Tier changes can move the default engine (draft prefers the free lane).updateEngineAvailability();updateEstimate();+ reflectHighAccess(tierId);+}++// The High tier is a $THREE holder perk (gated server-side). When the user picks+// it, surface their access up front — a frosted lock with a Get $THREE path for+// non-holders (and the Generate button disabled for High), an "Unlocked" ribbon+// for holders (pass primed so their request clears the gate without a round-trip+// stall). Draft and Standard clear the lock (they're free, never gated). Degrades+// safely: if the access read fails we show a retry but DON'T trap the user — the+// server stays the final authority and a 403 falls back to the upsell modal.+let _accessHost = null;+let highLocked = false; // true → High is selected but the holder isn't eligible+let _highAccess = null; // last resolved forge.high access payload (for the gate modal)++function accessHost() {+ if (_accessHost || !els.tier) return _accessHost;+ const host = document.createElement('div');+ host.className = 'fq-access';+ host.hidden = true;+ (els.estimate || els.tier).insertAdjacentElement('afterend', host);+ _accessHost = host;+ return host;+}++// Reflect the High-tier gate onto the Generate button: disabled + relabelled+// while High is selected and the user is ineligible. Only touches the button when+// not mid-job (setBusy owns the busy label).+function applyHighGate() {+ if (!els.generate || els.generate.dataset.busy === '1') return;+ const locked = selectedTier === 'high' && highLocked;+ els.generate.disabled = locked;+ els.generate.classList.toggle('is-gated', locked);+ if (els.generateLabel) {+ els.generateLabel.textContent = locked ? 'Hold $THREE for High' : 'Generate';+ }+}++async function reflectHighAccess(tierId) {+ const host = accessHost();+ if (!host) return;+ if (tierId !== 'high') {+ highLocked = false;+ _highAccess = null;+ renderLock(host, { clear: true });+ // High isn't selected — let the persistent hint advertise it again.+ if (els.holderNote) els.holderNote.hidden = false;+ 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.+ 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;+ 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).+ _highAccess = null;+ highLocked = false;+ renderLock(host, { error: true, onRetry: () => reflectHighAccess('high') });+ applyHighGate();+ return;+ }+ _highAccess = access;+ highLocked = !access.eligible;+ renderLock(+ host,+ lockStateFromAccess(access, {+ getThreeUrl: '/three',+ onUseFree: () => selectTier('standard'),+ useFreeLabel: 'Use Standard (free)',+ // Working Pay-per-use CTA: pay $THREE for one High generation in place.+ onPayPerUse: (pay) => payThenGenerate(pay),+ }),+ );+ applyHighGate();+ // Keep the persistent button pill + note in sync with the fresh verdict.+ applyHighAffordances(access);+ if (access.eligible) primeTierPass();+}++// Small lock glyph for the High-tier button pill. Stroke = currentColor so it+// tracks the pill's locked (gold) / unlocked (green) tone.+const TIER_LOCK_SVG =+ '<svg class="tier-lock-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="5" y="11" width="14" height="9" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></svg>';++// Paint the persistent High-tier affordances — the lock pill on the High button+// and the inline holder note under the Quality row — from a single-feature access+// payload (the `.access` from getAccess('forge.high'), or a 403 gate body, which+// both carry `eligible`/`required`/`held`). Holders get the quiet unlocked+// treatment; everyone else (and the null/unknown case) keeps the $THREE lock so+// High reads as the premium lane before it's ever selected. Purely cosmetic — the+// server stays the only authority on eligibility.+function applyHighAffordances(access) {+ const eligible = Boolean(access?.eligible);+ const state = eligible ? 'unlocked' : 'locked';+ const btn = els.tier?.querySelector('button[data-tier="high"]');+ if (btn) {+ btn.dataset.access = state;+ btn.setAttribute(+ 'aria-label',+ eligible ? 'High quality — unlocked, you hold $THREE' : 'High quality — $THREE holder feature',+ );+ const pill = btn.querySelector('.tier-lock');+ if (pill) {+ pill.dataset.state = state;+ pill.title = eligible ? 'Unlocked — you hold $THREE' : 'High quality is a $THREE holder feature';+ pill.innerHTML = eligible+ ? '<span class="tier-lock-ico" aria-hidden="true">✓</span><span class="tier-lock-txt">$THREE</span>'+ : `${TIER_LOCK_SVG}<span class="tier-lock-txt">$THREE</span>`;+ }+ }+ const note = els.holderNote;+ if (note) {+ note.dataset.state = state;+ note.innerHTML = eligible+ ? '<span class="fq-holder-ico" aria-hidden="true">◆</span> High quality is unlocked — you hold <a href="/three">$THREE</a>.'+ : '<span class="fq-holder-ico" aria-hidden="true">◆</span> High quality is a <a href="/three">$THREE holder</a> feature — hold to unlock, or pay per generation.';+ }+}++// One-time read on load: reflect the viewer's forge.high access onto the High+// button pill + the inline note so the holder gate is legible before the tier is+// even selected. Seeds the gate cache and primes the tier pass for real holders so+// their first High submit clears the server gate without an RPC stall.+async function reflectHighButtonAccess() {+ const data = await getAccess('forge.high');+ const access = data?.access || null;+ if (access) _highAccess = access;+ applyHighAffordances(access);+ if (access?.eligible) primeTierPass();}// Render the honest time/cost/poly estimate for the current engine + tier from@@ -998,10 +1142,14 @@ function firstPreviewUrl() {function forgeHeaders(extra) {const h = { ...CLIENT_HEADERS, ...extra };if (providerKey) h['x-forge-provider-key'] = providerKey;+ // Carry the holder's $THREE tier pass so an eligible holder clears the High-tier+ // gate (and gets their free-lane multiplier). No-op for anonymous users — the+ // request simply proceeds at the base entitlement.+ attachTierPass(h);return h;}-async function startJob({ prompt, imageUrls, skipValidation }) {+async function startJob({ prompt, imageUrls, skipValidation, payment }) {const base = { path: selectedEngine.path, tier: selectedTier, backend: selectedEngine.backend };const body =Array.isArray(imageUrls) && imageUrls.length@@ -1009,6 +1157,12 @@ async function startJob({ prompt, imageUrls, skipValidation }) {: { prompt, aspect_ratio: aspectRatio, ...base };// Caller already saw the vision warning and chose to proceed (Consumer 1).if (skipValidation) body.skip_validation = true;+ // Pay-per-use proof: a non-holder who paid $THREE for this High generation+ // presents the settled payment so the server's gate is satisfied per use.+ if (payment?.paymentId && payment?.refId) {+ body.payment_id = payment.paymentId;+ body.ref_id = payment.refId;+ }const res = await fetch('/api/forge', {method: 'POST',@@ -1067,6 +1221,34 @@ async function startJob({ prompt, imageUrls, skipValidation }) {e.unavailable = unavailable;throw e;}+ // High-tier hold-to-access gate ($THREE) — a hold-OR-pay 402 (three_hold_required).+ // Recoverable: the user can hold $THREE (Get $THREE) or drop to Draft/Standard.+ // Carries the full gate payload (held vs required, usd_to_go, acquire, pay_per_use)+ // straight to the upsell modal.+ if (res.status === 402 && data.error === 'three_hold_required') {+ const e = new Error(data.message || 'High-quality generation is a $THREE holder perk.');+ e.kind = 'hold_required';+ e.gate = data;+ throw e;+ }+ // Pay-per-use proof was rejected (bad/expired payment) or already spent — both+ // recoverable by paying again. payment_invalid/expired re-offer Pay; an already+ // used payment also clears the stale proof so a retry doesn't replay it.+ if (+ res.status === 402 &&+ (data.error === 'payment_invalid' || data.error === 'payment_expired')+ ) {+ const e = new Error(data.message || 'That $THREE payment could not be verified.');+ e.kind = 'payment_invalid';+ e.gate = data;+ throw e;+ }+ if (res.status === 409 && data.error === 'payment_already_used') {+ const e = new Error(data.message || 'That payment was already used. Pay again to generate.');+ e.kind = 'payment_used';+ e.gate = data;+ throw e;+ }if (!res.ok) {throw new Error(data.message || `The generator returned ${res.status}.`);}@@ -1647,6 +1829,10 @@ async function run(cfg) {const done = job.status === 'done' && job.glb_url ? job : await pollUntilDone(job.job_id);if (pollAbort || !done) return; // cancelled+ // A pay-per-use proof is single-use and now redeemed on the server — drop it+ // so a later Retry/Refine of this job never replays a spent payment.+ if (lastJob) delete lastJob.payment;+if (done.creation_id) currentCreationId = done.creation_id;setStep('mesh', 'done');setStep('finish', 'done');@@ -1706,6 +1892,41 @@ async function run(cfg) {showRateLimited({ retryAfter: err.retryAfter, unavailable: err.unavailable });return;}+ // High-tier $THREE gate: open the designed upsell (Get $THREE / what you hold+ // vs. need — plus the working Pay-per-use CTA) and reset to the idle composer+ // so the user can switch tier, hold, or pay.+ if (err.kind === 'hold_required') {+ stopElapsed();+ showState('empty');+ // Reflect the server's verdict back onto the composer (lock the High+ // option + the button pill/note) before opening the upsell, so the gate is+ // felt in place too — not only in the modal.+ highLocked = true;+ _highAccess = err.gate || _highAccess;+ applyHighGate();+ applyHighAffordances(err.gate);+ onGate(err.gate, gateOpts());+ return;+ }+ // A presented pay-per-use proof was already spent — drop the stale payment so+ // Retry doesn't replay it, and re-open the pay flow for a fresh generation.+ if (err.kind === 'payment_used') {+ stopElapsed();+ if (lastJob) delete lastJob.payment;+ showState('empty');+ showError(err.message || 'That payment was already used. Pay again to generate.');+ return;+ }+ // The proof was rejected (bad/expired) before any model — drop it and surface+ // the gate's Pay-per-use path again so the user can pay cleanly.+ if (err.kind === 'payment_invalid') {+ stopElapsed();+ if (lastJob) delete lastJob.payment;+ showState('empty');+ if (err.gate) onGate(err.gate, gateOpts());+ else showError(err.message || 'That $THREE payment could not be verified.');+ return;+ }showError(err.message ||'Something went wrong. Try a simpler, single-subject prompt or cleaner photos.',@@ -1715,15 +1936,18 @@ async function run(cfg) {}}-function submit() {+// Gather + validate the active mode's composer inputs into a run cfg, or null+// when something's missing (focusing/flagging the offending field as a side+// effect, exactly as submit always has). Shared by the Generate button and the+// pay-per-use path so both build the job identically.+function collectComposerCfg() {if (mode === 'text') {const prompt = els.prompt.value.trim();if (prompt.length < 3) {els.prompt.focus();- return;+ return null;}- run({ prompt, imageUrls: [] });- return;+ return { prompt, imageUrls: [] };}// Sketch mode — one drawing + a required prompt naming what it depicts.@@ -1733,14 +1957,14 @@ function submit() {setTimeout(() => {if (!els.generate.disabled) els.generateLabel.textContent = 'Generate';}, 1600);- return;+ return null;}if (sketch.state !== 'uploaded' || !sketch.url) {const slot = sketchSlotEl();slot?.focus();slot?.classList.add('drop-target');setTimeout(() => slot?.classList.remove('drop-target'), 600);- return;+ return null;}const prompt = els.sketchPrompt.value.trim();if (prompt.length < 3) {@@ -1749,10 +1973,9 @@ function submit() {els.sketchPrompt.setAttribute('aria-invalid', 'true');if (els.sketchReqTag) els.sketchReqTag.dataset.missing = 'true';els.sketchPrompt.focus();- return;+ return null;}- run({ prompt, imageUrls: [sketch.url] });- return;+ return { prompt, imageUrls: [sketch.url] };}// Image / multi-view mode.@@ -1761,7 +1984,7 @@ function submit() {setTimeout(() => {if (!els.generate.disabled) els.generateLabel.textContent = 'Generate';}, 1600);- return;+ return null;}const urls = uploadedUrls();if (urls.length === 0) {@@ -1769,9 +1992,47 @@ function submit() {first?.focus();first?.classList.add('drop-target');setTimeout(() => first?.classList.remove('drop-target'), 600);+ return null;+ }+ return { prompt: els.imagePrompt.value.trim(), imageUrls: urls };+}++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) {+ if (_highAccess) onGate(_highAccess, gateOpts());+ else reflectHighAccess('high');return;}- run({ prompt: els.imagePrompt.value.trim(), imageUrls: urls });+ const cfg = collectComposerCfg();+ if (cfg) run(cfg);+}++// Options handed to the gate modal / in-place lock so their "Pay per generation"+// CTA actually works: pay $THREE for one High generation, then run the current+// composer inputs with the settled proof attached.+function gateOpts() {+ return { onPayPerUse: (pay) => payThenGenerate(pay) };+}++// The consumption lever, end to end: price comes from the gate's pay_per_use (or+// the resolved access), the user pays $THREE through the designed modal, and the+// generation re-fires immediately with { paymentId, refId } so the server's gate+// is satisfied per use. No-op if the composer inputs are incomplete (the field is+// focused) or the user cancels the payment.+async function payThenGenerate(pay) {+ const usd = Number(pay?.usd) || Number(_highAccess?.pay_per_use?.usd) || 0;+ if (!(usd > 0)) return;+ const cfg = collectComposerCfg();+ if (!cfg) return;+ // Ensure the job runs at High (the tier the payment buys) even if the click+ // came from the in-place lock before any submit.+ if (selectedTier !== 'high') selectTier('high');+ const result = await payForHighGeneration({ usd });+ if (!result?.ok) return; // cancelled or failed — the modal explained why+ run({ ...cfg, payment: { paymentId: result.paymentId, refId: result.refId } });}// Wiring ----------------------------------------------------------------------@@ -2075,6 +2336,10 @@ document.addEventListener('forge:open-creation', (e) => {// cost/time matrix). Falls back silently to the defaults if it can't load.loadCatalog();+// Surface the $THREE holder gate on the High control up front (pill + note),+// independent of the catalog so the affordance lands even on older deploys.+reflectHighButtonAccess();+// Surface any previously forged models for this browser on load.loadGallery().then(() => {const shareId = window.__forgeShareId;diff --git a/src/game/coincommunities.css b/src/game/coincommunities.cssindex 331e67e8b..ab8a9e224 100644--- a/src/game/coincommunities.css+++ b/src/game/coincommunities.css@@ -34,6 +34,18 @@ html, body {font-family: "Inter", system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;-webkit-font-smoothing: antialiased; overscroll-behavior: none;}+/* Transparent embed: `?bg=transparent` (set on <html> by the play.html boot script)+ drops every opaque page-level fill so the world composites onto the host page —+ e.g. the IBM x402 showcase — instead of sitting in its own black box. The WebGL+ canvas + sky are cleared engine-side (see coincommunities.js); these clear the+ HTML/CSS layers above it. Lobby content panels keep their own fills. */+html[data-bg="transparent"], html[data-bg="transparent"] body { background: transparent; }+html[data-bg="transparent"] #kx-loading, html[data-bg="transparent"] #cc-loading { background: transparent; }+html[data-bg="transparent"] #cc-lobby {+ background:+ radial-gradient(1000px 560px at 82% -12%, rgba(255, 255, 255, 0.06), transparent 60%),+ radial-gradient(820px 520px at 6% 112%, rgba(255, 255, 255, 0.045), transparent 60%);+}#kx-canvas, #cc-canvas {position: fixed; inset: 0; width: 100%; height: 100%; display: block;touch-action: none; cursor: grab;diff --git a/src/nav-tier-badge.js b/src/nav-tier-badge.jsnew file mode 100644index 000000000..352e6be6f--- /dev/null+++ b/src/nav-tier-badge.js@@ -0,0 +1,28 @@+// 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.+//+// 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.++import { mountTierBadge, getAccess } 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);+ });+}diff --git a/src/three-access.js b/src/three-access.jsnew file mode 100644index 000000000..e8a1039cc--- /dev/null+++ b/src/three-access.js@@ -0,0 +1,329 @@+// $THREE access — client helper + lock UI (Token Utility v1).+//+// 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+// expiry; 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+).+// • 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.+// • renderInlineLock(el) — a compact lock/unlock chip beside a gated control.+//+// 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.++const ACCESS_TTL_MS = 30_000;+let _matrix = { at: 0, data: null };+let _tierPass = null; // { pass, tier, exp(ms) }+let _stylesInjected = false;++const ECONOMY_URL = '/three';++function escapeHtml(s) {+ return String(s ?? '').replace(+ /[&<>"']/g,+ (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],+ );+}++// base64url → JSON (the tier-pass payload is the part before the first '.').+function decodePassExpMs(pass) {+ try {+ let b = String(pass).split('.')[0].replace(/-/g, '+').replace(/_/g, '/');+ while (b.length % 4) b += '=';+ const json = JSON.parse(atob(b));+ const exp = Number(json.exp) || 0;+ return exp > 0 ? exp * 1000 : 0;+ } catch {+ return 0;+ }+}++// ── Data ──────────────────────────────────────────────────────────────────────++/**+ * Fetch the access matrix (no arg) or a single feature's access.+ * Returns null on failure so callers render a safe locked state.+ * Matrix shape: { signed_in, wallet_linked, tier:{level,id,label,held_usd}, features:[…] }+ * 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) {+ return _matrix.data;+ }+ const url = feature+ ? `/api/three/access?feature=${encodeURIComponent(feature)}`+ : '/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 };+ return data;+ } catch {+ return null;+ }+}++/**+ * 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.+ */+export async function getTierPass() {+ const now = Date.now();+ if (_tierPass && _tierPass.exp - 60_000 > now) return _tierPass;+ 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 (!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;+ } catch {+ return null;+ }+}++/** The cached pass string for the x-three-tier-pass header, or null. Synchronous. */+export function tierPassHeader() {+ return _tierPass && _tierPass.exp - 60_000 > Date.now() ? _tierPass.pass : null;+}++/**+ * Attach the cached $THREE tier pass to a request headers object so an eligible+ * holder's entitlement rides along on a gated call. Synchronous and side-effect+ * free when no valid pass is cached — the request simply proceeds at the base+ * entitlement and the server stays the authority. Returns the same object for+ * chaining: `fetch(url, { headers: attachTierPass({ 'content-type': '…' }) })`.+ */+export function attachTierPass(headers = {}) {+ const pass = tierPassHeader();+ if (pass) headers['x-three-tier-pass'] = pass;+ return headers;+}++/** Fetch the pass in the background so it's ready when a gated request fires. */+export function primeTierPass() {+ getTierPass();+}++// ── Tier badge ─────────────────────────────────────────────────────────────────++/** Render the signed-in user's tier chip into `target`. Hides it for anonymous users. */+export async function mountTierBadge(target) {+ const el = typeof target === 'string' ? document.querySelector(target) : target;+ if (!el) return;+ injectStyles();+ 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) {+ el.hidden = true;+ el.innerHTML = '';+ return;+ }+ el.hidden = false;+ const t = data.tier;+ const held =+ t.held_usd > 0+ ? ` · $${Number(t.held_usd).toLocaleString('en-US', { maximumFractionDigits: 0 })} held`+ : '';+ el.innerHTML = `<a class="tg-badge tg-tier-${escapeHtml(t.id)}" href="${ECONOMY_URL}#tiers" title="Your $THREE holder tier — what it unlocks${held}">◆ ${escapeHtml(t.label)}</a>`;+}++// ── Inline lock chip (beside a gated control) ─────────────────────────────────++/**+ * Render a compact lock/unlock chip into `target` from a single-feature access+ * payload (the `.access` object from getAccess(feature)). Null clears it.+ */+export function renderInlineLock(target, access) {+ const el = typeof target === 'string' ? document.querySelector(target) : target;+ if (!el) return;+ injectStyles();+ if (!access) {+ el.innerHTML = '';+ el.hidden = true;+ return;+ }+ el.hidden = false;+ if (access.eligible) {+ el.innerHTML = `<span class="tg-chip tg-chip--ok" role="status">✓ Unlocked · ${escapeHtml(access.held?.label || 'Holder')}</span>`;+ return;+ }+ const req = access.required?.label || 'a higher tier';+ el.innerHTML =+ `<span class="tg-chip tg-chip--lock"><span class="tg-lock" aria-hidden="true">🔒</span> ${escapeHtml(req)} holder perk` ++ ` · <a href="${ECONOMY_URL}">Get $THREE →</a></span>`;+}++// ── Upsell modal (402 three_hold_required) ────────────────────────────────────++/**+ * Show the holder-gate upsell from a `three_hold_required` payload:+ * { feature, required:{level,id,label}, held:{level,id,label,usd?}, why,+ * get_three_url?, acquire?, usd_to_go?, pay_per_use?:{action,usd}|null, message? }+ * @param {object} gate+ * @param {{ onPayPerUse?: (pay)=>void }} [opts] when provided AND gate.pay_per_use+ * is present, a working "Pay per generation" button is rendered.+ */+export function showThreeGate(gate, opts = {}) {+ injectStyles();+ if (!gate || typeof document === 'undefined') return;+ closeThreeGate(); // never stack++ const required = gate.required || { label: 'a higher tier' };+ const held = gate.held || { label: 'Member', level: 0 };+ const getUrl = gate.get_three_url || ECONOMY_URL;+ const heldUsd = Number(held.usd) || 0;+ const reason = gate.reason || (held.level > 0 ? 'insufficient_tier' : '');++ const sub =+ reason === 'sign_in'+ ? 'Sign in and link a Solana wallet to check your tier.'+ : reason === 'link_wallet'+ ? 'Link a Solana wallet to your account so we can read your $THREE.'+ : `You hold <strong>${escapeHtml(held.label)}</strong>${heldUsd > 0 ? ` (≈ $${heldUsd.toLocaleString('en-US', { maximumFractionDigits: 0 })})` : ''}. Reach <strong>${escapeHtml(required.label)}</strong> to unlock this.`;++ const payBtn =+ gate.pay_per_use && typeof opts.onPayPerUse === 'function'+ ? `<button class="tg-btn tg-btn--ghost" id="tg-pay" type="button">Pay $${Number(gate.pay_per_use.usd).toFixed(2)} per generation</button>`+ : '';++ const overlay = document.createElement('div');+ overlay.className = 'tg-overlay';+ overlay.id = 'tg-overlay';+ overlay.innerHTML = `+ <div class="tg-modal" role="dialog" aria-modal="true" aria-labelledby="tg-title" aria-describedby="tg-desc">+ <button class="tg-x" id="tg-close" type="button" aria-label="Close">✕</button>+ <div class="tg-badge-lg" aria-hidden="true">◆</div>+ <h2 class="tg-title" id="tg-title">${escapeHtml(gate.message ? required.label + ' perk' : 'Hold $THREE to unlock')}</h2>+ <p class="tg-feature">${escapeHtml(gate.label || gate.message || 'This is a $THREE holder feature.')}</p>+ <p class="tg-desc" id="tg-desc">${sub}</p>+ ${gate.why ? `<p class="tg-why">${escapeHtml(gate.why)}</p>` : ''}+ <div class="tg-actions">+ <a class="tg-btn tg-btn--primary" id="tg-get" href="${escapeHtml(getUrl)}">Get $THREE</a>+ ${payBtn}+ <a class="tg-btn tg-btn--ghost" href="${ECONOMY_URL}#tiers">See holder tiers</a>+ </div>+ <p class="tg-foot">$THREE is the only coin on three.ws. Draft & Standard generation stay free, forever.</p>+ </div>`;++ document.body.appendChild(overlay);+ const modal = overlay.querySelector('.tg-modal');+ const close = () => closeThreeGate();+ overlay.addEventListener('click', (e) => {+ if (e.target === overlay) close();+ });+ overlay.querySelector('#tg-close').addEventListener('click', close);+ const payEl = overlay.querySelector('#tg-pay');+ if (payEl) {+ payEl.addEventListener('click', () => {+ close();+ opts.onPayPerUse(gate.pay_per_use);+ });+ }+ const onKey = (e) => {+ if (e.key === 'Escape') close();+ };+ overlay._onKey = onKey;+ document.addEventListener('keydown', onKey);+ requestAnimationFrame(() => {+ overlay.classList.add('tg-in');+ (overlay.querySelector('#tg-get') || modal).focus();+ });+}++export function closeThreeGate() {+ const overlay = document.getElementById('tg-overlay');+ if (!overlay) return;+ if (overlay._onKey) document.removeEventListener('keydown', overlay._onKey);+ overlay.classList.remove('tg-in');+ const remove = () => overlay.remove();+ overlay.addEventListener('transitionend', remove, { once: true });+ setTimeout(remove, 260); // fallback when transitions are disabled+}++/**+ * Open the holder-gate upsell from a `three_hold_required` 402 response body — the+ * entry point a gated request's error path calls when the server rejects a stale+ * or missing pass. The 402 payload already carries everything the modal needs+ * ({ feature, label, required, held, why, pay_per_use, reason }), so it is passed+ * straight through to {@link showThreeGate}. A thin, intent-named alias so call+ * sites read as "on gate → upsell" rather than reaching for the modal directly.+ * @param {object} payload the parsed `three_hold_required` 402 body+ * @param {{ onPayPerUse?: (pay)=>void }} [opts]+ */+export function onGate(payload, opts) {+ return showThreeGate(payload, opts);+}++// ── Styles ────────────────────────────────────────────────────────────────────++function injectStyles() {+ if (_stylesInjected || typeof document === 'undefined') return;+ _stylesInjected = true;+ const css = `+ .tg-badge{display:inline-flex;align-items:center;gap:6px;font:600 12px/1 Inter,system-ui,sans-serif;+ color:#6ee7a8;border:1px solid rgba(110,231,168,.3);background:rgba(110,231,168,.07);+ border-radius:999px;padding:6px 11px;text-decoration:none;transition:.16s cubic-bezier(.22,1,.36,1);white-space:nowrap;}+ .tg-badge:hover{transform:translateY(-1px);border-color:rgba(110,231,168,.55);background:rgba(110,231,168,.12);}+ .tg-tier-gold,.tg-tier-genesis{color:#f5c451;border-color:rgba(245,196,81,.32);background:rgba(245,196,81,.08);}+ .tg-tier-silver{color:#cfd6e4;border-color:rgba(207,214,228,.3);background:rgba(207,214,228,.06);}+ .tg-chip{display:inline-flex;align-items:center;gap:6px;font:600 11.5px/1.3 Inter,system-ui,sans-serif;+ border-radius:999px;padding:5px 10px;}+ .tg-chip--lock{color:#f0d488;background:rgba(245,196,81,.1);border:1px solid rgba(245,196,81,.24);}+ .tg-chip--lock a{color:#6ee7a8;text-decoration:none;font-weight:700;}+ .tg-chip--lock a:hover{text-decoration:underline;}+ .tg-chip--ok{color:#6ee7a8;background:rgba(110,231,168,.1);border:1px solid rgba(110,231,168,.24);}+ .tg-lock{font-size:11px;}+ .tg-overlay{position:fixed;inset:0;z-index:2147483000;display:flex;align-items:center;justify-content:center;+ padding:20px;background:rgba(4,4,7,.66);backdrop-filter:blur(7px);opacity:0;transition:opacity .2s ease;}+ .tg-overlay.tg-in{opacity:1;}+ .tg-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,sans-serif;box-shadow:0 30px 80px -30px rgba(0,0,0,.8);+ transform:translateY(10px) scale(.98);transition:transform .24s cubic-bezier(.22,1,.36,1);}+ .tg-overlay.tg-in .tg-modal{transform:none;}+ .tg-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;}+ .tg-x:hover{color:#f6f6f8;border-color:#34343f;}+ .tg-badge-lg{font-size:34px;color:#6ee7a8;filter:drop-shadow(0 0 14px rgba(110,231,168,.5));margin-bottom:8px;}+ .tg-title{font-size:22px;font-weight:820;letter-spacing:-.02em;margin:2px 0 8px;}+ .tg-feature{font-size:14.5px;color:#c9c9d2;margin:0 0 10px;line-height:1.45;}+ .tg-desc{font-size:13.5px;color:#9a9aa4;margin:0 0 8px;line-height:1.5;}+ .tg-desc strong{color:#f6f6f8;}+ .tg-why{font-size:12.5px;color:#80808b;margin:0 0 18px;line-height:1.5;font-style:italic;}+ .tg-actions{display:flex;flex-direction:column;gap:9px;margin-top:6px;}+ .tg-btn{display:inline-flex;align-items:center;justify-content:center;font-size:14px;font-weight:700;+ padding:12px 18px;border-radius:12px;text-decoration:none;cursor:pointer;border:1px solid #2a2a33;+ transition:.16s cubic-bezier(.22,1,.36,1);}+ .tg-btn--primary{background:#6ee7a8;color:#06120c;border-color:#6ee7a8;}+ .tg-btn--primary:hover{background:#8af0c0;transform:translateY(-1px);}+ .tg-btn--ghost{background:#0e0e13;color:#f6f6f8;}+ .tg-btn--ghost:hover{border-color:#3a3a44;transform:translateY(-1px);}+ .tg-foot{font-size:11px;color:#6a6a74;margin:16px 0 0;line-height:1.5;}+ :where(.tg-btn,.tg-badge,.tg-x):focus-visible{outline:2px solid #6ee7a8;outline-offset:2px;}+ @media (prefers-reduced-motion: reduce){+ .tg-overlay,.tg-modal,.tg-badge,.tg-btn{transition:none;}+ .tg-modal{transform:none;}+ }`;+ const el = document.createElement('style');+ el.id = 'tg-styles';+ el.textContent = css;+ document.head.appendChild(el);+}diff --git a/src/three-economy.js b/src/three-economy.jsindex c62732511..cdd4e55de 100644--- a/src/three-economy.js+++ b/src/three-economy.js@@ -262,15 +262,67 @@ function injectStyles() {.ec-tier .tn { font-size:17px; font-weight:780; }.ec-tier .tm { color:var(--muted); font-size:12.5px; margin:3px 0 14px; }.ec-tier ul { list-style:none; margin:0; padding:0; }- .ec-tier li { font-size:12.5px; color:#c9c9d2; padding:5px 0 5px 19px; position:relative; }+ .ec-tier li { font-size:12.5px; color:#c9c9d2; padding:5px 0 5px 19px; position:relative;+ display:flex; align-items:flex-start; gap:8px; }.ec-tier li::before { content:''; position:absolute; left:3px; top:11px; width:6px; height:6px; border-radius:50%;background:var(--green); }+ .ec-tier li .pk-label { flex:1; min-width:0; line-height:1.4; }+ .ec-tier li.is-planned { color:var(--muted); }+ .ec-tier li.is-planned::before { background:var(--muted-2); }+ .ec-tier li.pk-free { padding-left:0; }+ .ec-tier li.pk-free::before { display:none; }+ .pk-tag { flex-shrink:0; margin-top:1px; font-size:9px; font-weight:800; text-transform:uppercase; letter-spacing:.05em;+ padding:2px 7px; border-radius:999px; line-height:1.55; }+ .pk-tag.pk-live { color:var(--green); background:rgba(110,231,168,.13); }+ .pk-tag.pk-planned { color:var(--muted); background:rgba(139,139,150,.14); }.ec-progress { margin:20px 0 0; }.ec-progress .bar { height:8px; border-radius:999px; background:var(--line); overflow:hidden; }.ec-progress .fill { height:100%; border-radius:999px; background:linear-gradient(90deg,var(--green),#a8f0c8);width:0; transition:width 1s var(--ease); }.ec-progress .lbl { display:flex; justify-content:space-between; font-size:12.5px; color:var(--muted); margin-top:9px; }+ /* Your access (personal feature matrix) */+ .ta-panel { border:1px solid var(--line); border-radius:16px; overflow:hidden;+ background:linear-gradient(180deg,var(--panel),var(--panel-2)); }+ .ta-head { display:flex; align-items:center; gap:12px; flex-wrap:wrap; padding:18px 20px; border-bottom:1px solid var(--line); }+ .ta-tier { display:inline-flex; align-items:center; gap:7px; font-size:14px; font-weight:740; color:var(--muted);+ border:1px solid var(--line-2); background:var(--panel); border-radius:999px; padding:7px 13px; }+ .ta-tier.t-member { color:#a7a7b2; }+ .ta-tier.t-bronze { color:#d8a06a; border-color:rgba(216,160,106,.34); background:rgba(216,160,106,.08); }+ .ta-tier.t-silver { color:#cfd6e4; border-color:rgba(207,214,228,.3); background:rgba(207,214,228,.06); }+ .ta-tier.t-gold { color:var(--gold); border-color:rgba(245,196,81,.34); background:rgba(245,196,81,.08); }+ .ta-tier.t-genesis { color:var(--violet); border-color:rgba(196,168,255,.34); background:rgba(196,168,255,.08); }+ .ta-held { font-size:13px; color:var(--muted); font-variant-numeric:tabular-nums; }+ .ta-count { margin-left:auto; font-size:12px; color:var(--muted-2); font-variant-numeric:tabular-nums; }+ .ta-note { margin:0; padding:11px 20px; font-size:12.5px; color:#f0d488; background:rgba(245,196,81,.06);+ border-bottom:1px solid var(--line); }+ .ta-rows { list-style:none; margin:0; padding:0; }+ .ta-row { display:flex; align-items:center; justify-content:space-between; gap:16px; padding:15px 20px;+ border-top:1px solid var(--line); }+ .ta-row:first-child { border-top:none; }+ .ta-row-info { min-width:0; }+ .ta-row-label { display:block; font-size:14px; }+ .ta-why { display:block; font-size:12px; color:var(--muted-2); margin-top:3px; line-height:1.45; }+ .ta-row-status { display:flex; align-items:center; gap:10px; flex-shrink:0; }+ .ta-ppu { font-size:12px; color:var(--muted-2); white-space:nowrap; font-variant-numeric:tabular-nums; }+ .ta-pill { display:inline-flex; align-items:center; gap:6px; font-size:12px; font-weight:700; border-radius:999px;+ padding:5px 11px; white-space:nowrap; }+ .ta-pill--ok { color:var(--green); background:rgba(110,231,168,.1); border:1px solid rgba(110,231,168,.26); }+ .ta-pill--lock { color:#f0d488; background:rgba(245,196,81,.09); border:1px solid rgba(245,196,81,.22); }+ .ta-pill--soon { color:var(--muted); background:rgba(139,139,150,.12); border:1px solid rgba(139,139,150,.24); }+ .ta-row--planned .ta-row-label { color:var(--muted); }+ .ta-empty { border:1px dashed var(--line-2); border-radius:16px; padding:34px 24px; text-align:center;+ background:linear-gradient(180deg,var(--panel),var(--panel-2)); }+ .ta-empty-mark { font-size:30px; color:var(--green); filter:drop-shadow(0 0 12px rgba(110,231,168,.4)); margin-bottom:8px; }+ .ta-empty-title { font-size:18px; font-weight:760; margin:0 0 6px; }+ .ta-empty-sub { font-size:13.5px; color:var(--muted); margin:0 auto 18px; max-width:420px; line-height:1.55; }+ .ta-empty-cta { display:flex; gap:11px; justify-content:center; flex-wrap:wrap; }+ .ta-msg { font-size:12.5px; color:#ff9b9b; margin:12px 0 0; }+ @media (max-width:560px){+ .ta-row{ flex-direction:column; align-items:flex-start; gap:9px; }+ .ta-count{ margin-left:0; }+ }+/* Pricing explorer */.ec-px { display:grid; gap:16px; grid-template-columns:1fr 1fr; }@media (max-width:760px){ .ec-px{ grid-template-columns:1fr; } }@@ -651,18 +703,59 @@ function reflectedHTML(stats) {</div>`;}-function tiersHTML(tierData) {+// One perk line for a tier card, tagged with whether the perk is enforced ("Live")+// or merely registered ("Planned") — so the ladder never claims an unwired feature+// is available today.+function perkLi(label, enforced) {+ const tag = enforced+ ? '<span class="pk-tag pk-live">Live</span>'+ : '<span class="pk-tag pk-planned">Planned</span>';+ return `<li class="${enforced ? 'is-live' : 'is-planned'}"><span class="pk-label">${esc(label)}</span>${tag}</li>`;+}++// A tier's perk list, driven from the LIVE gated-feature matrix (api/three/access)+// grouped by the level that unlocks each feature: the holder fee discount (enforced+// at charge time) leads every paying tier, then each feature it unlocks, marked Live+// or Planned. `byLevel` is null until the matrix loads — until then we show the+// tier's own static copy so the ladder is never empty.+function tierPerksHTML(t, byLevel) {+ if (!byLevel) {+ return (t.perks || []).slice(0, 4).map((p) => `<li><span class="pk-label">${esc(p)}</span></li>`).join('');+ }+ const items = [];+ if (t.discount_bps > 0) {+ items.push(perkLi(`${(t.discount_bps / 100).toFixed(0)}% off all $THREE compute`, true));+ }+ for (const f of byLevel[t.level] || []) {+ items.push(perkLi(f.label, f.enforced !== false));+ }+ if (!items.length) {+ items.push('<li class="pk-free"><span class="pk-label">Everything free-forever — create, discover, embed, social, basic worlds</span></li>');+ }+ return items.join('');+}++function tiersHTML(tierData, features) {const ladder = tierData?.ladder || [];const cur = tierData?.tier?.level ?? null;+ // Group the live gated-feature matrix by the tier level that unlocks each feature,+ // so every tier card lists exactly what holding to it unlocks. Null until loaded.+ let byLevel = null;+ if (Array.isArray(features)) {+ byLevel = {};+ for (const f of features) {+ const lvl = Number(f?.required?.level);+ if (Number.isFinite(lvl)) (byLevel[lvl] ||= []).push(f);+ }+ }const cards = ladder.map((t) => {const is = t.level === cur;- const perks = (t.perks || []).slice(0, 4).map((p) => `<li>${esc(p)}</li>`).join('');return `<div class="ec-tier${is ? ' cur' : ''}">${is ? '<span class="you">You</span>' : ''}<div class="tn">${esc(t.label)}</div>- <div class="tm">${t.min_usd > 0 ? `Hold ${fmtUsd(t.min_usd)}+` : 'Free — everyone'}${t.discount_bps > 0 ? ` · ${(t.discount_bps / 100).toFixed(0)}% off` : ''}</div>- <ul>${perks}</ul>+ <div class="tm">${t.min_usd > 0 ? `Hold ${fmtUsd(t.min_usd)}+` : 'Free — everyone'}</div>+ <ul>${tierPerksHTML(t, byLevel)}</ul></div>`;}).join('');@@ -686,6 +779,78 @@ function tiersHTML(tierData) {return `<div class="ec-tiers">${cards}</div>${progress}`;}+// The signed-out / no-session empty state for the personal access panel — honest and+// actionable (Sign in to resolve a tier, or Get $THREE first), never a dead void.+function accessSignedOutHTML() {+ return `<div class="ta-empty">+ <div class="ta-empty-mark" aria-hidden="true">◆</div>+ <h3 class="ta-empty-title">See what your $THREE unlocks</h3>+ <p class="ta-empty-sub">We resolve your holder tier from your on-chain $THREE. Sign in to see your unlocks here — or get $THREE first.</p>+ <div class="ta-empty-cta">+ <button class="ec-btn primary" id="ec-access-signin" type="button">Sign in</button>+ <a class="ec-btn" href="/three-token">Get $THREE</a>+ </div>+ </div>`;+}++// One feature row: label, a status pill, and (when relevant) a sub-line. A feature+// that isn't enforced yet reads "Planned" — never "Unlocked" — even for a holder who+// is over the bar, so the panel never promises a perk the platform can't yet deliver.+// An enforced, locked perk shows the why + a pay-per-use escape hatch when one exists.+function accessRowHTML(f) {+ const enforced = f.enforced !== false;+ const ok = Boolean(f.eligible);+ const required = f.required?.label || 'a higher tier';+ let pill;+ if (!enforced) {+ pill = '<span class="ta-pill ta-pill--soon">Planned</span>';+ } else if (ok) {+ pill = '<span class="ta-pill ta-pill--ok">Unlocked ✓</span>';+ } else {+ pill = `<span class="ta-pill ta-pill--lock">Hold to ${esc(required)}</span>`;+ }+ const ppu =+ enforced && !ok && f.pay_per_use && Number(f.pay_per_use.usd) > 0+ ? `<span class="ta-ppu">or ${esc(fmtUsd(f.pay_per_use.usd))} / use</span>`+ : '';+ const sub = !enforced+ ? `<span class="ta-why">Unlocks at ${esc(required)} when it ships.</span>`+ : !ok && f.why+ ? `<span class="ta-why">${esc(f.why)}</span>`+ : '';+ const cls = !enforced ? ' ta-row--planned' : ok ? ' ta-row--ok' : '';+ return `<li class="ta-row${cls}">+ <div class="ta-row-info"><span class="ta-row-label">${esc(f.label)}</span>${sub}</div>+ <div class="ta-row-status">${pill}${ppu}</div>+ </li>`;+}++// The populated matrix: a current-tier chip + how many ENFORCED features it unlocks+// (planned perks are counted separately, never as "unlocked"), then one real list row+// per gated feature. A signed-in user with no linked wallet is read as Member and told+// (once) how to fix it, rather than silently shown an all-locked grid.+function accessMatrixHTML(data) {+ const tier = data.tier || { id: 'member', label: 'Member', held_usd: 0 };+ const features = Array.isArray(data.features) ? data.features : [];+ const live = features.filter((f) => f.enforced !== false);+ const unlocked = live.filter((f) => f.eligible).length;+ const planned = features.length - live.length;+ const held = Number(tier.held_usd) > 0 ? `<span class="ta-held">${esc(fmtUsd(tier.held_usd))} held</span>` : '';+ const note =+ data.signed_in && !data.wallet_linked+ ? `<p class="ta-note">Link a Solana wallet to read your real $THREE — you're seeing the Member view.</p>`+ : '';+ return `<div class="ta-panel">+ <div class="ta-head">+ <span class="ta-tier t-${esc(tier.id)}">◆ ${esc(tier.label)}</span>+ ${held}+ <span class="ta-count">${unlocked} of ${live.length} unlocked${planned > 0 ? ` · ${planned} planned` : ''}</span>+ </div>+ ${note}+ <ul class="ta-rows" role="list">${features.map(accessRowHTML).join('')}</ul>+ </div>`;+}+function catalogGroups(actions) {const byCat = {};for (const a of actions) (byCat[a.category] ||= []).push(a);@@ -762,6 +927,13 @@ function shell() {<div id="ec-tiers"><div class="ec-tiers">${'<div class="ec-tier ec-skel" style="height:170px"></div>'.repeat(5)}</div></div></section>+ <section class="ec-section ec-reveal" id="access">+ <p class="ec-htitle">Your access</p>+ <h2 class="ec-h2">What your $THREE unlocks</h2>+ <p class="ec-desc">Your tier, resolved live from your on-chain $THREE — and exactly which holder features it unlocks for you right now.</p>+ <div id="ec-access">${'<div class="ec-skel" style="height:62px;margin-bottom:9px;border-radius:12px"></div>'.repeat(4)}</div>+ </section>+<section class="ec-section ec-reveal" id="pricing"><p class="ec-htitle">What you pay for</p><h2 class="ec-h2">Pricing explorer</h2>@@ -797,6 +969,21 @@ function shell() {let LIVE_PRICE = 0; // $THREE/USD, fetched once for conversionslet DISCOUNT_BPS = 0; // current holder's tier discount+let _accessBound = false; // wallet:changed listener attached once+let _tierData = null; // last /api/three/tier payload (ladder + current tier + progress)+let _accessFeatures = null; // last gated-feature matrix from /api/three/access (Live/Planned)++// Render the holder-tier ladder from whatever we know so far: the ladder + current+// tier from /api/three/tier, and the live gated-feature matrix from /api/three/access+// (which supplies each tier's Live/Planned perks). Either source may arrive first or+// be absent (signed-out / failed call); we fall back to the static ladder so the+// section is never empty. Called by both loaders as their data lands.+function renderTiers() {+ const el = document.getElementById('ec-tiers');+ if (!el) return;+ const td = _tierData?.ladder?.length ? _tierData : { ladder: DEFAULT_LADDER, tier: null, next: null };+ el.innerHTML = tiersHTML(td, _accessFeatures);+}function discountedUsd(usd) {if (!(usd > 0) || DISCOUNT_BPS <= 0) return usd;@@ -1009,14 +1196,33 @@ async function load(root) {// The tier ladder is always-on info content, so render the baseline immediately// (never an empty/error box), then enhance with the holder's live "current" tier- // + progress when the authed call succeeds. A signed-out or failed call simply- // leaves the informative ladder in place.- const tiersEl = document.getElementById('ec-tiers');- if (tiersEl) tiersEl.innerHTML = tiersHTML({ ladder: DEFAULT_LADDER, tier: null, next: null });- getJSON(`${API}/tier`)+ // + progress (loadTier) and each tier's Live/Planned perks (loadAccess) as they+ // land. A signed-out or failed call simply leaves the informative ladder in place.+ renderTiers();+ loadTier();++ // Personal "Your access" panel: what THIS visitor's $THREE unlocks right now. Renders+ // the signed-out empty state for anonymous viewers and the live feature matrix for a+ // holder session, and re-fetches whenever a Solana wallet connects/disconnects so the+ // panel stays truthful without a reload.+ loadAccess();+ if (!_accessBound) {+ _accessBound = true;+ addEventListener('wallet:changed', () => loadAccess());+ }++ wireNameStudio(root);+}++// Fetch + render the holder tier ladder and apply the tier discount to the pricing+// explorer. Reusable so a fresh sign-in can refresh it without a full reload. The+// baseline ladder is already on screen, so any failure simply leaves it in place.+function loadTier() {+ return getJSON(`${API}/tier`).then((t) => {DISCOUNT_BPS = Number(t?.tier?.discount_bps) || 0;- if (tiersEl && t?.ladder?.length) tiersEl.innerHTML = tiersHTML(t);+ if (t?.ladder?.length) _tierData = t;+ renderTiers();// Re-render the price detail now that the discount is known.const sel = document.querySelector('.ec-px-item.sel');if (sel) sel.click();@@ -1024,8 +1230,59 @@ async function load(root) {.catch(() => {/* keep the baseline ladder — it's informative without auth */});+}- wireNameStudio(root);+// Render the personal access panel from /api/three/access. Anonymous → empty state;+// signed-in → the live feature matrix. Degrades to its own error box on failure, so+// the rest of /three (including the always-on ladder above) is unaffected.+function loadAccess() {+ const el = document.getElementById('ec-access');+ return getJSON(`${API}/access`)+ .then((data) => {+ // The matrix feeds both the per-tier Live/Planned perks above and the+ // personal panel below — one call, two surfaces. Features come back for+ // anonymous callers too (all locked), so the ladder enriches regardless.+ _accessFeatures = Array.isArray(data?.features) ? data.features : null;+ renderTiers();+ if (el) {+ el.innerHTML = data?.signed_in ? accessMatrixHTML(data) : accessSignedOutHTML();+ wireAccessActions();+ }+ })+ .catch(() => {+ if (el) el.innerHTML = '<div class="ec-err">Your access is temporarily unavailable.</div>';+ });+}++// Wire the empty-state Sign in button. On success the new session yields the live+// matrix (and refreshes the ladder's "You" chip + the pricing discount); a cancelled+// or failed sign-in restores the button and shows an inline, recoverable message.+function wireAccessActions() {+ const signin = document.getElementById('ec-access-signin');+ if (!signin) return;+ signin.addEventListener('click', async () => {+ const label = signin.textContent;+ signin.disabled = true;+ signin.textContent = 'Signing in…';+ try {+ const { signInWithWallet } = await import('./wallet-auth.js');+ await signInWithWallet();+ await loadAccess();+ loadTier();+ } catch {+ signin.disabled = false;+ signin.textContent = label;+ const cta = signin.closest('.ta-empty-cta');+ if (cta && !document.getElementById('ec-access-msg')) {+ const msg = document.createElement('p');+ msg.id = 'ec-access-msg';+ msg.className = 'ta-msg';+ msg.setAttribute('role', 'alert');+ msg.textContent = 'Sign-in was cancelled or failed. Try again.';+ cta.insertAdjacentElement('afterend', msg);+ }+ }+ });}// Static ladder shape so a signed-out visitor still sees the tiers (the livediff --git a/src/three-gate.css b/src/three-gate.cssnew file mode 100644index 000000000..4d61905d4--- /dev/null+++ b/src/three-gate.css@@ -0,0 +1,561 @@+/* <three-gate> — scoped styles injected into the element's shadow root.+ *+ * Self-contained: the palette is declared on :host (reusing the site's established+ * dark tokens — green/gold/silver on near-black panels) so the component is safe to+ * drop on any page without depending on page-level CSS variables. Every state is+ * designed: loading skeleton, locked card (overlay + replace modes), the brief+ * reveal to unlocked, and an actionable error. Responsive 320 → 1440, reduced-motion+ * aware, full keyboard focus rings. */++:host {+ /* Palette — kept byte-aligned with three-lock.js / three-economy.js. */+ --tg-bg: #0e0e13;+ --tg-bg-2: #0a0a0e;+ --tg-line: #23232c;+ --tg-line-2: #2a2a33;+ --tg-ink: #f6f6f8;+ --tg-muted: #a6a6b0;+ --tg-muted-2: #80808b;+ --tg-green: #6ee7a8;+ --tg-green-2: #9bf0c4;+ --tg-gold: #f5c451;+ --tg-gold-2: #ffd980;+ --tg-silver: #cfd6e4;+ --tg-silver-2: #eef2f8;+ --tg-ease: cubic-bezier(0.22, 1, 0.36, 1);++ display: block;+ position: relative;+ font-family: Inter, system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;+ color: var(--tg-ink);+}++*,+*::before,+*::after {+ box-sizing: border-box;+}++.tg-root {+ position: relative;+}++/* Visually-hidden live region for screen readers (loading announcement). */+.tg-sr {+ position: absolute;+ width: 1px;+ height: 1px;+ padding: 0;+ margin: -1px;+ overflow: hidden;+ clip: rect(0 0 0 0);+ white-space: nowrap;+ border: 0;+}++/* ── The slotted premium UI ──────────────────────────────────────────────── */++.tg-content {+ transition: opacity 0.32s var(--tg-ease), filter 0.32s var(--tg-ease);+}++/* While loading / locked / errored, the real UI is dimmed and frosted behind the+ * veil (overlay mode). Interaction is additionally blocked via the `inert`+ * attribute the component sets on the slotted children, so this is purely visual. */+.tg-root[data-state='loading'] .tg-content,+.tg-root[data-state='locked'] .tg-content,+.tg-root[data-state='error'] .tg-content {+ opacity: 0.34;+ filter: blur(2.5px) saturate(0.82);+ pointer-events: none;+ user-select: none;+}++/* Replace mode hides the real UI entirely until it's unlocked — only the lock+ * card occupies the box. */+.tg-root[data-mode='replace']:not([data-state='unlocked']) .tg-content {+ display: none;+}++/* The unlocked reveal: un-dim and rise in. */+.tg-root[data-state='unlocked'] .tg-content {+ opacity: 1;+ filter: none;+ pointer-events: auto;+ animation: tg-reveal 0.42s var(--tg-ease);+}++/* ── The veil (carries the lock card / skeleton / error) ─────────────────── */++.tg-veil {+ position: absolute;+ inset: 0;+ display: flex;+ align-items: center;+ justify-content: center;+ padding: 18px;+ pointer-events: none; /* re-enabled on the card itself */+}++/* In replace mode the veil takes normal flow so the component has intrinsic height. */+.tg-root[data-mode='replace'] .tg-veil {+ position: relative;+ inset: auto;+}++.tg-root[data-state='unlocked'] .tg-veil {+ display: none;+}++.tg-veil-inner {+ width: min(440px, 100%);+ pointer-events: auto;+}++/* ── Card shell ──────────────────────────────────────────────────────────── */++.tg-card {+ position: relative;+ overflow: hidden;+ border-radius: 18px;+ padding: 20px 20px 18px;+ background: linear-gradient(180deg, var(--tg-bg), var(--tg-bg-2));+ border: 1px solid var(--tg-line);+ box-shadow: 0 24px 60px -28px rgba(0, 0, 0, 0.85);+ backdrop-filter: blur(10px);+ -webkit-backdrop-filter: blur(10px);+ animation: tg-rise 0.3s var(--tg-ease);+}++/* Tier tone — gold for the top tiers, silver, else green (mirrors the badge/lock). */+.tg-card.tg-green {+ border-color: rgba(110, 231, 168, 0.26);+}+.tg-card.tg-silver {+ border-color: rgba(207, 214, 228, 0.26);+}+.tg-card.tg-gold {+ border-color: rgba(245, 196, 81, 0.28);+}++/* A soft glow strip along the card top, tinted by tier. */+.tg-card::before {+ content: '';+ position: absolute;+ top: 0;+ left: 0;+ right: 0;+ height: 1px;+ background: linear-gradient(90deg, transparent, var(--tg-green), transparent);+ opacity: 0.55;+}+.tg-card.tg-silver::before {+ background: linear-gradient(90deg, transparent, var(--tg-silver), transparent);+}+.tg-card.tg-gold::before {+ background: linear-gradient(90deg, transparent, var(--tg-gold), transparent);+}++.tg-card-head {+ display: flex;+ align-items: center;+ gap: 13px;+ margin-bottom: 12px;+}++.tg-glyph {+ flex-shrink: 0;+ width: 42px;+ height: 42px;+ border-radius: 12px;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ color: var(--tg-green);+ background: rgba(110, 231, 168, 0.1);+ border: 1px solid rgba(110, 231, 168, 0.22);+}+.tg-glyph svg {+ width: 21px;+ height: 21px;+}+.tg-silver .tg-glyph {+ color: var(--tg-silver);+ background: rgba(207, 214, 228, 0.1);+ border-color: rgba(207, 214, 228, 0.22);+}+.tg-gold .tg-glyph {+ color: var(--tg-gold);+ background: rgba(245, 196, 81, 0.1);+ border-color: rgba(245, 196, 81, 0.24);+}++.tg-card-titles {+ min-width: 0;+}+.tg-eyebrow {+ margin: 0 0 2px;+ font-size: 11px;+ font-weight: 700;+ letter-spacing: 0.07em;+ text-transform: uppercase;+ color: var(--tg-green);+}+.tg-silver .tg-eyebrow {+ color: var(--tg-silver);+}+.tg-gold .tg-eyebrow {+ color: var(--tg-gold);+}+.tg-label {+ margin: 0;+ font-size: 15.5px;+ font-weight: 800;+ letter-spacing: -0.01em;+ line-height: 1.3;+ color: var(--tg-ink);+}++.tg-why {+ margin: 0 0 14px;+ font-size: 12.5px;+ line-height: 1.5;+ color: var(--tg-muted-2);+ font-style: italic;+}++/* Held vs required */+.tg-meta {+ display: flex;+ align-items: stretch;+ gap: 10px;+ margin: 0 0 12px;+}+.tg-meta-col {+ flex: 1;+ min-width: 0;+ display: flex;+ flex-direction: column;+ gap: 3px;+ padding: 10px 12px;+ border-radius: 11px;+ background: rgba(255, 255, 255, 0.025);+ border: 1px solid var(--tg-line);+}+.tg-meta-col--req {+ border-color: rgba(110, 231, 168, 0.22);+ background: rgba(110, 231, 168, 0.05);+}+.tg-silver .tg-meta-col--req {+ border-color: rgba(207, 214, 228, 0.22);+ background: rgba(207, 214, 228, 0.05);+}+.tg-gold .tg-meta-col--req {+ border-color: rgba(245, 196, 81, 0.22);+ background: rgba(245, 196, 81, 0.06);+}+.tg-meta-k {+ font-size: 10.5px;+ font-weight: 600;+ letter-spacing: 0.05em;+ text-transform: uppercase;+ color: var(--tg-muted-2);+}+.tg-meta-v {+ font-size: 13.5px;+ font-weight: 700;+ color: var(--tg-ink);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}+.tg-meta-arrow {+ align-self: center;+ flex-shrink: 0;+ color: var(--tg-muted-2);+ font-size: 14px;+}++/* Progress (held_usd / required min_usd) */+.tg-prog {+ display: flex;+ align-items: center;+ gap: 10px;+ margin: 0 0 16px;+}+.tg-prog-track {+ flex: 1;+ height: 6px;+ border-radius: 999px;+ background: rgba(255, 255, 255, 0.07);+ overflow: hidden;+}+.tg-prog-fill {+ display: block;+ height: 100%;+ border-radius: 999px;+ background: linear-gradient(90deg, var(--tg-green), var(--tg-green-2));+ transition: width 0.5s var(--tg-ease);+}+.tg-silver .tg-prog-fill {+ background: linear-gradient(90deg, var(--tg-silver), var(--tg-silver-2));+}+.tg-gold .tg-prog-fill {+ background: linear-gradient(90deg, var(--tg-gold), var(--tg-gold-2));+}+.tg-prog-cap {+ flex-shrink: 0;+ font-size: 11px;+ font-weight: 600;+ color: var(--tg-muted);+ white-space: nowrap;+}++/* Actions */+.tg-actions {+ display: flex;+ flex-wrap: wrap;+ gap: 9px;+ align-items: center;+}+.tg-btn {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ font: 700 13px/1 Inter, system-ui, sans-serif;+ padding: 11px 16px;+ border-radius: 11px;+ text-decoration: none;+ cursor: pointer;+ border: 1px solid var(--tg-line-2);+ background: #13131a;+ color: var(--tg-ink);+ transition: transform 0.15s var(--tg-ease), background 0.15s ease, border-color 0.15s ease,+ box-shadow 0.15s ease;+}+.tg-btn--sm {+ padding: 8px 13px;+ font-size: 12px;+}+.tg-btn--primary {+ background: var(--tg-green);+ color: #06120c;+ border-color: var(--tg-green);+ box-shadow: 0 0 0 0 rgba(110, 231, 168, 0);+}+.tg-btn--primary:hover {+ background: var(--tg-green-2);+ transform: translateY(-1px);+ box-shadow: 0 8px 24px -8px rgba(110, 231, 168, 0.55);+}+.tg-silver .tg-btn--primary {+ background: var(--tg-silver);+ color: #10131a;+ border-color: var(--tg-silver);+}+.tg-silver .tg-btn--primary:hover {+ background: var(--tg-silver-2);+ box-shadow: 0 8px 24px -8px rgba(207, 214, 228, 0.5);+}+.tg-gold .tg-btn--primary {+ background: var(--tg-gold);+ color: #1a1303;+ border-color: var(--tg-gold);+}+.tg-gold .tg-btn--primary:hover {+ background: var(--tg-gold-2);+ box-shadow: 0 8px 24px -8px rgba(245, 196, 81, 0.5);+}+.tg-btn--ghost {+ background: #0e0e13;+}+.tg-btn--ghost:hover {+ border-color: #3a3a44;+ background: #181820;+ transform: translateY(-1px);+}++.tg-hold-hint {+ font-size: 12px;+ color: var(--tg-muted);+ line-height: 1.4;+}++.tg-pay {+ margin: 11px 0 0;+ font-size: 12px;+ color: var(--tg-muted);+}+.tg-pay strong {+ color: var(--tg-ink);+ font-weight: 700;+}++.tg-perks {+ display: inline-block;+ margin-top: 14px;+ font-size: 12px;+ font-weight: 600;+ color: var(--tg-muted);+ text-decoration: none;+ transition: color 0.15s ease;+}+.tg-perks:hover {+ color: var(--tg-ink);+ text-decoration: underline;+}++/* ── Loading skeleton ────────────────────────────────────────────────────── */++.tg-card--skel {+ display: flex;+ align-items: center;+ gap: 14px;+}+.tg-skel {+ display: block;+ border-radius: 9px;+ background: linear-gradient(90deg, #15151b, #20202a, #15151b);+ background-size: 200% 100%;+ animation: tg-shimmer 1.3s infinite;+}+.tg-skel--glyph {+ width: 42px;+ height: 42px;+ flex-shrink: 0;+ border-radius: 12px;+}+.tg-skel-lines {+ flex: 1;+ display: flex;+ flex-direction: column;+ gap: 8px;+}+.tg-skel--l1 {+ height: 12px;+ width: 64%;+}+.tg-skel--l2 {+ height: 10px;+ width: 88%;+}+.tg-skel--l3 {+ height: 10px;+ width: 40%;+}++/* ── Error ───────────────────────────────────────────────────────────────── */++.tg-card--err {+ display: flex;+ align-items: center;+ gap: 12px;+ border-color: #3a2222;+ background: linear-gradient(180deg, rgba(34, 18, 18, 0.95), rgba(22, 12, 12, 0.95));+ animation: none;+}+.tg-card--err::before {+ display: none;+}+.tg-err-ico {+ flex-shrink: 0;+ width: 24px;+ height: 24px;+ border-radius: 50%;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ font-weight: 800;+ font-size: 13px;+ color: #ff9b9b;+ background: rgba(255, 120, 120, 0.12);+ border: 1px solid rgba(255, 120, 120, 0.3);+}+.tg-err-body {+ flex: 1;+ min-width: 0;+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+}+.tg-err-text {+ margin: 0;+ font-size: 12.5px;+ color: #f0c2c2;+}++/* ── Focus + motion ──────────────────────────────────────────────────────── */++.tg-btn:focus-visible,+.tg-perks:focus-visible {+ outline: 2px solid var(--tg-green);+ outline-offset: 2px;+}+.tg-gold .tg-btn:focus-visible {+ outline-color: var(--tg-gold);+}+.tg-silver .tg-btn:focus-visible {+ outline-color: var(--tg-silver);+}++@keyframes tg-shimmer {+ 0% {+ background-position: 200% 0;+ }+ 100% {+ background-position: -200% 0;+ }+}+@keyframes tg-rise {+ from {+ opacity: 0;+ transform: translateY(8px);+ }+ to {+ opacity: 1;+ transform: none;+ }+}+@keyframes tg-reveal {+ from {+ opacity: 0;+ transform: translateY(6px) scale(0.995);+ }+ to {+ opacity: 1;+ transform: none;+ }+}++/* ── Responsive ──────────────────────────────────────────────────────────── */++@media (max-width: 420px) {+ .tg-card {+ padding: 16px 15px 15px;+ }+ .tg-meta {+ flex-direction: column;+ gap: 8px;+ }+ .tg-meta-arrow {+ transform: rotate(90deg);+ }+ .tg-actions {+ width: 100%;+ }+ .tg-actions .tg-btn {+ flex: 1;+ }+}++@media (prefers-reduced-motion: reduce) {+ .tg-content,+ .tg-card,+ .tg-prog-fill,+ .tg-btn,+ .tg-skel {+ transition: none;+ animation: none;+ }+}diff --git a/src/three-gate.js b/src/three-gate.jsnew file mode 100644index 000000000..b1d6ffcf7--- /dev/null+++ b/src/three-gate.js@@ -0,0 +1,333 @@+// <three-gate feature="forge.high"> — the drop-in $THREE paywall element.+//+// Wrap any premium UI in this element and it renders a designed lock for+// non-holders (what you hold vs. what's required, why it's gated, a working+// "Get $THREE" path) and reveals the real UI — your slotted children — for+// holders. The host page stays declarative:+//+// <three-gate feature="forge.high">+// <button class="generate-high">Generate (High)</button>+// </three-gate>+//+// Attributes:+// • feature (required) — a gated feature id (forge.high, worlds.private, …).+// • mode (optional) — "overlay" (default): dim + frost the children behind a+// lock card; "replace": hide the children entirely, show only the+// card.+//+// Data comes from GET /api/three/access?feature= (via three-tier-pass.js), which+// already returns the tier, required tier, held USD, lock reason, and the+// pay-per-use price. The server stays the only authority — this element only+// renders affordances; it never grants access on its own.+//+// Emits `three-gate:unlocked` (bubbling, composed) when the holder is eligible, so+// the host can enable its control. Re-checks on `three:tier-changed` and+// `wallet:changed`. Reduced-motion aware, fully keyboard-navigable, scoped styles.++import gateStyles from './three-gate.css?inline';+import { getAccess } from './three-tier-pass.js';+import { log } from './shared/log.js';++// The one and only coin. Hardcoded (matching src/pump/three-token-data.js) so the+// acquire links work even before any access payload resolves.+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+const SOL_MINT = 'So11111111111111111111111111111111111111112';+const JUPITER_SWAP_URL = `https://jup.ag/swap/SOL-${THREE_MINT}`;+const ECONOMY_URL = '/three';+const SIGN_IN_URL = '/login'; // matches src/three-lock.js++const LOCK_GLYPH =+ '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' ++ '<rect x="4.5" y="10.5" width="15" height="10" rx="2.2"/><path d="M8 10.5V7a4 4 0 0 1 8 0v3.5"/><circle cx="12" cy="15.5" r="1.4" fill="currentColor" stroke="none"/></svg>';++function escapeHtml(s) {+ return String(s ?? '').replace(+ /[&<>"']/g,+ (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],+ );+}++// Compact USD: integers for ≥ $1, fixed two decimals for sub-dollar amounts+// (so a $0.50 pay-per-use reads as currency, not "$0.5"), "$0" floor.+function fmtUsd(n) {+ const v = Number(n) || 0;+ if (v <= 0) return '$0';+ if (v < 1) {+ return `$${v.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;+ }+ return `$${v.toLocaleString('en-US', { maximumFractionDigits: 0 })}`;+}++// Tier tone, mirroring three-lock.js / nav-tier-badge so the gate reads as one system.+function tierTone(id) {+ if (id === 'gold' || id === 'genesis') return 'tg-gold';+ if (id === 'silver') return 'tg-silver';+ return 'tg-green';+}++// Open the in-page Jupiter swap when a Solana wallet is present; otherwise fall+// back to the canonical Jupiter swap URL in a new tab. Mirrors the buy flow in+// src/three-token-page.js so "Get $THREE" behaves consistently across the site.+async function acquireThree() {+ const provider =+ (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 wallet = resp?.publicKey?.toString?.();+ if (wallet) {+ const mod = await import('./swap-jupiter.js').catch(() => null);+ if (mod && typeof mod.openSwapModal === 'function') {+ mod.openSwapModal({+ wallet,+ getProvider: () => provider,+ defaultInputMint: SOL_MINT,+ defaultOutputMint: THREE_MINT,+ });+ return;+ }+ }+ } catch {+ /* fall through to the hosted swap URL */+ }+ }+ window.open(JUPITER_SWAP_URL, '_blank', 'noopener');+}++// Run the same connect flow the nav button uses, without coupling to it: prefer the+// programmatic export, else click an on-page connect button if one exists.+async function connectWallet() {+ try {+ const mod = await import('./wallet.js').catch(() => null);+ if (mod && typeof mod.connectWallet === 'function') {+ await mod.connectWallet();+ return;+ }+ } catch {+ /* fall through */+ }+ document.getElementById('connect-wallet-btn')?.click();+}++class ThreeGate extends HTMLElement {+ static get observedAttributes() {+ return ['feature', 'mode'];+ }++ constructor() {+ super();+ this._root = this.attachShadow({ mode: 'open' });+ this._reqToken = 0; // guards against a stale fetch resolving after a newer one+ this._gatedChildren = []; // light-DOM children we marked inert while locked+ this._onExternalChange = this._onExternalChange.bind(this);+ this._scheduled = false;+ this._root.innerHTML = `<style>${gateStyles}</style>+ <div class="tg-root" data-state="loading" data-mode="overlay">+ <div class="tg-content"><slot></slot></div>+ <div class="tg-veil"><div class="tg-veil-inner"></div></div>+ </div>`;+ this._rootEl = this._root.querySelector('.tg-root');+ this._veil = this._root.querySelector('.tg-veil-inner');+ }++ connectedCallback() {+ this._rootEl.dataset.mode = this._mode();+ this._renderLoading();+ this.refresh();+ window.addEventListener('three:tier-changed', this._onExternalChange);+ window.addEventListener('wallet:changed', this._onExternalChange);+ }++ disconnectedCallback() {+ window.removeEventListener('three:tier-changed', this._onExternalChange);+ window.removeEventListener('wallet:changed', this._onExternalChange);+ this._setGatedInert(false);+ }++ attributeChangedCallback(name, oldVal, newVal) {+ if (oldVal === newVal || !this.isConnected) return;+ if (name === 'mode') this._rootEl.dataset.mode = this._mode();+ this.refresh();+ }++ _mode() {+ return this.getAttribute('mode') === 'replace' ? 'replace' : 'overlay';+ }++ // `three:tier-changed` is dispatched off `wallet:changed`, so both can fire for a+ // single connect — coalesce into one refresh on the next frame.+ _onExternalChange() {+ if (this._scheduled) return;+ this._scheduled = true;+ const run = () => {+ this._scheduled = false;+ if (this.isConnected) this.refresh();+ };+ if (typeof requestAnimationFrame === 'function') requestAnimationFrame(run);+ else setTimeout(run, 0);+ }++ /** Re-read access and render the matching state. Safe to call repeatedly. */+ async refresh() {+ const feature = (this.getAttribute('feature') || '').trim();+ if (!feature) {+ // A gate with no feature can't be evaluated — fail closed (never reveal the+ // premium UI) and surface the misconfiguration to the developer.+ log.warn('[three-gate] missing required "feature" attribute — staying locked.');+ this._renderError(false);+ return;+ }++ const token = ++this._reqToken;+ this._renderLoading();+ const data = await getAccess(feature);+ if (token !== this._reqToken || !this.isConnected) return; // superseded++ const access = data?.access;+ if (data?._error || !access) {+ this._renderError(true);+ return;+ }+ if (access.eligible) {+ this._renderUnlocked(data.tier || access.held);+ return;+ }+ this._renderLocked(access);+ }++ // ── State renderers ──────────────────────────────────────────────────────++ _renderLoading() {+ this._setGatedInert(true);+ this._rootEl.dataset.state = 'loading';+ this._veil.innerHTML =+ `<div class="tg-card tg-card--skel" aria-hidden="true">` ++ `<span class="tg-skel tg-skel--glyph"></span>` ++ `<span class="tg-skel-lines"><span class="tg-skel tg-skel--l1"></span>` ++ `<span class="tg-skel tg-skel--l2"></span><span class="tg-skel tg-skel--l3"></span></span>` ++ `</div>` ++ `<span class="tg-sr" role="status">Checking your $THREE access…</span>`;+ }++ _renderError(retryable) {+ this._setGatedInert(true);+ this._rootEl.dataset.state = 'error';+ this._veil.innerHTML =+ `<div class="tg-card tg-card--err" role="alert">` ++ `<span class="tg-err-ico" aria-hidden="true">!</span>` ++ `<div class="tg-err-body">` ++ `<p class="tg-err-text">Couldn’t check your $THREE access.</p>` ++ (retryable+ ? `<button type="button" class="tg-btn tg-btn--ghost tg-btn--sm" data-tg-retry>Retry</button>`+ : '') ++ `</div></div>`;+ const retry = this._veil.querySelector('[data-tg-retry]');+ if (retry) retry.addEventListener('click', () => this.refresh());+ }++ _renderUnlocked(tier) {+ this._setGatedInert(false);+ this._rootEl.dataset.state = 'unlocked';+ this._veil.innerHTML = '';+ this.dispatchEvent(+ new CustomEvent('three-gate:unlocked', {+ bubbles: true,+ composed: true,+ detail: { feature: this.getAttribute('feature'), tier: tier || null },+ }),+ );+ }++ _renderLocked(access) {+ this._setGatedInert(true);+ this._rootEl.dataset.state = 'locked';++ const required = access.required || { label: 'a higher tier', id: '', min_usd: 0 };+ const held = access.held || { label: 'Member', id: 'member', usd: 0 };+ const reason = access.reason || 'insufficient_tier';+ 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 secondary =+ reason === 'sign_in'+ ? `<a class="tg-btn tg-btn--ghost" href="${SIGN_IN_URL}">Sign in</a>`+ : reason === 'link_wallet'+ ? `<button type="button" class="tg-btn tg-btn--ghost" data-tg-connect>Connect wallet</button>`+ : `<span class="tg-hold-hint">Hold to unlock — your tier is read live from your wallet.</span>`;++ this._veil.innerHTML =+ `<div class="tg-card ${tone}" role="group" aria-label="Locked — requires ${escapeHtml(required.label)} ($THREE holder)">` ++ `<div class="tg-card-head">` ++ `<span class="tg-glyph">${LOCK_GLYPH}</span>` ++ `<div class="tg-card-titles">` ++ `<p class="tg-eyebrow">$THREE holder perk</p>` ++ `<h3 class="tg-label">${escapeHtml(access.label || 'Holder feature')}</h3>` ++ `</div></div>` ++ (access.why ? `<p class="tg-why">${escapeHtml(access.why)}</p>` : '') ++ `<div class="tg-meta">` ++ `<div class="tg-meta-col"><span class="tg-meta-k">You hold</span>` ++ `<span class="tg-meta-v">${fmtUsd(heldUsd)} · ${escapeHtml(held.label || 'Member')}</span></div>` ++ `<span class="tg-meta-arrow" aria-hidden="true">→</span>` ++ `<div class="tg-meta-col tg-meta-col--req"><span class="tg-meta-k">Requires</span>` ++ `<span class="tg-meta-v">${escapeHtml(required.label)} · ${fmtUsd(reqMin)}</span></div>` ++ `</div>` ++ `<div class="tg-prog">` ++ `<span class="tg-prog-track"><span class="tg-prog-fill" style="width:${pct}%"></span></span>` ++ `<span class="tg-prog-cap">${pct}% there</span>` ++ `</div>` ++ `<div class="tg-actions">` ++ `<a class="tg-btn tg-btn--primary" data-tg-get href="${JUPITER_SWAP_URL}" target="_blank" rel="noopener">Get $THREE</a>` ++ secondary ++ `</div>` ++ (pay+ ? `<p class="tg-pay">or pay <strong>${fmtUsd(pay.usd)}</strong> per use</p>`+ : '') ++ `<a class="tg-perks" href="${ECONOMY_URL}">See all holder perks →</a>` ++ `</div>`;++ this._wireLocked();+ }++ _wireLocked() {+ const get = this._veil.querySelector('[data-tg-get]');+ if (get) {+ get.addEventListener('click', (e) => {+ e.preventDefault();+ acquireThree();+ });+ }+ const connect = this._veil.querySelector('[data-tg-connect]');+ if (connect) connect.addEventListener('click', () => connectWallet());+ }++ // Block keyboard/AT interaction with the gated children while locked. `inert`+ // removes them from the tab order and the accessibility tree; we only touch the+ // children we set so re-entrancy can't strand a child as permanently inert.+ _setGatedInert(on) {+ if (on) {+ for (const child of Array.from(this.children)) {+ if (child.nodeType !== 1) continue;+ child.inert = true;+ if (!this._gatedChildren.includes(child)) this._gatedChildren.push(child);+ }+ } else {+ for (const child of this._gatedChildren) {+ try {+ child.inert = false;+ } catch {+ /* child detached — nothing to clear */+ }+ }+ this._gatedChildren = [];+ }+ }+}++if (typeof customElements !== 'undefined' && !customElements.get('three-gate')) {+ customElements.define('three-gate', ThreeGate);+}++export { ThreeGate };diff --git a/src/three-lock.js b/src/three-lock.jsnew file mode 100644index 000000000..df4241208--- /dev/null+++ b/src/three-lock.js@@ -0,0 +1,360 @@+// $THREE lock — the in-place, designed gate that renders over a holder-gated+// control. Sibling to three-access.js: that module owns the data (access matrix,+// tier pass) and the full-screen upsell modal; this one owns the *affordance the+// user sees on the control itself* — a frosted lock panel in every state:+//+// • loading — skeleton shimmer while access is being checked.+// • locked — frosted overlay + lock glyph, "Requires {tier} — hold $THREE",+// the held-vs-required progress, and a working Get $THREE CTA+// (plus reason-specific secondaries: Sign in / Link a wallet /+// Use a free tier / Pay per use when a handler is supplied).+// • unlocked — a subtle "✓ Unlocked · {tier}" ribbon, no overlay.+// • error — inline, actionable: "Couldn't check access — retry".+// • cleared — empty + hidden (the control is ungated).+//+// One entry point: renderLock(target, state). Pass the access payload through+// lockStateFromAccess() to map it to a state, or build the state object by hand.+// Fully keyboard-navigable (real <a>/<button>), ARIA-labelled, reduced-motion+// aware, and responsive. Never throws — a missing target is a no-op.++const ECONOMY_URL = '/three';+const SIGN_IN_URL = '/login';+const LINK_WALLET_URL = '/dashboard/account#wallets';++let _stylesInjected = false;++function escapeHtml(s) {+ return String(s ?? '').replace(+ /[&<>"']/g,+ (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],+ );+}++function resolveEl(target) {+ return typeof target === 'string' ? document.querySelector(target) : target;+}++// Tone class by tier id, mirroring three-access.js so the lock, the badge, and+// the upsell modal read as one system (gold for the top tiers, silver, else green).+function tierTone(id) {+ if (id === 'gold' || id === 'genesis') return 'tl-gold';+ if (id === 'silver') return 'tl-silver';+ return 'tl-green';+}++function usdLabel(usd) {+ const n = Number(usd) || 0;+ if (n <= 0) return '';+ return `≈ $${n.toLocaleString('en-US', { maximumFractionDigits: 0 })}`;+}++const LOCK_GLYPH =+ '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' ++ '<rect x="4.5" y="10.5" width="15" height="10" rx="2.2"/><path d="M8 10.5V7a4 4 0 0 1 8 0v3.5"/><circle cx="12" cy="15.5" r="1.4" fill="currentColor" stroke="none"/></svg>';++/**+ * Map a single-feature access payload (the `.access` object from+ * getAccess(feature)) to a renderLock state. `extra` is merged in so callers can+ * attach handlers/urls (onGetThree, onPayPerUse, onUseFree, getThreeUrl). A null+ * access (network failure) maps to the error state so the UI degrades safely.+ */+export function lockStateFromAccess(access, extra = {}) {+ if (!access) return { error: true, ...extra };+ if (access.eligible) return { eligible: true, tier: access.held, ...extra };+ const pay = access.pay_per_use && access.pay_per_use.usd != null ? access.pay_per_use : null;+ return {+ feature: access.feature,+ label: access.label,+ why: access.why,+ required: access.required,+ held: access.held,+ reason: access.reason,+ payPerUse: pay,+ ...extra,+ };+}++/**+ * Render the lock for a gated control into `target`.+ * @param {Element|string} target+ * @param {object} state one of:+ * { clear:true } → empty + hidden+ * { loading:true } → skeleton shimmer+ * { error:true, onRetry? } → inline retry+ * { eligible:true, tier:{id,label} } → unlocked ribbon+ * { required, held, reason, payPerUse?, label?, why?,+ * getThreeUrl?, onGetThree?, onPayPerUse?, onUseFree?, useFreeLabel? } → locked+ */+export function renderLock(target, state = {}) {+ const el = resolveEl(target);+ if (!el) return;+ injectStyles();+ el.classList.add('tl-host');++ if (!state || state.clear) {+ el.hidden = true;+ el.innerHTML = '';+ return;+ }+ el.hidden = false;++ if (state.loading) {+ el.innerHTML = renderLoading();+ return;+ }+ if (state.error) {+ el.innerHTML = renderError();+ const retry = el.querySelector('[data-tl-retry]');+ if (retry && typeof state.onRetry === 'function') {+ retry.addEventListener('click', () => state.onRetry());+ } else if (retry) {+ retry.remove();+ }+ return;+ }+ if (state.eligible) {+ el.innerHTML = renderUnlocked(state.tier || {});+ return;+ }++ el.innerHTML = renderLocked(state);+ wireLocked(el, state);+}++// ── State renderers ─────────────────────────────────────────────────────────++function renderLoading() {+ return (+ `<div class="tl-card tl-card--skel" aria-hidden="true">` ++ `<span class="tl-skel tl-skel--glyph"></span>` ++ `<span class="tl-skel-lines"><span class="tl-skel tl-skel--l1"></span><span class="tl-skel tl-skel--l2"></span></span>` ++ `</div>` ++ `<span class="tl-sr" role="status">Checking your $THREE access…</span>`+ );+}++function renderError() {+ return (+ `<div class="tl-card tl-card--err" role="alert">` ++ `<span class="tl-err-ico" aria-hidden="true">!</span>` ++ `<span class="tl-err-text">Couldn’t check access.</span>` ++ `<button type="button" class="tl-btn tl-btn--ghost tl-btn--sm" data-tl-retry>Retry</button>` ++ `</div>`+ );+}++function renderUnlocked(tier) {+ const tone = tierTone(tier.id);+ const label = escapeHtml(tier.label || 'Holder');+ return (+ `<div class="tl-ribbon ${tone}" role="status">` ++ `<span class="tl-ribbon-ico" aria-hidden="true">✓</span>` ++ `<span>Unlocked · <strong>${label}</strong></span>` ++ `</div>`+ );+}++function renderLocked(state) {+ const required = state.required || { label: 'a higher tier', id: '' };+ const held = state.held || { label: 'Member', level: 0 };+ const reason = state.reason || 'insufficient_tier';+ const tone = tierTone(required.id);+ const getUrl = escapeHtml(state.getThreeUrl || ECONOMY_URL);++ const sub =+ reason === 'sign_in'+ ? 'Sign in to check your tier.'+ : reason === 'link_wallet'+ ? 'Link a Solana wallet so we can read your $THREE.'+ : heldLine(held);++ const progress = reason === 'insufficient_tier' ? renderProgress(held, required) : '';++ const actions = [+ `<a class="tl-btn tl-btn--primary" data-tl-get href="${getUrl}">Get $THREE</a>`,+ ];+ if (reason === 'sign_in') {+ actions.push(`<a class="tl-btn tl-btn--ghost" href="${SIGN_IN_URL}">Sign in</a>`);+ } else if (reason === 'link_wallet') {+ actions.push(`<a class="tl-btn tl-btn--ghost" href="${LINK_WALLET_URL}">Link a wallet</a>`);+ }+ // Pay-per-use is only offered when the caller wires a working handler — a+ // button that does nothing is worse than no button.+ if (state.payPerUse && typeof state.onPayPerUse === 'function') {+ actions.push(+ `<button type="button" class="tl-btn tl-btn--ghost" data-tl-pay>Pay $${Number(state.payPerUse.usd).toFixed(2)} per generation</button>`,+ );+ }+ if (typeof state.onUseFree === 'function') {+ actions.push(+ `<button type="button" class="tl-btn tl-btn--quiet" data-tl-free>${escapeHtml(state.useFreeLabel || 'Use a free tier')}</button>`,+ );+ }++ const feature = escapeHtml(state.label || 'This is a $THREE holder feature.');++ return (+ `<div class="tl-card tl-card--lock ${tone}" role="group" aria-label="Locked — requires ${escapeHtml(required.label)} ($THREE holder)">` ++ `<span class="tl-glyph" aria-hidden="true">${LOCK_GLYPH}</span>` ++ `<div class="tl-body">` ++ `<p class="tl-headline">Requires <strong>${escapeHtml(required.label)}</strong> — hold $THREE</p>` ++ `<p class="tl-sub">${sub}</p>` ++ (state.why ? `<p class="tl-why">${escapeHtml(state.why)}</p>` : '') ++ progress ++ `<div class="tl-actions">${actions.join('')}</div>` ++ `<p class="tl-foot">${feature}</p>` ++ `</div>` ++ `</div>`+ );+}++function heldLine(held) {+ const usd = usdLabel(held.usd);+ return `You hold <strong>${escapeHtml(held.label || 'Member')}</strong>${usd ? ` (${usd})` : ''}.`;+}++// A small held→required tier-ladder track. Honest with the data we have (tier+// levels, not exact thresholds): the fill is the held level as a fraction of the+// required level, so a Silver holder facing a Gold gate reads as two-thirds there.+function renderProgress(held, required) {+ const reqLevel = Math.max(1, Number(required.level) || 1);+ const heldLevel = Math.max(0, Number(held.level) || 0);+ const pct = Math.min(100, Math.round((heldLevel / reqLevel) * 100));+ return (+ `<div class="tl-prog" role="presentation">` ++ `<span class="tl-prog-track"><span class="tl-prog-fill" style="width:${pct}%"></span></span>` ++ `<span class="tl-prog-cap">${escapeHtml(held.label || 'Member')} → <strong>${escapeHtml(required.label)}</strong></span>` ++ `</div>`+ );+}++function wireLocked(el, state) {+ const get = el.querySelector('[data-tl-get]');+ if (get && typeof state.onGetThree === 'function') {+ get.addEventListener('click', (e) => {+ e.preventDefault();+ state.onGetThree();+ });+ }+ const pay = el.querySelector('[data-tl-pay]');+ if (pay && typeof state.onPayPerUse === 'function') {+ pay.addEventListener('click', () => state.onPayPerUse(state.payPerUse));+ }+ const free = el.querySelector('[data-tl-free]');+ if (free && typeof state.onUseFree === 'function') {+ free.addEventListener('click', () => state.onUseFree());+ }+}++// ── Styles ───────────────────────────────────────────────────────────────────++function injectStyles() {+ if (_stylesInjected || typeof document === 'undefined') return;+ _stylesInjected = true;+ const css = `+ .tl-host{display:block;margin:10px 0 2px;font-family:Inter,system-ui,sans-serif;}+ .tl-sr{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;+ clip:rect(0 0 0 0);white-space:nowrap;border:0;}++ /* Frosted lock panel */+ .tl-card{position:relative;display:flex;gap:13px;align-items:flex-start;+ border-radius:16px;padding:15px 16px;overflow:hidden;+ background:linear-gradient(180deg,rgba(20,20,27,.92),rgba(12,12,17,.92));+ border:1px solid #23232c;backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px);+ box-shadow:0 14px 40px -22px rgba(0,0,0,.85);+ animation:tl-rise .26s cubic-bezier(.22,1,.36,1);}+ .tl-card--lock.tl-green{border-color:rgba(110,231,168,.28);}+ .tl-card--lock.tl-silver{border-color:rgba(207,214,228,.28);}+ .tl-card--lock.tl-gold{border-color:rgba(245,196,81,.30);}++ .tl-glyph{flex-shrink:0;width:38px;height:38px;border-radius:11px;display:inline-flex;+ align-items:center;justify-content:center;color:#6ee7a8;+ background:rgba(110,231,168,.1);border:1px solid rgba(110,231,168,.22);}+ .tl-glyph svg{width:19px;height:19px;}+ .tl-silver .tl-glyph{color:#cfd6e4;background:rgba(207,214,228,.1);border-color:rgba(207,214,228,.22);}+ .tl-gold .tl-glyph{color:#f5c451;background:rgba(245,196,81,.1);border-color:rgba(245,196,81,.24);}++ .tl-body{min-width:0;flex:1;}+ .tl-headline{margin:0 0 3px;font-size:13.5px;font-weight:700;color:#f6f6f8;line-height:1.35;}+ .tl-headline strong{color:#6ee7a8;}+ .tl-silver .tl-headline strong{color:#dfe5ef;}+ .tl-gold .tl-headline strong{color:#f5c451;}+ .tl-sub{margin:0 0 6px;font-size:12.5px;color:#a6a6b0;line-height:1.5;}+ .tl-sub strong{color:#e9e9ee;}+ .tl-why{margin:0 0 9px;font-size:11.5px;color:#7c7c86;font-style:italic;line-height:1.5;}++ .tl-prog{display:flex;align-items:center;gap:9px;margin:0 0 12px;}+ .tl-prog-track{flex:1;height:6px;border-radius:999px;background:rgba(255,255,255,.07);overflow:hidden;}+ .tl-prog-fill{display:block;height:100%;border-radius:999px;+ background:linear-gradient(90deg,#6ee7a8,#9bf0c4);transition:width .4s cubic-bezier(.22,1,.36,1);}+ .tl-silver .tl-prog-fill{background:linear-gradient(90deg,#cfd6e4,#eef2f8);}+ .tl-gold .tl-prog-fill{background:linear-gradient(90deg,#f5c451,#ffd980);}+ .tl-prog-cap{flex-shrink:0;font-size:11px;color:#8c8c96;white-space:nowrap;}+ .tl-prog-cap strong{color:#cfcfd6;}++ .tl-actions{display:flex;flex-wrap:wrap;gap:8px;}+ .tl-btn{display:inline-flex;align-items:center;justify-content:center;font:700 12.5px/1 Inter,system-ui,sans-serif;+ padding:9px 14px;border-radius:10px;text-decoration:none;cursor:pointer;border:1px solid #2a2a33;+ background:#13131a;color:#f1f1f4;transition:transform .15s cubic-bezier(.22,1,.36,1),+ background .15s ease,border-color .15s ease;}+ .tl-btn--sm{padding:7px 11px;font-size:12px;}+ .tl-btn--primary{background:#6ee7a8;color:#06120c;border-color:#6ee7a8;}+ .tl-btn--primary:hover{background:#8af0c0;transform:translateY(-1px);}+ .tl-silver .tl-btn--primary{background:#dfe5ef;color:#10131a;border-color:#dfe5ef;}+ .tl-silver .tl-btn--primary:hover{background:#eef2f8;}+ .tl-gold .tl-btn--primary{background:#f5c451;color:#1a1303;border-color:#f5c451;}+ .tl-gold .tl-btn--primary:hover{background:#ffd980;}+ .tl-btn--ghost:hover{border-color:#3a3a44;background:#181820;transform:translateY(-1px);}+ .tl-btn--quiet{background:transparent;border-color:transparent;color:#9a9aa4;padding-left:8px;padding-right:8px;}+ .tl-btn--quiet:hover{color:#e9e9ee;background:rgba(255,255,255,.04);}+ .tl-foot{margin:11px 0 0;font-size:11px;color:#6c6c76;line-height:1.5;}++ /* Unlocked ribbon */+ .tl-ribbon{display:inline-flex;align-items:center;gap:7px;font:700 12.5px/1 Inter,system-ui,sans-serif;+ padding:8px 13px;border-radius:999px;color:#6ee7a8;+ background:rgba(110,231,168,.1);border:1px solid rgba(110,231,168,.26);+ animation:tl-rise .26s cubic-bezier(.22,1,.36,1);}+ .tl-ribbon strong{font-weight:800;}+ .tl-ribbon-ico{font-size:11px;}+ .tl-ribbon.tl-silver{color:#dfe5ef;background:rgba(207,214,228,.1);border-color:rgba(207,214,228,.26);}+ .tl-ribbon.tl-gold{color:#f5c451;background:rgba(245,196,81,.11);border-color:rgba(245,196,81,.28);}++ /* Error */+ .tl-card--err{align-items:center;gap:10px;border-color:#3a2222;+ background:linear-gradient(180deg,rgba(34,18,18,.92),rgba(22,12,12,.92));}+ .tl-err-ico{flex-shrink:0;width:22px;height:22px;border-radius:50%;display:inline-flex;+ align-items:center;justify-content:center;font-weight:800;font-size:13px;+ color:#ff9b9b;background:rgba(255,120,120,.12);border:1px solid rgba(255,120,120,.3);}+ .tl-err-text{flex:1;font-size:12.5px;color:#f0c2c2;}++ /* Loading skeleton */+ .tl-card--skel{gap:13px;align-items:center;}+ .tl-skel{display:block;border-radius:9px;+ background:linear-gradient(90deg,#15151b,#20202a,#15151b);background-size:200% 100%;+ animation:tl-sh 1.3s infinite;}+ .tl-skel--glyph{width:38px;height:38px;flex-shrink:0;border-radius:11px;}+ .tl-skel-lines{flex:1;display:flex;flex-direction:column;gap:7px;}+ .tl-skel--l1{height:11px;width:72%;}+ .tl-skel--l2{height:11px;width:46%;}++ .tl-btn:focus-visible,.tl-ribbon:focus-visible{outline:2px solid #6ee7a8;outline-offset:2px;}++ @keyframes tl-sh{0%{background-position:200% 0}100%{background-position:-200% 0}}+ @keyframes tl-rise{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}}++ @media (max-width:480px){+ .tl-card{flex-direction:column;}+ .tl-actions{width:100%;}+ .tl-btn{flex:1;}+ .tl-prog-cap{white-space:normal;}+ }+ @media (prefers-reduced-motion: reduce){+ .tl-card,.tl-ribbon{animation:none;}+ .tl-skel{animation:none;}+ .tl-prog-fill,.tl-btn{transition:none;}+ }`;+ const el = document.createElement('style');+ el.id = 'tl-styles';+ el.textContent = css;+ document.head.appendChild(el);+}diff --git a/src/three-tier-pass.js b/src/three-tier-pass.jsnew file mode 100644index 000000000..7a1a29b10--- /dev/null+++ b/src/three-tier-pass.js@@ -0,0 +1,205 @@+// $THREE tier-pass helper — the tiny, dependency-free seam every gated surface+// uses to (a) read the caller's hold-to-access tier and (b) carry a portable,+// RPC-free proof of holder tier on a gated request.+//+// Two server reads back it:+// • GET /api/three/access?feature=… — the tier + per-feature entitlement matrix+// (auth optional; anonymous callers get the Member view so a page can render a+// locked state without forcing sign-in).+// • POST /api/three/tier-pass — mints a short-lived (10 min) HMAC-signed+// pass bound to the holder's wallet. A gated endpoint trusts the pass even when+// a live RPC read would hiccup, so a holder is never locked out by an outage.+//+// The pass is cached in memory AND sessionStorage so it survives in-tab navigation+// without re-minting, and is treated as stale ~2 min before the server expiry+// (≈ 8 min of useful life) so a request never rides a pass that expires mid-flight.+//+// Resilience contract: every network path is try/caught and degrades gracefully —+// getTierPass() → null, getAccess() → a Member-shaped fallback. Nothing here ever+// throws to the caller, and the server stays the only authority on eligibility.++const ACCESS_URL = '/api/three/access';+const TIER_PASS_URL = '/api/three/tier-pass';+const PASS_STORE_KEY = 'three_tier_pass';++// Passes live 10 min server-side; re-mint ~2 min early so an in-flight gated+// request never carries an about-to-expire pass.+const PASS_STALE_BEFORE_EXP_MS = 2 * 60 * 1000;+// Fallback lifetime when the pass payload's exp can't be decoded (~8 min useful).+const PASS_FALLBACK_TTL_MS = 8 * 60 * 1000;++// In-memory cache: { pass: string, exp: number(ms) } or null.+let _cache = null;++// ── helpers ─────────────────────────────────────────────────────────────────++const hasWindow = typeof window !== 'undefined';++// base64url → JSON. The tier pass is `<payload>.<sig>`; the payload carries `exp`+// in unix seconds. Returns the expiry in ms, or 0 when it can't be decoded.+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;+ }+}++function isFresh(entry) {+ return Boolean(entry && entry.pass && entry.exp - PASS_STALE_BEFORE_EXP_MS > Date.now());+}++// sessionStorage access can throw (private mode, disabled storage) — never let it.+function readStored() {+ if (!hasWindow) return null;+ try {+ const raw = window.sessionStorage.getItem(PASS_STORE_KEY);+ if (!raw) return null;+ const entry = JSON.parse(raw);+ if (entry && typeof entry.pass === 'string' && Number.isFinite(entry.exp)) return entry;+ return null;+ } catch {+ return null;+ }+}++function writeStored(entry) {+ if (!hasWindow) return;+ try {+ window.sessionStorage.setItem(PASS_STORE_KEY, JSON.stringify(entry));+ } catch {+ /* storage full / unavailable — the in-memory cache still serves this tab */+ }+}++function dropStored() {+ if (!hasWindow) return;+ try {+ window.sessionStorage.removeItem(PASS_STORE_KEY);+ } catch {+ /* ignore */+ }+}++// A Member-shaped access payload so a caller can always render a safe locked state+// after a network failure. `_error` flags the degraded read so a richer UI (the+// <three-gate> element) can show "couldn't check — retry" instead of a wrong lock.+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,+ },+ };+}++// ── public API ──────────────────────────────────────────────────────────────++/**+ * Mint (or reuse) the signed $THREE tier pass for the current caller.+ * @returns {Promise<string|null>} the cached/fresh pass string, or null when the+ * caller is anonymous / has no linked wallet (the endpoint 401/403s) or on any+ * network failure — callers then simply omit the x-three-tier-pass header.+ */+export async function getTierPass() {+ if (isFresh(_cache)) return _cache.pass;++ // A pass minted earlier this tab session is still good after a soft navigation.+ const stored = readStored();+ if (isFresh(stored)) {+ _cache = stored;+ return _cache.pass;+ }++ try {+ const r = await fetch(TIER_PASS_URL, { method: 'POST', credentials: 'include' });+ if (!r.ok) {+ // 401/403 → anonymous or no linked wallet: there's no pass to hold.+ clearTierPass();+ return null;+ }+ const data = await r.json().catch(() => null);+ const pass = data && typeof data.pass === 'string' ? data.pass : null;+ if (!pass) {+ clearTierPass();+ return null;+ }+ const exp = decodePassExpMs(pass) || Date.now() + PASS_FALLBACK_TTL_MS;+ _cache = { pass, exp };+ writeStored(_cache);+ return pass;+ } catch {+ // Transient network error — leave any existing cache for the next attempt.+ return null;+ }+}++/**+ * Read the hold-to-access matrix (no arg) or a single feature's entitlement.+ * @param {string} [feature] a gated feature id (e.g. 'forge.high').+ * @returns {Promise<object>} the parsed payload, or a Member-shaped fallback+ * (flagged `_error: true`) on any network failure. Never throws.+ * Feature shape: { signed_in, wallet_linked, tier:{level,id,label,held_usd},+ * access:{ feature, label, why, eligible, required, held,+ * reason, pay_per_use } }+ */+export async function getAccess(feature) {+ const url = feature ? `${ACCESS_URL}?feature=${encodeURIComponent(feature)}` : ACCESS_URL;+ try {+ const r = await fetch(url, { credentials: 'include' });+ if (!r.ok) return memberFallback(feature);+ const data = await r.json().catch(() => null);+ return data && typeof data === 'object' ? data : memberFallback(feature);+ } catch {+ return memberFallback(feature);+ }+}++/**+ * Headers to spread into a gated fetch so an eligible holder's entitlement rides+ * along. Returns { 'x-three-tier-pass': <pass> } when a pass is available, else {}.+ * @returns {Promise<Record<string,string>>}+ */+export async function threeHeaders() {+ const pass = await getTierPass();+ return pass ? { 'x-three-tier-pass': pass } : {};+}++/** Drop the cached pass (memory + sessionStorage). Call on wallet change / sign-out. */+export function clearTierPass() {+ _cache = null;+ dropStored();+}++// ── auto-wire ───────────────────────────────────────────────────────────────+// A wallet connect/disconnect changes who the caller is, so any cached pass is now+// for the wrong wallet. Drop it and broadcast `three:tier-changed` so mounted gates+// re-read their access — the one live coupling, kept lightweight.+if (hasWindow && typeof window.addEventListener === 'function') {+ window.addEventListener('wallet:changed', (e) => {+ clearTierPass();+ try {+ window.dispatchEvent(+ new CustomEvent('three:tier-changed', {+ detail: { address: e?.detail?.address ?? null, reason: 'wallet:changed' },+ }),+ );+ } catch {+ /* CustomEvent unsupported — gates also listen to wallet:changed directly */+ }+ });+}diff --git a/tests/api/three-access.test.js b/tests/api/three-access.test.jsnew file mode 100644index 000000000..72e136fe9--- /dev/null+++ b/tests/api/three-access.test.js@@ -0,0 +1,209 @@+// HTTP-level tests for the hold-to-access read surface in api/three/[action].js:+// GET /api/three/access — full gated-feature matrix in one call+// GET /api/three/access?feature=<id> — a single feature's access result+// GET /api/three/access?wallet=<addr> — account-less resolution for a connected wallet+//+// The library matrix (every tier × every feature) is unit-tested in+// tests/three-access.test.js. These tests exercise the ENDPOINT: the reason+// taxonomy (anonymous → sign_in, signed-in-no-wallet → link_wallet, wallet in+// hand under the bar → insufficient_tier), the wallet-mode tier resolution, the+// pay-per-use price attached from the catalog, and the typed 404.+//+// Balance/price reads are mocked so the tier resolves deterministically; the+// session user is mocked so the signed-in paths run without a DB.++import { describe, it, expect, beforeAll, beforeEach, vi } from 'vitest';+import { Readable } from 'node:stream';++const getBalances = vi.fn();+const getTokenPriceUsd = vi.fn();+const getSessionUser = vi.fn();+vi.mock('../../api/_lib/balances.js', () => ({ getBalances: (...a) => getBalances(...a) }));+vi.mock('../../api/_lib/token/price.js', () => ({ getTokenPriceUsd: (...a) => getTokenPriceUsd(...a) }));+vi.mock('../../api/_lib/auth.js', async (orig) => ({+ ...(await orig()),+ getSessionUser: (...a) => getSessionUser(...a),+}));++let handler, TOKEN_MINT, FEATURE_IDS;++const WALLET = 'So11111111111111111111111111111111111111112';++function mockRes() {+ return {+ statusCode: 200,+ _headers: {},+ _body: '',+ _ended: false,+ setHeader(k, v) { this._headers[k.toLowerCase()] = v; },+ getHeader(k) { return this._headers[k.toLowerCase()]; },+ end(b) { this._body = b || ''; this._ended = true; },+ get json() { try { return JSON.parse(this._body); } catch { return null; } },+ };+}++function mockReq({ method = 'GET', url = '/' } = {}) {+ const r = Readable.from([]);+ r.method = method;+ r.url = url;+ r.headers = { origin: 'http://localhost:3000' };+ return r;+}++const get = async (url) => {+ const res = mockRes();+ await handler(mockReq({ url }), res);+ return res;+};++// Make a connected wallet resolve to a given held USD (amount==usd, price==1 so+// both the entry-usd and amount×price paths agree). usd=0 → Member floor.+function mockHeldUsd(usd) {+ getBalances.mockResolvedValue({ tokens: [{ mint: TOKEN_MINT, amount: usd, usd, price: 1 }] });+}++beforeAll(async () => {+ process.env.NODE_ENV = 'development';+ process.env.HOLDER_PASS_SECRET = 'three-access-endpoint-test-secret';+ handler = (await import('../../api/three/[action].js')).default;+ ({ TOKEN_MINT } = await import('../../api/_lib/token/config.js'));+ ({ listGatedFeatures: FEATURE_IDS } = await import('../../api/_lib/three-access.js'));+ FEATURE_IDS = FEATURE_IDS();+});++beforeEach(() => {+ vi.clearAllMocks();+ getSessionUser.mockResolvedValue(null); // anonymous unless a test says otherwise+});++describe('GET /api/three/access — full matrix (anonymous)', () => {+ it('returns every gated feature in one call, all locked with reason sign_in', async () => {+ const res = await get('/api/three/access');+ expect(res.statusCode).toBe(200);+ expect(res.json.signed_in).toBe(false);+ expect(res.json.wallet_linked).toBe(false);+ expect(res.json.tier.id).toBe('member');+ expect(res.json.tier.held_usd).toBe(0);++ const ids = res.json.features.map((f) => f.feature).sort();+ expect(ids).toEqual(FEATURE_IDS.slice().sort());+ for (const f of res.json.features) {+ expect(f.eligible).toBe(false);+ expect(f.reason).toBe('sign_in');+ expect(f.held.id).toBe('member');+ expect(f.required.level).toBeGreaterThanOrEqual(1);+ }+ // Anonymous resolution must not touch the chain.+ expect(getBalances).not.toHaveBeenCalled();+ });++ it('attaches the catalog price to a pay-per-use feature, null-priced for variable ones', async () => {+ const res = await get('/api/three/access');+ const byId = Object.fromEntries(res.json.features.map((f) => [f.feature, f]));++ // forge.high is payable per-use at a fixed catalog price.+ expect(byId['forge.high'].pay_per_use.action).toBe('forge.high');+ expect(byId['forge.high'].pay_per_use.usd).toBeGreaterThan(0);++ // names.first_dibs is payable, but priced per-name (variable) → usd null.+ expect(byId['names.first_dibs'].pay_per_use.action).toBe('name.auction');+ expect(byId['names.first_dibs'].pay_per_use.usd).toBeNull();++ // Hold-only features expose no pay-per-use path.+ expect(byId['worlds.private'].pay_per_use).toBeNull();+ });++ it('surfaces the enforced flag so the page can mark Live vs Planned perks', async () => {+ const res = await get('/api/three/access');+ const byId = Object.fromEntries(res.json.features.map((f) => [f.feature, f]));+ // Only the wired forge.high gate is enforced today; the rest are planned.+ expect(byId['forge.high'].enforced).toBe(true);+ expect(byId['worlds.private'].enforced).toBe(false);+ expect(byId['names.first_dibs'].enforced).toBe(false);+ });+});++describe('GET /api/three/access?feature=<id>', () => {+ it('returns the single feature result for a known id', async () => {+ const res = await get('/api/three/access?feature=forge.high');+ expect(res.statusCode).toBe(200);+ expect(res.json.features).toBeUndefined();+ expect(res.json.access.feature).toBe('forge.high');+ expect(res.json.access.eligible).toBe(false);+ expect(res.json.access.reason).toBe('sign_in');+ expect(res.json.access.required.id).toBe('bronze');+ expect(res.json.access.pay_per_use.action).toBe('forge.high');+ });++ it('returns a typed 404 for an unknown feature', async () => {+ const res = await get('/api/three/access?feature=forge.ultra');+ expect(res.statusCode).toBe(404);+ expect(res.json.error).toBe('unknown_feature');+ expect(res.json.error_description).toContain('forge.ultra');+ });+});++describe('GET /api/three/access?wallet=<addr> — account-less resolution', () => {+ it('rejects a malformed wallet with 400', async () => {+ const res = await get('/api/three/access?wallet=not-a-wallet');+ expect(res.statusCode).toBe(400);+ expect(res.json.error).toBe('invalid_wallet');+ });++ it('a Gold wallet unlocks forge.high + worlds.branded, locks names.first_dibs as insufficient_tier', async () => {+ mockHeldUsd(600); // gold (≥ $500)+ const res = await get(`/api/three/access?wallet=${WALLET}`);+ expect(res.statusCode).toBe(200);+ expect(res.json.wallet_linked).toBe(true);+ expect(res.json.tier.id).toBe('gold');+ expect(res.json.tier.held_usd).toBe(600);++ const byId = Object.fromEntries(res.json.features.map((f) => [f.feature, f]));+ expect(byId['forge.high'].eligible).toBe(true);+ expect(byId['forge.high'].reason).toBe('eligible');+ expect(byId['worlds.branded'].eligible).toBe(true);+ // Wallet in hand under the bar → "hold more", never sign_in / link_wallet.+ expect(byId['names.first_dibs'].eligible).toBe(false);+ expect(byId['names.first_dibs'].reason).toBe('insufficient_tier');+ });++ it('a zero-balance wallet is Member, every feature locked with insufficient_tier', async () => {+ mockHeldUsd(0);+ const res = await get(`/api/three/access?wallet=${WALLET}`);+ expect(res.json.tier.id).toBe('member');+ for (const f of res.json.features) {+ expect(f.eligible).toBe(false);+ expect(f.reason).toBe('insufficient_tier');+ }+ });++ it('degrades a wallet to Member (never 500s) on a balance read failure', async () => {+ getBalances.mockRejectedValue(new Error('rpc down'));+ const res = await get(`/api/three/access?feature=forge.high&wallet=${WALLET}`);+ expect(res.statusCode).toBe(200);+ expect(res.json.tier.id).toBe('member');+ expect(res.json.access.eligible).toBe(false);+ });+});++describe('GET /api/three/access — signed-in reasons', () => {+ it('signed-in without a linked wallet → reason link_wallet, no chain read', async () => {+ getSessionUser.mockResolvedValue({ id: 'u1' });+ const res = await get('/api/three/access?feature=forge.high');+ expect(res.json.signed_in).toBe(true);+ expect(res.json.wallet_linked).toBe(false);+ expect(res.json.access.reason).toBe('link_wallet');+ expect(getBalances).not.toHaveBeenCalled();+ });++ it("signed-in holder above the bar is eligible from the session wallet", async () => {+ getSessionUser.mockResolvedValue({ id: 'u2', wallet_address: WALLET });+ mockHeldUsd(30); // bronze (≥ $25)+ const res = await get('/api/three/access?feature=forge.high');+ expect(res.json.signed_in).toBe(true);+ expect(res.json.wallet_linked).toBe(true);+ expect(res.json.tier.id).toBe('bronze');+ expect(res.json.access.eligible).toBe(true);+ expect(res.json.access.reason).toBe('eligible');+ });+});diff --git a/tests/forge-high-gate.test.js b/tests/forge-high-gate.test.jsnew file mode 100644index 000000000..4d51510ee--- /dev/null+++ b/tests/forge-high-gate.test.js@@ -0,0 +1,150 @@+// HTTP-level tests for the $THREE hold-to-access gate on POST /api/forge.+//+// The High tier (200k poly + PBR) on a PLATFORM-keyed backend spends real+// GPU/vendor budget, so it's reserved for $THREE holders (Bronze+), proven by a+// signed tier pass (pure-HMAC, no RPC) or — when no pass is presented — the+// session user's on-chain tier. A non-holder gets a hold-or-pay 402. These tests+// pin the contract edges:+// • High + platform backend + no pass → 402 three_hold_required (full payload)+// • High + platform backend + valid Bronze → gate lets it through (not 402)+// • High + BYOK backend (caller's own key) → never gated (key-gated instead)+// • Standard / Draft tier → never gated+// • Tampered pass → gated as a non-holder+//+// The gate runs BEFORE the rate limiter and any provider call, so the 402 path is+// fully network-free (anonymous → no DB/RPC). The pass-allows / BYOK / standard+// paths fall through to a designed downstream state (needs_key / unconfigured)+// because no vendor key is configured — never a real upstream call.++import { describe, it, expect, beforeAll } from 'vitest';+import { Readable } from 'node:stream';+import { signTierPass } from '../api/_lib/three-tier.js';+import { TOKEN_MINT } from '../api/_lib/token/config.js';++let forge;++function mockRes() {+ return {+ statusCode: 200, _headers: {}, _body: '', _ended: false,+ setHeader(k, v) { this._headers[k.toLowerCase()] = v; },+ getHeader(k) { return this._headers[k.toLowerCase()]; },+ end(b) { this._body = b || ''; this._ended = true; },+ get json() { try { return JSON.parse(this._body); } catch { return null; } },+ };+}++function mockReq({ body = null, headers = {} } = {}) {+ const chunks = body != null ? [Buffer.from(JSON.stringify(body))] : [];+ const r = Readable.from(chunks);+ r.method = 'POST';+ r.url = '/api/forge';+ r.headers = { origin: 'http://localhost:3000', 'content-type': 'application/json', ...headers };+ return r;+}++// A synthetic Solana-shaped wallet — signTierPass doesn't validate the address,+// and the gate trusts the signed level, never the wallet.+const WALLET = 'THREEsynthetic1111111111111111111111111111';++beforeAll(async () => {+ // Dev secret for tier-pass sign/verify symmetry; in-memory (fail-open) limiter.+ process.env.NODE_ENV = 'development';+ delete process.env.HOLDER_PASS_SECRET;+ // No platform vendor key → the post-gate platform path lands on a clean 503+ // 'unconfigured' instead of making a real Replicate call. Keeps every+ // not-402 assertion hermetic regardless of the CI environment.+ delete process.env.REPLICATE_API_TOKEN;+ forge = (await import('../api/forge.js')).default;+});++describe('POST /api/forge — $THREE High-tier gate', () => {+ it('blocks High on a platform backend with no pass — 402 three_hold_required + full payload', async () => {+ const res = mockRes();+ await forge(mockReq({ body: { prompt: 'a brass telescope', tier: 'high', backend: 'trellis' } }), res);++ expect(res.statusCode).toBe(402);+ const b = res.json;+ expect(b.error).toBe('three_hold_required');+ expect(b.feature).toBe('forge.high');+ // Required tier is Bronze (level 1); the anonymous caller holds Member (level 0).+ expect(b.required).toMatchObject({ level: 1, id: 'bronze', min_usd: 25 });+ expect(b.held).toMatchObject({ level: 0, id: 'member', usd: 0 });+ expect(typeof b.why).toBe('string');+ expect(b.why.length).toBeGreaterThan(0);+ // Anonymous → sign in, with the exact gap to the entry tier.+ expect(b.reason).toBe('sign_in');+ expect(b.usd_to_go).toBe(25);+ // Designed acquire block + exact pay-per-use price pulled from the catalog ($0.50).+ expect(b.acquire.mint).toBe(TOKEN_MINT);+ expect(b.acquire.swap_url).toContain(TOKEN_MINT);+ expect(b.pay_per_use).toMatchObject({ action: 'forge.high', usd: 0.5 });+ expect(b.message).toMatch(/Bronze/);+ });++ it('lets High through with a valid Bronze+ pass (not blocked by the gate)', async () => {+ const pass = signTierPass({ wallet: WALLET, level: 1, tierId: 'bronze', usd: 30 });+ const res = mockRes();+ await forge(+ mockReq({+ body: { prompt: 'a brass telescope', tier: 'high', backend: 'trellis' },+ headers: { 'x-three-tier-pass': pass },+ }),+ res,+ );++ // The gate must not fire: it falls through to the (unconfigured) generation+ // path, never the 402 holder lock.+ expect(res.statusCode).not.toBe(402);+ expect(res.json?.error).not.toBe('three_hold_required');+ expect(res.json?.error).toBe('unconfigured');+ });++ it('accepts the pass via body.tier_pass as well as the header', async () => {+ const pass = signTierPass({ wallet: WALLET, level: 2, tierId: 'silver', usd: 120 });+ const res = mockRes();+ await forge(+ mockReq({ body: { prompt: 'a brass telescope', tier: 'high', backend: 'trellis', tier_pass: pass } }),+ res,+ );+ expect(res.statusCode).not.toBe(402);+ expect(res.json?.error).not.toBe('three_hold_required');+ });++ it('does not gate High on a BYOK backend — key-gated, not hold-gated', async () => {+ const res = mockRes();+ await forge(mockReq({ body: { prompt: 'a brass telescope', tier: 'high', backend: 'meshy' } }), res);++ // BYOK backends are exempt (the caller pays their own vendor). With no key+ // supplied they get the designed needs_key state — never the $THREE gate.+ expect(res.statusCode).not.toBe(402);+ expect(res.json?.error).not.toBe('three_hold_required');+ expect(res.json?.error).toBe('needs_key');+ });++ it('never gates the Standard tier', async () => {+ const res = mockRes();+ await forge(mockReq({ body: { prompt: 'a brass telescope', tier: 'standard', backend: 'trellis' } }), res);+ expect(res.statusCode).not.toBe(402);+ expect(res.json?.error).not.toBe('three_hold_required');+ });++ it('never gates the Draft tier', async () => {+ const res = mockRes();+ await forge(mockReq({ body: { prompt: 'a brass telescope', tier: 'draft', backend: 'trellis' } }), res);+ expect(res.statusCode).not.toBe(402);+ expect(res.json?.error).not.toBe('three_hold_required');+ });++ it('rejects a tampered / invalid pass and gates as a non-holder', async () => {+ const res = mockRes();+ await forge(+ mockReq({+ body: { prompt: 'a brass telescope', tier: 'high', backend: 'trellis' },+ headers: { 'x-three-tier-pass': 'not.a.valid.pass' },+ }),+ res,+ );+ expect(res.statusCode).toBe(402);+ expect(res.json.error).toBe('three_hold_required');+ });+});diff --git a/tests/forge-high-pay.test.js b/tests/forge-high-pay.test.jsnew file mode 100644index 000000000..70cd23ab3--- /dev/null+++ b/tests/forge-high-pay.test.js@@ -0,0 +1,134 @@+// HTTP-level tests for the Forge High pay-per-use branch on POST /api/forge.+//+// Companion to forge-high-gate.test.js (the hold-or-pay gate): these pin the+// consumption lever — a non-holder presenting a settled $THREE payment+// (payment_id + the client nonce) instead of holding. The payment helper is+// mocked so no DB/RPC is touched; what's under test is how api/forge.js routes a+// valid / invalid / already-used proof:+// • valid proof → satisfies the gate (not 402), claimed before dispatch,+// and released because the platform lane is unconfigured+// (no model delivered → reusable on retry).+// • invalid proof → the assert error is surfaced verbatim (402 payment_invalid).+// • lost the claim race → 409 payment_already_used, nothing released.++import { describe, it, expect, beforeAll, beforeEach, vi } from 'vitest';+import { Readable } from 'node:stream';++const assertForgePayment = vi.fn();+const redeemForgePayment = vi.fn();+const releaseForgePayment = vi.fn();+vi.mock('../api/_lib/forge-high-payment.js', () => ({+ assertForgePayment: (...a) => assertForgePayment(...a),+ redeemForgePayment: (...a) => redeemForgePayment(...a),+ releaseForgePayment: (...a) => releaseForgePayment(...a),+}));++let forge;++function mockRes() {+ return {+ statusCode: 200, _headers: {}, _body: '', _ended: false,+ setHeader(k, v) { this._headers[k.toLowerCase()] = v; },+ getHeader(k) { return this._headers[k.toLowerCase()]; },+ end(b) { this._body = b || ''; this._ended = true; },+ get json() { try { return JSON.parse(this._body); } catch { return null; } },+ };+}++function mockReq({ body = null } = {}) {+ const chunks = body != null ? [Buffer.from(JSON.stringify(body))] : [];+ const r = Readable.from(chunks);+ r.method = 'POST';+ r.url = '/api/forge';+ r.headers = { origin: 'http://localhost:3000', 'content-type': 'application/json' };+ return r;+}++const PAY_BODY = {+ prompt: 'a brass telescope',+ tier: 'high',+ backend: 'trellis',+ payment_id: 'pay-1',+ ref_id: 'forge-high-abc123',+};++beforeAll(async () => {+ process.env.NODE_ENV = 'development';+ delete process.env.HOLDER_PASS_SECRET;+ // No platform vendor key → the post-gate platform path lands on a clean+ // 'unconfigured' instead of a real Replicate call, so a gate-passing request+ // resolves hermetically.+ delete process.env.REPLICATE_API_TOKEN;+ forge = (await import('../api/forge.js')).default;+});++beforeEach(() => {+ vi.clearAllMocks();+ // Defaults: a valid, claimable, releasable payment.+ assertForgePayment.mockResolvedValue({+ ok: true,+ payment: { id: 'pay-1', usd: 0.5, settledAt: new Date().toISOString() },+ });+ redeemForgePayment.mockResolvedValue({ redeemed: true });+ releaseForgePayment.mockResolvedValue(undefined);+});++describe('POST /api/forge — Forge High pay-per-use', () => {+ it('a valid payment proof satisfies the gate (not 402) and is claimed', async () => {+ const res = mockRes();+ await forge(mockReq({ body: PAY_BODY }), res);++ // Gate passed: never the hold-or-pay 402.+ expect(res.statusCode).not.toBe(402);+ expect(res.json?.error).not.toBe('three_hold_required');+ // Validated read-only at the gate, then claimed atomically before dispatch.+ expect(assertForgePayment).toHaveBeenCalledWith(+ expect.objectContaining({ paymentId: 'pay-1', refId: 'forge-high-abc123' }),+ );+ expect(redeemForgePayment).toHaveBeenCalledWith(+ expect.objectContaining({ paymentId: 'pay-1', refId: 'forge-high-abc123' }),+ );+ // Platform lane is unconfigured here → no model delivered → the claim is+ // released so the settled payment stays reusable on retry.+ expect(res.json?.error).toBe('unconfigured');+ expect(releaseForgePayment).toHaveBeenCalledWith({ paymentId: 'pay-1' });+ });++ it('surfaces an invalid proof verbatim and never reaches the claim', async () => {+ assertForgePayment.mockRejectedValueOnce(+ Object.assign(new Error('No settled $THREE payment found for this generation.'), {+ status: 402,+ code: 'payment_invalid',+ }),+ );+ const res = mockRes();+ await forge(mockReq({ body: PAY_BODY }), res);++ expect(res.statusCode).toBe(402);+ expect(res.json.error).toBe('payment_invalid');+ expect(res.json.feature).toBe('forge.high');+ expect(res.json.pay_per_use).toMatchObject({ action: 'forge.high', usd: 0.5 });+ expect(redeemForgePayment).not.toHaveBeenCalled();+ expect(releaseForgePayment).not.toHaveBeenCalled();+ });++ it('returns 409 when the claim is lost (payment already used) and releases nothing', async () => {+ redeemForgePayment.mockResolvedValueOnce({ redeemed: false });+ const res = mockRes();+ await forge(mockReq({ body: PAY_BODY }), res);++ expect(res.statusCode).toBe(409);+ expect(res.json.error).toBe('payment_already_used');+ expect(releaseForgePayment).not.toHaveBeenCalled();+ });++ it('falls through to the hold-or-pay gate when no proof is presented', async () => {+ const res = mockRes();+ await forge(mockReq({ body: { prompt: 'a brass telescope', tier: 'high', backend: 'trellis' } }), res);++ // Anonymous, no proof → the normal 402 hold-or-pay gate (require-three.js).+ expect(res.statusCode).toBe(402);+ expect(res.json.error).toBe('three_hold_required');+ expect(assertForgePayment).not.toHaveBeenCalled();+ });+});diff --git a/tests/forge-high-payment.test.js b/tests/forge-high-payment.test.jsnew file mode 100644index 000000000..c19b1b0c1--- /dev/null+++ b/tests/forge-high-payment.test.js@@ -0,0 +1,168 @@+// Unit tests for the Forge High pay-per-use proof (api/_lib/forge-high-payment.js).+//+// The consumption lever: a settled $THREE `consumption` payment, bound to+// ref_type:'forge' + the client nonce, stands in for holding $THREE on one High+// generation. These prove the validation contract (purpose/ref/price/recency/+// single-use), the atomic single-use claim, and the release-on-failure path that+// keeps a payment reusable when a generation fails before delivering a model.+//+// The DB is mocked: a tagged-template `sql` that returns whatever the test queues.+// priceForAction is the real pure catalog ($0.50 for forge.high), so a silent+// price change fails here.++import { describe, it, expect, vi, beforeEach } from 'vitest';++const queue = [];+vi.mock('../api/_lib/db.js', () => {+ const sql = vi.fn(async () => (queue.length ? queue.shift() : []));+ return { sql };+});++import {+ assertForgePayment,+ redeemForgePayment,+ releaseForgePayment,+} from '../api/_lib/forge-high-payment.js';+import { sql } from '../api/_lib/db.js';+import { priceForAction } from '../api/_lib/pricing/catalog.js';++const HIGH_USD = Number(priceForAction('forge.high').usd); // 0.50 from the catalog+const REF_ID = 'forge-high-abc123';++// A settled consumption payment row as token_payments returns it (numeric usd+// comes back as a string from the driver). `confirmed_at` defaults to now.+function paymentRow(over = {}) {+ return {+ id: 'pay-1',+ purpose: 'consumption',+ usd: HIGH_USD.toFixed(6),+ ref_type: 'forge',+ ref_id: REF_ID,+ confirmed_at: new Date().toISOString(),+ created_at: new Date().toISOString(),+ ...over,+ };+}++// Queue the two reads assertForgePayment makes: the payment lookup, then the+// redemption-existence check.+function queueAssert({ payment = paymentRow(), redeemed = false } = {}) {+ queue.push(payment ? [payment] : []); // lookupPayment+ queue.push(redeemed ? [{ payment_id: 'pay-1' }] : []); // isRedeemed+}++beforeEach(() => {+ queue.length = 0;+ vi.clearAllMocks();+});++describe('assertForgePayment', () => {+ it('accepts a settled, ref-bound, correctly-priced, recent, unredeemed payment', async () => {+ queueAssert();+ const r = await assertForgePayment({ paymentId: 'pay-1', refId: REF_ID });+ expect(r.ok).toBe(true);+ expect(r.payment).toMatchObject({ id: 'pay-1', usd: HIGH_USD });+ expect(r.payment.settledAt).toBeTruthy();+ });++ it('requires both payment_id and ref_id', async () => {+ await expect(assertForgePayment({ paymentId: '', refId: REF_ID })).rejects.toMatchObject({+ status: 400,+ code: 'bad_request',+ });+ await expect(assertForgePayment({ paymentId: 'pay-1', refId: '' })).rejects.toMatchObject({+ status: 400,+ code: 'bad_request',+ });+ });++ it('rejects an unknown payment as payment_invalid (402)', async () => {+ queue.push([]); // lookupPayment → none+ await expect(assertForgePayment({ paymentId: 'nope', refId: REF_ID })).rejects.toMatchObject({+ status: 402,+ code: 'payment_invalid',+ });+ });++ it('rejects a non-consumption / non-forge payment (a different action) ', async () => {+ queueAssert({ payment: paymentRow({ purpose: 'spin' }) });+ await expect(assertForgePayment({ paymentId: 'pay-1', refId: REF_ID })).rejects.toMatchObject({+ code: 'payment_invalid',+ });++ queueAssert({ payment: paymentRow({ ref_type: 'voice' }) });+ await expect(assertForgePayment({ paymentId: 'pay-1', refId: REF_ID })).rejects.toMatchObject({+ code: 'payment_invalid',+ });+ });++ it('rejects a payment bound to a different ref_id', async () => {+ queueAssert({ payment: paymentRow({ ref_id: 'someone-elses-nonce' }) });+ await expect(assertForgePayment({ paymentId: 'pay-1', refId: REF_ID })).rejects.toMatchObject({+ code: 'payment_invalid',+ });+ });++ it('rejects an underpaid payment (price must cover forge.high)', async () => {+ queueAssert({ payment: paymentRow({ usd: '0.100000' }) });+ await expect(assertForgePayment({ paymentId: 'pay-1', refId: REF_ID })).rejects.toMatchObject({+ code: 'payment_invalid',+ });+ });++ it('rejects a payment older than the redemption window (payment_expired)', async () => {+ const old = new Date(Date.now() - 48 * 60 * 60 * 1000).toISOString();+ queueAssert({ payment: paymentRow({ confirmed_at: old, created_at: old }) });+ await expect(assertForgePayment({ paymentId: 'pay-1', refId: REF_ID })).rejects.toMatchObject({+ status: 402,+ code: 'payment_expired',+ });+ });++ it('rejects an already-redeemed payment (409 payment_already_used)', async () => {+ queueAssert({ redeemed: true });+ await expect(assertForgePayment({ paymentId: 'pay-1', refId: REF_ID })).rejects.toMatchObject({+ status: 409,+ code: 'payment_already_used',+ });+ });++ it('applies the holder discount to the expected price when a discount rides along', async () => {+ const discounted = Number(priceForAction('forge.high', { discountBps: 500 }).usd); // 0.475+ expect(discounted).toBeLessThan(HIGH_USD);+ // A payment for the discounted amount clears with the discount applied…+ queueAssert({ payment: paymentRow({ usd: discounted.toFixed(6) }) });+ const r = await assertForgePayment({ paymentId: 'pay-1', refId: REF_ID, discountBps: 500 });+ expect(r.ok).toBe(true);+ // …but the same discounted payment fails at full price (no discount presented).+ queueAssert({ payment: paymentRow({ usd: discounted.toFixed(6) }) });+ await expect(assertForgePayment({ paymentId: 'pay-1', refId: REF_ID })).rejects.toMatchObject({+ code: 'payment_invalid',+ });+ });+});++describe('redeemForgePayment', () => {+ it('claims a payment when the insert wins (returns a row)', async () => {+ queue.push([{ payment_id: 'pay-1' }]);+ const r = await redeemForgePayment({ paymentId: 'pay-1', refId: REF_ID });+ expect(r.redeemed).toBe(true);+ expect(sql).toHaveBeenCalledOnce();+ });++ it('does not claim when the row already exists (ON CONFLICT DO NOTHING → no row)', async () => {+ queue.push([]); // conflict → nothing returned+ const r = await redeemForgePayment({ paymentId: 'pay-1', refId: REF_ID });+ expect(r.redeemed).toBe(false);+ });+});++describe('releaseForgePayment', () => {+ it('deletes the claim so the payment is reusable on retry', async () => {+ queue.push([]);+ await releaseForgePayment({ paymentId: 'pay-1' });+ expect(sql).toHaveBeenCalledOnce();+ // The interpolated payment id is passed as the query's 2nd arg.+ expect(sql.mock.calls[0].slice(1).map(String)).toContain('pay-1');+ });+});diff --git a/tests/three-access.test.js b/tests/three-access.test.jsnew file mode 100644index 000000000..ee6cdbcba--- /dev/null+++ b/tests/three-access.test.js@@ -0,0 +1,254 @@+// Unit tests for the $THREE gated-feature access registry (api/_lib/three-access.js).+// Balance/price reads are mocked (same rig as three-tier.test.js). These prove the+// full tier×feature eligibility matrix, the pure level check, the reason taxonomy+// (anonymous → sign_in, signed-in-no-wallet → link_wallet, under threshold →+// insufficient_tier), graceful degradation to Member on an RPC/price hiccup, the+// pay-per-use passthrough, and the typed 404 for an unknown feature.++import { describe, it, expect, vi, beforeEach } from 'vitest';++const getBalances = vi.fn();+const getTokenPriceUsd = vi.fn();+vi.mock('../api/_lib/balances.js', () => ({ getBalances: (...a) => getBalances(...a) }));+vi.mock('../api/_lib/token/price.js', () => ({ getTokenPriceUsd: (...a) => getTokenPriceUsd(...a) }));++import {+ GATED_FEATURES,+ gatedFeature,+ requiredTierFor,+ listGatedFeatures,+ accessFromTierLevel,+ resolveAccess,+} from '../api/_lib/three-access.js';+import { TOKEN_MINT } from '../api/_lib/token/config.js';++const WALLET = 'So11111111111111111111111111111111111111112';++// Source-of-truth expectations, kept independent of the module under test so a+// silent change to the registry (a shifted threshold, a dropped feature) fails here.+const MIN_LEVEL = {+ 'forge.high': 1,+ 'worlds.private': 2,+ 'mcp.priority': 2,+ 'worlds.branded': 3,+ 'drops.early': 3,+ 'names.first_dibs': 4,+};+const REQUIRED_TIER_ID = {+ 'forge.high': 'bronze',+ 'worlds.private': 'silver',+ 'mcp.priority': 'silver',+ 'worlds.branded': 'gold',+ 'drops.early': 'gold',+ 'names.first_dibs': 'genesis',+};+const PAY_PER_USE = {+ 'forge.high': 'forge.high',+ 'worlds.private': null,+ 'mcp.priority': null,+ 'worlds.branded': null,+ 'drops.early': null,+ 'names.first_dibs': 'name.auction',+};+// Only forge.high is WIRED today (the High-tier Forge gate). The rest are planned —+// registered so the UI can show them, but not yet enforced anywhere. /three reads+// this flag to mark each perk "Live" vs "Planned"; pinning it here makes flipping a+// feature to enforced a deliberate, tested change rather than a silent one.+const ENFORCED = {+ 'forge.high': true,+ 'worlds.private': false,+ 'mcp.priority': false,+ 'worlds.branded': false,+ 'drops.early': false,+ 'names.first_dibs': false,+};+const TIER_ID_BY_LEVEL = ['member', 'bronze', 'silver', 'gold', 'genesis'];+const FEATURE_IDS = Object.keys(MIN_LEVEL);++// USD value of $THREE that resolves to each tier level (just over each threshold).+const USD_FOR_LEVEL = [0, 25, 100, 500, 2500];++// Make holderUsd resolve to `usd`: amount==usd, price==1 so both the entry-usd and+// the amount×price code paths agree, and usd=0 → amount 0 → the Member floor.+function mockHeldUsd(usd) {+ getBalances.mockResolvedValue({ tokens: [{ mint: TOKEN_MINT, amount: usd, usd, price: 1 }] });+}++beforeEach(() => {+ vi.clearAllMocks();+});++describe('registry shape', () => {+ it('exposes exactly the six gated features and is deeply frozen', () => {+ expect(listGatedFeatures().sort()).toEqual(FEATURE_IDS.slice().sort());+ expect(Object.isFrozen(GATED_FEATURES)).toBe(true);+ for (const id of FEATURE_IDS) {+ expect(Object.isFrozen(GATED_FEATURES[id])).toBe(true);+ }+ });++ it('every entry carries minLevel, holder-readable copy, a payPerUse key, and an enforced flag', () => {+ for (const id of FEATURE_IDS) {+ const f = GATED_FEATURES[id];+ expect(f.minLevel).toBe(MIN_LEVEL[id]);+ expect(typeof f.label).toBe('string');+ expect(f.label.length).toBeGreaterThan(0);+ expect(typeof f.why).toBe('string');+ expect(f.why.length).toBeGreaterThan(0);+ expect(f).toHaveProperty('payPerUse');+ expect(f.payPerUse).toBe(PAY_PER_USE[id]);+ expect(typeof f.enforced).toBe('boolean');+ expect(f.enforced).toBe(ENFORCED[id]);+ }+ });++ it('marks only forge.high enforced today — the rest are planned', () => {+ const enforced = FEATURE_IDS.filter((id) => GATED_FEATURES[id].enforced);+ expect(enforced).toEqual(['forge.high']);+ });++ it('references no coin other than $THREE in its copy', () => {+ // Strip the legitimate `.sol` SNS TLD (names.first_dibs targets *.threews.sol)+ // so it isn't mistaken for the SOL coin, then scan for foreign tickers.+ const blob = JSON.stringify(GATED_FEATURES).toLowerCase().replace(/\.sol\b/g, '');+ expect(blob).not.toMatch(/\busdc\b|\bbonk\b|\bwif\b|\bdoge\b|\bpepe\b|\bbtc\b|ethereum|\beth\b/);+ });+});++describe('gatedFeature / requiredTierFor', () => {+ it('returns the entry for a known feature', () => {+ expect(gatedFeature('forge.high')).toBe(GATED_FEATURES['forge.high']);+ });++ it('throws a typed 404 for an unknown feature', () => {+ let err;+ try {+ gatedFeature('forge.ultra');+ } catch (e) {+ err = e;+ }+ expect(err).toBeInstanceOf(Error);+ expect(err.status).toBe(404);+ expect(err.code).toBe('unknown_feature');+ expect(err.message).toContain('forge.ultra');+ });++ it('maps each feature to the correct required tier', () => {+ for (const id of FEATURE_IDS) {+ expect(requiredTierFor(id).id).toBe(REQUIRED_TIER_ID[id]);+ expect(requiredTierFor(id).level).toBe(MIN_LEVEL[id]);+ }+ });+});++describe('accessFromTierLevel — pure tier×feature matrix', () => {+ for (let level = 0; level <= 4; level++) {+ for (const id of FEATURE_IDS) {+ const eligible = level >= MIN_LEVEL[id];+ it(`level ${level} (${TIER_ID_BY_LEVEL[level]}) × ${id} → ${eligible ? 'eligible' : 'locked'}`, () => {+ const a = accessFromTierLevel(level, id);+ expect(a.eligible).toBe(eligible);+ expect(a.feature).toBe(id);+ expect(a.required.level).toBe(MIN_LEVEL[id]);+ expect(a.required.id).toBe(REQUIRED_TIER_ID[id]);+ expect(a.held.level).toBe(level);+ expect(a.held.id).toBe(TIER_ID_BY_LEVEL[level]);+ expect(a.pay_per_use).toBe(PAY_PER_USE[id]);+ expect(a.enforced).toBe(ENFORCED[id]);+ expect(a.reason).toBe(eligible ? 'eligible' : 'insufficient_tier');+ });+ }+ }++ it('does no I/O (never touches the balance reader)', () => {+ accessFromTierLevel(4, 'names.first_dibs');+ expect(getBalances).not.toHaveBeenCalled();+ });++ it('clamps an out-of-range level to the Member floor without throwing', () => {+ const a = accessFromTierLevel(-3, 'forge.high');+ expect(a.held.id).toBe('member');+ expect(a.eligible).toBe(false);+ });++ it('throws a typed 404 for an unknown feature', () => {+ expect(() => accessFromTierLevel(4, 'nope')).toThrow(/unknown gated feature/);+ });+});++describe('resolveAccess — anonymous and signed-in reasons', () => {+ it('anonymous user is Member, locked on every paid feature with reason sign_in, no RPC', async () => {+ for (const id of FEATURE_IDS) {+ const a = await resolveAccess(null, id);+ expect(a.eligible).toBe(false);+ expect(a.reason).toBe('sign_in');+ expect(a.held.id).toBe('member');+ expect(a.held.usd).toBe(0);+ expect(a.pay_per_use).toBe(PAY_PER_USE[id]);+ }+ expect(getBalances).not.toHaveBeenCalled();+ });++ it('signed-in user without a linked wallet is locked with reason link_wallet, no RPC', async () => {+ const a = await resolveAccess({ id: 'u1' }, 'forge.high');+ expect(a.eligible).toBe(false);+ expect(a.reason).toBe('link_wallet');+ expect(a.held.id).toBe('member');+ expect(getBalances).not.toHaveBeenCalled();+ });++ it('signed-in holder under the threshold is locked with reason insufficient_tier', async () => {+ mockHeldUsd(USD_FOR_LEVEL[1]); // bronze+ const a = await resolveAccess({ wallet_address: WALLET }, 'worlds.private'); // needs silver+ expect(a.held.id).toBe('bronze');+ expect(a.eligible).toBe(false);+ expect(a.reason).toBe('insufficient_tier');+ expect(a.pay_per_use).toBeNull();+ });++ it('surfaces the pay-per-use action when a non-holder can pay instead', async () => {+ const a = await resolveAccess(null, 'forge.high');+ expect(a.pay_per_use).toBe('forge.high');+ const b = await resolveAccess(null, 'names.first_dibs');+ expect(b.pay_per_use).toBe('name.auction');+ });+});++describe('resolveAccess — on-chain tier resolution maps held value to eligibility', () => {+ for (let level = 0; level <= 4; level++) {+ it(`holding $${USD_FOR_LEVEL[level]} (${TIER_ID_BY_LEVEL[level]}) gates every feature by its min level`, async () => {+ mockHeldUsd(USD_FOR_LEVEL[level]);+ for (const id of FEATURE_IDS) {+ const a = await resolveAccess({ wallet_address: WALLET }, id);+ expect(a.held.id).toBe(TIER_ID_BY_LEVEL[level]);+ expect(a.held.usd).toBe(USD_FOR_LEVEL[level]);+ expect(a.eligible).toBe(level >= MIN_LEVEL[id]);+ expect(a.reason).toBe(level >= MIN_LEVEL[id] ? 'eligible' : 'insufficient_tier');+ }+ });+ }++ it('rounds the held USD to cents', async () => {+ mockHeldUsd(123.456);+ const a = await resolveAccess({ wallet_address: WALLET }, 'forge.high');+ expect(a.held.usd).toBe(123.46);+ });+});++describe('resolveAccess — graceful degradation', () => {+ it('degrades a holder to Member on a balance read failure (never throws)', async () => {+ getBalances.mockRejectedValue(new Error('rpc down'));+ const a = await resolveAccess({ wallet_address: WALLET }, 'forge.high');+ expect(a.held.id).toBe('member');+ expect(a.held.usd).toBe(0);+ expect(a.eligible).toBe(false);+ expect(a.reason).toBe('insufficient_tier');+ });++ it('still throws the typed 404 for an unknown feature (bad input, not an outage)', async () => {+ await expect(resolveAccess({ wallet_address: WALLET }, 'ghost')).rejects.toMatchObject({+ status: 404,+ code: 'unknown_feature',+ });+ });+});diff --git a/tests/three-gate.test.js b/tests/three-gate.test.jsnew file mode 100644index 000000000..8f816eca6--- /dev/null+++ b/tests/three-gate.test.js@@ -0,0 +1,357 @@+// @vitest-environment jsdom+//+// Unit tests for the reusable $THREE paywall: the tier-pass helper+// (src/three-tier-pass.js) and the <three-gate> custom element (src/three-gate.js).+//+// The helper is exercised against a mocked fetch (real cache + sessionStorage ++// auto-wire); the element is mounted for real and driven through the same mocked+// endpoint, proving the loading → locked / unlocked / error states, the held-vs-+// required copy + progress, the reason-specific secondaries, the pay-per-use line,+// the `three-gate:unlocked` event, that gated children are made inert while locked+// and freed when unlocked, fail-closed on a missing feature, and HTML escaping. No+// network — the live endpoint is covered by the api/_lib three-access registry ++// HTTP tests.++import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import {+ getAccess,+ getTierPass,+ threeHeaders,+ clearTierPass,+} from '../src/three-tier-pass.js';+import '../src/three-gate.js';++// ── fixtures ────────────────────────────────────────────────────────────────++const LOCKED = {+ signed_in: true,+ wallet_linked: true,+ tier: { level: 0, id: 'member', label: 'Member', held_usd: 10 },+ access: {+ feature: 'forge.high',+ label: 'High-quality generation (200k poly + PBR)',+ why: 'The High tier spends real GPU/vendor 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: 10 },+ reason: 'insufficient_tier',+ pay_per_use: { action: 'forge.high', usd: 0.5 },+ },+};++const UNLOCKED = {+ signed_in: true,+ wallet_linked: true,+ tier: { level: 2, id: 'silver', label: 'Silver', held_usd: 120 },+ access: {+ feature: 'forge.high',+ label: 'High-quality generation (200k poly + PBR)',+ why: '',+ eligible: true,+ required: { level: 1, id: 'bronze', label: 'Bronze', min_usd: 25 },+ held: { level: 2, id: 'silver', label: 'Silver', min_usd: 100, usd: 120 },+ reason: 'eligible',+ pay_per_use: { action: 'forge.high', usd: 0.5 },+ },+};++function withReason(reason, over = {}) {+ return {+ ...LOCKED,+ signed_in: reason !== 'sign_in',+ wallet_linked: reason === 'insufficient_tier',+ access: { ...LOCKED.access, reason, ...over },+ };+}++// ── helpers ─────────────────────────────────────────────────────────────────++function jsonRes(status, body) {+ return Promise.resolve({+ ok: status >= 200 && status < 300,+ status,+ json: () => Promise.resolve(body),+ });+}++// A pass string in the real `<base64url(payload)>.<sig>` shape, carrying `exp`+// (unix seconds) so the helper's expiry decode + freshness window are exercised.+function makePass(expSec) {+ const payload = Buffer.from(JSON.stringify({ exp: expSec, w: 'wallet' }))+ .toString('base64')+ .replace(/\+/g, '-')+ .replace(/\//g, '_')+ .replace(/=+$/, '');+ return `${payload}.signature`;+}+const freshPass = () => makePass(Math.floor(Date.now() / 1000) + 600);++const tick = () => new Promise((r) => setTimeout(r, 0));+const flush = async () => {+ await tick();+ await tick();+};++function mountGate(attrs = {}, childId = 'premium') {+ const el = document.createElement('three-gate');+ for (const [k, v] of Object.entries(attrs)) el.setAttribute(k, v);+ const child = document.createElement('button');+ child.id = childId;+ child.textContent = 'Generate (High)';+ el.appendChild(child);+ document.body.appendChild(el);+ return el;+}++beforeEach(() => {+ document.body.innerHTML = '';+ window.sessionStorage.clear();+ clearTierPass();+});+afterEach(() => {+ vi.restoreAllMocks();+});++// ── three-tier-pass.js ──────────────────────────────────────────────────────++describe('getAccess', () => {+ it('returns the parsed payload and sends credentials', async () => {+ global.fetch = vi.fn(() => jsonRes(200, LOCKED));+ const data = await getAccess('forge.high');+ expect(data).toEqual(LOCKED);+ expect(global.fetch).toHaveBeenCalledWith('/api/three/access?feature=forge.high', {+ credentials: 'include',+ });+ });++ it('returns a Member-shaped fallback (flagged _error) on a network failure', async () => {+ global.fetch = vi.fn(() => Promise.reject(new Error('offline')));+ const data = await getAccess('forge.high');+ expect(data._error).toBe(true);+ expect(data.tier.id).toBe('member');+ expect(data.access.eligible).toBe(false);+ expect(data.access.reason).toBe('error');+ });++ it('falls back on a non-OK response too', async () => {+ global.fetch = vi.fn(() => jsonRes(500, { error: 'boom' }));+ const data = await getAccess('forge.high');+ expect(data._error).toBe(true);+ });+});++describe('getTierPass', () => {+ it('mints a pass, returns the string, and caches it in sessionStorage', async () => {+ const pass = freshPass();+ const fetchMock = vi.fn(() => jsonRes(201, { pass, tier: { id: 'bronze' } }));+ global.fetch = fetchMock;++ const p1 = await getTierPass();+ expect(p1).toBe(pass);+ expect(fetchMock).toHaveBeenCalledWith('/api/three/tier-pass', {+ method: 'POST',+ credentials: 'include',+ });+ expect(JSON.parse(window.sessionStorage.getItem('three_tier_pass')).pass).toBe(pass);++ // A fresh pass is reused — no second network call.+ const p2 = await getTierPass();+ expect(p2).toBe(pass);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ it('returns null and stores nothing when unauthenticated (401)', async () => {+ global.fetch = vi.fn(() => jsonRes(401, { error: 'unauthorized' }));+ expect(await getTierPass()).toBeNull();+ expect(window.sessionStorage.getItem('three_tier_pass')).toBeNull();+ });++ it('re-mints once the pass is within the staleness window', async () => {+ const nearExpiry = makePass(Math.floor(Date.now() / 1000) + 60); // < 2-min buffer+ const fetchMock = vi.fn(() => jsonRes(201, { pass: nearExpiry }));+ global.fetch = fetchMock;+ await getTierPass();+ await getTierPass();+ expect(fetchMock).toHaveBeenCalledTimes(2);+ });++ it('re-fetches after clearTierPass drops the cache', async () => {+ const fetchMock = vi.fn(() => jsonRes(201, { pass: freshPass() }));+ global.fetch = fetchMock;+ await getTierPass();+ clearTierPass();+ await getTierPass();+ expect(fetchMock).toHaveBeenCalledTimes(2);+ });+});++describe('threeHeaders', () => {+ it('carries the pass header when a pass is available', async () => {+ const pass = freshPass();+ global.fetch = vi.fn(() => jsonRes(201, { pass }));+ expect(await threeHeaders()).toEqual({ 'x-three-tier-pass': pass });+ });++ it('is an empty object when no pass is available', async () => {+ global.fetch = vi.fn(() => jsonRes(401, {}));+ expect(await threeHeaders()).toEqual({});+ });+});++describe('wallet:changed auto-wire', () => {+ it('clears the cached pass and broadcasts three:tier-changed', async () => {+ global.fetch = vi.fn(() => jsonRes(201, { pass: freshPass() }));+ await getTierPass();+ expect(window.sessionStorage.getItem('three_tier_pass')).toBeTruthy();++ const relay = vi.fn();+ window.addEventListener('three:tier-changed', relay);+ window.dispatchEvent(new CustomEvent('wallet:changed', { detail: { address: null } }));+ window.removeEventListener('three:tier-changed', relay);++ expect(relay).toHaveBeenCalledOnce();+ expect(window.sessionStorage.getItem('three_tier_pass')).toBeNull();+ });+});++// ── <three-gate> ────────────────────────────────────────────────────────────++describe('<three-gate> — lifecycle & states', () => {+ it('shows a skeleton (not a flash of locked) while access is resolving', async () => {+ global.fetch = vi.fn(() => new Promise(() => {})); // never resolves+ const el = mountGate({ feature: 'forge.high' });+ const root = el.shadowRoot;+ expect(root.querySelector('.tg-root').dataset.state).toBe('loading');+ expect(root.querySelector('.tg-card--skel')).toBeTruthy();+ expect(root.querySelector('[role="status"]').textContent).toMatch(/checking/i);+ // Gated child is inert (not tab-reachable) while we don't yet know access.+ expect(el.querySelector('#premium').inert).toBe(true);+ });++ it('renders the locked card with held-vs-required, progress, CTA and pay line', async () => {+ global.fetch = vi.fn(() => jsonRes(200, LOCKED));+ const el = mountGate({ feature: 'forge.high' });+ await flush();+ const root = el.shadowRoot;+ expect(root.querySelector('.tg-root').dataset.state).toBe('locked');++ const card = root.querySelector('.tg-card');+ expect(card.getAttribute('role')).toBe('group');+ expect(card.textContent).toMatch(/You hold\s*\$10\s*·\s*Member/);+ expect(card.textContent).toMatch(/Requires\s*Bronze\s*·\s*\$25/);++ // Progress = held_usd (10) / required min_usd (25) = 40%.+ const fill = root.querySelector('.tg-prog-fill');+ expect(fill.getAttribute('style')).toContain('width:40%');+ expect(root.querySelector('.tg-prog-cap').textContent).toMatch(/40% there/);++ // Get $THREE → a real Jupiter swap URL for the canonical mint.+ const get = root.querySelector('[data-tg-get]');+ expect(get.tagName).toBe('A');+ expect(get.getAttribute('href')).toBe(+ 'https://jup.ag/swap/SOL-FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump',+ );+ expect(get.getAttribute('target')).toBe('_blank');++ // pay-per-use line + perks link.+ expect(card.textContent).toMatch(/or pay\s*\$0\.50\s*per use/);+ expect(root.querySelector('a.tg-perks').getAttribute('href')).toBe('/three');++ // Child stays inert behind the lock.+ expect(el.querySelector('#premium').inert).toBe(true);+ });++ it('reveals children, clears inert, and emits three-gate:unlocked for a holder', async () => {+ global.fetch = vi.fn(() => jsonRes(200, UNLOCKED));+ const el = mountGate({ feature: 'forge.high' });+ const detail = vi.fn();+ el.addEventListener('three-gate:unlocked', (e) => detail(e.detail));+ await flush();+ const root = el.shadowRoot;++ expect(root.querySelector('.tg-root').dataset.state).toBe('unlocked');+ expect(root.querySelector('.tg-veil-inner').innerHTML).toBe('');+ expect(el.querySelector('#premium').inert).toBe(false);+ expect(detail).toHaveBeenCalledOnce();+ expect(detail.mock.calls[0][0]).toMatchObject({ feature: 'forge.high', tier: { id: 'silver' } });+ });++ it('renders an actionable, retryable error on a degraded read', async () => {+ const fetchMock = vi.fn(() => Promise.reject(new Error('offline')));+ global.fetch = fetchMock;+ const el = mountGate({ feature: 'forge.high' });+ await flush();+ const root = el.shadowRoot;+ expect(root.querySelector('.tg-root').dataset.state).toBe('error');+ expect(root.querySelector('[role="alert"]').textContent).toMatch(/couldn.t check/i);++ // Retry re-reads access; this time it resolves to unlocked.+ fetchMock.mockImplementation(() => jsonRes(200, UNLOCKED));+ root.querySelector('[data-tg-retry]').click();+ await flush();+ expect(root.querySelector('.tg-root').dataset.state).toBe('unlocked');+ });++ it('fails closed (locked + inert) when the required feature attribute is missing', async () => {+ global.fetch = vi.fn(() => jsonRes(200, UNLOCKED));+ const el = mountGate({}); // no feature+ await flush();+ expect(el.shadowRoot.querySelector('.tg-root').dataset.state).toBe('error');+ expect(global.fetch).not.toHaveBeenCalled();+ expect(el.querySelector('#premium').inert).toBe(true);+ });+});++describe('<three-gate> — reason-specific secondaries', () => {+ it('reason=sign_in offers a Sign in link', async () => {+ global.fetch = vi.fn(() => jsonRes(200, withReason('sign_in')));+ const el = mountGate({ feature: 'forge.high' });+ await flush();+ expect(el.shadowRoot.querySelector('a[href="/login"]')).toBeTruthy();+ });++ it('reason=link_wallet offers a Connect wallet button', async () => {+ global.fetch = vi.fn(() => jsonRes(200, withReason('link_wallet')));+ const el = mountGate({ feature: 'forge.high' });+ await flush();+ const connect = el.shadowRoot.querySelector('[data-tg-connect]');+ expect(connect).toBeTruthy();+ expect(connect.tagName).toBe('BUTTON');+ });++ it('reason=insufficient_tier shows a "hold to unlock" explainer instead of a button', async () => {+ global.fetch = vi.fn(() => jsonRes(200, LOCKED));+ const el = mountGate({ feature: 'forge.high' });+ await flush();+ const root = el.shadowRoot;+ expect(root.querySelector('.tg-hold-hint')).toBeTruthy();+ expect(root.querySelector('[data-tg-connect]')).toBeNull();+ });+});++describe('<three-gate> — hardening', () => {+ it('escapes untrusted strings from the access payload', async () => {+ global.fetch = vi.fn(() =>+ jsonRes(200, {+ ...LOCKED,+ access: {+ ...LOCKED.access,+ label: '<img src=x onerror=alert(1)>',+ required: { ...LOCKED.access.required, label: '<script>bad</script>' },+ },+ }),+ );+ const el = mountGate({ feature: 'forge.high' });+ await flush();+ const root = el.shadowRoot;+ expect(root.querySelector('img')).toBeNull();+ expect(root.querySelector('script')).toBeNull();+ });++ it('reflects the mode attribute onto the root for replace styling', async () => {+ global.fetch = vi.fn(() => jsonRes(200, LOCKED));+ const el = mountGate({ feature: 'forge.high', mode: 'replace' });+ await flush();+ expect(el.shadowRoot.querySelector('.tg-root').dataset.mode).toBe('replace');+ });+});diff --git a/tests/three-lock.test.js b/tests/three-lock.test.jsnew file mode 100644index 000000000..56d9fe902--- /dev/null+++ b/tests/three-lock.test.js@@ -0,0 +1,215 @@+// @vitest-environment jsdom+//+// Unit tests for the $THREE in-place lock UI (src/three-lock.js) and the headers+// helper on src/three-access.js. These prove the five rendered states, the access+// → state mapping, the "no dead button" rule (pay/use-free only when a handler is+// wired), the handler wiring (retry / use-free / pay / get-three), and that a+// gated request carries no tier-pass header when none is cached. DOM-only; no+// network — the live endpoint is covered by the api/_lib/three-access registry+// tests and the forge-high-gate HTTP tests.++import { describe, it, expect, beforeEach, vi } from 'vitest';+import { renderLock, lockStateFromAccess } from '../src/three-lock.js';+import { attachTierPass } from '../src/three-access.js';++function host() {+ const el = document.createElement('div');+ document.body.appendChild(el);+ return el;+}++const INELIGIBLE = {+ feature: 'forge.high',+ label: 'High-quality generation (200k poly + PBR)',+ why: 'The High tier spends real GPU/vendor budget.',+ eligible: false,+ required: { level: 1, id: 'bronze', label: 'Bronze' },+ held: { level: 0, id: 'member', label: 'Member', usd: 0 },+ reason: 'insufficient_tier',+ pay_per_use: { action: 'forge.high', usd: 0.5 },+};++const ELIGIBLE = {+ feature: 'forge.high',+ label: 'High-quality generation',+ eligible: true,+ required: { level: 1, id: 'bronze', label: 'Bronze' },+ held: { level: 2, id: 'silver', label: 'Silver', usd: 120 },+ reason: 'eligible',+ pay_per_use: { action: 'forge.high', usd: 0.5 },+};++beforeEach(() => {+ document.body.innerHTML = '';+});++describe('lockStateFromAccess', () => {+ it('maps an eligible payload to the unlocked state', () => {+ const s = lockStateFromAccess(ELIGIBLE);+ expect(s.eligible).toBe(true);+ expect(s.tier).toEqual(ELIGIBLE.held);+ });++ it('maps an ineligible payload to a locked state with pay-per-use', () => {+ const s = lockStateFromAccess(INELIGIBLE);+ expect(s.eligible).toBeUndefined();+ expect(s.reason).toBe('insufficient_tier');+ expect(s.required.label).toBe('Bronze');+ expect(s.payPerUse).toEqual({ action: 'forge.high', usd: 0.5 });+ });++ it('maps a null payload (network failure) to the error state', () => {+ expect(lockStateFromAccess(null)).toEqual({ error: true });+ });++ it('merges extra handlers/urls through', () => {+ const onUseFree = () => {};+ const s = lockStateFromAccess(INELIGIBLE, { getThreeUrl: '/three', onUseFree });+ expect(s.getThreeUrl).toBe('/three');+ expect(s.onUseFree).toBe(onUseFree);+ });+});++describe('renderLock — states', () => {+ it('loading renders a skeleton + an SR status, no overlay card', () => {+ const el = host();+ renderLock(el, { loading: true });+ expect(el.hidden).toBe(false);+ expect(el.querySelector('.tl-card--skel')).toBeTruthy();+ expect(el.querySelector('[role="status"]').textContent).toMatch(/checking/i);+ });++ it('clear empties + hides the host', () => {+ const el = host();+ renderLock(el, { loading: true });+ renderLock(el, { clear: true });+ expect(el.hidden).toBe(true);+ expect(el.innerHTML).toBe('');+ });++ it('unlocked renders a ribbon tinted by tier (silver)', () => {+ const el = host();+ renderLock(el, { eligible: true, tier: { id: 'silver', label: 'Silver' } });+ const ribbon = el.querySelector('.tl-ribbon');+ expect(ribbon).toBeTruthy();+ expect(ribbon.classList.contains('tl-silver')).toBe(true);+ expect(ribbon.textContent).toMatch(/Unlocked · Silver/);+ expect(el.querySelector('.tl-card--lock')).toBeNull();+ });++ it('locked (insufficient_tier) shows required tier, held line, progress + Get $THREE', () => {+ const el = host();+ renderLock(el, lockStateFromAccess(INELIGIBLE, { getThreeUrl: '/three' }));+ const card = el.querySelector('.tl-card--lock');+ expect(card).toBeTruthy();+ expect(card.getAttribute('role')).toBe('group');+ expect(card.textContent).toMatch(/Requires\s*Bronze/);+ expect(card.textContent).toMatch(/You hold\s*Member/);+ const get = el.querySelector('[data-tl-get]');+ expect(get.tagName).toBe('A');+ expect(get.getAttribute('href')).toBe('/three');+ expect(el.querySelector('.tl-prog')).toBeTruthy();+ });++ it('reason=sign_in shows the sign-in sub + a working Sign in link, no progress', () => {+ const el = host();+ renderLock(el, {+ required: { level: 1, id: 'bronze', label: 'Bronze' },+ held: { level: 0, id: 'member', label: 'Member' },+ reason: 'sign_in',+ });+ expect(el.querySelector('.tl-sub').textContent).toMatch(/sign in/i);+ expect(el.querySelector('a[href="/login"]')).toBeTruthy();+ expect(el.querySelector('.tl-prog')).toBeNull();+ });++ it('reason=link_wallet shows a Link a wallet link', () => {+ const el = host();+ renderLock(el, {+ required: { level: 1, id: 'bronze', label: 'Bronze' },+ held: { level: 0, id: 'member', label: 'Member' },+ reason: 'link_wallet',+ });+ expect(el.querySelector('.tl-sub').textContent).toMatch(/link a solana wallet/i);+ expect(el.querySelector('a[href*="wallets"]')).toBeTruthy();+ });++ it('error renders an alert and a wired Retry button', () => {+ const el = host();+ const onRetry = vi.fn();+ renderLock(el, { error: true, onRetry });+ const alert = el.querySelector('[role="alert"]');+ expect(alert.textContent).toMatch(/couldn.t check access/i);+ el.querySelector('[data-tl-retry]').click();+ expect(onRetry).toHaveBeenCalledOnce();+ });++ it('error without an onRetry drops the dead Retry button', () => {+ const el = host();+ renderLock(el, { error: true });+ expect(el.querySelector('[data-tl-retry]')).toBeNull();+ });+});++describe('renderLock — no dead buttons & wiring', () => {+ it('omits Pay-per-use when no handler is supplied (no dead button)', () => {+ const el = host();+ renderLock(el, lockStateFromAccess(INELIGIBLE)); // payPerUse present, no handler+ expect(el.querySelector('[data-tl-pay]')).toBeNull();+ });++ it('renders + wires Pay-per-use when a handler is supplied', () => {+ const el = host();+ const onPayPerUse = vi.fn();+ renderLock(el, lockStateFromAccess(INELIGIBLE, { onPayPerUse }));+ const pay = el.querySelector('[data-tl-pay]');+ expect(pay).toBeTruthy();+ expect(pay.textContent).toMatch(/\$0\.50 per generation/);+ pay.click();+ expect(onPayPerUse).toHaveBeenCalledWith({ action: 'forge.high', usd: 0.5 });+ });++ it('wires Use-a-free-tier and Get $THREE handlers', () => {+ const el = host();+ const onUseFree = vi.fn();+ const onGetThree = vi.fn();+ renderLock(el, lockStateFromAccess(INELIGIBLE, { onUseFree, onGetThree, useFreeLabel: 'Use Standard (free)' }));+ const free = el.querySelector('[data-tl-free]');+ expect(free.textContent).toBe('Use Standard (free)');+ free.click();+ expect(onUseFree).toHaveBeenCalledOnce();+ const get = el.querySelector('[data-tl-get]');+ get.dispatchEvent(new window.Event('click', { cancelable: true, bubbles: true }));+ expect(onGetThree).toHaveBeenCalledOnce();+ });++ it('escapes untrusted strings in the locked card', () => {+ const el = host();+ renderLock(el, {+ required: { level: 1, id: 'bronze', label: '<img src=x>' },+ held: { level: 0, id: 'member', label: 'Member' },+ reason: 'insufficient_tier',+ label: '<script>alert(1)</script>',+ });+ expect(el.querySelector('img')).toBeNull();+ expect(el.querySelector('script')).toBeNull();+ });++ it('a missing target is a safe no-op', () => {+ expect(() => renderLock(null, { loading: true })).not.toThrow();+ expect(() => renderLock('#nope', { loading: true })).not.toThrow();+ });+});++describe('attachTierPass', () => {+ it('returns the headers object unchanged when no pass is cached', () => {+ const h = { 'content-type': 'application/json' };+ const out = attachTierPass(h);+ expect(out).toBe(h);+ expect(out['x-three-tier-pass']).toBeUndefined();+ });++ it('defaults to a fresh object when called with no args', () => {+ expect(attachTierPass()).toEqual({});+ });+});diff --git a/tests/three-require.test.js b/tests/three-require.test.jsnew file mode 100644index 000000000..1a750162d--- /dev/null+++ b/tests/three-require.test.js@@ -0,0 +1,184 @@+// Unit tests for the $THREE server-enforcement helper (api/_lib/require-three.js).+//+// requireFeatureAccess is the keystone gate: it turns the three-access registry+// into a real entitlement check. These prove the resolution order (pass-first,+// then on-chain, then anonymous Member), the hold-or-pay 402 payload, the typed+// 404 for an unknown feature, and that a valid pass is never blocked by an RPC+// outage. Balance/price reads and the session lookup are mocked — no DB, no RPC.++import { describe, it, expect, vi, beforeEach } from 'vitest';++const getBalances = vi.fn();+const getTokenPriceUsd = vi.fn();+const getSessionUser = vi.fn();+vi.mock('../api/_lib/balances.js', () => ({ getBalances: (...a) => getBalances(...a) }));+vi.mock('../api/_lib/token/price.js', () => ({ getTokenPriceUsd: (...a) => getTokenPriceUsd(...a) }));+vi.mock('../api/_lib/auth.js', () => ({ getSessionUser: (...a) => getSessionUser(...a) }));++import { requireFeatureAccess } from '../api/_lib/require-three.js';+import { signTierPass } from '../api/_lib/three-tier.js';+import { TOKEN_MINT } from '../api/_lib/token/config.js';++const WALLET = 'So11111111111111111111111111111111111111112';++function mockRes() {+ return {+ statusCode: 200, _headers: {}, _body: '', _ended: false,+ setHeader(k, v) { this._headers[k.toLowerCase()] = v; },+ getHeader(k) { return this._headers[k.toLowerCase()]; },+ end(b) { this._body = b || ''; this._ended = true; },+ get json() { try { return JSON.parse(this._body); } catch { return null; } },+ };+}++function mockReq({ headers = {} } = {}) {+ return { method: 'POST', url: '/api/forge', headers: { ...headers } };+}++// Drive resolveUserTier(user) → tierForUsd via the mocked balance read.+function balancesWorthUsd(usd) {+ getBalances.mockResolvedValue({ tokens: [{ mint: TOKEN_MINT, amount: 1, usd, price: usd }] });+}++beforeEach(() => {+ vi.clearAllMocks();+ // Symmetric sign/verify + bypass the prod secret guard.+ process.env.HOLDER_PASS_SECRET = 'three-require-test-secret';+ process.env.NODE_ENV = 'test';+ getSessionUser.mockResolvedValue(null); // anonymous unless a case overrides it+});++describe('requireFeatureAccess — pass-first resolution', () => {+ it('allows a valid pass at/above the required level and writes nothing', async () => {+ const pass = signTierPass({ wallet: WALLET, level: 1, tierId: 'bronze', usd: 30 });+ const res = mockRes();+ const gate = await requireFeatureAccess(+ mockReq({ headers: { 'x-three-tier-pass': pass } }),+ res,+ 'forge.high',+ );+ expect(gate.ok).toBe(true);+ expect(gate.level).toBe(1);+ expect(gate.wallet).toBe(WALLET);+ expect(res._ended).toBe(false); // nothing written on the allow path+ expect(getSessionUser).not.toHaveBeenCalled(); // pass short-circuits before auth/RPC+ });++ it('blocks a valid pass BELOW the required level — 402 with the full payload', async () => {+ const pass = signTierPass({ wallet: WALLET, level: 0, tierId: 'member', usd: 0 });+ const res = mockRes();+ const gate = await requireFeatureAccess(+ mockReq({ headers: { 'x-three-tier-pass': pass } }),+ res,+ 'forge.high',+ );+ expect(gate.ok).toBe(false);+ expect(res.statusCode).toBe(402);+ const b = res.json;+ expect(b.error).toBe('three_hold_required');+ expect(b.feature).toBe('forge.high');+ expect(b.required).toMatchObject({ level: 1, id: 'bronze', min_usd: 25 });+ expect(b.held).toMatchObject({ level: 0, id: 'member', usd: 0 });+ expect(b.reason).toBe('insufficient_tier'); // a presented pass is not "sign in"+ expect(b.pay_per_use).toMatchObject({ action: 'forge.high', usd: 0.5 });+ });++ it('does NOT block a valid pass holder when the balance RPC throws', async () => {+ getBalances.mockRejectedValue(new Error('rpc down'));+ const pass = signTierPass({ wallet: WALLET, level: 2, tierId: 'silver', usd: 150 });+ const res = mockRes();+ const gate = await requireFeatureAccess(+ mockReq({ headers: { 'x-three-tier-pass': pass } }),+ res,+ 'forge.high',+ );+ expect(gate.ok).toBe(true);+ expect(getBalances).not.toHaveBeenCalled(); // pass path never reaches the RPC+ });+});++describe('requireFeatureAccess — on-chain fallback (no pass)', () => {+ it('allows a holder resolved via their linked wallet (mock balances → Bronze)', async () => {+ getSessionUser.mockResolvedValue({ id: 'u1', wallet_address: WALLET });+ balancesWorthUsd(30); // ≥ $25 → Bronze+ const res = mockRes();+ const gate = await requireFeatureAccess(mockReq(), res, 'forge.high');+ expect(gate.ok).toBe(true);+ expect(gate.level).toBe(1);+ expect(res._ended).toBe(false);+ });++ it('blocks a signed-in holder whose wallet is below the threshold — reason insufficient_tier', async () => {+ getSessionUser.mockResolvedValue({ id: 'u1', wallet_address: WALLET });+ balancesWorthUsd(10); // < $25 → Member+ const res = mockRes();+ const gate = await requireFeatureAccess(mockReq(), res, 'forge.high');+ expect(gate.ok).toBe(false);+ expect(res.statusCode).toBe(402);+ expect(res.json.reason).toBe('insufficient_tier');+ expect(res.json.held).toMatchObject({ level: 0, usd: 10 });+ expect(res.json.usd_to_go).toBe(15); // 25 − 10+ });++ it('blocks a signed-in user with no linked wallet — reason link_wallet', async () => {+ getSessionUser.mockResolvedValue({ id: 'u1', wallet_address: null });+ const res = mockRes();+ const gate = await requireFeatureAccess(mockReq(), res, 'forge.high');+ expect(gate.ok).toBe(false);+ expect(res.statusCode).toBe(402);+ expect(res.json.reason).toBe('link_wallet');+ });+});++describe('requireFeatureAccess — anonymous + options + errors', () => {+ it('blocks an anonymous caller — 402 reason sign_in + canonical acquire block', async () => {+ const res = mockRes();+ const gate = await requireFeatureAccess(mockReq(), res, 'forge.high');+ expect(gate.ok).toBe(false);+ expect(res.statusCode).toBe(402);+ const b = res.json;+ expect(b.reason).toBe('sign_in');+ expect(b.acquire.mint).toBe(TOKEN_MINT);+ expect(b.acquire.swap_url).toContain(TOKEN_MINT);+ expect(b.acquire.pump_url).toContain(TOKEN_MINT);+ expect(b.acquire.symbol).toBe('THREE');+ expect(b.usd_to_go).toBe(25);+ });++ it('omits pay-per-use when allowPayPerUse is false', async () => {+ const res = mockRes();+ const gate = await requireFeatureAccess(mockReq(), res, 'forge.high', { allowPayPerUse: false });+ expect(gate.ok).toBe(false);+ expect(res.json.pay_per_use).toBeNull();+ });++ it('reads the pass from opts.body.tier_pass as well as the header', async () => {+ const pass = signTierPass({ wallet: WALLET, level: 1, tierId: 'bronze', usd: 30 });+ const res = mockRes();+ const gate = await requireFeatureAccess(mockReq(), res, 'forge.high', { body: { tier_pass: pass } });+ expect(gate.ok).toBe(true);+ });++ it('returns a typed 404 for an unknown feature id', async () => {+ const res = mockRes();+ const gate = await requireFeatureAccess(mockReq(), res, 'forge.nope');+ expect(gate.ok).toBe(false);+ expect(res.statusCode).toBe(404);+ expect(res.json.error).toBe('unknown_feature');+ });++ it('gates a higher-tier feature (worlds.private, Silver) for a Bronze holder', async () => {+ const pass = signTierPass({ wallet: WALLET, level: 1, tierId: 'bronze', usd: 30 });+ const res = mockRes();+ const gate = await requireFeatureAccess(+ mockReq({ headers: { 'x-three-tier-pass': pass } }),+ res,+ 'worlds.private',+ );+ expect(gate.ok).toBe(false);+ expect(res.statusCode).toBe(402);+ expect(res.json.required).toMatchObject({ level: 2, id: 'silver' });+ // worlds.private has no pay-per-use path — it's hold-only.+ expect(res.json.pay_per_use).toBeNull();+ });+});diff --git a/tests/three-tier-public.test.js b/tests/three-tier-public.test.jsnew file mode 100644index 000000000..47c8f0432--- /dev/null+++ b/tests/three-tier-public.test.js@@ -0,0 +1,155 @@+// HTTP-level tests for the public $THREE tier surface added in api/three/[action].js:+// GET /api/three/tier?wallet=<addr> — account-less tier read for a connected wallet+// POST /api/three/tier-pass — signature-proven tier pass (no account)+//+// Balance/price reads are mocked so the tier resolves deterministically; signatures+// are produced with real ed25519 keypairs so the verify path runs end-to-end.++import { describe, it, expect, beforeAll, vi } from 'vitest';+import { Readable } from 'node:stream';+import { ed25519 } from '@noble/curves/ed25519.js';+import bs58mod from 'bs58';++const bs58 = bs58mod.default || bs58mod;++// $THREE held-USD comes from getBalances(); mock it so we control the tier.+const getBalances = vi.fn();+const getTokenPriceUsd = vi.fn();+vi.mock('../api/_lib/balances.js', () => ({ getBalances: (...a) => getBalances(...a) }));+vi.mock('../api/_lib/token/price.js', () => ({ getTokenPriceUsd: (...a) => getTokenPriceUsd(...a) }));++let handler, TOKEN_MINT, verifyTierPass;++function mockRes() {+ return {+ statusCode: 200,+ _headers: {},+ _body: '',+ _ended: false,+ setHeader(k, v) { this._headers[k.toLowerCase()] = v; },+ getHeader(k) { return this._headers[k.toLowerCase()]; },+ end(b) { this._body = b || ''; this._ended = true; },+ get json() { try { return JSON.parse(this._body); } catch { return null; } },+ };+}++function mockReq({ method = 'GET', url = '/', body = null } = {}) {+ const chunks = body != null ? [Buffer.from(JSON.stringify(body))] : [];+ const r = Readable.from(chunks);+ r.method = method;+ r.url = url;+ r.headers = { origin: 'http://localhost:3000', 'content-type': 'application/json' };+ return r;+}++function newKeypair() {+ const sk = ed25519.utils.randomSecretKey();+ const pk = ed25519.getPublicKey(sk);+ return { sk, pk, address: bs58.encode(pk) };+}++// MUST stay byte-identical to the client builder (src/three/holder.js) and the+// server validator (checkTierPassMessage in api/three/[action].js).+function buildTierPassMessage(wallet, issuedAt = new Date().toISOString()) {+ 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');+}++function sign(sk, message) {+ return bs58.encode(ed25519.sign(new TextEncoder().encode(message), sk));+}++beforeAll(async () => {+ process.env.NODE_ENV = 'development';+ process.env.HOLDER_PASS_SECRET = 'three-tier-public-test-secret';+ const mod = await import('../api/three/[action].js');+ handler = mod.default;+ ({ TOKEN_MINT } = await import('../api/_lib/token/config.js'));+ ({ verifyTierPass } = await import('../api/_lib/three-tier.js'));+});++describe('GET /api/three/tier?wallet=', () => {+ it('resolves Member for a zero-balance wallet, no account needed', async () => {+ getBalances.mockResolvedValue({ tokens: [] });+ const { address } = newKeypair();+ const res = mockRes();+ await handler(mockReq({ url: `/api/three/tier?wallet=${address}` }), res);+ expect(res.statusCode).toBe(200);+ expect(res.json.tier.id).toBe('member');+ expect(res.json.source).toBe('wallet');+ expect(res.json.wallet).toBe(address);+ expect(Array.isArray(res.json.ladder)).toBe(true);+ });++ it('resolves the right tier from held USD', async () => {+ getBalances.mockResolvedValue({ tokens: [{ mint: TOKEN_MINT, amount: 5000, usd: 600, price: 0.12 }] });+ const { address } = newKeypair();+ const res = mockRes();+ await handler(mockReq({ url: `/api/three/tier?wallet=${address}` }), res);+ expect(res.statusCode).toBe(200);+ expect(res.json.tier.id).toBe('gold');+ expect(res.json.held_usd).toBe(600);+ });++ it('rejects a malformed wallet with 400', async () => {+ const res = mockRes();+ await handler(mockReq({ url: '/api/three/tier?wallet=not-a-wallet' }), res);+ expect(res.statusCode).toBe(400);+ expect(res.json.error).toBe('invalid_wallet');+ });+});++describe('POST /api/three/tier-pass (signature path)', () => {+ it('mints a verifiable, wallet-bound pass for a valid signature', async () => {+ getBalances.mockResolvedValue({ tokens: [{ mint: TOKEN_MINT, amount: 5000, usd: 600, price: 0.12 }] });+ const { sk, address } = newKeypair();+ const message = buildTierPassMessage(address);+ const res = mockRes();+ await handler(mockReq({ method: 'POST', url: '/api/three/tier-pass', body: { wallet: address, message, signature: sign(sk, message) } }), res);+ expect(res.statusCode).toBe(201);+ expect(typeof res.json.pass).toBe('string');+ const payload = verifyTierPass(res.json.pass);+ expect(payload).toBeTruthy();+ expect(payload.wallet).toBe(address);+ expect(payload.tierId).toBe('gold');+ expect(payload.level).toBe(3);+ });++ it('rejects a signature that does not match the wallet', async () => {+ getBalances.mockResolvedValue({ tokens: [] });+ const { address } = newKeypair();+ const other = newKeypair();+ const message = buildTierPassMessage(address);+ const res = mockRes();+ await handler(mockReq({ method: 'POST', url: '/api/three/tier-pass', body: { wallet: address, message, signature: sign(other.sk, message) } }), res);+ expect(res.statusCode).toBe(401);+ expect(res.json.error).toBe('bad_signature');+ });++ it('rejects a stale message (issued too long ago)', async () => {+ const { sk, address } = newKeypair();+ const stale = new Date(Date.now() - 10 * 60 * 1000).toISOString();+ const message = buildTierPassMessage(address, stale);+ const res = mockRes();+ await handler(mockReq({ method: 'POST', url: '/api/three/tier-pass', body: { wallet: address, message, signature: sign(sk, message) } }), res);+ expect(res.statusCode).toBe(401);+ expect(res.json.error).toBe('stale_message');+ });++ it('rejects a message not bound to the wallet', async () => {+ const { sk, address } = newKeypair();+ const other = newKeypair();+ // Signed correctly for `address`, but the message names a different wallet.+ const message = buildTierPassMessage(other.address);+ const res = mockRes();+ await handler(mockReq({ method: 'POST', url: '/api/three/tier-pass', body: { wallet: address, message, signature: sign(sk, message) } }), res);+ expect(res.statusCode).toBe(401);+ expect(res.json.error).toBe('wallet_mismatch');+ });+});diff --git a/vite.config.js b/vite.config.jsindex e2891f8fd..8d7fb1287 100644--- a/vite.config.js+++ b/vite.config.js@@ -262,7 +262,8 @@ const appConfig = {entryFileNames: (chunk) =>chunk.name === 'footer-bot' ||chunk.name === 'walk-companion' ||- chunk.name === 'notifications'+ chunk.name === 'notifications' ||+ chunk.name === 'nav-tier-badge'? `${chunk.name}.js`: 'assets/[name]-[hash].js',},@@ -270,6 +271,7 @@ const appConfig = {'footer-bot': resolve(__dirname, 'src/footer-bot.js'),'walk-companion': resolve(__dirname, 'src/walk-companion.js'),notifications: resolve(__dirname, 'src/notifications.js'),+ 'nav-tier-badge': resolve(__dirname, 'src/nav-tier-badge.js'),app: resolve(__dirname, 'pages/app.html'),'app-demo': resolve(__dirname, 'pages/app-demo.html'),'app-next': resolve(__dirname, 'pages/app-next.html'),@@ -1194,6 +1196,12 @@ support: resolve(__dirname, 'pages/support.html'),req.url = '/src/notifications.js';return next();}+ // /nav-tier-badge.js — nav.js loads this module for the $THREE+ // holder tier chip (built to a stable, unhashed name in prod).+ if (path === '/nav-tier-badge.js') {+ req.url = '/src/nav-tier-badge.js';+ return next();+ }// Avatar Studio (rebranded Character Studio fork) — serve the// production build out of character-studio/build/ at /avatar-studio/*// so the demo iframe works in dev. Run `npm run build --prefix