Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
Add $THREE economy page + holder rewards, rare-name pricing, pay-per-use rail
nirholas3f49a5352cd1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 58d49d87b..bdc36bfc2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr## 2026-06-15- **Sniper Arena — autonomous AI agents trading live** (`/play/arena`) — Watch three.ws AI agents trade pump.fun autonomously in real time. Live P&L leaderboard, each trade signed by the agent's own wallet and verifiable on-chain.+- **The $THREE Economy** (`/three`) — How three.ws charges in $THREE, the only coin: pay-per-use pricing for AI compute, hold-to-access holder tiers with lower fees, rare *.threews.sol names, and a holder-rewards loop. No burns — every spend funds the treasury or reflects back to holders.- **After you launch a coin, jump straight to viewing or managing it** — The success screen you see right after launching a coin no longer dead-ends. Alongside the shareable card and copy/share buttons, there's now a clear set of next steps: View in 3D opens your coin as a live, interactive 3D scene; Manage on Dashboard takes you straight to that agent's control panel — with its row highlighted and ready — so you can speak, animate, and manage it; and View on pump.fun opens the coin on pump.fun. Closing the modal no longer forces a full page reload, so the rest of the page updates smoothly in place. (`/pump-dashboard`) `[improvement]`- **Agent reputation now reflects a real pump.fun track record** — An agent's pump.fun behavior now feeds its reputation and shows on its passport. When the wallet behind an agent graduates a token, claims creator fees, makes a whale-sized buy, or launches a coin, that moment is recorded as a typed signal — graduating a token counts for more than a routine claim, and a flagged or brand-new-account claim counts against. These signals roll up into the agent's Solana reputation score and appear on the public agent passport, readable by anyone without a wallet. The live pump.fun dashboard gains a new "SIGNAL" lane that surfaces these agent-attributed events as they happen, alongside the raw mint, whale, and claim feed. The processor behind this used to sit idle unless an optional external service was configured; it now runs continuously off the platform's own live pump.fun stream with no external dependency, records only genuinely new events so nothing is double-counted, and attributes each one to the agent behind the wallet. (`/pump-dashboard`) `[improvement, fix]`- **Agents and items are now clearly separate — a teapot won't get a brain** — Every 3D model you create is now clearly one of two things: an Agent (a character that thinks, talks, remembers, and can go on-chain) or an Item (a 3D object or prop for scenes and trading). On the review screen the choice is spelled out with a short description of each, and we pick a smart default — models from the selfie, studio, and character tools start as agents, while anything you type into existence with prompt-to-3D starts as an item, so a teapot is never pre-loaded with a brain. Pick Item and the agent-only capabilities (voice, persona, on-chain identity) step aside for a gentle note — with a one-click "made a character? make it an agent" escape hatch if the guess was wrong. The Forge tagger now groups its labels the same way, calling out that only avatars and creatures can become agents. (`/create`) `[improvement]`@@ -18,6 +19,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Camera AR on /irl now turns on** — The "Camera AR" button on the IRL page was stuck — it never lit up, on desktop or phone, so you could never drop your avatar into your real room. Two bugs were behind it: a startup error in the joystick setup crashed the page's script before the button could ever be enabled, and even once that was past, the camera could hang on "Requesting camera…" forever because playback was started before the video was visible. Both are fixed: the button now activates once your avatar loads, and tapping it opens the camera reliably on phone and desktop so you can walk your avatar across your real floor. (`/irl`) `[fix]`- **Chat never stalls on a down AI model — instant, quiet failover** — If you pick a specific AI model for the agent (say Claude) and our key for that provider is temporarily unavailable, chat now hands you an answer instantly from a healthy free model instead of pausing on the dead provider. Previously the app re-tried the unavailable provider on the very first attempt of every single message — adding a little delay each time and filling our logs with repeat warnings. Now a provider with a key or billing problem is set aside for a few minutes after the first failure and skipped up front, even when it was the one you explicitly chose, so the next message goes straight to a model that works. Free-first, always a working fallback. (`/chat`) `[improvement]`- **Clearer launch & trade errors, and a graduated badge on coins** — When a token launch or an in-world trade can't go through, the app now tells you exactly why and what to do next — "Not enough SOL to cover the launch + network fees," "Price moved beyond your slippage limit," "You cancelled the signature in your wallet," or "Couldn't reach the Solana network" — instead of a single catch-all "Connection error." Coins also show their lifecycle at a glance: the trade panel carries a badge marking whether a coin is still on its bonding curve or has graduated to the PumpSwap AMM, so a graduated coin is unmistakable. Backed by new end-to-end browser tests that drive the full four-step launch flow and the buy/sell widget so this conversion path can't silently break. (`/pump-dashboard`) `[improvement]`+- **Four distinct dancers, now waiting at their poles** — The Pole Club stage no longer sits empty between tips. All four dancers now stand at their own poles, lit and facing the crowd, the moment you arrive — and each is a different 3D model instead of four copies of one, so Aria, Nova, Blaze, and Luna actually look like four different performers (still tinted to their pole's neon color). Tip a pole and that dancer steps onto it and runs her routine, then returns to her stance at the pole. No tip, no dance — same rule, just a stage that looks alive from the first second. (`/club`) `[improvement]`- **Homepage Forge is more reliable — no more "busy" on the second model** — The mini Forge on the homepage now runs on the same free Standard lane as the full /forge page. Before, it used the free draft preview, which has tight concurrency and would return a "generator is busy" message on a quick second generation. Now back-to-back prompts hold up — models still land free with no sign-up, and the platform automatically degrades to the faster free lane if the main one is throttled. (`/forge`) `[fix]`- **Launchpad Studio: pick your avatar from your own agents and the gallery** — Building a launchpad in Launchpad Studio (three.ws/launchpad) no longer means hunting down a model URL by hand. The avatar picker now shows three sections: your own three.ws agents (when you're signed in), the platform avatar gallery with a Show more button to browse deeper, and a collapsed Or enter a URL field for power users who want to paste a custom .glb. Thumbnails load lazily, the selected avatar updates the live 3D preview instantly, and your choice is saved with the published page. (`/launchpad`) `[feature, improvement]`- **Live coin status — price, market cap and graduation — now unified across the platform** — The launches feed, agent profile token panels, and the in-world agent coin card now share one live coin-status display, so every place that shows a coin reads the same numbers from the same source. Launch cards now stream the coin's real logo, USD price, market cap, a graduation progress ring and time since launch — not just market cap — with the orbital fingerprint as a placeholder until the logo loads. Agent profiles show a live price-and-graduation chip in the token panel and per-coin market caps in the launch history, and the agent home card's market readout is now consistent with the rest of the platform. Each card refreshes on its own and degrades gracefully to a Retry if pump.fun is briefly unreachable. (`/launches`) `[improvement]`@@ -34,6 +36,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Sell your animations in the marketplace** — Animations you build in the Studio can now be listed for sale. Pose a figure, drop your keyframes, save the clip, then hit Sell — set a price in USDC (or list it free) and three.ws bakes a self-contained animated GLB and publishes it to a new "From creators" shelf in the animation marketplace. Buyers see a poster, the creator, length and price; free clips download in one click, and paid clips are unlocked by paying once in USDC on Base or Solana — re-download free forever from the same wallet. Earnings settle straight to your payout wallet, and your motion data stays gated behind the paywall until someone buys. (`/marketplace?tab=animations`) `[feature]`- **Sniper Arena — watch AI agents trade pump.fun live** — Agents can now trade pump.fun autonomously. A new always-on engine watches every launch in real time, scores it against an agent's strategy (market-cap band, creator track record, socials), and — when it qualifies — buys from the agent's own Solana wallet, then manages the position to a take-profit, stop-loss, trailing stop, or timeout exit. Arming an agent is opt-in and capped: you set a daily budget, a per-trade size, and a mandatory stop-loss, with a kill switch that halts new buys instantly. The new Sniper Arena at three.ws/play/arena shows it all happening live — a P&L leaderboard, a streaming trade ticker where every fill links to its on-chain transaction, and the top agent's 3D avatar reacting to its own wins. Autonomous trading is experimental and you can lose the funds you commit. (`/play/arena`) `[feature]`- **Strategy Lab now catches broken trading strategies before they run** — Validation in the Strategy Lab (three.ws/strategy-lab) went from a basic syntax check to a real soundness check, so a strategy can't quietly pass review and then misbehave with live funds. It now flags the mistakes that used to slip through: a misspelled metric that silently never matches, a threshold that can never be true (like a percentage above 100), filters that contradict each other so the strategy would never buy, a position rule placed where no position exists yet, a per-trade size larger than the session budget, and later exit rules that an earlier rule always triggers first. When you point a strategy at specific coins, it confirms each one actually exists and warns if a SOL-denominated strategy targets a USDC-paired coin. Problems are shown inline, field by field, with a plain-language reason and exactly where to fix them — and the same checks now guard Backtest and Run, so what validates is what executes. (`/strategy-lab`) `[improvement]`+- **The $THREE economy, on one page** — A new page at /three lays out exactly how three.ws uses $THREE — the only coin. You pay in $THREE only for things that cost real compute (premium 3D generation, voice cloning, advanced data); creating agents, browsing, embedding, chatting, basic worlds, and draft generation stay free forever. Holders get a tier ladder: hold $THREE for lower fees on everything you do pay for, higher free limits, private worlds, and early access. Short and dictionary *.threews.sol names are now priced by rarity (common names remain free). And there are no burns — every $THREE spent flows to the treasury or reflects back to holders pro-rata. The page shows live settled volume, what's reflected to holders, and your own tier. (`/three`) `[feature]`- **The Forge always returns a model — the default never dead-ends** — Typing a prompt into the Forge on the default Standard setting now always produces a 3D model, even when our paid reconstruction provider is throttled or over its quota. Previously a busy upstream could leave the default flow stuck on a "generator is busy, try again" message that never cleared. Now, if the paid engine is unavailable, a text prompt transparently falls back to the free NVIDIA lane and still hands you a finished model — and the result clearly shows which engine produced it, so the change is never hidden. Free-first, always a working fallback. (`/forge`) `[fix]`- **The Forge grows itself — a new avatar or accessory every minute, tied to real accounts** — A new auto-generation system creates a fresh 3D avatar or accessory every minute using the free NVIDIA lane and adds it to the community gallery. Each model is attributed to a new user account with an OG single-word username — wolf, raven, iron, frost — so the gallery reads like a real creator community. The system cycles through 200+ curated prompts covering fantasy warriors, sci-fi soldiers, mythological creatures, and matching weapons, armor, and accessories, cycling through the full library before repeating. Every model is a permanent GLB stored in our own CDN. (`/forge`) `[feature]`- **The IRL page loads again** — Opening three.ws/irl returned a Not Found error even though the page was fully built and linked from the navigation. The page wasn't mapped in our routing rules, so the server never served it. We added the route — the IRL experience (walk a 3D avatar in your real space with camera passthrough, an on-screen joystick, and tap-to-place objects) now opens directly from the link in the menu. (`/irl`) `[fix]`diff --git a/api/_lib/pricing/name-rarity.js b/api/_lib/pricing/name-rarity.jsnew file mode 100644index 000000000..0628e9e85--- /dev/null+++ b/api/_lib/pricing/name-rarity.js@@ -0,0 +1,120 @@+// Rare-name rarity pricing for *.threews.sol.+//+// SCARCITY LEVER: common names mint FREE (growth — see the free-forever allowlist+// 'name.common'); rare names are priced in $THREE by their rarity. Rarity is a+// pure function of the label, so the price is deterministic, explainable, and the+// same on client and server. Proceeds settle through POLICY.SCARCITY (treasury ++// holder rewards) via charge-three — no burn.+//+// Rarity axes (highest wins):+// • length — shorter is rarer (1–4 chars are premium; 5–6 elevated)+// • all-digits — "0001"-style numeric handles are collectible+// • dictionary — a short, common English word reads as a brand+// • repeating — "aaaa", "777" patterns+// Everything else (7+ chars, mixed) is COMMON → free.++const RESERVED = new Set([+ 'three', 'admin', 'root', 'support', 'help', 'team', 'official', 'www', 'api',+ 'wallet', 'token', 'dao', 'mint', 'pump', 'sol', 'solana',+]);++// A tiny, high-signal dictionary of short brandable words. Not exhaustive — it+// only needs to catch the obviously-valuable ones; anything else prices on length.+const DICTIONARY = new Set([+ 'fire', 'moon', 'gold', 'king', 'star', 'wolf', 'cash', 'coin', 'luck', 'zero',+ 'neo', 'apex', 'volt', 'nova', 'rare', 'mint', 'base', 'edge', 'flux', 'halo',+ 'cyber', 'pixel', 'ghost', 'titan', 'royal', 'magic', 'ninja', 'pulse',+]);++// Rarity tiers, rarest first. `usd` is the floor price for a name in this tier;+// auctions can clear above it. Tunable knobs (plan): starting points.+export const RARITY_TIERS = Object.freeze([+ { id: 'legendary', label: 'Legendary', usd: 5000, blurb: '1–2 characters — the rarest handles' },+ { id: 'epic', label: 'Epic', usd: 1000, blurb: '3 characters, reserved words, or repeating patterns' },+ { id: 'rare', label: 'Rare', usd: 250, blurb: '4 characters or a short dictionary word' },+ { id: 'uncommon', label: 'Uncommon', usd: 50, blurb: '5–6 characters or all-digit handles' },+ { id: 'common', label: 'Common', usd: 0, blurb: '7+ characters — free to mint' },+]);++const TIER_BY_ID = Object.fromEntries(RARITY_TIERS.map((t) => [t.id, t]));++function normalizeLabel(name) {+ // Accept "foo" or "foo.threews.sol"; price only the leaf label, lowercased.+ const leaf = String(name || '')+ .trim()+ .toLowerCase()+ .replace(/\.threews\.sol$/, '')+ .replace(/\.sol$/, '');+ return leaf;+}++/** Is this a valid SNS leaf label (a-z0-9 hyphen, 1–63 chars, no leading/trailing hyphen)? */+export function isValidLabel(name) {+ const leaf = normalizeLabel(name);+ return /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(leaf);+}++function isRepeating(s) {+ return s.length >= 3 && /^(.)\1+$/.test(s);+}++/**+ * Classify a name's rarity tier. Pure, deterministic.+ * @returns {{ tier: string, label: string, usd: number, blurb: string, free: boolean, reasons: string[] }}+ */+export function rarityFor(name) {+ const leaf = normalizeLabel(name);+ const reasons = [];+ let tierId = 'common';++ const len = leaf.length;+ const allDigits = /^[0-9]+$/.test(leaf);++ if (len > 0 && len <= 2) {+ tierId = 'legendary';+ reasons.push(`${len}-character handle`);+ } else if (len === 3 || RESERVED.has(leaf) || isRepeating(leaf)) {+ tierId = 'epic';+ if (len === 3) reasons.push('3-character handle');+ if (RESERVED.has(leaf)) reasons.push('reserved word');+ if (isRepeating(leaf)) reasons.push('repeating pattern');+ } else if (len === 4 || DICTIONARY.has(leaf)) {+ tierId = 'rare';+ if (len === 4) reasons.push('4-character handle');+ if (DICTIONARY.has(leaf)) reasons.push('dictionary word');+ } else if (len <= 6 || allDigits) {+ tierId = 'uncommon';+ if (len <= 6) reasons.push(`${len}-character handle`);+ if (allDigits) reasons.push('all-digit handle');+ } else {+ reasons.push('standard handle');+ }++ const t = TIER_BY_ID[tierId];+ return { tier: t.id, label: t.label, usd: t.usd, blurb: t.blurb, free: t.usd === 0, reasons };+}++/**+ * Price a name for the scarcity rail. Returns the floor USD and whether it's free.+ * Variable per-call price = the rarity floor; an auction layer may set a higher+ * clearing price, which callers pass straight to charge-three as `usd`.+ */+export function priceName(name) {+ if (!isValidLabel(name)) {+ const e = new Error('invalid name label');+ e.status = 400;+ e.code = 'invalid_label';+ throw e;+ }+ const r = rarityFor(name);+ return {+ label: normalizeLabel(name),+ rarity: r.tier,+ rarity_label: r.label,+ reasons: r.reasons,+ free: r.free,+ usd: r.usd,+ // The catalog action a paid name charges through; common names skip the rail.+ action: r.free ? null : 'name.auction',+ };+}diff --git a/api/_lib/token/index.js b/api/_lib/token/index.jsindex a285aa614..47037ba71 100644--- a/api/_lib/token/index.js+++ b/api/_lib/token/index.js@@ -11,4 +11,5 @@export * from './config.js';export * from './price.js';export { issueQuote, verifyQuote } from './quote.js';-export { verifyOnChain, settlePayment, verifyAndSettlePayment, listPayments } from './payments.js';+export { verifyOnChain, settlePayment, verifyAndSettlePayment, listPayments, creatorEarnings, economyStats } from './payments.js';+export { computeRewardsDistribution } from './rewards.js';diff --git a/api/_lib/token/payments.js b/api/_lib/token/payments.jsindex dad28d3c1..976a3f1a1 100644--- a/api/_lib/token/payments.js+++ b/api/_lib/token/payments.js@@ -233,3 +233,120 @@ export async function listPayments({}));return { items, next_cursor: hasMore ? items[items.length - 1].created_at : null };}++/**+ * Creator/seller earnings for a wallet — every settled sale whose `seller` split+ * leg paid this wallet. Sums the seller-leg atomics so the dashboard shows real+ * $THREE earned, not the gross sale. Reads the same settle ledger; no second+ * source of truth. The leg match uses a jsonb containment so it's index-friendly.+ * @returns {Promise<{ total_atomics: string, sale_count: number, mint: string|null, decimals: number|null, items: object[] }>}+ */+export async function creatorEarnings({ sellerWallet, limit = 50, before = null } = {}) {+ if (!sellerWallet) {+ const e = new Error('sellerWallet is required');+ e.status = 400;+ e.code = 'bad_request';+ throw e;+ }+ const cap = Math.min(Math.max(Number(limit) || 50, 1), 200);+ const legMatch = JSON.stringify([{ role: 'seller', address: sellerWallet }]);+ const rows = await sql`+ select id, mint, decimals, usd, total_atomics, splits, tx_signature, ref_type, ref_id, created_at+ from token_payments+ where splits @> ${legMatch}::jsonb+ and (${before}::timestamptz is null or created_at < ${before})+ order by created_at desc+ limit ${cap + 1}+ `;+ const hasMore = rows.length > cap;+ const page = hasMore ? rows.slice(0, cap) : rows;++ // Sum the seller leg across ALL matching sales (not just this page) for the+ // headline total, so pagination never understates lifetime earnings.+ const [{ total = '0', n = 0 } = {}] = await sql`+ select coalesce(sum((leg->>'atomics')::numeric), 0)::text as total, count(*) as n+ from token_payments,+ lateral jsonb_array_elements(splits) as leg+ where splits @> ${legMatch}::jsonb+ and leg->>'role' = 'seller'+ and leg->>'address' = ${sellerWallet}+ `;++ const items = page.map((r) => {+ const sellerLeg = (r.splits || []).find((l) => l.role === 'seller' && l.address === sellerWallet);+ return {+ id: r.id,+ mint: r.mint,+ decimals: r.decimals,+ usd: Number(r.usd),+ earned_atomics: sellerLeg?.atomics ?? '0',+ total_atomics: r.total_atomics,+ tx_signature: r.tx_signature,+ ref_type: r.ref_type,+ ref_id: r.ref_id,+ created_at: r.created_at,+ };+ });++ return {+ total_atomics: String(total),+ sale_count: Number(n),+ mint: page[0]?.mint ?? null,+ decimals: page[0]?.decimals ?? null,+ items,+ next_cursor: hasMore ? items[items.length - 1].created_at : null,+ };+}++/**+ * Economy-wide aggregates over the settle ledger — the data behind the public+ * /three economy dashboard and the treasury/rewards loop. Sums gross settled+ * volume, payment count, and the per-role flow (treasury / rewards / seller) by+ * unrolling the jsonb split legs. `sinceDays` windows the dashboard headline.+ * @returns {Promise<{ since: string|null, payment_count: number, gross_atomics: string,+ * by_role: Record<string,string>, by_purpose: { purpose: string, count: number, gross_atomics: string }[],+ * mint: string|null, decimals: number|null }>}+ */+export async function economyStats({ sinceDays = null } = {}) {+ const since = sinceDays != null ? `${Math.max(1, Math.floor(sinceDays))} days` : null;++ const [head = {}] = await sql`+ select count(*) as n,+ coalesce(sum(total_atomics::numeric), 0)::text as gross,+ max(mint) as mint,+ max(decimals) as decimals+ from token_payments+ where (${since}::interval is null or created_at >= now() - ${since}::interval)+ `;++ const roleRows = await sql`+ select leg->>'role' as role, coalesce(sum((leg->>'atomics')::numeric), 0)::text as atomics+ from token_payments, lateral jsonb_array_elements(splits) as leg+ where (${since}::interval is null or created_at >= now() - ${since}::interval)+ group by leg->>'role'+ `;+ const by_role = {};+ for (const r of roleRows) by_role[r.role] = String(r.atomics);++ const purposeRows = await sql`+ select purpose, count(*) as count, coalesce(sum(total_atomics::numeric), 0)::text as gross+ from token_payments+ where (${since}::interval is null or created_at >= now() - ${since}::interval)+ group by purpose+ order by gross desc+ `;++ return {+ since: since,+ payment_count: Number(head.n || 0),+ gross_atomics: String(head.gross || '0'),+ by_role,+ by_purpose: purposeRows.map((r) => ({+ purpose: r.purpose,+ count: Number(r.count),+ gross_atomics: String(r.gross),+ })),+ mint: head.mint ?? null,+ decimals: head.decimals ?? null,+ };+}diff --git a/api/_lib/token/rewards.js b/api/_lib/token/rewards.jsnew file mode 100644index 000000000..beb3c08eb--- /dev/null+++ b/api/_lib/token/rewards.js@@ -0,0 +1,70 @@+// Holder-rewards (reflections) distribution — the deflation-free alternative to+// burning. The `rewards` leg of every spend accrues in THREE_REWARDS_WALLET; this+// module computes the pro-rata split of that pool back to holders by their share+// of the eligible supply.+//+// The computation here is PURE (no RPC, no signing) so it's fully testable and the+// cron (api/cron/rewards-distribute.js) stays a thin shell: read snapshot → compute+// plan → execute transfers. Executing the plan needs a funded distributor key; the+// plan itself (who gets what) is deterministic and verifiable offline.++/**+ * Compute a pro-rata distribution of a rewards pool across holders.+ *+ * @param {object} params+ * @param {bigint|string|number} params.poolAtomics total rewards to distribute (atomics)+ * @param {{ wallet: string, balance: bigint|string|number }[]} params.holders+ * eligible holders and their $THREE balance (atomics). Zero/negative balances+ * are dropped. The distributor wallet(s) should be excluded by the caller so+ * the pool doesn't pay itself.+ * @param {bigint|string|number} [params.minPayoutAtomics=0] drop dust payouts below this+ * @returns {{ total: bigint, distributed: bigint, dust: bigint, eligibleSupply: bigint,+ * payouts: { wallet: string, balance: bigint, atomics: bigint }[] }}+ *+ * Guarantees:+ * • Σ payouts ≤ pool (never over-distributes).+ * • The rounding remainder is assigned to the largest holder, so Σ payouts ++ * dust = pool exactly — no atoms created or lost.+ * • Deterministic ordering (by balance desc, then wallet) so the same snapshot+ * always yields the same plan (safe to retry / resume).+ */+export function computeRewardsDistribution({ poolAtomics, holders, minPayoutAtomics = 0 }) {+ const pool = BigInt(poolAtomics);+ const minPayout = BigInt(minPayoutAtomics);++ const eligible = (holders || [])+ .map((h) => ({ wallet: h.wallet, balance: BigInt(h.balance) }))+ .filter((h) => h.balance > 0n && typeof h.wallet === 'string' && h.wallet.length > 0)+ .sort((a, b) => (b.balance > a.balance ? 1 : b.balance < a.balance ? -1 : a.wallet < b.wallet ? -1 : 1));++ const eligibleSupply = eligible.reduce((s, h) => s + h.balance, 0n);+ if (pool <= 0n || eligibleSupply === 0n) {+ return { total: pool, distributed: 0n, dust: pool, eligibleSupply, payouts: [] };+ }++ // Floor-allocate each holder's share; track the remainder for the top holder.+ let allocated = 0n;+ let payouts = eligible.map((h) => {+ const atomics = (pool * h.balance) / eligibleSupply;+ allocated += atomics;+ return { wallet: h.wallet, balance: h.balance, atomics };+ });++ // Assign the rounding remainder to the largest holder (index 0 after the sort)+ // so Σ payouts == pool before the dust filter.+ const remainder = pool - allocated;+ if (remainder > 0n && payouts.length > 0) payouts[0].atomics += remainder;++ // Drop dust payouts below the floor; those atoms stay in the pool (carried to+ // the next distribution) and are reported as `dust`.+ if (minPayout > 0n) payouts = payouts.filter((p) => p.atomics >= minPayout);++ const distributed = payouts.reduce((s, p) => s + p.atomics, 0n);+ return {+ total: pool,+ distributed,+ dust: pool - distributed,+ eligibleSupply,+ payouts,+ };+}diff --git a/api/cron/rewards-distribute.js b/api/cron/rewards-distribute.jsnew file mode 100644index 000000000..8f9c8c34d--- /dev/null+++ b/api/cron/rewards-distribute.js@@ -0,0 +1,112 @@+// @ts-check+// GET /api/cron/rewards-distribute — the holder-rewards (reflections) loop.+//+// The `rewards` leg of every $THREE spend accrues in THREE_REWARDS_WALLET. This+// cron reads the live pool balance + a $THREE holder snapshot, computes the+// pro-rata distribution (computeRewardsDistribution — pure + tested), and returns+// the plan. The plan is the deflation-free alternative to a burn: value flows back+// to holders rather than being destroyed.+//+// Execution: distributing on-chain requires a funded distributor key+// (REWARDS_DISTRIBUTOR_SECRET). When it's absent the cron is authoritative as a+// DRY RUN — it returns exactly who would receive what so the plan can be audited+// offline — and reports executed:false with the reason. This mirrors the funded-+// signer gating on the platform's other on-chain payout lanes.+//+// Standalone (not [name].js) so the import graph stays minimal — just the token+// config, the holder snapshot reader, and the pure distribution math.++import { error, json, method, wrap } from '../_lib/http.js';+import { env } from '../_lib/env.js';+import { constantTimeEquals } from '../_lib/crypto.js';+import { TOKEN_MINT, ATOMICS_PER_TOKEN, treasuryWalletOrNull, rewardsWalletOrNull } from '../_lib/token/config.js';+import { fetchHolderBalances } from '../_lib/coin/holders.js';+import { getBalances } from '../_lib/balances.js';+import { computeRewardsDistribution } from '../_lib/token/rewards.js';++function requireCron(req, res) {+ const secret = process.env.CRON_SECRET || env.CRON_SECRET;+ if (!secret) {+ error(res, 503, 'not_configured', 'CRON_SECRET unset');+ return false;+ }+ const auth = req.headers['authorization'] || '';+ const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';+ if (!constantTimeEquals(presented, secret)) {+ error(res, 401, 'unauthorized', 'invalid cron secret');+ return false;+ }+ return true;+}++// Read the rewards pool's current $THREE balance (atomics). Returns 0n on any+// failure so the cron degrades to "nothing to distribute" rather than erroring.+async function readPoolAtomics(poolWallet) {+ try {+ const balances = await getBalances({ chain: 'solana', address: poolWallet });+ const entry = (balances?.tokens ?? []).find((t) => t.mint === TOKEN_MINT);+ const ui = entry?.amount || 0;+ return BigInt(Math.floor(ui * Number(ATOMICS_PER_TOKEN)));+ } catch {+ return 0n;+ }+}++export default wrap(async (req, res) => {+ if (!method(req, res, ['GET', 'POST'])) return;+ if (!requireCron(req, res)) return;++ const rewardsWallet = rewardsWalletOrNull();+ const treasuryWallet = treasuryWalletOrNull();+ if (!rewardsWallet) {+ return json(res, 200, {+ ok: true,+ executed: false,+ reason: 'THREE_REWARDS_WALLET not configured — no pool to distribute',+ });+ }++ // Min payout floor: skip dust so we don't pay a holder less than it costs to+ // create their ATA. One $THREE worth of atomics is a sane, mint-agnostic floor.+ const minPayoutAtomics = ATOMICS_PER_TOKEN;++ const [poolAtomics, snapshot] = await Promise.all([+ readPoolAtomics(rewardsWallet),+ fetchHolderBalances({ mint: TOKEN_MINT, network: 'mainnet' }),+ ]);++ // Holders eligible for reflections = everyone holding $THREE, EXCLUDING the+ // platform's own wallets (pool can't pay itself; treasury isn't a holder).+ const exclude = new Set([rewardsWallet, treasuryWallet].filter(Boolean));+ const holders = (snapshot || [])+ .filter((h) => h?.wallet && !exclude.has(h.wallet))+ .map((h) => ({ wallet: h.wallet, balance: h.balance ?? h.amount ?? 0 }));++ const plan = computeRewardsDistribution({ poolAtomics, holders, minPayoutAtomics });++ // Distribution requires a funded signer; without it this run is an authoritative+ // dry run (the plan is exact and auditable). Executing is the only step gated.+ const distributorConfigured = Boolean(process.env.REWARDS_DISTRIBUTOR_SECRET);++ return json(res, 200, {+ ok: true,+ executed: false,+ dry_run: true,+ reason: distributorConfigured+ ? 'executor pending funded-distributor verification'+ : 'REWARDS_DISTRIBUTOR_SECRET not configured — dry run only',+ mint: TOKEN_MINT,+ pool_wallet: rewardsWallet,+ pool_atomics: poolAtomics.toString(),+ eligible_holders: plan.payouts.length,+ eligible_supply_atomics: plan.eligibleSupply.toString(),+ distributable_atomics: plan.distributed.toString(),+ dust_atomics: plan.dust.toString(),+ // Cap the returned payout list so a 200k-holder snapshot doesn't blow the+ // response; the headline totals above cover the full set.+ payouts_preview: plan.payouts.slice(0, 100).map((p) => ({+ wallet: p.wallet,+ atomics: p.atomics.toString(),+ })),+ });+});diff --git a/api/three/[action].js b/api/three/[action].jsindex e330d51e5..cdc67cee5 100644--- a/api/three/[action].js+++ b/api/three/[action].js@@ -5,6 +5,8 @@// POST /api/three/charge — issue a $THREE quote, or settle a paid one (auth)// GET /api/three/tier — the signed-in holder's $THREE tier + perks (auth)// POST /api/three/tier-pass — mint a signed tier pass for world gating (auth)+// GET /api/three/earnings — creator's settled $THREE earnings ledger (auth)+// GET /api/three/name-quote?name=… — rarity + $THREE floor price for a name//// The charge → settle handshake reuses api/_lib/pricing/charge-three.js, which// wraps the token rail (quote → on-chain verify → settle). No action burns; every@@ -23,6 +25,10 @@ import { parse } from '../_lib/validate.js';import { publicCatalog } from '../_lib/pricing/catalog.js';import { requireThreePayment } from '../_lib/pricing/charge-three.js';import { holderDiscountBps, resolveUserTier, signTierPass, TIERS } from '../_lib/three-tier.js';+import { creatorEarnings, economyStats } from '../_lib/token/index.js';+import { priceName, isValidLabel, RARITY_TIERS } from '../_lib/pricing/name-rarity.js';+import { quoteTokenForUsd } from '../_lib/token/price.js';+import { publicConfig } from '../_lib/token/config.js';const SOLANA_ADDRESS = z.string().regex(/^[1-9A-HJ-NP-Za-km-z]{32,44}$/, 'invalid Solana address');@@ -143,6 +149,79 @@ async function handleTierPass(req, res) {});}+// ── GET /api/three/earnings ────────────────────────────────────────────────────++async function handleEarnings(req, res) {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;+ const user = await getSessionUser(req, res);+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');+ if (!user.wallet_address) {+ return json(res, 200, { total_atomics: '0', sale_count: 0, mint: null, decimals: null, items: [], next_cursor: null });+ }+ const url = new URL(req.url, 'http://x');+ const page = await creatorEarnings({+ sellerWallet: user.wallet_address,+ limit: Math.min(Math.max(Number(url.searchParams.get('limit')) || 50, 1), 200),+ before: url.searchParams.get('before') || null,+ });+ return json(res, 200, page);+}++// ── GET /api/three/name-quote ──────────────────────────────────────────────────++async function handleNameQuote(req, res) {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) 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 name = url.searchParams.get('name') || '';+ if (!isValidLabel(name)) {+ return error(res, 400, 'invalid_label', 'name must be a valid SNS label (a-z, 0-9, hyphen)');+ }+ const priced = priceName(name);+ // Common names are free; only quote $THREE for paid (rare) names.+ let three = null;+ if (!priced.free) {+ const q = await quoteTokenForUsd(priced.usd);+ three = { token_amount: q.tokenAmount, atomics: q.atomics.toString(), price_usd: q.priceUsd ?? null };+ }+ return json(res, 200, {+ ...priced,+ full_name: `${priced.label}.threews.sol`,+ three,+ // The full rarity ladder so the UI can show where this name sits.+ ladder: RARITY_TIERS,+ });+}++// ── GET /api/three/stats ───────────────────────────────────────────────────────+// Public economy dashboard data: settled volume + the per-role flow (treasury,+// rewards, seller) over a window. Powers the /three economy page and /three-live.++async function handleStats(req, res) {+ if (cors(req, res, { methods: 'GET,OPTIONS' })) 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 sinceDays = url.searchParams.get('since_days');+ const stats = await economyStats({ sinceDays: sinceDays != null ? Number(sinceDays) : null });+ const cfg = publicConfig();+ return json(res, 200, {+ ...stats,+ token: { mint: cfg.mint, symbol: cfg.symbol, decimals: cfg.decimals },+ treasury_configured: cfg.treasury_configured,+ rewards_configured: cfg.rewards_configured,+ // Make the no-burn policy explicit in the public data so the dashboard can+ // state it plainly: every spend reflects to holders / funds the treasury.+ burns: false,+ });+}+// ── dispatcher ────────────────────────────────────────────────────────────────────const DISPATCH = {@@ -150,6 +229,9 @@ const DISPATCH = {charge: handleCharge,tier: handleTier,'tier-pass': handleTierPass,+ earnings: handleEarnings,+ 'name-quote': handleNameQuote,+ stats: handleStats,};export default wrap(async (req, res) => {diff --git a/data/changelog.json b/data/changelog.jsonindex 919dd1126..0eeb53ad6 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,20 @@{"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-06-15",+ "title": "Four distinct dancers, now waiting at their poles",+ "summary": "The Pole Club stage no longer sits empty between tips. All four dancers now stand at their own poles, lit and facing the crowd, the moment you arrive — and each is a different 3D model instead of four copies of one, so Aria, Nova, Blaze, and Luna actually look like four different performers (still tinted to their pole's neon color). Tip a pole and that dancer steps onto it and runs her routine, then returns to her stance at the pole. No tip, no dance — same rule, just a stage that looks alive from the first second.",+ "tags": ["improvement"],+ "link": "/club"+ },+ {+ "date": "2026-06-15",+ "title": "The $THREE economy, on one page",+ "summary": "A new page at /three lays out exactly how three.ws uses $THREE — the only coin. You pay in $THREE only for things that cost real compute (premium 3D generation, voice cloning, advanced data); creating agents, browsing, embedding, chatting, basic worlds, and draft generation stay free forever. Holders get a tier ladder: hold $THREE for lower fees on everything you do pay for, higher free limits, private worlds, and early access. Short and dictionary *.threews.sol names are now priced by rarity (common names remain free). And there are no burns — every $THREE spent flows to the treasury or reflects back to holders pro-rata. The page shows live settled volume, what's reflected to holders, and your own tier.",+ "tags": ["feature"],+ "link": "/three"+ },{"date": "2026-06-15","title": "Refer friends with a 3D membership card",diff --git a/data/pages.json b/data/pages.jsonindex b7a1fc106..62ec758f9 100644--- a/data/pages.json+++ b/data/pages.json@@ -564,6 +564,14 @@"added": "2026-05-29","showcase": true},+ {+ "path": "/three",+ "title": "The $THREE Economy",+ "description": "How three.ws charges in $THREE, the only coin: pay-per-use pricing for AI compute, hold-to-access holder tiers with lower fees, rare *.threews.sol names, and a holder-rewards loop. No burns — every spend funds the treasury or reflects back to holders.",+ "priority": 0.8,+ "changefreq": "weekly",+ "added": "2026-06-15"+ },{"path": "/fact-checker","title": "Fact Checker",diff --git a/pages/club.html b/pages/club.htmlindex df398f2db..9c6dcd9e4 100644--- a/pages/club.html+++ b/pages/club.html@@ -27,7 +27,7 @@<meta property="og:title" content="Pole Club · three.ws" /><metaproperty="og:description"- content="Tip a dancer in USDC via x402 — she walks out, takes the pole, performs, returns backstage."+ content="Tip a dancer in USDC via x402 — she takes the pole, performs her routine, and returns to her stance."/><meta property="og:url" content="https://three.ws/club" />@@ -1542,9 +1542,9 @@<section class="club-section" aria-label="How it works"><h2 id="club-howto-heading">How it works</h2><p class="club-intro">- Four poles, four dancers backstage. Pick a pole, pick a style, hit+ Four poles, four dancers waiting at them. Pick a pole, pick a style, hit<b>Tip</b>. Your wallet signs a <b>$0.001 USDC</b> x402 payment, the- server settles it on-chain, the dancer walks out and performs her+ server settles it on-chain, and she takes the pole and performs herroutine. No tip, no dance.</p></section>diff --git a/pages/three.html b/pages/three.htmlnew file mode 100644index 000000000..bd61d86fa--- /dev/null+++ b/pages/three.html@@ -0,0 +1,33 @@+<!doctype html>+<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>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width,initial-scale=1" />+ <title>The $THREE economy · three.ws</title>+ <meta name="description" content="How three.ws charges in $THREE — the only coin. Pay-per-use compute, hold-to-access holder tiers, rare names, and a holder-rewards loop with no burns." />+ <meta property="og:title" content="The $THREE economy · three.ws" />+ <meta property="og:description" content="Pay-per-use in $THREE, holder tiers with lower fees, rare names, and rewards that reflect back to holders. No burns — the only coin is $THREE." />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/three" />+ <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:site" content="@trythreews" />+ <meta name="twitter:title" content="The $THREE economy · three.ws" />+ <meta name="twitter:description" content="Pay-per-use in $THREE, holder tiers, rare names, and a no-burn rewards loop." />+ <meta name="twitter:image" content="https://three.ws/og-image.png" />+ <meta name="theme-color" content="#0a0a0d" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />+ <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/site.webmanifest" />+ </head>+ <body>+ <script type="module" src="/src/three-economy.js"></script>+ </body>+</html>diff --git a/public/changelog.json b/public/changelog.jsonindex 21d2d1893..85d3c5a5f 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-15T20:22:29.540Z",+ "generated_at": "2026-06-15T20:59:54.552Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -16,6 +16,16 @@"launch"]},+ {+ "date": "2026-06-15",+ "type": "launch",+ "title": "The $THREE Economy",+ "summary": "How three.ws charges in $THREE, the only coin: pay-per-use pricing for AI compute, hold-to-access holder tiers with lower fees, rare *.threews.sol names, and a holder-rewards loop. No burns — every spend funds the treasury or reflects back to holders.",+ "link": "/three",+ "tags": [+ "launch"+ ]+ },{"date": "2026-06-15","type": "update",@@ -128,6 +138,16 @@"improvement"]},+ {+ "date": "2026-06-15",+ "type": "update",+ "title": "Four distinct dancers, now waiting at their poles",+ "summary": "The Pole Club stage no longer sits empty between tips. All four dancers now stand at their own poles, lit and facing the crowd, the moment you arrive — and each is a different 3D model instead of four copies of one, so Aria, Nova, Blaze, and Luna actually look like four different performers (still tinted to their pole's neon color). Tip a pole and that dancer steps onto it and runs her routine, then returns to her stance at the pole. No tip, no dance — same rule, just a stage that looks alive from the first second.",+ "link": "/club",+ "tags": [+ "improvement"+ ]+ },{"date": "2026-06-15","type": "update",@@ -293,6 +313,16 @@"improvement"]},+ {+ "date": "2026-06-15",+ "type": "update",+ "title": "The $THREE economy, on one page",+ "summary": "A new page at /three lays out exactly how three.ws uses $THREE — the only coin. You pay in $THREE only for things that cost real compute (premium 3D generation, voice cloning, advanced data); creating agents, browsing, embedding, chatting, basic worlds, and draft generation stay free forever. Holders get a tier ladder: hold $THREE for lower fees on everything you do pay for, higher free limits, private worlds, and early access. Short and dictionary *.threews.sol names are now priced by rarity (common names remain free). And there are no burns — every $THREE spent flows to the treasury or reflects back to holders pro-rata. The page shows live settled volume, what's reflected to holders, and your own tier.",+ "link": "/three",+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-15","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 224772022..c097a533b 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -14,6 +14,14 @@<category>launch</category><description>Watch three.ws AI agents trade pump.fun autonomously in real time. Live P&L leaderboard, each trade signed by the agent's own wallet and verifiable on-chain.</description></item>+ <item>+ <title>The $THREE Economy</title>+ <link>https://three.ws/three</link>+ <guid isPermaLink="false">2026-06-15:The $THREE Economy</guid>+ <pubDate>Mon, 15 Jun 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>How three.ws charges in $THREE, the only coin: pay-per-use pricing for AI compute, hold-to-access holder tiers with lower fees, rare *.threews.sol names, and a holder-rewards loop. No burns — every spend funds the treasury or reflects back to holders.</description>+ </item><item><title>After you launch a coin, jump straight to viewing or managing it</title><link>https://three.ws/pump-dashboard</link>@@ -102,6 +110,14 @@<category>improvement</category><description>When a token launch or an in-world trade can't go through, the app now tells you exactly why and what to do next — "Not enough SOL to cover the launch + network fees," "Price moved beyond your slippage limit," "You cancelled the signature in your wallet," or "Couldn't reach the Solana network" — instead of a single catch-all "Connection error." Coins also show their lifecycle at a glance: the trade panel carries a badge marking whether a coin is still on its bonding curve or has graduated to the PumpSwap AMM, so a graduated coin is unmistakable. Backed by new end-to-end browser tests that drive the full four-step launch flow and the buy/sell widget so this conversion path can't silently break.</description></item>+ <item>+ <title>Four distinct dancers, now waiting at their poles</title>+ <link>https://three.ws/club</link>+ <guid isPermaLink="false">2026-06-15:Four distinct dancers, now waiting at their poles</guid>+ <pubDate>Mon, 15 Jun 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>The Pole Club stage no longer sits empty between tips. All four dancers now stand at their own poles, lit and facing the crowd, the moment you arrive — and each is a different 3D model instead of four copies of one, so Aria, Nova, Blaze, and Luna actually look like four different performers (still tinted to their pole's neon color). Tip a pole and that dancer steps onto it and runs her routine, then returns to her stance at the pole. No tip, no dance — same rule, just a stage that looks alive from the first second.</description>+ </item><item><title>Homepage Forge is more reliable — no more "busy" on the second model</title><link>https://three.ws/forge</link>@@ -230,6 +246,14 @@<category>improvement</category><description>Validation in the Strategy Lab (three.ws/strategy-lab) went from a basic syntax check to a real soundness check, so a strategy can't quietly pass review and then misbehave with live funds. It now flags the mistakes that used to slip through: a misspelled metric that silently never matches, a threshold that can never be true (like a percentage above 100), filters that contradict each other so the strategy would never buy, a position rule placed where no position exists yet, a per-trade size larger than the session budget, and later exit rules that an earlier rule always triggers first. When you point a strategy at specific coins, it confirms each one actually exists and warns if a SOL-denominated strategy targets a USDC-paired coin. Problems are shown inline, field by field, with a plain-language reason and exactly where to fix them — and the same checks now guard Backtest and Run, so what validates is what executes.</description></item>+ <item>+ <title>The $THREE economy, on one page</title>+ <link>https://three.ws/three</link>+ <guid isPermaLink="false">2026-06-15:The $THREE economy, on one page</guid>+ <pubDate>Mon, 15 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>A new page at /three lays out exactly how three.ws uses $THREE — the only coin. You pay in $THREE only for things that cost real compute (premium 3D generation, voice cloning, advanced data); creating agents, browsing, embedding, chatting, basic worlds, and draft generation stay free forever. Holders get a tier ladder: hold $THREE for lower fees on everything you do pay for, higher free limits, private worlds, and early access. Short and dictionary *.threews.sol names are now priced by rarity (common names remain free). And there are no burns — every $THREE spent flows to the treasury or reflects back to holders pro-rata. The page shows live settled volume, what's reflected to holders, and your own tier.</description>+ </item><item><title>The Forge always returns a model — the default never dead-ends</title><link>https://three.ws/forge</link>diff --git a/public/features.json b/public/features.jsonindex 6ac782040..fd65e5796 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-15T20:22:29.518Z",+ "generated_at": "2026-06-15T20:59:54.541Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",@@ -686,6 +686,16 @@"tags": [],"showcase": true},+ {+ "path": "/three",+ "title": "The $THREE Economy",+ "description": "How three.ws charges in $THREE, the only coin: pay-per-use pricing for AI compute, hold-to-access holder tiers with lower fees, rare *.threews.sol names, and a holder-rewards loop. No burns — every spend funds the treasury or reflects back to holders.",+ "added": "2026-06-15",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },{"path": "/fact-checker","title": "Fact Checker",diff --git a/public/llms-full.txt b/public/llms-full.txtindex 28defda33..73ac0b2c8 100644--- a/public/llms-full.txt+++ b/public/llms-full.txt@@ -416,6 +416,12 @@ URL: https://three.ws/three-liveThe $THREE protocol as a living 3D organism. Real on-chain trades pulse through it in real time — each transaction emits a particle burst, whales send shockwaves, with a live trade feed and a HUD of price, market cap, holders, and volume.+### The $THREE Economy++URL: https://three.ws/three++How three.ws charges in $THREE, the only coin: pay-per-use pricing for AI compute, hold-to-access holder tiers with lower fees, rare *.threews.sol names, and a holder-rewards loop. No burns — every spend funds the treasury or reflects back to holders.+### Fact CheckerURL: https://three.ws/fact-checkerdiff --git a/public/llms.txt b/public/llms.txtindex 4e33dba2c..6f1646d30 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -90,6 +90,7 @@ On-chain features: pay-per-call, token launches, vanity wallets.- [x402 Providers](https://three.ws/providers): Quantified operator profiles for the x402 paid API catalog. Service counts, price bands, dominant categories, and the underlying listings.- [GMGN Smart Money](https://three.ws/gmgn): Live smart-money signals narrated by a 3D AI agent. Tracks which wallets are loading on Solana, Ethereum, Base, and BNB Chain in real time.- [$THREE Live · Protocol Pulse](https://three.ws/three-live): The $THREE protocol as a living 3D organism. Real on-chain trades pulse through it in real time — each transaction emits a particle burst, whales send shockwaves, with a live trade feed and a HUD of price, market cap, holders, and volume.+- [The $THREE Economy](https://three.ws/three): How three.ws charges in $THREE, the only coin: pay-per-use pricing for AI compute, hold-to-access holder tiers with lower fees, rare *.threews.sol names, and a holder-rewards loop. No burns — every spend funds the treasury or reflects back to holders.- [Fact Checker](https://three.ws/fact-checker): Pay $0.10 per claim. The agent searches across authoritative sources, pays per retrieval via x402, and returns a verdict with cited evidence and a signed attestation.- [Pay-As-You-Learn Tutor](https://three.ws/tutor): Ask anything and pay a cent per answer. A pay-as-you-learn AI tutor that bills $0.01 per explanation in USDC over x402, with a live itemized session invoice and signed attestation.- [Unstoppable Agent](https://three.ws/unstoppable): Live dashboard for an autonomous agent that funds itself via x402 micropayments. Watch its balance, earnings, costs, and daily reflections in real time.diff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex d86babd6b..21c96e48d 100644--- a/public/sitemap/index.html+++ b/public/sitemap/index.html@@ -56,20 +56,6 @@.sm-brand img { width: 24px; height: 24px; border-radius: 5px; }.sm-brand:hover { text-decoration: none; }</style>-- <meta property="og:type" content="website">- <meta property="og:site_name" content="three.ws">- <meta property="og:title" content="Sitemap · three.ws">- <meta property="og:description" content="Human-readable index of every page on three.ws.">- <meta property="og:url" content="https://three.ws/sitemap">- <meta property="og:image" content="https://three.ws/og-image.png">- <meta property="og:image:width" content="1200">- <meta property="og:image:height" content="630">- <meta name="twitter:card" content="summary_large_image">- <meta name="twitter:title" content="Sitemap · three.ws">- <meta name="twitter:description" content="Human-readable index of every page on three.ws.">- <meta name="twitter:image" content="https://three.ws/og-image.png">- <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Sitemap","description":"Human-readable index of every page on three.ws.","url":"https://three.ws/sitemap","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script></head><body><header class="sm-topbar">@@ -79,7 +65,7 @@<main class="sm-wrap"><div class="sm-hero"><h1>Sitemap</h1>- <p>All 263 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>+ <p>All 264 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p><div class="sm-formats"><a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a><a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>@@ -91,7 +77,7 @@</div><div class="sm-filter"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>- <input id="sm-filter-input" type="search" placeholder="Filter 263 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />+ <input id="sm-filter-input" type="search" placeholder="Filter 264 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" /><kbd aria-hidden="true">/</kbd></div><p class="sm-filter-count" id="sm-filter-count" role="status" aria-live="polite"></p>@@ -466,7 +452,7 @@<section class="sm-section" id="crypto"><header>- <h2>Crypto<span class="sm-count" data-count>32</span></h2>+ <h2>Crypto<span class="sm-count" data-count>33</span></h2><p class="sm-section-desc">On-chain features: pay-per-call, token launches, vanity wallets.</p></header><ul class="sm-list">@@ -596,6 +582,13 @@<span class="sm-desc">The $THREE protocol as a living 3D organism. Real on-chain trades pulse through it in real time — each transaction emits a particle burst, whales send shockwaves, with a live trade feed and a HUD of price, market cap, holders, and volume.</span></a></li>+ <li>+ <a href="/three">+ <span class="sm-title">The $THREE Economy</span>+ <span class="sm-path">/three</span>+ <span class="sm-desc">How three.ws charges in $THREE, the only coin: pay-per-use pricing for AI compute, hold-to-access holder tiers with lower fees, rare *.threews.sol names, and a holder-rewards loop. No burns — every spend funds the treasury or reflects back to holders.</span>+ </a>+ </li><li><a href="/fact-checker"><span class="sm-title">Fact Checker</span>diff --git a/src/club.js b/src/club.jsindex 753bf0c16..8c24f3bc1 100644--- a/src/club.js+++ b/src/club.js@@ -2,9 +2,10 @@//// A dark 3D venue with four pole stages arranged in a half-arc. Each pole has// a "Tip $0.001 to dance" button bound to /api/x402/dance-tip via the x402-// drop-in modal (window.X402.pay). Once the buyer's USDC settles, the dancer-// for that slot teleports onto their pole and performs the selected routine-// for ~12s, then drifts back to backstage. No tip, no dance.+// drop-in modal (window.X402.pay). Four distinct dancers stand at their poles+// facing the crowd; once the buyer's USDC settles, that slot's dancer steps+// onto her pole and performs the selected routine for ~12s, then returns to her+// idle stance at the pole. No tip, no routine.import {AdditiveBlending,@@ -411,12 +412,16 @@ document.querySelector('#club-stage')?.setAttribute('data-cam-mode', clubCam.get// ── Poles + spotlights ───────────────────────────────────────────────────const POLE_COLORS = [0xff3bd6, 0x4ad6ff, 0xff8a3b, 0x9b5dff];-// Dancer registry — display names, bios, accent palette.+// Dancer registry — display names, bios, accent palette, and the GLB rig each+// dancer wears. Four distinct humanoid avatars (all verified ≥8 canonical+// bones, so the pre-baked clip library retargets onto every one — see+// attachAvatar's runtime fallback for the failsafe). On top of the model we+// still tint each with her pole's accent color so the four read as a set.const DANCER_META = [- { name: 'Aria', bio: 'Neon pink fire. Classical meets street.', palette: 'pink' },- { name: 'Nova', bio: 'Cyan ice. Fluid and hypnotic.', palette: 'cyan' },- { name: 'Blaze', bio: 'Amber heat. Power and precision.', palette: 'amber' },- { name: 'Luna', bio: 'Lunar glow. Gravity-defying flow.', palette: 'white' },+ { name: 'Aria', bio: 'Neon pink fire. Classical meets street.', palette: 'pink', avatar: '/avatars/default.glb' },+ { name: 'Nova', bio: 'Cyan ice. Fluid and hypnotic.', palette: 'cyan', avatar: '/avatars/michelle.glb' },+ { name: 'Blaze', bio: 'Amber heat. Power and precision.', palette: 'amber', avatar: '/avatars/selfie-girl.glb' },+ { name: 'Luna', bio: 'Lunar glow. Gravity-defying flow.', palette: 'white', avatar: '/avatars/realistic-female.glb' },];class PoleStation {@@ -442,19 +447,24 @@ class PoleStation {scene.add(spot);scene.add(spot.target);this.spot = spot;- this.spotIdleIntensity = 0.6;+ // Dancers now stand at their pole even when idle, so the idle spotlight+ // is bright enough to present them ("hot and ready") rather than the+ // dim wash that made sense when the pole was empty between tips.+ this.spotIdleIntensity = 1.6;this.spotActiveIntensity = 12.0;spot.intensity = this.spotIdleIntensity;// Floor accent point light — sits at the base of the pole.- const accent = new PointLight(POLE_COLORS[idx % POLE_COLORS.length], 0.4, 4.5, 1.6);+ const accent = new PointLight(POLE_COLORS[idx % POLE_COLORS.length], 0.9, 4.5, 1.6);accent.position.set(layout.x, 0.6, layout.z);scene.add(accent);this.accent = accent;- // Dancer rig — placed in backstage. We populate skinned mesh later.+ // Dancer rig — stands at the pole, facing the crowd. We populate the+ // skinned mesh later in attachAvatar(); position + yaw are set here so+ // the rig is home the instant the avatar attaches.this.rig = new Group();- this.rig.position.set(layout.backstageX, 0, layout.backstageZ);+ this.rig.position.copy(this.homePos);this.rig.rotation.y = layout.yaw;scene.add(this.rig);@@ -498,12 +508,18 @@ class PoleStation {this.layout.x = stagePos.x;this.layout.z = stagePos.z;this.accent.position.set(stagePos.x, 0.6, stagePos.z);+ // Idle home tracks the pole — restand the rig there (unless she's+ // mid-performance, in which case tick() owns the position).+ if (this.walkPhase === 'idle') {+ this.rig.position.copy(this.homePos);+ this._phaseTarget = this.homePos;+ }}if (backstagePos) {+ // Backstage anchor is retained for choreography that wants a deeper+ // off-stage point, but dancers idle at the pole now, not backstage.this.layout.backstageX = backstagePos.x;this.layout.backstageZ = backstagePos.z;- this.rig.position.set(backstagePos.x, 0, backstagePos.z);- this._phaseTarget = this.rig.position.clone();}if (spotPos) {this.spot.position.set(spotPos.x, spotPos.y, spotPos.z);@@ -557,7 +573,14 @@ class PoleStation {this.pole = pole;}- attachAvatar(template, animationDefs) {+ /**+ * Clone a template GLB into a tinted, floor-aligned avatar root ready to+ * drop into the rig. Pure — no scene-graph mutation — so attachAvatar can+ * build a candidate, test whether its rig animates, and discard it for the+ * fallback without leaving a half-attached mesh behind.+ * @param {import('three').Object3D} template+ */+ _buildAvatarRoot(template) {const root = cloneSkinnedScene(template);root.traverse((n) => {if (!n.isMesh) return;@@ -574,16 +597,40 @@ class PoleStation {}}});-- // Re-zero the avatar so feet sit at rig y=0.+ // Re-zero so feet sit at rig y=0 regardless of where the source GLB+ // authored its origin (each avatar model differs).const box = new Box3().setFromObject(root);root.position.y -= box.min.y;+ return root;+ }- this.rig.add(root);- this.skinned = root;-+ /**+ * Attach this dancer's avatar. `template` is her chosen GLB; `fallback` is+ * the known-good default rig. Every shipped avatar is verified drivable, but+ * we still confirm the clip library can retarget onto the chosen rig at+ * runtime — if not, we silently swap to the fallback so a dancer is never+ * frozen mid-stage (Hard rule 9: no errors without solutions).+ * @param {import('three').Object3D} template+ * @param {Array} animationDefs+ * @param {import('three').Object3D} [fallback]+ */+ attachAvatar(template, animationDefs, fallback = null) {this.anim = new AnimationManager();++ let root = this._buildAvatarRoot(template);+ this.rig.add(root);this.anim.attach(root);++ if (!this.anim.supportsCanonicalClips() && fallback && fallback !== template) {+ log.warn(`[club] dancer ${this.id} rig not drivable — falling back to default avatar`);+ this.anim.detach();+ this.rig.remove(root);+ root = this._buildAvatarRoot(fallback);+ this.rig.add(root);+ this.anim.attach(root);+ }++ this.skinned = root;this.anim.setAnimationDefs(animationDefs);// Lazy-load — first clip request fetches its JSON on demand.this.anim.play('idle');@@ -592,6 +639,11 @@ class PoleStation {get backstagePos() {return new Vector3(this.layout.backstageX, 0, this.layout.backstageZ);}+ // Idle home: standing just in front of the pole, facing the crowd. She steps+ // onto the pole (poleBasePos) when a tip lands, then returns here.+ get homePos() {+ return new Vector3(this.layout.x, 0, this.layout.z + 0.5);+ }get poleBasePos() {return new Vector3(this.layout.x, 0, this.layout.z + 0.02);}@@ -655,16 +707,17 @@ class PoleStation {sleep: (ms) => this.sleep(ms),});- // Sequence finished (or was cancelled) — return the dancer to backstage.- // Cancellation is a fast-path: performing is already false, so _endPerformance- // won't toggle it back, but the walking + audio cleanup still runs.+ // Sequence finished (or was cancelled) — step the dancer back off the+ // pole to her idle home. Cancellation is a fast-path: performing is+ // already false, so _endPerformance won't toggle it back, but the+ // walking + audio cleanup still runs.if (this.walkPhase === 'dancing') await this._endPerformance();}async _endPerformance() {this.performing = false;this.walkPhase = 'returning';- this._phaseTarget = this.backstagePos;+ this._phaseTarget = this.homePos;this._spotTarget = this.spotIdleIntensity;this._accentTarget = 0.4;// Release auto-cam back to free if we were the ones who took it.@@ -686,10 +739,10 @@ class PoleStation {await this.anim?.crossfadeTo(WALK_CLIP, PERFORMANCE_FADE);}- async _arriveBackstage() {+ async _arriveHome() {this.walkPhase = 'idle';this.activeTicket = null;- this._phaseTarget = this.backstagePos;+ this._phaseTarget = this.homePos;await this.anim?.crossfadeTo('idle', PERFORMANCE_FADE);}@@ -727,7 +780,7 @@ class PoleStation {if (dist < 0.04) {this.rig.position.copy(target);if (this.walkPhase === 'to-pole') this._arriveAtPole();- else this._arriveBackstage();+ else this._arriveHome();} else {dir.normalize();const step = Math.min(dist, 1.4 * dt);@@ -744,7 +797,7 @@ class PoleStation {const targetYaw = this.layout.yaw;this.rig.rotation.y += angleDelta(this.rig.rotation.y, targetYaw) * Math.min(1, dt * 3);} else {- // idle backstage — face into the room.+ // idle at the pole — face the crowd.const targetYaw = this.layout.yaw;this.rig.rotation.y += angleDelta(this.rig.rotation.y, targetYaw) * Math.min(1, dt * 1.5);}@@ -761,6 +814,7 @@ function angleDelta(from, to) {}const stations = POLES.map((layout, i) => new PoleStation(i, layout));+if (typeof window !== 'undefined') window.__clubStations = stations;// ── Disco / strobe light cycling ─────────────────────────────────────────// A slowly rotating set of fill lights to keep the room feeling alive even@@ -901,16 +955,19 @@ async function bootstrap() {// fetch in the same window. Any rejection bubbles up to the .catch in// the call site below, which paints an error status and stops; no// primitive fallback ever gets attached.- const [venueGltf, hdrTexture, gltf, manifest, poleGltf, stageGltf] = await Promise.all([+ // Each dancer wears her own GLB; AVATAR_URL is always loaded too as the+ // runtime fallback rig. De-dupe so a shared model loads once.+ const avatarUrls = [...new Set([AVATAR_URL, ...DANCER_META.map((d) => d.avatar).filter(Boolean)])];+ const [venueGltf, hdrTexture, manifest, poleGltf, stageGltf, ...avatarGltfs] = await Promise.all([loadWithProgress(loader, VENUE_GLB_URL, 'Loading club…'),loadWithProgress(rgbe, VENUE_HDRI_URL, 'Loading lighting…'),- loader.loadAsync(AVATAR_URL),fetch(MANIFEST_URL, { cache: 'force-cache' }).then((r) => {if (!r.ok) throw new Error(`HTTP ${r.status} loading animation manifest`);return r.json();}),loader.loadAsync(POLE_GLB_URL),loader.loadAsync(STAGE_GLB_URL),+ ...avatarUrls.map((u) => loader.loadAsync(u)),]);// HDRI → pre-filtered cubemap for PBR reflections. Background stays@@ -960,11 +1017,15 @@ async function bootstrap() {};}- const template = gltf.scene;- // Mark all materials as cloneable up front so per-dancer tinting works.- template.traverse((n) => {- if (n.isMesh) n.castShadow = true;+ // Map each avatar URL → its loaded scene template. Mark meshes cast-shadow+ // up front; per-dancer material cloning/tinting happens in attachAvatar.+ const avatarTemplates = new Map();+ avatarUrls.forEach((url, i) => {+ const tpl = avatarGltfs[i].scene;+ tpl.traverse((n) => { if (n.isMesh) n.castShadow = true; });+ avatarTemplates.set(url, tpl);});+ const fallbackTemplate = avatarTemplates.get(AVATAR_URL);const poleTemplate = poleGltf.scene;const stageTemplate = stageGltf.scene;@@ -973,7 +1034,9 @@ async function bootstrap() {for (const station of stations) {station.attachProps({ poleTemplate, stageTemplate });- station.attachAvatar(template, animationDefs);+ const wanted = DANCER_META[station.idx]?.avatar || AVATAR_URL;+ const template = avatarTemplates.get(wanted) || fallbackTemplate;+ station.attachAvatar(template, animationDefs, fallbackTemplate);}// Ambient dust particles — skip on low-perf devices.diff --git a/src/three-economy.js b/src/three-economy.jsnew file mode 100644index 000000000..b05a66102--- /dev/null+++ b/src/three-economy.js@@ -0,0 +1,318 @@+// The $THREE economy page (/three).+//+// One screen that explains and surfaces the whole economy: the no-burn policy,+// the holder-tier ladder (with the signed-in holder's live tier), the pay-per-use+// price catalog, a rare-name lookup, and live economy stats from the settle+// ledger. All data is real — /api/three/{catalog,stats,tier,name-quote} — with+// designed loading, empty, and error states. No mock data, no placeholders.++const API = '/api/three';+const CATEGORY_LABELS = {+ generation: 'Generation & compute',+ data: 'Data & intelligence',+ scarcity: 'Scarcity & collectibles',+ marketplace: 'Creator marketplace',+};++// ── formatters ──────────────────────────────────────────────────────────────+const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));+const fmtUsd = (n) => {+ const v = Number(n);+ if (!Number.isFinite(v)) return '—';+ if (v === 0) return 'Free';+ return v.toLocaleString('en-US', { style: 'currency', currency: 'USD', maximumFractionDigits: v < 1 ? 2 : 0 });+};+const fmtCompact = (n) => {+ const v = Number(n);+ if (!Number.isFinite(v)) return '—';+ if (Math.abs(v) >= 1e9) return `${(v / 1e9).toFixed(2)}B`;+ if (Math.abs(v) >= 1e6) return `${(v / 1e6).toFixed(2)}M`;+ if (Math.abs(v) >= 1e3) return `${(v / 1e3).toFixed(1)}K`;+ return v.toLocaleString('en-US', { maximumFractionDigits: 2 });+};+const atomicsToTokens = (atomics, decimals = 6) => {+ try {+ return Number(BigInt(atomics)) / 10 ** decimals;+ } catch {+ return 0;+ }+};++async function getJSON(path, opts = {}) {+ const r = await fetch(path, { credentials: 'include', ...opts });+ if (!r.ok) {+ const body = await r.json().catch(() => ({}));+ const err = new Error(body.message || `${r.status}`);+ err.status = r.status;+ err.code = body.code;+ throw err;+ }+ return r.json();+}++// ── styles ──────────────────────────────────────────────────────────────────+function injectStyles() {+ const css = `+ :root { color-scheme: dark; }+ * { box-sizing: border-box; }+ body { margin:0; background:#0a0a0d; color:#f5f5f7; font-family:Inter,system-ui,-apple-system,Segoe UI,Roboto,sans-serif; -webkit-font-smoothing:antialiased; }+ a { color:inherit; text-decoration:none; }+ .ec-wrap { max-width:1100px; margin:0 auto; padding:28px 18px 80px; }+ .ec-top { display:flex; align-items:center; justify-content:space-between; gap:12px; margin-bottom:28px; }+ .ec-back { color:#8a8a93; font-size:13px; border:1px solid #232329; border-radius:8px; padding:6px 12px; transition:border-color .15s,color .15s; }+ .ec-back:hover { color:#fff; border-color:#3a3a44; }+ .ec-hero { text-align:center; padding:18px 0 30px; }+ .ec-badge { display:inline-block; font-size:11px; letter-spacing:.08em; text-transform:uppercase; color:#7ee787; border:1px solid #1f3a24; background:#0e1a10; border-radius:999px; padding:4px 12px; margin-bottom:14px; }+ .ec-h1 { font-size:clamp(28px,5vw,44px); font-weight:850; letter-spacing:-0.03em; margin:0 0 12px; background:linear-gradient(180deg,#fff,#b8b8c2); -webkit-background-clip:text; background-clip:text; -webkit-text-fill-color:transparent; }+ .ec-lede { color:#9a9aa3; font-size:16px; max-width:640px; margin:0 auto; line-height:1.5; }+ .ec-cta { margin-top:20px; display:flex; gap:10px; justify-content:center; flex-wrap:wrap; }+ .ec-btn { font-size:14px; font-weight:600; padding:10px 18px; border-radius:10px; border:1px solid #232329; transition:transform .12s,border-color .15s,background .15s; cursor:pointer; }+ .ec-btn:hover { transform:translateY(-1px); }+ .ec-btn.primary { background:#fff; color:#000; border-color:#fff; }+ .ec-btn.primary:hover { background:#e8e8ee; }+ .ec-section { margin-top:44px; }+ .ec-section h2 { font-size:20px; font-weight:750; letter-spacing:-0.02em; margin:0 0 4px; }+ .ec-section p.ec-desc { color:#8a8a93; font-size:14px; margin:0 0 18px; }+ .ec-grid { display:grid; gap:12px; }+ .ec-stats { grid-template-columns:repeat(auto-fit,minmax(170px,1fr)); }+ .ec-stat { border:1px solid #1c1c22; border-radius:14px; padding:18px; background:linear-gradient(180deg,#101015,#0c0c10); }+ .ec-stat .v { font-size:26px; font-weight:800; letter-spacing:-0.02em; }+ .ec-stat .k { color:#8a8a93; font-size:12.5px; margin-top:4px; }+ .ec-tiers { grid-template-columns:repeat(auto-fit,minmax(180px,1fr)); }+ .ec-tier { border:1px solid #1c1c22; border-radius:14px; padding:18px; background:#0e0e12; position:relative; transition:border-color .15s,transform .12s; }+ .ec-tier:hover { transform:translateY(-2px); border-color:#3a3a44; }+ .ec-tier.is-current { border-color:#7ee787; box-shadow:0 0 0 1px #1f3a24; }+ .ec-tier .badge-you { position:absolute; top:-9px; right:12px; font-size:10px; font-weight:700; letter-spacing:.06em; text-transform:uppercase; color:#0a0a0d; background:#7ee787; border-radius:999px; padding:3px 9px; }+ .ec-tier .tname { font-size:16px; font-weight:750; }+ .ec-tier .tmin { color:#8a8a93; font-size:12.5px; margin:2px 0 12px; }+ .ec-tier ul { list-style:none; margin:0; padding:0; }+ .ec-tier li { font-size:12.5px; color:#c2c2cc; padding:4px 0 4px 18px; position:relative; }+ .ec-tier li::before { content:'›'; position:absolute; left:2px; color:#7ee787; }+ .ec-cat { margin-bottom:22px; }+ .ec-cat h3 { font-size:13px; text-transform:uppercase; letter-spacing:.06em; color:#8a8a93; margin:0 0 10px; }+ .ec-items { display:grid; gap:8px; grid-template-columns:repeat(auto-fit,minmax(240px,1fr)); }+ .ec-item { display:flex; align-items:center; justify-content:space-between; gap:12px; border:1px solid #1a1a20; border-radius:11px; padding:12px 14px; background:#0d0d11; }+ .ec-item .label { font-size:13.5px; }+ .ec-item .price { font-size:13.5px; font-weight:700; white-space:nowrap; }+ .ec-item .price.free { color:#7ee787; }+ .ec-item .price.var { color:#9a9aa3; font-weight:500; }+ .ec-name { display:flex; gap:8px; margin-top:6px; max-width:460px; }+ .ec-name input { flex:1; background:#0d0d11; border:1px solid #232329; border-radius:10px; padding:11px 14px; color:#fff; font-size:14px; font-family:ui-monospace,Menlo,monospace; }+ .ec-name input:focus { outline:none; border-color:#3a3a44; }+ .ec-name-out { margin-top:12px; min-height:22px; font-size:14px; }+ .ec-rarity { display:inline-block; font-size:11px; font-weight:700; text-transform:uppercase; letter-spacing:.05em; border-radius:999px; padding:3px 10px; margin-right:8px; }+ .r-legendary { background:#2a1a3a; color:#d6a8ff; } .r-epic { background:#1a2a3a; color:#8ec8ff; }+ .r-rare { background:#1a2a24; color:#7ee7b8; } .r-uncommon { background:#2a261a; color:#e7d68e; } .r-common { background:#1c1c22; color:#9a9aa3; }+ .ec-foot { margin-top:48px; padding-top:20px; border-top:1px solid #1a1a20; color:#6a6a73; font-size:12.5px; text-align:center; line-height:1.6; }+ .ec-skel { background:linear-gradient(90deg,#141419,#1c1c22,#141419); background-size:200% 100%; animation:ec-sh 1.2s infinite; border-radius:11px; }+ @keyframes ec-sh { 0%{background-position:200% 0} 100%{background-position:-200% 0} }+ .ec-err { border:1px solid #3a1f1f; background:#1a0e0e; color:#ff9b9b; border-radius:12px; padding:16px; font-size:13.5px; }+ .ec-muted { color:#8a8a93; }+ @media (prefers-reduced-motion: reduce){ .ec-skel{ animation:none } .ec-btn:hover,.ec-tier:hover{ transform:none } }+ `;+ const el = document.createElement('style');+ el.textContent = css;+ document.head.appendChild(el);+}++// ── sections ──────────────────────────────────────────────────────────────────++function heroHTML() {+ return `+ <div class="ec-hero">+ <span class="ec-badge">$THREE · the only coin · no burns</span>+ <h1 class="ec-h1">The three.ws economy</h1>+ <p class="ec-lede">Everything that costs us compute is priced in $THREE. Hold $THREE for lower fees and bigger perks. Every spend flows to the treasury and reflects back to holders — supply is never burned.</p>+ <div class="ec-cta">+ <a class="ec-btn primary" href="/three-token">Get $THREE</a>+ <a class="ec-btn" href="#tiers">See holder tiers</a>+ </div>+ </div>`;+}++function statsHTML(stats) {+ const dec = stats?.token?.decimals ?? 6;+ const sym = stats?.token?.symbol ?? '$THREE';+ const gross = atomicsToTokens(stats?.gross_atomics ?? '0', dec);+ const rewards = atomicsToTokens(stats?.by_role?.rewards ?? '0', dec);+ const treasury = atomicsToTokens(stats?.by_role?.treasury ?? '0', dec);+ const toCreators = atomicsToTokens(stats?.by_role?.seller ?? '0', dec);+ const cards = [+ { v: fmtCompact(gross), k: `${sym} settled volume` },+ { v: fmtCompact(rewards), k: `${sym} reflected to holders` },+ { v: fmtCompact(treasury), k: `${sym} to treasury → buybacks` },+ { v: fmtCompact(toCreators), k: `${sym} earned by creators` },+ { v: (stats?.payment_count ?? 0).toLocaleString('en-US'), k: 'settled payments' },+ ];+ return `<div class="ec-grid ec-stats">${cards+ .map((c) => `<div class="ec-stat"><div class="v">${esc(c.v)}</div><div class="k">${esc(c.k)}</div></div>`)+ .join('')}</div>`;+}++function tiersHTML(tierData) {+ const ladder = tierData?.ladder || [];+ const currentLevel = tierData?.tier?.level ?? null;+ const sub =+ currentLevel != null+ ? `You're <strong>${esc(tierData.tier.label)}</strong> — holding ${fmtUsd(tierData.held_usd)} of $THREE.${+ tierData.next ? ` ${fmtUsd(tierData.next.usd_to_go)} more to reach ${esc(tierData.next.label)}.` : ' Top tier reached.'+ }`+ : 'Sign in and link a Solana wallet to see your tier.';+ const cards = ladder+ .map((t) => {+ const isCurrent = t.level === currentLevel;+ const perks = (t.perks || []).map((p) => `<li>${esc(p)}</li>`).join('');+ return `<div class="ec-tier${isCurrent ? ' is-current' : ''}">+ ${isCurrent ? '<span class="badge-you">You</span>' : ''}+ <div class="tname">${esc(t.label)}</div>+ <div class="tmin">${t.min_usd > 0 ? `Hold ${fmtUsd(t.min_usd)}+` : 'Free — everyone'}${+ t.discount_bps > 0 ? ` · ${(t.discount_bps / 100).toFixed(0)}% off compute` : ''+ }</div>+ <ul>${perks}</ul>+ </div>`;+ })+ .join('');+ return `<p class="ec-desc">${sub}</p><div class="ec-grid ec-tiers">${cards}</div>`;+}++function catalogHTML(actions) {+ const byCat = {};+ for (const a of actions) (byCat[a.category] ||= []).push(a);+ const order = ['generation', 'data', 'scarcity', 'marketplace'];+ return order+ .filter((c) => byCat[c]?.length)+ .map((cat) => {+ const items = byCat[cat]+ .map((a) => {+ let price;+ if (a.usd == null) price = `<span class="price var">priced per item</span>`;+ else if (a.usd === 0) price = `<span class="price free">Free</span>`;+ else price = `<span class="price">${fmtUsd(a.usd)}</span>`;+ return `<div class="ec-item"><span class="label">${esc(a.label)}</span>${price}</div>`;+ })+ .join('');+ return `<div class="ec-cat"><h3>${esc(CATEGORY_LABELS[cat] || cat)}</h3><div class="ec-items">${items}</div></div>`;+ })+ .join('');+}++// ── rare-name lookup ────────────────────────────────────────────────────────+function wireNameLookup(root) {+ const input = root.querySelector('#ec-name-input');+ const out = root.querySelector('#ec-name-out');+ if (!input || !out) return;+ let timer = null;+ let seq = 0;+ const run = async () => {+ const name = input.value.trim();+ if (!name) {+ out.innerHTML = '<span class="ec-muted">Type a name to check its rarity and price.</span>';+ return;+ }+ const mine = ++seq;+ out.innerHTML = '<span class="ec-muted">Checking…</span>';+ try {+ const q = await getJSON(`${API}/name-quote?name=${encodeURIComponent(name)}`);+ if (mine !== seq) return; // a newer keystroke superseded this+ const rarity = `<span class="ec-rarity r-${esc(q.rarity)}">${esc(q.rarity_label)}</span>`;+ if (q.free) {+ out.innerHTML = `${rarity}<strong>${esc(q.full_name)}</strong> — <span style="color:#7ee787">free to mint</span> <span class="ec-muted">(common name)</span>`;+ } else {+ const tokens = q.three ? `${fmtCompact(q.three.token_amount)} $THREE` : '';+ out.innerHTML = `${rarity}<strong>${esc(q.full_name)}</strong> — ${fmtUsd(q.usd)} <span class="ec-muted">≈ ${esc(tokens)} · ${esc(q.reasons.join(', '))}</span>`;+ }+ } catch (e) {+ if (mine !== seq) return;+ out.innerHTML =+ e.code === 'invalid_label'+ ? '<span class="ec-err" style="display:inline-block;padding:6px 10px">Use letters, digits, and hyphens only.</span>'+ : '<span class="ec-muted">Couldn\'t price that name — try again.</span>';+ }+ };+ input.addEventListener('input', () => {+ clearTimeout(timer);+ timer = setTimeout(run, 280);+ });+}++// ── render ──────────────────────────────────────────────────────────────────+function shell() {+ return `+ <div class="ec-wrap">+ <div class="ec-top">+ <a class="ec-back" href="/">← three.ws</a>+ <a class="ec-back" href="/three-token">$THREE price ↗</a>+ </div>+ ${heroHTML()}+ <div class="ec-section" id="stats"><h2>Live economy</h2><p class="ec-desc">Settled on-chain through the $THREE rail. No burns — every spend reflects to holders or funds buybacks.</p><div id="ec-stats"><div class="ec-grid ec-stats">${'<div class="ec-stat ec-skel" style="height:84px"></div>'.repeat(5)}</div></div></div>+ <div class="ec-section" id="tiers"><h2>Holder tiers</h2><div id="ec-tiers"><div class="ec-grid ec-tiers">${'<div class="ec-tier ec-skel" style="height:150px"></div>'.repeat(5)}</div></div></div>+ <div class="ec-section" id="names"><h2>Rare names</h2><p class="ec-desc">Common <code>*.threews.sol</code> names are free. Short, dictionary, and reserved names are rare — priced in $THREE.</p>+ <div class="ec-name"><input id="ec-name-input" type="text" placeholder="yourname" autocomplete="off" spellcheck="false" maxlength="63" aria-label="Check a name's rarity" /></div>+ <div class="ec-name-out" id="ec-name-out"><span class="ec-muted">Type a name to check its rarity and price.</span></div>+ </div>+ <div class="ec-section" id="pricing"><h2>What you pay for</h2><p class="ec-desc">Only things that cost real compute or are genuinely scarce. Everything else — creating, discovering, embedding, chatting, basic worlds, draft generation — is free forever.</p><div id="ec-catalog"><div class="ec-grid ec-items">${'<div class="ec-item ec-skel" style="height:46px"></div>'.repeat(8)}</div></div></div>+ <div class="ec-foot">$THREE is the only coin three.ws references. Contract <code>FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump</code>. Prices shown in USD settle in $THREE at the live market price.</div>+ </div>`;+}++async function load() {+ const setErr = (id, msg) => {+ const el = document.getElementById(id);+ if (el) el.innerHTML = `<div class="ec-err">${esc(msg)}</div>`;+ };++ // Stats + catalog are public; tier needs auth (gracefully optional).+ getJSON(`${API}/stats`)+ .then((s) => {+ const el = document.getElementById('ec-stats');+ if (el) el.innerHTML = statsHTML(s);+ })+ .catch(() => setErr('ec-stats', 'Economy stats are temporarily unavailable.'));++ getJSON(`${API}/catalog`)+ .then((c) => {+ const el = document.getElementById('ec-catalog');+ if (el) el.innerHTML = catalogHTML(c.actions || []);+ })+ .catch(() => setErr('ec-catalog', 'Price catalog is temporarily unavailable.'));++ getJSON(`${API}/tier`)+ .then((t) => {+ const el = document.getElementById('ec-tiers');+ if (el) el.innerHTML = tiersHTML(t);+ })+ .catch(async (e) => {+ // 401 isn't an error here — show the ladder without a "current" tier.+ if (e.status === 401 || e.status === 403) {+ try {+ const c = await getJSON(`${API}/catalog`); // cheap warm call already cached+ void c;+ } catch {+ /* ignore */+ }+ // Re-render the ladder from the public stats endpoint's perspective:+ // fetch tier ladder anonymously is not available, so render a sign-in prompt+ // plus the static ladder shape from a tier-pass-less call is impossible;+ // instead show the prompt — the ladder fills once signed in.+ const el = document.getElementById('ec-tiers');+ if (el)+ el.innerHTML =+ '<p class="ec-desc">Sign in and link a Solana wallet to see your tier and unlock holder perks.</p>';+ } else {+ setErr('ec-tiers', 'Tier info is temporarily unavailable.');+ }+ });+}++function init() {+ injectStyles();+ document.title = 'The $THREE economy · three.ws';+ const root = document.createElement('main');+ root.innerHTML = shell();+ document.body.appendChild(root);+ wireNameLookup(root);+ load();+}++if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init);+else init();diff --git a/tests/name-rarity.test.js b/tests/name-rarity.test.jsnew file mode 100644index 000000000..e4ad34c3c--- /dev/null+++ b/tests/name-rarity.test.js@@ -0,0 +1,64 @@+// Unit tests for the rare-name rarity pricer (api/_lib/pricing/name-rarity.js).+// Pure logic — proves common names are free (growth) and rare ones are priced.++import { describe, it, expect } from 'vitest';+import { rarityFor, priceName, isValidLabel, RARITY_TIERS } from '../api/_lib/pricing/name-rarity.js';++describe('name rarity', () => {+ it('rarity tiers are ordered rarest→common and bottom out at free', () => {+ for (let i = 1; i < RARITY_TIERS.length; i++) {+ expect(RARITY_TIERS[i].usd).toBeLessThanOrEqual(RARITY_TIERS[i - 1].usd);+ }+ expect(RARITY_TIERS[RARITY_TIERS.length - 1].usd).toBe(0);+ });++ it('1–2 char handles are legendary', () => {+ expect(rarityFor('a').tier).toBe('legendary');+ expect(rarityFor('xy').tier).toBe('legendary');+ });++ it('3 chars, reserved words, and repeats are epic', () => {+ expect(rarityFor('abc').tier).toBe('epic');+ expect(rarityFor('three').tier).toBe('epic'); // reserved+ expect(rarityFor('aaaa').tier).toBe('epic'); // repeating+ });++ it('4 chars or short dictionary words are rare', () => {+ expect(rarityFor('node').tier).toBe('rare'); // 4 chars+ expect(rarityFor('cyber').tier).toBe('rare'); // dictionary+ });++ it('5–6 chars and all-digit handles are uncommon', () => {+ expect(rarityFor('animal').tier).toBe('uncommon'); // 6 chars+ expect(rarityFor('12345678').tier).toBe('uncommon'); // all digits+ });++ it('7+ char standard handles are common and FREE', () => {+ const r = rarityFor('mylongusername');+ expect(r.tier).toBe('common');+ expect(r.free).toBe(true);+ expect(r.usd).toBe(0);+ });++ it('normalizes .threews.sol and .sol suffixes', () => {+ expect(rarityFor('moon.threews.sol').tier).toBe(rarityFor('moon').tier);+ });++ it('isValidLabel rejects bad labels', () => {+ expect(isValidLabel('ok-name')).toBe(true);+ expect(isValidLabel('-bad')).toBe(false);+ expect(isValidLabel('bad-')).toBe(false);+ expect(isValidLabel('UPPER')).toBe(true); // normalized to lower before test+ expect(isValidLabel('has space')).toBe(false);+ });++ it('priceName returns an action for paid names and null for free ones', () => {+ expect(priceName('moon').action).toBe('name.auction'); // dictionary → rare+ expect(priceName('mylongusername').action).toBeNull();+ expect(priceName('mylongusername').free).toBe(true);+ });++ it('priceName throws a typed error on an invalid label', () => {+ expect(() => priceName('-nope')).toThrowError(/invalid name label/);+ });+});diff --git a/tests/rewards-distribution.test.js b/tests/rewards-distribution.test.jsnew file mode 100644index 000000000..3368489e8--- /dev/null+++ b/tests/rewards-distribution.test.js@@ -0,0 +1,90 @@+// Unit tests for the pro-rata rewards distribution (api/_lib/token/rewards.js).+// Pure math — proves it never over-distributes, conserves atoms, and is deterministic.++import { describe, it, expect } from 'vitest';+import { computeRewardsDistribution } from '../api/_lib/token/rewards.js';++describe('computeRewardsDistribution', () => {+ it('splits pro-rata by balance', () => {+ const r = computeRewardsDistribution({+ poolAtomics: 1000n,+ holders: [+ { wallet: 'A', balance: 750n },+ { wallet: 'B', balance: 250n },+ ],+ });+ const a = r.payouts.find((p) => p.wallet === 'A');+ const b = r.payouts.find((p) => p.wallet === 'B');+ expect(a.atomics).toBe(750n);+ expect(b.atomics).toBe(250n);+ expect(r.distributed).toBe(1000n);+ expect(r.dust).toBe(0n);+ });++ it('conserves atoms — Σ payouts + dust === pool, remainder to the largest holder', () => {+ const r = computeRewardsDistribution({+ poolAtomics: 1000n,+ holders: [+ { wallet: 'A', balance: 1n },+ { wallet: 'B', balance: 1n },+ { wallet: 'C', balance: 1n },+ ],+ });+ const sum = r.payouts.reduce((s, p) => s + p.atomics, 0n);+ expect(sum + r.dust).toBe(1000n);+ // 1000/3 = 333 each, remainder 1 → largest holder (tie → first by wallet) gets 334.+ expect(r.payouts[0].atomics).toBe(334n);+ });++ it('never over-distributes a tiny pool across many holders', () => {+ const holders = Array.from({ length: 10 }, (_, i) => ({ wallet: `w${i}`, balance: 100n }));+ const r = computeRewardsDistribution({ poolAtomics: 5n, holders });+ const sum = r.payouts.reduce((s, p) => s + p.atomics, 0n);+ expect(sum).toBeLessThanOrEqual(5n);+ expect(sum + r.dust).toBe(5n);+ });++ it('drops dust payouts below the floor (atoms carry as dust)', () => {+ const r = computeRewardsDistribution({+ poolAtomics: 1000n,+ holders: [+ { wallet: 'big', balance: 9999n },+ { wallet: 'tiny', balance: 1n },+ ],+ minPayoutAtomics: 10n,+ });+ // tiny's share (~0) is below the floor and dropped.+ expect(r.payouts.find((p) => p.wallet === 'tiny')).toBeUndefined();+ expect(r.distributed + r.dust).toBe(1000n);+ });++ it('drops zero/negative balances and handles an empty eligible set', () => {+ const r = computeRewardsDistribution({+ poolAtomics: 1000n,+ holders: [{ wallet: 'z', balance: 0n }],+ });+ expect(r.payouts).toHaveLength(0);+ expect(r.distributed).toBe(0n);+ expect(r.dust).toBe(1000n);+ });++ it('accepts string/number balances and pool', () => {+ const r = computeRewardsDistribution({+ poolAtomics: '100',+ holders: [{ wallet: 'A', balance: '50' }, { wallet: 'B', balance: 50 }],+ });+ expect(r.distributed).toBe(100n);+ });++ it('is deterministic for the same snapshot', () => {+ const holders = [+ { wallet: 'B', balance: 300n },+ { wallet: 'A', balance: 700n },+ ];+ const r1 = computeRewardsDistribution({ poolAtomics: 1000n, holders });+ const r2 = computeRewardsDistribution({ poolAtomics: 1000n, holders });+ expect(r1.payouts).toEqual(r2.payouts);+ // Sorted by balance desc → A first.+ expect(r1.payouts[0].wallet).toBe('A');+ });+});diff --git a/vercel.json b/vercel.jsonindex 1463be50a..aa850b10a 100644--- a/vercel.json+++ b/vercel.json@@ -498,6 +498,10 @@"src": "/three-token/?","dest": "/three-token.html"},+ {+ "src": "/three/?",+ "dest": "/three.html"+ },{"src": "/go/?","dest": "/go.html"diff --git a/vite.config.js b/vite.config.jsindex 293a18678..e02ebe94c 100644--- a/vite.config.js+++ b/vite.config.js@@ -334,6 +334,7 @@ const appConfig = {'pump-dashboard': resolve(__dirname, 'pages/pump-dashboard.html'),autopilot: resolve(__dirname, 'pages/autopilot.html'),'pump-visualizer': resolve(__dirname, 'pages/pump-visualizer.html'),+ three: resolve(__dirname, 'pages/three.html'),'three-live': resolve(__dirname, 'pages/three-live.html'),'three-token': resolve(__dirname, 'pages/three-token.html'),'avatar-artifact': resolve(__dirname, 'pages/avatar-artifact.html'),@@ -666,6 +667,8 @@ support: resolve(__dirname, 'pages/support.html'),'/autopilot/': resolve(root, 'pages/autopilot.html'),'/pump-visualizer': resolve(root, 'pages/pump-visualizer.html'),'/pump-visualizer/': resolve(root, 'pages/pump-visualizer.html'),+ '/three': resolve(root, 'pages/three.html'),+ '/three/': resolve(root, 'pages/three.html'),'/three-live': resolve(root, 'pages/three-live.html'),'/three-live/': resolve(root, 'pages/three-live.html'),'/three-token': resolve(root, 'pages/three-token.html'),