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
feat: x402 SDK docs/examples/tutorials, walk page rename, universal avatar rig docs, three-access updates
nirholas7e1bffb4c11f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8c4063e30..b8961ee9a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -44,7 +44,6 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **IRL stays fast and recovers gracefully in long AR sessions** — IRL is built to run for an hour without slowing down. Swapping your avatar now fully releases the previous 3D model from memory instead of leaving it behind, so trying on a dozen looks in one session no longer piles up. If your phone reclaims graphics memory and the camera view would otherwise go black — a common thing on mobile after the tab sits idle — IRL now pauses cleanly and restores the scene, with a clear "AR paused, restoring…" card and a one-tap reload if your device needs it. Backgrounding the tab pauses the render loop and quiets the camera to save battery, then resumes the moment you come back. And as you move, avatars you walk past stop holding a load slot ahead of the ones you're heading toward, so the nearest agents always render first. (`/irl`) `[improvement]`- **IRL surfaces now show clear loading, empty, and error states** — Every IRL screen that loads data now has a designed loading, empty, and error state — no more stuck "Loading…" or blank screens. Open "My pins" and you'll see a skeleton while it loads, a friendly nudge to drop your first agent when you have none, and a one-tap Retry if the network hiccups. Tapping an agent shows the same care: if its profile can't load, you get a clear message and Retry while its name and a link to the full profile stay put. The nearby radar reads as intentionally empty ("Be the first to pin here") instead of a broken dial, and the count beside it no longer flashes "0 nearby" before we've finished looking. On devices that can't run the AR view, you get a helpful card explaining why and where to go next — not a bare error. (`/irl`) `[improvement]`- **IRL teaches you how to find agents — and an empty area now feels alive** — IRL has no map and no list on purpose: you find agents by walking up to them and looking through your camera. The first time you open it, a short card now explains that idea — agents are hidden in the world around you, dropping your own lets someone else stumble on it later, and we never show a roster of where agents are, not even to you. You can reopen that explainer any time from the small "?" in the corner. And when you're somewhere quiet with nobody pinned yet, instead of a blank screen you'll see a gentle "Look around 👀 · or be the first to pin here" prompt with a one-tap way to place your own agent — so an empty spot reads as "keep exploring," not "this is broken." The moment a real agent comes into range, the prompt fades away on its own. (`/irl`) `[improvement]`-- **Live x402 payment challenges on the IBM partnership page** — The “Accelerating outcomes” section on the IBM × three.ws page had two empty gradient boxes under its AI agents and Crypto tabs. They're now live: each reads a real three.ws endpoint's HTTP 402 response on the spot and shows the exact terms the server is quoting — price in USDC, settlement network, and recipient. The AI agents tab shows what an autonomous agent reads before paying for live market data; the Crypto tab shows how any endpoint becomes pay-per-call. No wallet needed to watch it. (`/ibm/x402-demo`) `[improvement]`- **Memory Studio — watch your agent’s memory form, curate it, and trust it** — The Memory tab in Agent Studio turns your agent’s memory into something you can see and shape. A live Timeline streams every memory as it forms — chats, lessons, rules, trades — each tagged by tier (working, recall, archival) and salience, with one-click pin, edit, merge, forget, and a slider to dial importance. A knowledge Graph maps the coins, wallets, people, and strategies your agent has learned, linked by what shows up together; click any coin to replay how your agent’s understanding of it evolved over time. Recall runs real semantic search over real embeddings, so asking “lessons from losing trades” or “rules my agent follows” returns what it actually knows — and an In-Context view shows exactly what the agent carries into every reply, with a live token budget so the core stays sharp. Seed it in seconds from your GitHub, X, and Farcaster, and the Brain’s Memory node recalls all of it for real. (`/agent-studio`) `[feature]`- **Mobile menu plays nicely with screen readers and keyboards** — The mobile navigation drawer now fully hides itself from assistive tech and the keyboard tab order when it's closed, instead of leaving its links reachable but invisible. Screen-reader and keyboard users can no longer land focus on a link inside a collapsed menu, and the browser's accessibility warning about hidden-but-focused links is gone. `[fix]`- **New Club lineup — Dylan, Nich and Boss Vernington take the poles** — The three dancers on the Club floor have a fresh lineup: Dylan, Nich and Boss Vernington, each on their own distinct rig and tinted with their pole's accent color. Their names now show everywhere in the Club — on the pole cards, in the live tip ticker, and in chat — so when you tip, you tip them by name. (`/club`) `[improvement]`@@ -53,6 +52,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Paid market-intel never charges you for unavailable data** — The pay-per-call market-intel endpoints (the $THREE Town Oracle and the crypto-intel kiosk) used to hand back an estimated "neutral" reading — and still take the payment — when their live price feed was rate-limited. They now return a clean "temporarily unavailable, retry shortly" instead, and crucially the payment is never settled when live data is missing. You only pay when you get a real, live signal. `[fix]`- **Pay-per-call vanity wallets now do seed phrases and encrypted delivery** — The on-demand vanity address service — the one any app or agent can call and pay for per use, no account needed — can now hand back a 12- or 24-word seed phrase instead of just a raw key, so the wallet it grinds restores straight into Phantom, Solflare, or any wallet as a recovery phrase. And if you'd rather the secret never travel in the clear, you can now have it encrypted to a key only you hold: the service seals the result so the private key or seed phrase is unreadable to anyone in between — it isn't written to any log or cache, and only you can open it. The plain address still comes back in the clear so you can look it up right away. (`/vanity-wallet`) `[feature, security]`- **Payment dialog no longer pushes its Pay button off-screen** — On agent profiles, the Unlock skill / purchase dialog had no height limit. When the form ran tall — wallet area, price, fee note, Confirm button, and QR code together — it grew past the screen, so the title was shoved above the top edge and the Pay button dropped below the bottom, and neither could be scrolled to. The dialog is now capped to the visible screen with the form scrolling inside it and the header pinned, so the Pay button is always reachable on any screen size. `[fix]`+- **Pick who walks your pages — diverse avatar roster + Walk SDK** — The walking companion that strolls the corner of every page (and detaches into the full-page playground) now lets you choose your character. A new picker offers a diverse roster — a robot mascot, humanoids, photoreal people, a fox, dancers and showpieces — and swaps the avatar live. Each one is animated correctly whether its model ships its own moves or borrows the shared motion library, so nobody ever freezes mid-stride. Under the hood the whole companion + playground is now a standalone SDK (@three-ws/walk) you can drop into any Three.js site. `[feature, sdk]`- **Pinning your agent holds up when GPS gets flaky** — Anchoring an agent to a real spot now survives the rough edges of phone GPS. If your location drops for a moment — stepping indoors, into a garage, under heavy cover — IRL quietly re-acquires it on its own instead of going dark until you reload. When you pin before your phone has its first fix, it waits on a clear "Getting your location…" note and only drops the agent once a real position lands, so an agent can never be saved at the wrong place. The moment that precise fix arrives, your agent eases into its anchored spot instead of jumping. And when GPS is only roughly sure where you are, we say so — your pin is labelled an approximate spot with the accuracy in metres rather than pretending it's pinpoint. (`/irl`) `[fix]`- **Place AI agents at fixed spots around a real room** — IRL has a new way to author a scene: stand where you are, aim your phone at a real spot — the couch, the doorway, the empty chair across the table — set how far away it should sit, and tap Place to drop an agent right there. Drop several around you and each one stays locked to its real-world spot: turn away and it's gone, turn back and it slides into frame exactly where you left it, and the wall you never aimed at stays empty. The whole group is anchored as one shared room, so the layout holds its shape no matter how your GPS drifts — agents you placed metres apart stay metres apart on the right sides — and the next person who opens IRL at that spot sees the same arrangement you built. If the room ever lands slightly off, one drag nudges the entire cluster onto its true spot at once instead of fixing each agent by hand. Every part of the flow works by keyboard and reads its state aloud, and when your compass isn't calibrated we tell you honestly that others may see the room rotated rather than pretending it's perfect. (`/irl`) `[feature]`- **Platform-wide API security hardening** — We completed a full security audit of the API and tightened it across the board. Server errors no longer echo internal details back to callers — they return a short reference code you can quote to support, while the real diagnostics stay server-side (this also closes a path where a backend service key could surface in an error message). Account-changing actions made from the website — updating preferences, managing webhooks and payout wallets, marking notifications read, scheduling posts, setting skill prices — now carry cross-site request-forgery protection, so a malicious page can't act on your behalf. Sign-in, wallet-linking, GitHub connect and sensitive admin actions gained rate limits, and image-analysis requests are now screened so a supplied URL can't be used to probe internal systems. API access via developer keys is unaffected. `[security]`@@ -72,8 +72,10 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Token Oracle follow / unfollow is working again** — Subscribing an agent to a token's oracle alerts — and unsubscribing — was silently failing for everyone; only the status check worked. Both now go through correctly, so you can opt an agent into (and out of) score-based alerts as intended. `[fix]`- **Unity & Unreal avatar loading documented with code that actually works** — The developer hub's Unity and Unreal cards used to show sample code for an SDK that doesn't exist yet. They now show the real, working way to load a three.ws avatar today — your avatar's GLB endpoint loaded at runtime with glTFast (Unity) or glTFRuntime (Unreal), both standard glTF importers — alongside an honest note that a native package is still on the roadmap. (`/dashboard/developers`) `[docs, improvement]`- **Vanity wallets for every agent — opt-in, owned per user** — Every agent and avatar has its own custodial Solana wallet, and you own it per creation: make an avatar and its agent wallet is yours; if someone forks or saves that avatar, they get a brand-new wallet they alone control — yours is never shared or copied. A new Vanity tab in the agent wallet hub lets you grind a custom address (your own prefix and/or suffix) on demand. If the wallet already holds funds, they're automatically and safely swept to the new address before the switch completes, so funds are never stranded. The wallet now appears everywhere an agent or avatar shows up — profiles, avatar pages, your Agents and Avatars dashboards, the Characters feed and Trending — each with one-tap copy, an explorer link, and a vanity badge. (`/vanity-wallet`) `[feature]`+- **Walk mode moves to three.ws/temporary** — The drive-your-avatar walk demo — joystick or WASD movement, AR back-camera passthrough, and the live coin-world mainland — now lives at three.ws/temporary. Every link across the site already points to the new path, and avatar deep-links (three.ws/wk/…) follow along. The old /walk address is freed up for what's coming next. (`/temporary`) `[improvement]`- **Walk Playground no longer loses your character when it falls** — When you walked the little robot off a ledge it could plummet faster than the page could keep up and slip off the bottom of the screen, leaving you unable to find it. The camera now tracks falls tightly and keeps the character in view, and on pages that can't scroll it catches the character and drops it right back into view. (`/features/walk`) `[fix]`- **Walk Playground now has two modes you can switch between** — Click the corner walking companion to step into the page and you can now pick how he moves. Stroll mode is the relaxed top-down view — no gravity, wander anywhere across the page. Platformer mode turns the page's headings, cards and links into solid ground, with gravity, jumping and the chance to fall off edges. Flip between them live with the mode button (top-right) or the M key, and your choice is remembered as you walk from page to page. `[feature]`+- **Walk the IBM partnership page with a 3D agent** — The “Accelerating outcomes” section on the IBM × three.ws page had two empty gradient boxes. The AI agents tab now has a real 3D robot standing on it — click it (or press Enter) and the agent drops onto the page so you can walk the whole partnership page: every section becomes solid ground, arrow keys / WASD move and jump on desktop, and an on-screen joystick appears on phones. The Crypto tab now links straight to the live Forge and Play demos. The walk playground is also now loadable on its own from a stable URL, so any page can launch it. (`/ibm/partnership`) `[feature]`- **Walk the whole page — the site is now a playground** — The corner walking companion can now step out of its spot. Click it and the character detaches into a gentle bird's-eye view of the page, and you steer him anywhere across it with the arrow keys or WASD (an on-screen d-pad on phones) — no falling, just free roaming over the whole page. Step onto any link and it lights up like a doorway; pause on it or press the dive key and the character drops through, and you fall into the next page, arriving on the other side. It loads nothing extra until you click in, so normal browsing pays no cost. Jump straight in from any page with ?walk=play. `[feature]`## 2026-06-18@@ -241,7 +243,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **The Pole Club now has a real soundtrack** — Walk into the Pole Club and music starts playing the moment you interact — a full-length club anthem that rolls straight into a second track and then loops back to the top, so the room is never silent. The soundtrack streams (no heavy decode) and runs through the same room acoustics as everything else: muffled like it's heard through the door while you're outside, then opening up to full clarity the instant you're admitted. A tipped dancer's track and the walk-in anthem duck the music underneath them, and the Audio toggle in the top bar silences it all. (`/club`) `[feature, improvement]`- **The sniper now runs as an always-on service — armed strategies fire in real time** — An armed sniper strategy now has a live engine behind it. The sniper runs as a dedicated always-on worker that holds the pump.fun launch feed open continuously and acts the moment a launch matches your rules — not on a slow timer. It starts in a safe simulate mode (real scoring, zero spend) and going live is a deliberate, gated step that needs a funded agent wallet, so nothing trades real money by accident. If the launch feed ever drops, the worker reconnects on its own and pages the operators, and a public health check at /api/sniper/status reports whether it's live, reconnecting, or down — so 'is the sniper actually working right now?' is always answerable. Every safety limit you set — daily budget, per-trade size, max open positions, mandatory stop-loss, price-impact cutoff — is enforced by the running service exactly as configured. (`/dashboard/sniper`) `[infra, feature]`- **Try x402 live — pay a tenth of a cent to call a real API from your own wallet** — There's now a live, self-contained x402 demo you can try in a browser. Pay $0.001 USDC from your own wallet — MetaMask on Base or Phantom on Solana — and call a real three.ws data API. The page reads the live HTTP 402 price the server quotes, runs the paid call once your wallet signs a gasless authorization, and shows the response next to an on-chain transaction receipt you can open on Basescan or Solscan. Nothing is mocked and there's no account or backend. The same eight-line embed it runs on — one script tag from three.ws plus any button carrying a data-x402-endpoint — is copy-pasteable into any site, so a developer can add a working pay-per-call paywall in minutes. Built with IBM as the public face of the partnership and designed to host cleanly on a strict-CSP enterprise page. (`/ibm/x402-demo`) `[feature, sdk]`-- **Walking avatars now travel the right way on every rig** — Animations with root motion — walking, running, jumping with travel — now move your avatar in the correct world direction and distance no matter what tool the avatar came from. Avatars exported from Mixamo, Ready Player Me, Blender, and others orient their skeletons differently; previously a walk could drift sideways, sink into the floor, or moonwalk on rigs that didn't match the standard convention. The viewer now re-expresses each clip's root motion in the target rig's own frame, so two avatars built in different tools walk side by side in the same direction. Avatars that already matched the reference rig are byte-for-byte unchanged. (`/walk`) `[fix, improvement]`+- **Walking avatars now travel the right way on every rig** — Animations with root motion — walking, running, jumping with travel — now move your avatar in the correct world direction and distance no matter what tool the avatar came from. Avatars exported from Mixamo, Ready Player Me, Blender, and others orient their skeletons differently; previously a walk could drift sideways, sink into the floor, or moonwalk on rigs that didn't match the standard convention. The viewer now re-expresses each clip's root motion in the target rig's own frame, so two avatars built in different tools walk side by side in the same direction. Avatars that already matched the reference rig are byte-for-byte unchanged. (`/temporary`) `[fix, improvement]`- **Withdraw your agent's funds any time — plus spend limits and a full custody audit trail** — Your agent's Solana wallet is custodial, so we've made getting funds out and keeping them safe first-class. The Agent Wallet hub now has a working Withdraw tab: sweep all your SOL or any token the wallet holds to any address or .sol name (paste or scan a QR), with a clear review step, a confirmed explorer link, and every state designed. A small amount of SOL is always kept back on a "Max" sweep so the wallet can never get stuck. Withdrawals are signed on the server and are safe to retry — the same request never sends twice. A new Limits & Safety section lets you set a daily spend cap, a per-transaction cap, and an allowlist of addresses funds may be withdrawn to; those limits apply to everything the agent does — trades, snipes, and payments — not just withdrawals. And an Activity log shows exactly what your custodial wallet has done: every withdrawal, automated spend, limit change, and each time the key was used to sign, with the reason. The wallet's secret key never leaves our servers, is never shown or logged, and is only ever used after we confirm you own the agent. `[feature, security]`- **x402 live demo: dark theme, smoother motion, and a full accessibility pass** — The live x402 demo got a polish pass. It now carries a complete dark theme for dark IBM contexts, refined button and loading states, and a subtle price-update animation — and every bit of motion respects your reduced-motion setting. The layout holds from 320px phones to desktop with proper touch-target sizing, detects a connected browser wallet (or, on mobile, guides you to open the page inside your wallet's in-app browser), and passes a WCAG-AA accessibility pass: semantic markup, screen-reader-friendly status announcements, visible focus rings, and full keyboard operation. (`/ibm/x402-demo`) `[improvement]`- **Your IRL agent dashboard now lights up the instant someone interacts** — When a stranger taps, messages, or pays one of your agents placed out in the real world, your dashboard now reflects it within about a second — no refresh. The agent's card flashes, the unread count ticks up live, and a payment or a new message pops a notification so you feel the moment it happens, even from the other side of the planet. A small Live indicator shows when the realtime connection is up; if it ever drops, the inbox keeps updating on a short delay instead, so you never miss an encounter. Only your agent's name and the kind of interaction are ever shared with you — never the visitor's location or wallet. (`/dashboard/irl-placements`) `[feature, improvement]`@@ -357,7 +359,6 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Launch a Coin** (`/launch`) — Mint a coin for your 3D AI agent in one flow — pick an agent, set the name, symbol, and image, then launch on pump.fun straight from your wallet with an optional three.ws-branded vanity mint.- **Smart Money Radar — follow the wallets that win on pump.fun** (`/smart-money`) — A live first-party reputation graph of every pump.fun wallet. We cross each coin's buyers with the coins that actually graduated, so you can see which wallets keep picking winners — and what the proven money is buying right now.- **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.- **Trader Leaderboard** (`/leaderboard`) — Pump.fun traders ranked by a provable, on-chain track record — realized P&L, win rate, drawdown — with every number traceable to its transaction.- **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]`@@ -426,7 +427,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Scene Composer** (`/compose`) — Real-time 3D scene composer: forge items from text, attach them to your avatar's skeleton bones, arrange and scale freely, then export your creation or save it as an outfit.- **3D model categories — every model is now typed as Avatar, Accessory, Item, Scene, Creature, or Vehicle** — All 3D models on the platform now carry a category that describes what they actually are, not just how they were created. Avatar cards in the marketplace show a color-coded type badge (Avatar, Accessory, Item, Scene, Creature, or Vehicle) and a new filter row lets you browse by type. The Forge gallery shows the same badges on showcase cards, and when you finish forging a model you can tag it right in the result bar with a single click. This is the foundation for the upcoming agent equipment system — where your agents will be able to wear accessories, hold items, and inhabit scenes. (`/marketplace`) `[feature, improvement]`- **All 14 three.ws MCP servers are now live on npm and the official MCP registry** — Every three.ws MCP server is now publicly installable and discoverable. The eight install-and-run servers ship on npm under the @three-ws scope — pull any of them with one command, e.g. npx -y @three-ws/mcp-server (3D + agent tools), @three-ws/three-token-mcp ($THREE price, hold, and burn), @three-ws/pumpfun-mcp, @three-ws/ibm-x402-mcp, @three-ws/avatar-agent, and more. Together with the six hosted remote servers, all 14 are registered in the official Model Context Protocol registry, so any MCP-compatible client — Claude, Cursor, and others — can find them by name. No more dead install links: the documented commands now work. (`/docs/mcp`) `[sdk, feature]`-- **Animation library expands: 100+ clips, FBX and BVH upload** — The platform animation library grows to 100+ retargeted motion clips drawn from Mixamo, Avaturn packs, and MIT-licensed Three.js example models (Soldier, Michelle, Xbot). The agent dashboard's Upload clip dialog now accepts .glb, .fbx, and .bvh files — FBX and BVH are converted to GLB client-side via three.js loaders before upload, so creators can bring mocap data directly from capture tools without a separate conversion step. A full Mixamo catalog download pipeline (scripts/mixamo-all.mjs) is in place to expand the library to 2,000+ clips as soon as credentials are supplied. (`/walk`) `[feature, improvement]`+- **Animation library expands: 100+ clips, FBX and BVH upload** — The platform animation library grows to 100+ retargeted motion clips drawn from Mixamo, Avaturn packs, and MIT-licensed Three.js example models (Soldier, Michelle, Xbot). The agent dashboard's Upload clip dialog now accepts .glb, .fbx, and .bvh files — FBX and BVH are converted to GLB client-side via three.js loaders before upload, so creators can bring mocap data directly from capture tools without a separate conversion step. A full Mixamo catalog download pipeline (scripts/mixamo-all.mjs) is in place to expand the library to 2,000+ clips as soon as credentials are supplied. (`/temporary`) `[feature, improvement]`- **AR is live on the homepage — place any 3D model in your real space from the front page** — The three.ws homepage now has a live AR section: real models from the Forge gallery load in an interactive 3D viewer, and on mobile you can tap 'Place in your space' to anchor the model in your real environment through the camera. On desktop a QR code appears so you can scan and place from your phone in one step. WebXR on Android, Quick Look on iOS — no app, no download. A full blog post explains how the AR pipeline works across both platforms. (`/blog/see-your-3d-in-ar`) `[feature, improvement]`- **Clearer ways to reach us — a full contact directory on the support page** — The support page now lists specialized, monitored contacts so your message reaches the right team fast: [email protected] for AWS Marketplace, IBM, and integration inquiries; [email protected] for data requests; [email protected] for terms; [email protected] for copyright notices; and [email protected] for misuse reports — each with a one-tap copy button, alongside the existing support@ and security@ channels. Transactional emails now send from [email protected] with replies routed to a real human at support@, and copyright takedowns route to a dedicated DMCA agent. (`/support`) `[improvement]`- **Copy any docs or tutorial page straight into your AI assistant** — Every page in the docs and tutorials now has a 'Copy page' button in the top-right. Click it to copy the full page as clean Markdown, ready to paste into Claude, ChatGPT, or any LLM. The dropdown beside it adds two more options: 'View as Markdown' opens the raw plain-text version in a new tab, and 'Open in Claude' launches Claude with the page already loaded so you can ask questions about it. Built for the way people actually read docs now — with an AI assistant open alongside. (`/docs`) `[feature, docs]`@@ -752,7 +753,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr## 2026-05-10- **Pay (x402)** (`/pay`) — Pay-per-call gateway: invoke any x402-protocol paid API with a USDC micro-transaction.-- **Walk** (`/walk`) — Drive a 3D avatar around with a joystick or WASD — toggle the back camera for AR-style passthrough.+- **Walk** (`/temporary`) — Drive a 3D avatar around with a joystick or WASD — toggle the back camera for AR-style passthrough.- **Launch-week recap published** — An interactive case study of launch week (Apr 29 – May 9) with the architecture timeline, partner ecosystem, lessons learned, and live engagement metrics. `[docs]`- **Marketplace v2 and creator dashboard** — Redesigned marketplace with trials, time passes, billing receipts, featured avatar galleries, and theme selection. `[feature]`- **Monetization v2** — Trials, time-based access passes, withdrawal processing, signed receipts, multi-wallet support, and 5% referral splits. `[feature]`diff --git a/CLAUDE.md b/CLAUDE.mdindex 2b12cacde..ff742f36e 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -164,6 +164,7 @@ Run both in the same step. If one fails, surface the error — do not silently l- Solana/agent SDKs in `sdk/`, `solana-agent-sdk/`, `agent-payments-sdk/`.- Real APIs in use: Pump.fun feed, Solana RPC, OpenAI/Anthropic via worker proxies. Never mock these.- **Orientation:** `STRUCTURE.md` maps every product surface to its directory. Read it before exploring the 60+ top-level dirs.+- **Avatar animation is universal — no rig allowlist.** Any humanoid avatar drives the pre-baked clip library: `src/glb-canonicalize.js` maps its bone names (Mixamo, Avaturn, Unreal, VRM/VRoid, VRM 1.0, Daz/Genesis, MakeHuman, Blender `.L`, simple `shoulderL` rigs) to the canonical set, and `src/animation-retarget.js` retargets idle/walk onto them — legs included. A rig that genuinely can't be skeleton-driven (no skin, non-humanoid prop) falls back to the default rig (`AnimationManager.supportsCanonicalClips()` gate), never a bind-pose T-pose. Hit a new skeleton convention? Add its bone-name mapping to `glb-canonicalize.js` (cover it with a case in `tests/glb-canonicalize.test.js`) — don't hardcode a curated rig list.## Known trapsdiff --git a/data/changelog.json b/data/changelog.jsonindex 09d83c4d4..58fca7f9f 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,15 @@{"$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-19",+ "title": "Pick who walks your pages — diverse avatar roster + Walk SDK",+ "summary": "The walking companion that strolls the corner of every page (and detaches into the full-page playground) now lets you choose your character. A new picker offers a diverse roster — a robot mascot, humanoids, photoreal people, a fox, dancers and showpieces — and swaps the avatar live. Each one is animated correctly whether its model ships its own moves or borrows the shared motion library, so nobody ever freezes mid-stride. Under the hood the whole companion + playground is now a standalone SDK (@three-ws/walk) you can drop into any Three.js site.",+ "tags": [+ "feature",+ "sdk"+ ]+ },{"date": "2026-06-19","title": "Walk mode moves to three.ws/temporary",@@ -129,12 +138,12 @@},{"date": "2026-06-19",- "title": "Live x402 payment challenges on the IBM partnership page",- "summary": "The “Accelerating outcomes” section on the IBM × three.ws page had two empty gradient boxes under its AI agents and Crypto tabs. They're now live: each reads a real three.ws endpoint's HTTP 402 response on the spot and shows the exact terms the server is quoting — price in USDC, settlement network, and recipient. The AI agents tab shows what an autonomous agent reads before paying for live market data; the Crypto tab shows how any endpoint becomes pay-per-call. No wallet needed to watch it.",+ "title": "Walk the IBM partnership page with a 3D agent",+ "summary": "The “Accelerating outcomes” section on the IBM × three.ws page had two empty gradient boxes. The AI agents tab now has a real 3D robot standing on it — click it (or press Enter) and the agent drops onto the page so you can walk the whole partnership page: every section becomes solid ground, arrow keys / WASD move and jump on desktop, and an on-screen joystick appears on phones. The Crypto tab now links straight to the live Forge and Play demos. The walk playground is also now loadable on its own from a stable URL, so any page can launch it.","tags": [- "improvement"+ "feature"],- "link": "/ibm/x402-demo"+ "link": "/ibm/partnership"},{"date": "2026-06-19",diff --git a/data/pages.json b/data/pages.jsonindex 14be698ad..5aa23d4cc 100644--- a/data/pages.json+++ b/data/pages.json@@ -725,14 +725,6 @@"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/page-agent-sdk/CONTRIBUTING.md b/page-agent-sdk/CONTRIBUTING.mdnew file mode 100644index 000000000..bca04ef6b--- /dev/null+++ b/page-agent-sdk/CONTRIBUTING.md@@ -0,0 +1,210 @@+# Contributing to `@three-ws/page-agent`++Thanks for helping build the best rigged 3D guide on the web. This package is+small, dependency-light (only `three`), and fully client-side — which makes it a+great place to contribute, whether you're adding an avatar, sharpening the+lipsync, or shipping a framework adapter.++- **New to the codebase?** Read the [docs](./docs/README.md) first — especially+ [Building blocks](./docs/guide-building-blocks.md), which mirrors the source+ layout.+- **Releasing?** That's [PUBLISHING.md](./PUBLISHING.md), not this file.++---++## Dev setup++The package lives inside the [three.ws](https://three.ws) monorepo but is+self-contained.++```bash+git clone https://github.com/nirholas/three.ws+cd three.ws/page-agent-sdk++npm install # at the repo root if the workspace needs it+npm run build # → dist/page-agent.{mjs,global.js,css}+npm test # catalog + lipsync unit tests+```++### Try your changes live++The example runs the **unbundled source** straight from disk via an import map —+no build step between edits:++```bash+npx serve . # or any static server at the package root+# open http://localhost:3000/examples/index.html+```++Edit a file in `src/`, refresh, see it. (The example imports `../src/index.js`.)++---++## Project layout++Each module is one focused piece. Keep them that way.++| File | Responsibility |+|------|----------------|+| [`src/index.js`](./src/index.js) | Public entry. Exports, `<page-agent>` registration, `data-page-agent` auto-init. |+| [`src/page-agent.js`](./src/page-agent.js) | The `PageAgent` controller: DOM chrome, drag, narration orchestration, events, `collectSegments`. |+| [`src/stage.js`](./src/stage.js) | `AvatarStage` — three.js scene, GLB load, framing, idle/talk animation, blink. |+| [`src/narrator.js`](./src/narrator.js) | `SpeechNarrator` — Web Speech queue, voice selection, lipsync driving. |+| [`src/lipsync.js`](./src/lipsync.js) | The text→viseme engine: `buildMorphMap`, `createLipsync`, `estimateDurationMs`. |+| [`src/picker.js`](./src/picker.js) | `AvatarPicker` — accessible modal roster grid. |+| [`src/catalog.js`](./src/catalog.js) | The rigged agent roster + `getAgent`/`agentUrl`/`filterAgents`. |+| [`src/element.js`](./src/element.js) | The `<page-agent>` custom element. |+| [`src/styles.js`](./src/styles.js) | The injected stylesheet (also emitted as `dist/page-agent.css`). |+| [`build.mjs`](./build.mjs) | esbuild: ESM (three external) + IIFE global (three inlined) + CSS. |+| [`types/index.d.ts`](./types/index.d.ts) | Hand-written types — **keep in sync with the source**. |++---++## Code style++Match the surrounding code; consistency over preference.++- **Tabs** for indentation; semicolons; single quotes.+- **ES modules**, modern browser APIs, no transpilation assumptions beyond ES2020.+- **No new runtime dependencies.** `three` is the only peer; the engine stays+ dependency-free. (Dev tooling like esbuild is fine.)+- **No mocks, no placeholders, no `TODO`s.** Finish what you start. Real APIs only.+- **Handle errors at the boundary** (load, speech). The graceful-degradation+ contract is sacred: if TTS fails or is muted, the avatar must still visibly+ "talk" and captions must still render — narration never silently stalls.+- **Accessibility is not optional.** Keep ARIA roles, focus management, keyboard+ paths, and `prefers-reduced-motion` support intact.+- Run the linter and tests before opening a PR.++---++## Testing++Unit tests run on Node's built-in test runner (no framework):++```bash+npm test+```++- Tests live in [`test/`](./test/) as `*.test.js`.+- The catalog and lipsync engine are pure and fully testable — **add coverage for+ any change there.** See [`test/catalog.test.js`](./test/catalog.test.js) for the+ shape: every agent must be rigged, lipsync-classified, point at a `.glb`, carry+ a voice profile, and have a valid hex accent — these invariants are enforced.+- DOM-heavy modules (`PageAgent`, `AvatarStage`) aren't unit-tested yet — a+ jsdom-based harness is a welcome contribution (see [ideas](#ideas-worth-building)).++---++## Add an agent to the catalog++The roster is deliberately diverse and **every entry must be rigged** — that's+enforced by tests, not vibes. To add a guide:++1. **Verify the rig.** Your GLB needs a skinned mesh + armature, ideally an idle+ clip and ARKit visemes. Confirm with `buildMorphMap` — see+ [Custom avatars → Verifying your rig](./docs/guide-custom-avatars.md#verifying-your-rig).+2. **Host the GLB** where the catalog's `assetBase` serves it (or give the entry+ an absolute `url`). Don't commit large binaries to the repo without discussing+ it in the issue first.+3. **Add the entry** to [`src/catalog.js`](./src/catalog.js):++ ```js+ {+ id: 'rio', // stable, unique, kebab/slug+ name: 'Rio',+ tagline: 'Warm, energetic host', // one line for the picker card+ persona: "I'm Rio — I'll make this quick and fun.", // plain language, no jargon+ file: 'rio.glb', // filename under assetBase+ rig: 'rpm', // 'rpm' | 'mixamo' | 'studio'+ lipsync: 'viseme', // 'viseme' | 'jaw' | 'animation'+ presents: 'neutral', // 'female' | 'male' | 'neutral' | 'robot'+ style: 'stylized', // 'realistic' | 'stylized' | 'robot'+ framing: 'upper', // 'bust' | 'upper' | 'full'+ voice: { lang: 'en-US', pitch: 1.0, rate: 1.0, match: ['aria', 'jenny'] },+ accent: '#10b981', // hex; used for UI chrome + highlights+ }+ ```++4. **Pick the right `lipsync`** for what the rig actually exposes (visemes → jaw →+ animation). Mis-declaring it makes the mouth look wrong.+5. **Tune the voice profile.** `match` is an ordered list of case-insensitive+ substrings tried against installed system voices; add a couple of good+ cross-platform options, plus a `lang`.+6. **Run `npm test`** — the catalog invariants must pass.+7. **Update the roster tables** in [`README.md`](./README.md) and+ [`docs/api-reference.md`](./docs/api-reference.md#the-roster).+8. Add a line to the platform changelog if this ships to users.++Keep the roster diverse: variety of `style`, `presents`, and `lipsync` is a+feature, not clutter.++---++## Improve the lipsync engine++[`src/lipsync.js`](./src/lipsync.js) is a deterministic text→viseme heuristic. It's+intentionally simple and dependency-free, but there's real headroom:++- A proper phoneme dictionary (grapheme→phoneme) for English, then other+ languages, would beat the per-character mapping.+- Coarticulation / blending between adjacent visemes for smoother mouths.+- An optional **audio-driven** mode: analyse `SpeechSynthesis` output (or an+ `<audio>` element) with a Web Audio `AnalyserNode` and drive `jawOpen` from+ amplitude for non-viseme rigs.++Keep the current API (`createLipsync(text, morph, opts).tick/stop/done/totalMs`)+stable, or add a new mode behind it. Cover changes with tests.++---++## Ship a framework adapter++An official React wrapper exists ([`@three-ws/react`](https://www.npmjs.com/package/@three-ws/react)).+Thin, well-typed adapters for **Vue, Svelte, Solid, or Angular** are very welcome —+follow the patterns in [Framework integration](./docs/guide-frameworks.md):+construct in a mount hook, expose `narrate`/`setAgent`, `dispose()` on unmount.++---++## Ideas worth building++Pick one, open an issue to claim it, and have at it. Roughly easy → ambitious:++- **More languages** — externalize the built-in strings (picker title/subtitle,+ the "not much text here" fallback line) and add locales.+- **Persisted position** — remember where a visitor dragged the agent.+- **Theming API** — expose CSS custom properties so hosts can restyle the chrome+ without overriding internals.+- **jsdom test harness** — unit-test `PageAgent` DOM wiring, events, and+ `collectSegments` segment selection.+- **Gesture cues in copy** — let `data-narrate` carry hints (`[wave]`, `[point]`)+ that trigger the talk/gesture clip or aim the agent at the highlighted element.+- **Point at the segment** — rotate/lean the avatar toward the element it's+ currently narrating.+- **Audio-driven lipsync** — the Web Audio analyser mode described above.+- **Ask-me-anything mode** — optional Web Speech *recognition* for voice+ questions, answered by a host-provided callback (bring-your-own LLM; the package+ stays backend-free by default).+- **Streaming narration** — accept an async iterator / stream of text so a+ host-side LLM can narrate as tokens arrive.+- **Bundle diet** — an entry that imports only the three.js bits used, to shrink+ the global build.+- **More rigged agents** — see [above](#add-an-agent-to-the-catalog).++Each of these should preserve the core promises: **client-side, no API key,+accessible, graceful, one WebGL context.**++---++## Pull requests++1. Branch from `main`. Keep the change focused.+2. `npm run build && npm test` — both green.+3. Update docs/types/roster tables touched by your change.+4. Describe the *why*, with a before/after or a short clip for UI/3D changes.+5. By contributing you agree your work is licensed under the project's+ [Apache-2.0](./LICENSE).++Questions or proposals → [open an issue](https://github.com/nirholas/three.ws/issues).+Thank you for making it better. 🙌diff --git a/page-agent-sdk/README.md b/page-agent-sdk/README.mdindex 252e9b8dc..9c74e6d83 100644--- a/page-agent-sdk/README.md+++ b/page-agent-sdk/README.md@@ -13,7 +13,7 @@ want — from a diverse roster of rigged agents.-[Quick start](#quick-start) · [The catalog](#the-rigged-catalog) · [API](#api) · [How it works](#how-it-works) · [FAQ](#faq)+[Quick start](#quick-start) · [Docs](#documentation) · [The catalog](#the-rigged-catalog) · [API](#api) · [How it works](#how-it-works) · [FAQ](#faq)</div>@@ -36,11 +36,11 @@ frozen, dead-faced statue. Those are excluded.### 1 — One script tag (zero JS)```html-<script type="module"- src="https://unpkg.com/@three-ws/page-agent/global"+<script src="https://unpkg.com/@three-ws/page-agent/dist/page-agent.global.js"data-page-agentdata-avatar="nova"- data-auto-narrate></script>+ data-auto-narrate+ defer></script>```That's it. `Nova` appears bottom-right and tours the page. The visitor can change@@ -69,6 +69,20 @@ guide.on('segment', ({ text, el }) => highlight(el));> small ESM build with `three` left external. The `/global` build inlines three> for a plain CDN `<script>`.+## Documentation++Full guides live in [`docs/`](./docs/README.md), tiered by experience:++- 🟢 **Basic** — [Getting started](./docs/getting-started.md) ·+ [Narrating your page](./docs/guide-narration.md) ·+ [Troubleshooting & FAQ](./docs/troubleshooting.md)+- 🟡 **Medium** — [Framework integration](./docs/guide-frameworks.md) (React, Next, Vue, Svelte, Astro, no-code) ·+ [Recipes](./docs/recipes.md) · [API reference](./docs/api-reference.md)+- 🔴 **Advanced** — [Custom avatars](./docs/guide-custom-avatars.md) ·+ [Building blocks](./docs/guide-building-blocks.md) (compose the engine yourself)+- 🛠️ **Contribute** — [CONTRIBUTING](./CONTRIBUTING.md) (add an agent, improve+ lipsync, ship an adapter) · [runnable examples](./examples/)+## The rigged catalogA deliberately diverse roster — realistic, stylized, and robot guides, withdiff --git a/page-agent-sdk/docs/api-reference.md b/page-agent-sdk/docs/api-reference.mdindex 8efc5413c..eda374574 100644--- a/page-agent-sdk/docs/api-reference.md+++ b/page-agent-sdk/docs/api-reference.md@@ -165,7 +165,9 @@ registerElement('site-guide'); // register under a custom tag → returns th----## HTML attributes (`data-page-agent` script)+## HTML attributes++For the `data-page-agent` auto-init script.Add `data-page-agent` to a `<script>` loading the global build and it auto-startsfrom its `data-*` attributes (the first such script wins; idempotent).diff --git a/page-agent-sdk/examples/README.md b/page-agent-sdk/examples/README.mdnew file mode 100644index 000000000..9782c46fd--- /dev/null+++ b/page-agent-sdk/examples/README.md@@ -0,0 +1,19 @@+# Examples++Run these from the **package root** with any static server so the import map can+resolve the unbundled source from `../src`:++```bash+npx serve .+# then open http://localhost:3000/examples/<file>+```++| File | Level | Shows |+|------|-------|-------|+| [`index.html`](./index.html) | 🟢 basic | The full `PageAgent` — drop-in guide, page tour, picker, controls. |+| [`react.jsx`](./react.jsx) | 🟡 medium | A reusable React hook + `<Guide>` component. Needs a bundler. |+| [`headless.html`](./headless.html) | 🔴 advanced | Your own UI on `AvatarStage` + `SpeechNarrator` + `AvatarPicker`. |+| [`custom-avatar.html`](./custom-avatar.html) | 🔴 advanced | Load **your** rigged GLB and inspect its lipsync tier. Accepts `?url=`. |++New to the package? Start with the [docs](../docs/README.md) →+[Getting started](../docs/getting-started.md).diff --git a/page-agent-sdk/examples/custom-avatar.html b/page-agent-sdk/examples/custom-avatar.htmlnew file mode 100644index 000000000..7a7eab1ff--- /dev/null+++ b/page-agent-sdk/examples/custom-avatar.html@@ -0,0 +1,120 @@+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <title>@three-ws/page-agent — custom avatar demo</title>+ <!--+ ADVANCED EXAMPLE — drive YOUR OWN rigged GLB through the building blocks,+ and inspect what lipsync tier it qualifies for. See+ docs/guide-custom-avatars.md. Run from the package root: `npx serve .`+ then open /examples/custom-avatar.html (optionally ?url=<your-glb>).+ -->+ <style>+ :root { color-scheme: dark; }+ body { margin: 0; font: 16px/1.5 system-ui, sans-serif; background: #0b0c10; color: #e9eaf0; }+ .wrap { max-width: 760px; margin: 0 auto; padding: 48px 24px; }+ h1 { font-size: 26px; margin: 0 0 6px; }+ #stage { width: 280px; height: 360px; margin: 16px 0;+ background: radial-gradient(120% 100% at 50% 0%, #1a1d27, #0c0e14); border-radius: 16px; }+ .row { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; margin: 10px 0; }+ input[type=url] { flex: 1; min-width: 260px; padding: 9px 12px; border-radius: 10px;+ border: 1px solid #2a2c38; background: #0d0e14; color: #e9eaf0; font: inherit; }+ button, select { cursor: pointer; border: 1px solid #2a2c38; background: #15161e; color: #e9eaf0;+ padding: 9px 14px; border-radius: 10px; font: inherit; font-weight: 600; }+ code, pre { background: #15161e; border-radius: 8px; }+ code { padding: 2px 6px; font-size: 14px; }+ pre { padding: 12px; overflow: auto; border: 1px solid #23252f; }+ .tier { font-weight: 700; }+ .tier[data-mode="arkit"] { color: #34d399; }+ .tier[data-mode="jaw"] { color: #fbbf24; }+ .tier[data-mode="none"] { color: #f87171; }+ </style>+</head>+<body>+ <div class="wrap">+ <h1>Bring your own rigged avatar</h1>+ <p>Paste a URL to a skeleton-rigged <code>.glb</code> (CORS-enabled) and load+ it. We'll render it and report which lipsync tier it qualifies for.</p>++ <div class="row">+ <input id="url" type="url" placeholder="https://your-cdn.com/avatar.glb" />+ <select id="framing">+ <option value="bust">bust</option>+ <option value="upper" selected>upper</option>+ <option value="full">full</option>+ </select>+ <button id="load">Load</button>+ </div>++ <div id="stage" aria-label="Custom avatar"></div>++ <div class="row">+ <button id="speak">▶ Speak a test line</button>+ <button id="stop">⏹ Stop</button>+ <span>Lipsync tier: <span class="tier" id="tier" data-mode="none">—</span></span>+ </div>++ <pre id="report">Load a model to inspect its rig…</pre>+ </div>++ <script type="importmap">+ {+ "imports": {+ "three": "https://unpkg.com/[email protected]/build/three.module.js",+ "three/addons/": "https://unpkg.com/[email protected]/examples/jsm/"+ }+ }+ </script>+ <script type="module">+ import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+ import { AvatarStage, SpeechNarrator, buildMorphMap } from '../src/index.js';++ const stage = new AvatarStage(document.getElementById('stage'), { background: 'transparent' });+ const narrator = new SpeechNarrator(stage, { onError: (e) => console.warn(e) });+ // A minimal voice profile is all the narrator needs for a custom avatar.+ narrator.setAgent({ voice: { lang: 'en-US', rate: 1, pitch: 1, match: ['samantha', 'aria', 'guy'] } });++ const tierEl = document.getElementById('tier');+ const reportEl = document.getElementById('report');++ async function load(url) {+ if (!url) return;+ const framing = document.getElementById('framing').value;+ reportEl.textContent = 'Loading ' + url + ' …';+ try {+ // Inspect the rig independently so we can report the tier even before framing.+ const gltf = await new GLTFLoader().loadAsync(url);+ const morph = buildMorphMap(gltf.scene);+ const mode = morph?.mode || 'none';+ tierEl.textContent = mode === 'arkit' ? 'viseme (best)' : mode === 'jaw' ? 'jaw' : 'animation only';+ tierEl.dataset.mode = mode;+ reportEl.textContent = [+ 'URL: ' + url,+ 'Lipsync: ' + (mode === 'none' ? 'no face morphs — needs a talk clip' : mode),+ 'Morphs: ' + (morph ? [...morph.map.keys()].join(', ') : '(none found)'),+ 'Clips: ' + (gltf.animations.map((c) => c.name).join(', ') || '(none — procedural idle will run)'),+ ].join('\n');++ await stage.load(url, { framing }); // render it+ } catch (err) {+ tierEl.textContent = 'load failed';+ tierEl.dataset.mode = 'none';+ reportEl.textContent = 'Failed to load: ' + (err?.message || err) ++ '\n\nCommon causes: 404, or the host is missing CORS headers (Access-Control-Allow-Origin).';+ }+ }++ document.getElementById('load').onclick = () => load(document.getElementById('url').value.trim());+ document.getElementById('speak').onclick = () =>+ narrator.speak('Hello — I am a custom rigged avatar driven by the page-agent engine.', { interrupt: true });+ document.getElementById('stop').onclick = () => narrator.cancel();++ // Honor ?url= for quick sharing; otherwise start with a known-good catalog rig.+ const fromQuery = new URLSearchParams(location.search).get('url');+ const start = fromQuery || 'https://three.ws/avatars/realistic-halfbody.glb';+ document.getElementById('url').value = start;+ load(start);+ </script>+</body>+</html>diff --git a/page-agent-sdk/examples/headless.html b/page-agent-sdk/examples/headless.htmlnew file mode 100644index 000000000..fae8e9481--- /dev/null+++ b/page-agent-sdk/examples/headless.html@@ -0,0 +1,129 @@+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <title>@three-ws/page-agent — building blocks (headless) demo</title>+ <!--+ ADVANCED EXAMPLE — compose AvatarStage + SpeechNarrator + AvatarPicker with+ your OWN UI. No PageAgent, no default chrome. This is the pattern from+ docs/guide-building-blocks.md. Run it with any static server from the+ package root, e.g. `npx serve .` then open /examples/headless.html+ -->+ <style>+ :root { color-scheme: dark; }+ * { box-sizing: border-box; }+ body { margin: 0; font: 16px/1.5 system-ui, sans-serif; background: #0b0c10; color: #e9eaf0; }+ .wrap { max-width: 760px; margin: 0 auto; padding: 48px 24px; }+ h1 { font-size: 28px; margin: 0 0 6px; }+ p.sub { color: #9aa; margin: 0 0 28px; }+ .panel {+ display: grid; grid-template-columns: 240px 1fr; gap: 20px;+ border: 1px solid #23252f; border-radius: 18px; padding: 20px; background: #101218;+ }+ #stage { width: 240px; height: 300px; border-radius: 14px; overflow: hidden;+ background: radial-gradient(120% 100% at 50% 0%, #1a1d27, #0c0e14); }+ .controls { display: flex; flex-direction: column; gap: 12px; }+ .row { display: flex; gap: 8px; flex-wrap: wrap; }+ button { cursor: pointer; border: 1px solid #2a2c38; background: #15161e; color: #e9eaf0;+ padding: 9px 14px; border-radius: 10px; font: inherit; font-weight: 600; }+ button:hover { background: #1d1f29; }+ button[aria-pressed="true"] { border-color: var(--accent, #6366f1); color: var(--accent, #818cf8); }+ textarea { width: 100%; min-height: 84px; resize: vertical; border-radius: 10px;+ border: 1px solid #2a2c38; background: #0d0e14; color: #e9eaf0; padding: 10px; font: inherit; }+ .caption { min-height: 1.5em; color: #aab; font-style: italic; }+ .who { font-weight: 700; } .who small { color: #8a8f9e; font-weight: 500; }+ [data-speaking="true"] #stage { box-shadow: 0 0 0 2px var(--accent, #6366f1); }+ </style>+</head>+<body>+ <div class="wrap">+ <h1>Headless building blocks</h1>+ <p class="sub">A custom guide built directly on <code>AvatarStage</code> ++ <code>SpeechNarrator</code> + <code>AvatarPicker</code> — your UI, our engine.</p>++ <div class="panel" id="panel">+ <div id="stage" aria-label="3D avatar"></div>+ <div class="controls">+ <div class="who"><span id="name">—</span> <small id="tag"></small></div>+ <textarea id="text">Hi! I'm a fully custom guide, built from the page-agent building blocks. Edit this text and press Speak.</textarea>+ <div class="row">+ <button id="speak">▶ Speak</button>+ <button id="stop">⏹ Stop</button>+ <button id="mute" aria-pressed="false">🔊 Mute</button>+ <button id="pick">🔀 Choose guide</button>+ </div>+ <div class="caption" id="caption" aria-live="polite"></div>+ </div>+ </div>+ </div>++ <!-- Map the bare `three` specifier so the unbundled ESM source runs from disk. -->+ <script type="importmap">+ {+ "imports": {+ "three": "https://unpkg.com/[email protected]/build/three.module.js",+ "three/addons/": "https://unpkg.com/[email protected]/examples/jsm/"+ }+ }+ </script>+ <script type="module">+ import {+ AvatarStage, SpeechNarrator, AvatarPicker,+ AGENTS, getAgent, agentUrl,+ } from '../src/index.js';++ const panel = document.getElementById('panel');+ const stageEl = document.getElementById('stage');+ const nameEl = document.getElementById('name');+ const tagEl = document.getElementById('tag');+ const captionEl = document.getElementById('caption');++ // 1) The 3D surface.+ const stage = new AvatarStage(stageEl, { background: 'transparent' });++ // 2) Speech + lipsync, wired to our own caption + speaking state.+ const narrator = new SpeechNarrator(stage, {+ onCaption: (t) => (captionEl.textContent = t || ''),+ onState: (s) => (panel.dataset.speaking = String(s === 'speaking')),+ onError: (e) => console.warn('[headless] speech error', e),+ });++ // 3) A picker over the full catalog.+ const picker = new AvatarPicker(AGENTS, {+ onSelect: (id) => use(id),+ getCurrent: () => current?.id,+ title: 'Choose your guide',+ });+ picker.mount();++ let current = null;+ async function use(id) {+ current = getAgent(id) || AGENTS[0];+ narrator.setAgent(current); // adopt its voice profile+ AvatarPicker.persist(current.id);+ nameEl.textContent = current.name;+ tagEl.textContent = current.tagline;+ panel.style.setProperty('--accent', current.accent);+ await stage.load(agentUrl(current), { framing: current.framing });+ }++ document.getElementById('speak').onclick = () =>+ narrator.speak(document.getElementById('text').value, { interrupt: true });+ document.getElementById('stop').onclick = () => narrator.cancel();+ document.getElementById('mute').onclick = (e) => {+ const on = e.currentTarget.getAttribute('aria-pressed') !== 'true';+ e.currentTarget.setAttribute('aria-pressed', String(on));+ e.currentTarget.textContent = on ? '🔇 Muted' : '🔊 Mute';+ narrator.setMuted(on);+ };+ document.getElementById('pick').onclick = () => picker.open();++ // Start with the visitor's saved choice, else the default.+ use(AvatarPicker.restore() || 'sol');++ // Tidy up if this view is ever torn down.+ addEventListener('beforeunload', () => { narrator.dispose(); stage.dispose(); picker.dispose(); });+ </script>+</body>+</html>diff --git a/page-agent-sdk/examples/react.jsx b/page-agent-sdk/examples/react.jsxnew file mode 100644index 000000000..a7618bbb8--- /dev/null+++ b/page-agent-sdk/examples/react.jsx@@ -0,0 +1,98 @@+/**+ * @three-ws/page-agent — React integration example+ * ================================================+ * A reusable hook + component. Requires a bundler (Vite, Next, CRA) with:+ *+ * npm install @three-ws/page-agent three+ *+ * See docs/guide-frameworks.md for Next.js (SSR), Vue, Svelte, and more.+ */++import { useEffect, useRef, useState, useCallback } from 'react';+import { PageAgent } from '@three-ws/page-agent';++/**+ * Owns a single PageAgent for the component's lifetime.+ * Construct ONCE — change the avatar/narration via methods, not by re-rendering.+ */+export function usePageAgent(config = {}) {+ const ref = useRef(null);+ const [agent, setAgent] = useState(null);++ useEffect(() => {+ // PageAgent is browser-only; useEffect never runs on the server.+ const guide = new PageAgent(config);+ ref.current = guide;+ setAgent(guide);+ return () => {+ guide.dispose(); // free the WebGL context + speech queue on unmount+ ref.current = null;+ };+ // Construct once. Intentionally empty deps.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);++ return agent;+}++/**+ * Drop-in guide. Renders nothing itself — the agent docks to <body>.+ * Exposes a few props that map to imperative calls after mount.+ */+export function Guide({ avatar = 'sol', autoNarrate = true, onSegment, onReady }) {+ const guide = usePageAgent({ agent: avatar, autoNarrate });++ useEffect(() => {+ if (!guide) return;+ if (onReady) guide.on('ready', onReady);+ if (onSegment) guide.on('segment', onSegment);+ return () => {+ if (onReady) guide.off('ready', onReady);+ if (onSegment) guide.off('segment', onSegment);+ };+ }, [guide, onReady, onSegment]);++ // Keep the live avatar in sync if the prop changes.+ useEffect(() => { guide?.setAgent(avatar); }, [guide, avatar]);++ return null;+}++/* ----------------------------------------------------------------------------+ * Example usage+ * ------------------------------------------------------------------------- */++export default function App() {+ const guide = usePageAgent({ agent: 'nova', autoNarrate: true });++ const explain = useCallback(+ (text) => () => guide?.narrate(text, { interrupt: true }),+ [guide],+ );++ return (+ <main>+ <h1 data-narrate="Welcome to the dashboard — here's where your day starts.">+ Dashboard+ </h1>++ <button onClick={explain('This button saves a draft without publishing.')}>+ What does Save do?+ </button>++ <button onClick={() => guide?.narratePage({ greet: true })}>+ Take the tour+ </button>++ <button onClick={() => guide?.openPicker()}>Change guide</button>+ <button onClick={() => guide?.stop()}>Stop</button>+ </main>+ );+}++/*+ * Or the declarative component form:+ *+ * import { Guide } from './react.jsx';+ * <Guide avatar="vera" autoNarrate onSegment={({ text }) => console.log(text)} />+ */diff --git a/pages/ibm/x402-demo.html b/pages/ibm/x402-demo.htmlindex 39fed35f2..79f3d441a 100644--- a/pages/ibm/x402-demo.html+++ b/pages/ibm/x402-demo.html@@ -1435,7 +1435,11 @@ agent-3d:defined ~ .agent-skel{display:none}.then(function (body) {var accepts = (body && body.accepts) || [];if (!accepts.length) throw new Error('no payment terms in challenge');- renderChallengePreview(accepts);+ // Solana-only checkout — quote just the Solana terms in the live preview+ // so it matches the wallet flow. Fall back to all terms if the server+ // ever omits Solana, so the preview never renders empty.+ var solanaOnly = accepts.filter(function (a) { return a && typeof a.network === 'string' && a.network.indexOf('solana') === 0; });+ renderChallengePreview(solanaOnly.length ? solanaOnly : accepts);}).catch(function (err) {var label = $('fgPvLabel'); label.className = 'preview-label err';@@ -1644,6 +1648,7 @@ agent-3d:defined ~ .agent-skel{display:none}body: { prompt: prompt, tier: tier, aspect_ratio: '1:1' },merchant: 'three.ws',action: 'Forge: ' + prompt.slice(0, 48),+ networks: ['solana'],caps: { maxPerCall: (TIER_ATOMIC[tier] || 500000) }}).then(function (out) {if (!out || !out.ok) { setResultError('The payment did not complete. Please try again.'); return; }diff --git a/pages/walk.html b/pages/temporary.htmlsimilarity index 100%rename from pages/walk.htmlrename to pages/temporary.htmldiff --git a/pages/three.html b/pages/three.htmldeleted file mode 100644index 4d4717a04..000000000--- a/pages/three.html+++ /dev/null@@ -1,40 +0,0 @@-<!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/api/page-og?s=crypto&t=The+%24THREE+Economy&d=How+three.ws+charges+in+%24THREE%2C+the+only+coin%3A+pay-per-use+pricing+for+AI+compute%2C+hold-to-access+holder+tiers+with+lower+fees%2C+rare+*.threews.sol+names%2C+and+a+&p=%2Fthree" />- <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/api/page-og?s=crypto&t=The+%24THREE+Economy&d=How+three.ws+charges+in+%24THREE%2C+the+only+coin%3A+pay-per-use+pricing+for+AI+compute%2C+hold-to-access+holder+tiers+with+lower+fees%2C+rare+*.threews.sol+names%2C+and+a+&p=%2Fthree" />- <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" />-- <link rel="canonical" href="https://three.ws/three">- <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"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.","url":"https://three.ws/three","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>-- <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">- <meta property="og:locale" content="en_US">- <meta property="og:image:alt" content="The $THREE Economy — three.ws">-</head>- <body>- <script type="module" src="/src/three-economy.js"></script>- </body>-</html>diff --git a/public/changelog.json b/public/changelog.jsonindex e1e537ea7..8a9730aa6 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-19T22:13:29.951Z",+ "generated_at": "2026-06-19T22:26:05.813Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -394,16 +394,6 @@"improvement"]},- {- "date": "2026-06-19",- "type": "update",- "title": "Live x402 payment challenges on the IBM partnership page",- "summary": "The “Accelerating outcomes” section on the IBM × three.ws page had two empty gradient boxes under its AI agents and Crypto tabs. They're now live: each reads a real three.ws endpoint's HTTP 402 response on the spot and shows the exact terms the server is quoting — price in USDC, settlement network, and recipient. The AI agents tab shows what an autonomous agent reads before paying for live market data; the Crypto tab shows how any endpoint becomes pay-per-call. No wallet needed to watch it.",- "link": "/ibm/x402-demo",- "tags": [- "improvement"- ]- },{"date": "2026-06-19","type": "update",@@ -486,6 +476,17 @@"fix"]},+ {+ "date": "2026-06-19",+ "type": "update",+ "title": "Pick who walks your pages — diverse avatar roster + Walk SDK",+ "summary": "The walking companion that strolls the corner of every page (and detaches into the full-page playground) now lets you choose your character. A new picker offers a diverse roster — a robot mascot, humanoids, photoreal people, a fox, dancers and showpieces — and swaps the avatar live. Each one is animated correctly whether its model ships its own moves or borrows the shared motion library, so nobody ever freezes mid-stride. Under the hood the whole companion + playground is now a standalone SDK (@three-ws/walk) you can drop into any Three.js site.",+ "link": null,+ "tags": [+ "feature",+ "sdk"+ ]+ },{"date": "2026-06-19","type": "update",@@ -682,6 +683,16 @@"feature"]},+ {+ "date": "2026-06-19",+ "type": "update",+ "title": "Walk mode moves to three.ws/temporary",+ "summary": "The drive-your-avatar walk demo — joystick or WASD movement, AR back-camera passthrough, and the live coin-world mainland — now lives at three.ws/temporary. Every link across the site already points to the new path, and avatar deep-links (three.ws/wk/…) follow along. The old /walk address is freed up for what's coming next.",+ "link": "/temporary",+ "tags": [+ "improvement"+ ]+ },{"date": "2026-06-19","type": "update",@@ -702,6 +713,16 @@"feature"]},+ {+ "date": "2026-06-19",+ "type": "update",+ "title": "Walk the IBM partnership page with a 3D agent",+ "summary": "The “Accelerating outcomes” section on the IBM × three.ws page had two empty gradient boxes. The AI agents tab now has a real 3D robot standing on it — click it (or press Enter) and the agent drops onto the page so you can walk the whole partnership page: every section becomes solid ground, arrow keys / WASD move and jump on desktop, and an on-screen joystick appears on phones. The Crypto tab now links straight to the live Forge and Play demos. The walk playground is also now loadable on its own from a stable URL, so any page can launch it.",+ "link": "/ibm/partnership",+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-19","type": "update",@@ -2378,7 +2399,7 @@"type": "update","title": "Walking avatars now travel the right way on every rig","summary": "Animations with root motion — walking, running, jumping with travel — now move your avatar in the correct world direction and distance no matter what tool the avatar came from. Avatars exported from Mixamo, Ready Player Me, Blender, and others orient their skeletons differently; previously a walk could drift sideways, sink into the floor, or moonwalk on rigs that didn't match the standard convention. The viewer now re-expresses each clip's root motion in the target rig's own frame, so two avatars built in different tools walk side by side in the same direction. Avatars that already matched the reference rig are byte-for-byte unchanged.",- "link": "/walk",+ "link": "/temporary","tags": ["fix","improvement"@@ -3502,16 +3523,6 @@"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": "launch",@@ -4157,7 +4168,7 @@"type": "update","title": "Animation library expands: 100+ clips, FBX and BVH upload","summary": "The platform animation library grows to 100+ retargeted motion clips drawn from Mixamo, Avaturn packs, and MIT-licensed Three.js example models (Soldier, Michelle, Xbot). The agent dashboard's Upload clip dialog now accepts .glb, .fbx, and .bvh files — FBX and BVH are converted to GLB client-side via three.js loaders before upload, so creators can bring mocap data directly from capture tools without a separate conversion step. A full Mixamo catalog download pipeline (scripts/mixamo-all.mjs) is in place to expand the library to 2,000+ clips as soon as credentials are supplied.",- "link": "/walk",+ "link": "/temporary","tags": ["feature","improvement"@@ -6575,7 +6586,7 @@"type": "launch","title": "Walk","summary": "Drive a 3D avatar around with a joystick or WASD — toggle the back camera for AR-style passthrough.",- "link": "/walk",+ "link": "/temporary","tags": ["launch"]diff --git a/public/changelog.xml b/public/changelog.xmlindex 9a1929896..29e0c028a 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -310,14 +310,6 @@<category>improvement</category><description>IRL has no map and no list on purpose: you find agents by walking up to them and looking through your camera. The first time you open it, a short card now explains that idea — agents are hidden in the world around you, dropping your own lets someone else stumble on it later, and we never show a roster of where agents are, not even to you. You can reopen that explainer any time from the small "?" in the corner. And when you're somewhere quiet with nobody pinned yet, instead of a blank screen you'll see a gentle "Look around 👀 · or be the first to pin here" prompt with a one-tap way to place your own agent — so an empty spot reads as "keep exploring," not "this is broken." The moment a real agent comes into range, the prompt fades away on its own.</description></item>- <item>- <title>Live x402 payment challenges on the IBM partnership page</title>- <link>https://three.ws/ibm/x402-demo</link>- <guid isPermaLink="false">2026-06-19:Live x402 payment challenges on the IBM partnership page</guid>- <pubDate>Fri, 19 Jun 2026 12:00:00 GMT</pubDate>- <category>improvement</category>- <description>The “Accelerating outcomes” section on the IBM × three.ws page had two empty gradient boxes under its AI agents and Crypto tabs. They're now live: each reads a real three.ws endpoint's HTTP 402 response on the spot and shows the exact terms the server is quoting — price in USDC, settlement network, and recipient. The AI agents tab shows what an autonomous agent reads before paying for live market data; the Crypto tab shows how any endpoint becomes pay-per-call. No wallet needed to watch it.</description>- </item><item><title>Memory Studio — watch your agent’s memory form, curate it, and trust it</title><link>https://three.ws/agent-studio</link>@@ -382,6 +374,14 @@<category>fix</category><description>On agent profiles, the Unlock skill / purchase dialog had no height limit. When the form ran tall — wallet area, price, fee note, Confirm button, and QR code together — it grew past the screen, so the title was shoved above the top edge and the Pay button dropped below the bottom, and neither could be scrolled to. The dialog is now capped to the visible screen with the form scrolling inside it and the header pinned, so the Pay button is always reachable on any screen size.</description></item>+ <item>+ <title>Pick who walks your pages — diverse avatar roster + Walk SDK</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-19:Pick who walks your pages — diverse avatar roster + Walk SDK</guid>+ <pubDate>Fri, 19 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>The walking companion that strolls the corner of every page (and detaches into the full-page playground) now lets you choose your character. A new picker offers a diverse roster — a robot mascot, humanoids, photoreal people, a fox, dancers and showpieces — and swaps the avatar live. Each one is animated correctly whether its model ships its own moves or borrows the shared motion library, so nobody ever freezes mid-stride. Under the hood the whole companion + playground is now a standalone SDK (@three-ws/walk) you can drop into any Three.js site.</description>+ </item><item><title>Pinning your agent holds up when GPS gets flaky</title><link>https://three.ws/irl</link>@@ -534,6 +534,14 @@<category>feature</category><description>Every agent and avatar has its own custodial Solana wallet, and you own it per creation: make an avatar and its agent wallet is yours; if someone forks or saves that avatar, they get a brand-new wallet they alone control — yours is never shared or copied. A new Vanity tab in the agent wallet hub lets you grind a custom address (your own prefix and/or suffix) on demand. If the wallet already holds funds, they're automatically and safely swept to the new address before the switch completes, so funds are never stranded. The wallet now appears everywhere an agent or avatar shows up — profiles, avatar pages, your Agents and Avatars dashboards, the Characters feed and Trending — each with one-tap copy, an explorer link, and a vanity badge.</description></item>+ <item>+ <title>Walk mode moves to three.ws/temporary</title>+ <link>https://three.ws/temporary</link>+ <guid isPermaLink="false">2026-06-19:Walk mode moves to three.ws/temporary</guid>+ <pubDate>Fri, 19 Jun 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>The drive-your-avatar walk demo — joystick or WASD movement, AR back-camera passthrough, and the live coin-world mainland — now lives at three.ws/temporary. Every link across the site already points to the new path, and avatar deep-links (three.ws/wk/…) follow along. The old /walk address is freed up for what's coming next.</description>+ </item><item><title>Walk Playground no longer loses your character when it falls</title><link>https://three.ws/features/walk</link>@@ -550,6 +558,14 @@<category>feature</category><description>Click the corner walking companion to step into the page and you can now pick how he moves. Stroll mode is the relaxed top-down view — no gravity, wander anywhere across the page. Platformer mode turns the page's headings, cards and links into solid ground, with gravity, jumping and the chance to fall off edges. Flip between them live with the mode button (top-right) or the M key, and your choice is remembered as you walk from page to page.</description></item>+ <item>+ <title>Walk the IBM partnership page with a 3D agent</title>+ <link>https://three.ws/ibm/partnership</link>+ <guid isPermaLink="false">2026-06-19:Walk the IBM partnership page with a 3D agent</guid>+ <pubDate>Fri, 19 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>The “Accelerating outcomes” section on the IBM × three.ws page had two empty gradient boxes. The AI agents tab now has a real 3D robot standing on it — click it (or press Enter) and the agent drops onto the page so you can walk the whole partnership page: every section becomes solid ground, arrow keys / WASD move and jump on desktop, and an on-screen joystick appears on phones. The Crypto tab now links straight to the live Forge and Play demos. The walk playground is also now loadable on its own from a stable URL, so any page can launch it.</description>+ </item><item><title>Walk the whole page — the site is now a playground</title><link>https://three.ws/changelog</link>@@ -1840,7 +1856,7 @@</item><item><title>Walking avatars now travel the right way on every rig</title>- <link>https://three.ws/walk</link>+ <link>https://three.ws/temporary</link><guid isPermaLink="false">2026-06-17:Walking avatars now travel the right way on every rig</guid><pubDate>Wed, 17 Jun 2026 12:00:00 GMT</pubDate><category>fix</category>@@ -2718,14 +2734,6 @@<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>Trader Leaderboard</title><link>https://three.ws/leaderboard</link>@@ -3224,7 +3232,7 @@</item><item><title>Animation library expands: 100+ clips, FBX and BVH upload</title>- <link>https://three.ws/walk</link>+ <link>https://three.ws/temporary</link><guid isPermaLink="false">2026-06-13:Animation library expands: 100+ clips, FBX and BVH upload</guid><pubDate>Sat, 13 Jun 2026 12:00:00 GMT</pubDate><category>feature</category>@@ -5112,7 +5120,7 @@</item><item><title>Walk</title>- <link>https://three.ws/walk</link>+ <link>https://three.ws/temporary</link><guid isPermaLink="false">2026-05-10:Walk</guid><pubDate>Sun, 10 May 2026 12:00:00 GMT</pubDate><category>launch</category>diff --git a/public/features.json b/public/features.jsonindex fe7a3fb0f..7e5d2844e 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-19T22:13:29.930Z",+ "generated_at": "2026-06-19T22:26:05.756Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",@@ -56,7 +56,7 @@"showcase": false},{- "path": "/walk",+ "path": "/temporary","title": "Walk","description": "Drive a 3D avatar around with a joystick or WASD — toggle the back camera for AR-style passthrough.","added": "2026-05-10",@@ -886,16 +886,6 @@"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 ed9c042b1..879ea1d49 100644--- a/public/llms-full.txt+++ b/public/llms-full.txt@@ -39,7 +39,7 @@ Browse and preview public animations authored by the three.ws community. Apply a### Walk-URL: https://three.ws/walk+URL: https://three.ws/temporaryDrive a 3D avatar around with a joystick or WASD — toggle the back camera for AR-style passthrough.@@ -538,12 +538,6 @@ 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 d531ccab4..ca6ec9943 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -15,7 +15,7 @@ Entry points into the product.- [Discover](https://three.ws/discover): On-chain agent directory (ERC-8004 + Solana). Browse, search, and inspect every registered agent.- [Avatar Gallery](https://three.ws/gallery): Every public 3D avatar in the system, browsable as a grid.- [Animation Gallery](https://three.ws/animations): Browse and preview public animations authored by the three.ws community. Apply any clip to your avatar in the Animation Studio.-- [Walk](https://three.ws/walk): Drive a 3D avatar around with a joystick or WASD — toggle the back camera for AR-style passthrough.+- [Walk](https://three.ws/temporary): Drive a 3D avatar around with a joystick or WASD — toggle the back camera for AR-style passthrough.- [IRL](https://three.ws/irl): Place a 3D avatar in your real environment. Camera AR passthrough, joystick movement, and tap-to-place 3D objects on your floor.- [How location works on IRL](https://three.ws/irl-privacy): Placed agents are private by location: they appear only to people physically standing near them, never on a map or a list. What's shared, what isn't, and how your camera, motion, and location are used.- [Marketplace](https://three.ws/marketplace): Buy access to agents, skills, and avatars from other creators.@@ -109,7 +109,6 @@ 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/nav-data.js b/public/nav-data.jsindex 439b59377..9e1629456 100644--- a/public/nav-data.js+++ b/public/nav-data.js@@ -83,10 +83,9 @@ export const NAV_GROUPS = [desc: 'Plain-English intro + real use-cases — start here',},{- title: 'The $THREE Economy',- href: '/three',- badge: 'New',- desc: 'Holder tiers, live pricing & rewards — and what holding $THREE unlocks',+ title: '$THREE Token',+ href: '/three-token',+ desc: 'Live price, bonding-curve chart, streaming trades & one-click buy',},{ title: 'Agents Index', href: '/agents', desc: 'Browse every registered agent' },{ title: 'Marketplace', href: '/marketplace', desc: 'Buy, sell & remix agents' },diff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex c5b1cb896..374872391 100644--- a/public/sitemap/index.html+++ b/public/sitemap/index.html@@ -56,6 +56,25 @@.sm-brand img { width: 24px; height: 24px; border-radius: 5px; }.sm-brand:hover { text-decoration: none; }</style>++ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">+ <meta property="og:type" content="website">+ <meta property="og:site_name" content="three.ws">+ <meta property="og:locale" content="en_US">+ <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/api/page-og?s=main&t=Sitemap&d=Human-readable+index+of+every+page+on+three.ws.&p=%2Fsitemap">+ <meta property="og:image:width" content="1200">+ <meta property="og:image:height" content="630">+ <meta property="og:image:type" content="image/png">+ <meta property="og:image:alt" content="Sitemap — three.ws">+ <meta name="twitter:card" content="summary_large_image">+ <meta name="twitter:site" content="@trythreews">+ <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/api/page-og?s=main&t=Sitemap&d=Human-readable+index+of+every+page+on+three.ws.&p=%2Fsitemap">+ <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@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"},"primaryImageOfPage":"https://three.ws/api/page-og?s=main&t=Sitemap&d=Human-readable+index+of+every+page+on+three.ws.&p=%2Fsitemap"}]}</script></head><body><header class="sm-topbar">@@ -65,7 +84,7 @@<main class="sm-wrap"><div class="sm-hero"><h1>Sitemap</h1>- <p>All 284 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>+ <p>All 283 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>@@ -77,7 +96,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 284 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />+ <input id="sm-filter-input" type="search" placeholder="Filter 283 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>@@ -129,9 +148,9 @@</a></li><li>- <a href="/walk">+ <a href="/temporary"><span class="sm-title">Walk</span>- <span class="sm-path">/walk</span>+ <span class="sm-path">/temporary</span><span class="sm-desc">Drive a 3D avatar around with a joystick or WASD — toggle the back camera for AR-style passthrough.</span></a></li>@@ -494,7 +513,7 @@<section class="sm-section" id="crypto"><header>- <h2>Crypto<span class="sm-count" data-count>47</span></h2>+ <h2>Crypto<span class="sm-count" data-count>46</span></h2><p class="sm-section-desc">On-chain features: pay-per-call, token launches, vanity wallets.</p></header><ul class="sm-list">@@ -722,13 +741,6 @@<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/scripts/console-sweep.mjs b/scripts/console-sweep.mjsindex da6e951b1..4d92bd31f 100644--- a/scripts/console-sweep.mjs+++ b/scripts/console-sweep.mjs@@ -44,7 +44,7 @@ const CANONICAL_ROUTES = [{ path: '/create/selfie', slug: 'create-selfie', engine: false, expectDegraded: true },{ path: '/forge', slug: 'forge', engine: true },{ path: '/play', slug: 'play', engine: true },- { path: '/walk', slug: 'walk', engine: true },+ { path: '/temporary', slug: 'temporary', engine: true },{ path: '/marketplace', slug: 'marketplace', engine: false, expectDegraded: true },{ path: '/agent-exchange', slug: 'agent-exchange', engine: false, expectDegraded: true },{ path: '/deploy', slug: 'deploy', engine: false, expectDegraded: true },diff --git a/scripts/lobby-check.mjs b/scripts/lobby-check.mjsindex 6cbc3c52c..9a80dd1e0 100644--- a/scripts/lobby-check.mjs+++ b/scripts/lobby-check.mjs@@ -24,7 +24,7 @@ await page.route('**/api/community/worlds', (route) =>const result = { steps: [] };try {- await page.goto(`${BASE}/walk`, { waitUntil: 'domcontentloaded', timeout: 30000 });+ await page.goto(`${BASE}/temporary`, { waitUntil: 'domcontentloaded', timeout: 30000 });await page.waitForTimeout(3000);const lobby = page.locator('.clobby');diff --git a/scripts/nav-check.mjs b/scripts/nav-check.mjsindex 08b4668d9..3fc5da247 100644--- a/scripts/nav-check.mjs+++ b/scripts/nav-check.mjs@@ -1,6 +1,6 @@import puppeteer from 'puppeteer';const base = 'http://localhost:3000';-const routes = ['/three-live','/pricing','/widgets','/marketplace','/walk','/community','/profile','/avatar-sdk','/mocap-studio','/pump-live','/pump-visualizer','/features','/home-v2','/tutorials','/pump-dashboard'];+const routes = ['/three-live','/pricing','/widgets','/marketplace','/temporary','/community','/profile','/avatar-sdk','/mocap-studio','/pump-live','/pump-visualizer','/features','/home-v2','/tutorials','/pump-dashboard'];const browser = await puppeteer.launch({ args:['--no-sandbox','--disable-setuid-sandbox'] });const out = {};for (const path of routes) {diff --git a/scripts/probe-walk-joystick.mjs b/scripts/probe-walk-joystick.mjsindex 6b7e62924..04cfbbd46 100644--- a/scripts/probe-walk-joystick.mjs+++ b/scripts/probe-walk-joystick.mjs@@ -4,7 +4,7 @@// input state and the avatar's world position before/after.import { chromium } from 'playwright';-const URL = process.env.URL || 'http://localhost:3000/walk';+const URL = process.env.URL || 'http://localhost:3000/temporary';const browser = await chromium.launch({args: [diff --git a/scripts/verify-communities.mjs b/scripts/verify-communities.mjsindex 2d9582c6c..3cc69f9f3 100644--- a/scripts/verify-communities.mjs+++ b/scripts/verify-communities.mjs@@ -35,7 +35,7 @@ try {// ── Enter a coin world ────────────────────────────────────────────────────log('→ clicking first coin');await Promise.all([- page.waitForURL(/\/walk\?.*coin=/, { timeout: 15000 }),+ page.waitForURL(/\/temporary\?.*coin=/, { timeout: 15000 }),first.click(),]);const url = new URL(page.url());@@ -63,10 +63,10 @@ try {// ── Mainland (no coin) still works ────────────────────────────────────────log('→ verifying mainland (no coin) has no coin HUD');- await page.goto(`${BASE}/walk`, { waitUntil: 'domcontentloaded' });+ await page.goto(`${BASE}/temporary`, { waitUntil: 'domcontentloaded' });await page.waitForTimeout(1500);const hudOnMainland = await page.locator('#walk-coin-hud').count();- if (hudOnMainland !== 0) errors.push('coin HUD wrongly present on mainland /walk');+ if (hudOnMainland !== 0) errors.push('coin HUD wrongly present on mainland /temporary');log(` coin HUD on mainland: ${hudOnMainland} (expect 0)`);} catch (e) {errors.push(`[harness] ${e.message}`);diff --git a/scripts/verify-walk-joystick.mjs b/scripts/verify-walk-joystick.mjsindex 4cd5e9822..56ced7548 100644--- a/scripts/verify-walk-joystick.mjs+++ b/scripts/verify-walk-joystick.mjs@@ -6,7 +6,7 @@// move → tick → avatar.position pipeline. Run while `npm run dev` is up.import puppeteer from 'puppeteer';-const URL = process.env.URL || 'http://localhost:3003/walk';+const URL = process.env.URL || 'http://localhost:3003/temporary';const browser = await puppeteer.launch({executablePath: '/home/codespace/.cache/puppeteer/chrome/linux-148.0.7778.97/chrome-linux64/chrome',diff --git a/scripts/verify-walk-mobile.mjs b/scripts/verify-walk-mobile.mjsindex 74bf5354a..92162c191 100644--- a/scripts/verify-walk-mobile.mjs+++ b/scripts/verify-walk-mobile.mjs@@ -5,7 +5,7 @@// (and, as a control, DOES auto-show on desktop)import puppeteer from 'puppeteer';-const URL = process.env.WALK_URL || 'http://localhost:3000/walk';+const URL = process.env.WALK_URL || 'http://localhost:3000/temporary';async function probe({ touch }) {const browser = await puppeteer.launch({diff --git a/scripts/verify-worlds-live.mjs b/scripts/verify-worlds-live.mjsindex dc1d0c648..e7e4980b9 100644--- a/scripts/verify-worlds-live.mjs+++ b/scripts/verify-worlds-live.mjs@@ -43,7 +43,7 @@ let entersWalk = false;let walkUrl = '';try {await page.locator('.wl-card:not(.wl-skel)').first().click();- await page.waitForURL('**/walk?**', { timeout: 10_000 });+ await page.waitForURL('**/temporary?**', { timeout: 10_000 });walkUrl = page.url();entersWalk = /[?&]coin=[1-9A-HJ-NP-Za-km-z]{32,44}/.test(walkUrl);} catch { /* stays false */ }diff --git a/src/forge-pay.js b/src/forge-pay.jsindex 04f84e430..858ff7704 100644--- a/src/forge-pay.js+++ b/src/forge-pay.js@@ -18,7 +18,7 @@import { payWithToken } from './token-pay.js';-const ECONOMY_URL = '/three';+const ECONOMY_URL = '/three-token';const SIGN_IN_URL = '/login';const WALLET_URL = 'https://phantom.app/';diff --git a/src/glb-canonicalize.js b/src/glb-canonicalize.jsindex a59313aea..2bd8daa88 100644--- a/src/glb-canonicalize.js+++ b/src/glb-canonicalize.js@@ -4,17 +4,22 @@//// Handled name variants:// • Mixamo: `mixamorig:LeftArm`, `mixamorig1:LeftArm`, `mixamorigLeftArm`-// • Blender: `Armature_LeftArm`, `Armature/LeftArm`+// • Blender: `Armature_LeftArm`, `Armature/LeftArm`, `upperarm.L` (.L/.R side)// • Rigify: `DEF-LeftArm`, `ORG-LeftArm`, `MCH-LeftArm`// • CharacterStudio: `CH_Hips`, `CH_LeftUpLeg` (CH_ prefix stripped)// • Unreal mannequin: `pelvis`, `clavicle_l`, `upperarm_l`, `thigh_l`, `calf_l`, … (alias map)+// • VRM / VRoid: `J_Bip_C_Hips`, `J_Bip_L_UpperArm`, `J_Bip_L_Little1` (alias map)+// • VRM 1.0: `upperChest`, `leftUpperArm`, `leftLowerLeg`, `leftToes` (camelCase)+// • Daz / Genesis: `hip`, `abdomen`, `lShldr`, `lForeArm`, `lThigh`, `lShin`, `lCollar`+// • MakeHuman: `upperarm.L`, `shin.L`, `clavicle.L` (shared with Unreal/Blender stems)+// • Simple rigs: `shoulderL`, `elbowL`, `wristL`, `hipL`, `kneeL`, `ankleL`, `chest`// • snake_case: `left_arm`, `Left_Arm`// • kebab-case: `left-arm`// • lowercase: `leftarm`, `lefthand`//-// VRM-style names (`J_Bip_L_UpperArm`) and skeletons that aren't humanoid-// (quadrupeds, custom rigs) deliberately fall through unchanged — there's no-// safe automatic mapping for those.+// Skeletons that aren't humanoid (quadrupeds, custom prop rigs) deliberately+// fall through unchanged — there's no safe automatic mapping for those, and+// callers fall back to a known-good rig rather than render a bind-pose T-pose.//// This module is pure JS — works in Node (vitest) and in the browser. It// rewrites the GLB JSON chunk in-place and repacks the binary container so@@ -80,6 +85,75 @@ const UNREAL_ALIASES = new Map(Object.entries({thighr: 'RightUpLeg', calfr: 'RightLeg', footr: 'RightFoot', ballr: 'RightToeBase',}));+// Extended humanoid alias map: VRM/VRoid, VRM 1.0, Daz/Genesis, MakeHuman, and+// simple/generic rigs. Keyed by the same separator-stripped, lowercased form+// `_lookupBone` produces (e.g. `J_Bip_L_UpperArm` → `jbiplupperarm`,+// `shoulderL` → `shoulderl`). Consulted AFTER the canonical/Mixamo and Unreal+// tables, so it only ever resolves names those don't already cover — it can+// never shadow a canonical spelling. Every entry maps onto the canonical bone+// set the clip library drives, so any rig using these conventions animates+// (idle + walk with legs moving) instead of freezing in its bind-pose T-pose.+const EXTRA_ALIASES = (() => {+ const m = new Map();+ const norm = (s) => s.replace(/[-_.\s]+/g, '').toLowerCase();+ // First spelling wins, so listing-order is the priority.+ const put = (variant, canonical) => { const k = norm(variant); if (!m.has(k)) m.set(k, canonical); };++ // VRM 0.x / VRoid skeletons (`J_Bip_<C|L|R>_<bone>`). The side lives in the+ // prefix, so each is mapped explicitly rather than via the side helper below.+ const VRM = [+ ['J_Bip_C_Hips', 'Hips'], ['J_Bip_C_Spine', 'Spine'], ['J_Bip_C_Chest', 'Spine1'],+ ['J_Bip_C_UpperChest', 'Spine2'], ['J_Bip_C_Neck', 'Neck'], ['J_Bip_C_Head', 'Head'],+ ['J_Bip_L_Shoulder', 'LeftShoulder'], ['J_Bip_L_UpperArm', 'LeftArm'], ['J_Bip_L_LowerArm', 'LeftForeArm'], ['J_Bip_L_Hand', 'LeftHand'],+ ['J_Bip_R_Shoulder', 'RightShoulder'], ['J_Bip_R_UpperArm', 'RightArm'], ['J_Bip_R_LowerArm', 'RightForeArm'], ['J_Bip_R_Hand', 'RightHand'],+ ['J_Bip_L_UpperLeg', 'LeftUpLeg'], ['J_Bip_L_LowerLeg', 'LeftLeg'], ['J_Bip_L_Foot', 'LeftFoot'], ['J_Bip_L_ToeBase', 'LeftToeBase'], ['J_Bip_L_Toes', 'LeftToeBase'],+ ['J_Bip_R_UpperLeg', 'RightUpLeg'], ['J_Bip_R_LowerLeg', 'RightLeg'], ['J_Bip_R_Foot', 'RightFoot'], ['J_Bip_R_ToeBase', 'RightToeBase'], ['J_Bip_R_Toes', 'RightToeBase'],+ ];+ for (const [v, c] of VRM) put(v, c);+ // VRoid finger chains: Thumb/Index/Middle/Ring map 1:1; "Little" is the pinky.+ for (const [vf, cf] of [['Thumb', 'Thumb'], ['Index', 'Index'], ['Middle', 'Middle'], ['Ring', 'Ring'], ['Little', 'Pinky']]) {+ for (let n = 1; n <= 3; n++) {+ put(`J_Bip_L_${vf}${n}`, `LeftHand${cf}${n}`);+ put(`J_Bip_R_${vf}${n}`, `RightHand${cf}${n}`);+ }+ }++ // Centre / torso bones with no side (VRM 1.0, Daz, generic single-chest rigs).+ for (const [v, c] of [+ ['chest', 'Spine1'], ['lowerChest', 'Spine1'], ['chestLower', 'Spine1'],+ ['upperChest', 'Spine2'], ['chestUpper', 'Spine2'],+ ['abdomen', 'Spine'], ['abdomenLower', 'Spine'], ['abdomenUpper', 'Spine1'],+ ['hip', 'Hips'],+ ['lowerNeck', 'Neck'], ['upperNeck', 'Neck'], ['neckLower', 'Neck'], ['neckUpper', 'Neck'],+ ]) put(v, c);++ // Side-paired limb bones, given as the LEFT spelling + its canonical; the+ // right twin is derived by swapping the side token (left→right, leading l→r,+ // trailing L→R). Covers VRM 1.0 camelCase, Daz/Genesis (`lShldr`, `lThigh`),+ // and simple rigs (`shoulderL`, `elbowL`, `hipL`).+ const SIDED = [+ ['leftUpperArm', 'LeftArm'], ['lUpperArm', 'LeftArm'], ['shoulderL', 'LeftArm'], ['lShldr', 'LeftArm'], ['lShldrBend', 'LeftArm'],+ ['leftLowerArm', 'LeftForeArm'], ['lLowerArm', 'LeftForeArm'], ['elbowL', 'LeftForeArm'], ['lForeArm', 'LeftForeArm'], ['lForearmBend', 'LeftForeArm'],+ ['wristL', 'LeftHand'], ['lHand', 'LeftHand'],+ ['lCollar', 'LeftShoulder'], ['collarL', 'LeftShoulder'],+ ['leftUpperLeg', 'LeftUpLeg'], ['lUpperLeg', 'LeftUpLeg'], ['hipL', 'LeftUpLeg'], ['lThigh', 'LeftUpLeg'], ['lThighBend', 'LeftUpLeg'],+ ['leftLowerLeg', 'LeftLeg'], ['lLowerLeg', 'LeftLeg'], ['kneeL', 'LeftLeg'], ['shinL', 'LeftLeg'], ['lShin', 'LeftLeg'],+ ['ankleL', 'LeftFoot'], ['lFoot', 'LeftFoot'],+ ['leftToes', 'LeftToeBase'], ['toeL', 'LeftToeBase'], ['lToe', 'LeftToeBase'],+ ];+ for (const [lv, lc] of SIDED) {+ put(lv, lc);+ const rc = lc.replace(/^Left/, 'Right');+ let rv;+ if (/^left/.test(lv)) rv = lv.replace(/^left/, 'right');+ else if (/^l[A-Z]/.test(lv)) rv = 'r' + lv.slice(1);+ else if (/L$/.test(lv)) rv = lv.replace(/L$/, 'R');+ else rv = lv;+ put(rv, rc);+ }+ return m;+})();+/*** Reduce a bone name to its canonical three.ws form, or null if it doesn't* correspond to a recognised humanoid bone.@@ -98,7 +172,8 @@ export function canonicalizeBoneName(name) {// removed — but only when the un-stripped form didn't already resolve, so a// genuinely numbered bone like `left_hand_index_1` still maps to// `LeftHandIndex1` before we'd ever strip its index.- const deduped = name.replace(/_\d+$/, '');+ // `_NN` (glTF/FBX) and `.NNN` (Blender) are both node-de-dup suffixes.+ const deduped = name.replace(/[._]\d+$/, '');if (deduped !== name) return _lookupBone(deduped);return null;}@@ -114,11 +189,13 @@ function _lookupBone(name) {// CharacterStudio exports prefix every joint `CH_` (`CH_Hips`, `CH_LeftUpLeg`),// whose stems are otherwise canonical — strip it like any other vendor prefix.s = s.replace(/^CH[_:]/i, '');- // Collapse separators so `Left_Arm`, `left-arm`, `left arm`, `LeftArm` all- // reach the same lookup key.- const key = s.replace(/[-_\s]+/g, '').toLowerCase();- // Canonical/Mixamo/Rigify spellings first, then the Unreal-mannequin aliases.- return LOOKUP.get(key) ?? UNREAL_ALIASES.get(key) ?? null;+ // Collapse separators so `Left_Arm`, `left-arm`, `left arm`, `LeftArm`,+ // `upperarm.L` all reach the same lookup key (`.` covers Blender/MakeHuman).+ const key = s.replace(/[-_.\s]+/g, '').toLowerCase();+ // Canonical/Mixamo/Rigify spellings first, then the Unreal-mannequin aliases,+ // then the extended VRM/Daz/MakeHuman/simple-rig table (lowest priority, so it+ // only catches names the first two don't already resolve).+ return LOOKUP.get(key) ?? UNREAL_ALIASES.get(key) ?? EXTRA_ALIASES.get(key) ?? null;}/**diff --git a/src/three-access.js b/src/three-access.jsindex dc26c599b..2c531d8ec 100644--- a/src/three-access.js+++ b/src/three-access.js@@ -38,7 +38,7 @@ let _tierPass = null; // { pass, tier, exp(ms), wallet } — wallet is the identlet _tierPassInFlight = null; // de-dupe concurrent mints onto one network/signature round-triplet _stylesInjected = false;-const ECONOMY_URL = '/three';+const ECONOMY_URL = '/three-token';// The connected Solana wallet address (Phantom on web, the Seeker TWA wallet on// mobile), or null when none is connected — in which case every read falls back to@@ -302,7 +302,7 @@ export async function mountTierBadge(target) {// Icon + label are separate spans so the nav can collapse the chip to just the ◆ on// the tightest viewports (≤520px) without losing the link or its accessible name.el.innerHTML =- `<a class="tg-badge tg-tier-${escapeHtml(t.id)}" href="${ECONOMY_URL}#tiers" ` ++ `<a class="tg-badge tg-tier-${escapeHtml(t.id)}" href="${ECONOMY_URL}" ` +`aria-label="Your $THREE tier: ${escapeHtml(t.label)}" ` +`title="Your $THREE holder tier — what it unlocks${held}">` +`<span class="tg-tier-mark" aria-hidden="true">◆</span>` +@@ -382,7 +382,7 @@ export function showThreeGate(gate, opts = {}) {<div class="tg-actions"><a class="tg-btn tg-btn--primary" id="tg-get" href="${escapeHtml(getUrl)}">Get $THREE</a>${payBtn}- <a class="tg-btn tg-btn--ghost" href="${ECONOMY_URL}#tiers">See holder tiers</a>+ <a class="tg-btn tg-btn--ghost" href="${ECONOMY_URL}">$THREE price & chart</a></div><p class="tg-foot">$THREE is the only coin on three.ws. Draft & Standard generation stay free, forever.</p></div>`;diff --git a/src/three-economy.js b/src/three-economy.jsdeleted file mode 100644index 0c8b7d67f..000000000--- a/src/three-economy.js+++ /dev/null@@ -1,1480 +0,0 @@-// The $THREE economy (/three) — the flagship surface for the platform economy.-//-// One page that makes the whole economy legible and verifiable: a live canvas-// visualization of value flowing through the protocol ("The Flow"), animated live-// stats, on-chain-verifiable treasury + rewards wallets, a real reflected-to--// holders history with a personal projector, an interactive holder-tier ladder,-// an interactive pricing explorer that applies your tier discount live, and a-// rare-name studio. All data is real — /api/three/{catalog,stats,tier,name-quote}-// and /api/token/price. No mock data, no placeholders; every state is designed.-//-// Design language: dark, premium, minimal. Split roles have a fixed color-// identity used everywhere — treasury=gold, rewards=green, creators=blue,-// scarcity=violet — so the same value is recognizable in the flow, the stats, and-// the catalog. Motion is purposeful and fully reduced-motion aware.--// Holder access reads go through the shared, wallet-aware data layer (three-access.js)-// so a connected wallet's tier surfaces here exactly as it does in the nav chip and-// Forge — one source of truth, no independent fetch. Wallet connect reuses the global-// connect button (initWalletButton wires the hidden #connect-wallet-btn this page mounts).-import { getAccess } from './three-access.js';-import { initWalletButton } from './wallet.js';--const API = '/api/three';-const MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';-const REDUCED_MOTION =- typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;--// Fixed color identity per split role — the page's visual grammar.-const ROLE = {- treasury: { color: '#f5c451', glow: 'rgba(245,196,81,.5)', label: 'Treasury' },- rewards: { color: '#6ee7a8', glow: 'rgba(110,231,168,.55)', label: 'Holder rewards' },- seller: { color: '#7cc4ff', glow: 'rgba(124,196,255,.5)', label: 'Creators' },- scarcity: { color: '#c4a8ff', glow: 'rgba(196,168,255,.5)', label: 'Scarcity' },-};-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 '0';- const a = Math.abs(v);- if (a >= 1e9) return `${(v / 1e9).toFixed(2)}B`;- if (a >= 1e6) return `${(v / 1e6).toFixed(2)}M`;- if (a >= 1e3) return `${(v / 1e3).toFixed(1)}K`;- return v.toLocaleString('en-US', { maximumFractionDigits: v < 1 && v > 0 ? 4 : 2 });-};-const atomicsToTokens = (atomics, decimals = 6) => {- try {- // Avoid Number overflow on huge atomics: split integer/fraction via BigInt.- const a = BigInt(atomics);- const d = 10n ** BigInt(decimals);- return Number(a / d) + Number(a % d) / Number(d);- } catch {- return 0;- }-};-const shortAddr = (a) => {- const s = String(a || '');- return s.length > 9 ? `${s.slice(0, 4)}…${s.slice(-4)}` : s;-};--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();-}--// Animate a number element from 0 (or its current value) to `target`, easing the-// rollup. Respects reduced-motion (sets the final value immediately). `format`-// renders the running value. Cancels cleanly if re-invoked on the same element.-function rollup(el, target, format = fmtCompact, ms = 900) {- if (!el) return;- const to = Number(target) || 0;- if (REDUCED_MOTION || ms <= 0) {- el.textContent = format(to);- return;- }- if (el._rollupRAF) cancelAnimationFrame(el._rollupRAF);- const from = Number(el._rollupValue) || 0;- let start = null;- const ease = (t) => 1 - Math.pow(1 - t, 3); // easeOutCubic- const step = (ts) => {- if (start === null) start = ts;- const p = Math.min(1, (ts - start) / ms);- const v = from + (to - from) * ease(p);- el.textContent = format(v);- if (p < 1) el._rollupRAF = requestAnimationFrame(step);- else {- el._rollupValue = to;- el.textContent = format(to);- }- };- el._rollupRAF = requestAnimationFrame(step);-}--// Reveal-on-scroll: fade/slide sections in as they enter the viewport. No-op under-// reduced motion (everything is simply visible).-function observeReveal(root) {- if (REDUCED_MOTION || typeof IntersectionObserver !== 'function') {- root.querySelectorAll('.ec-reveal').forEach((el) => el.classList.add('in'));- return;- }- const io = new IntersectionObserver(- (entries) => {- for (const e of entries) {- if (e.isIntersecting) {- e.target.classList.add('in');- io.unobserve(e.target);- }- }- },- { rootMargin: '0px 0px -10% 0px', threshold: 0.08 },- );- root.querySelectorAll('.ec-reveal').forEach((el) => io.observe(el));-}--// ── styles ──────────────────────────────────────────────────────────────────-function injectStyles() {- const css = `- :root {- --bg:#08080b; --panel:#0e0e13; --panel-2:#0b0b0f; --line:#1a1a22; --line-2:#23232c;- --ink:#f6f6f8; --muted:#9a9aa4; --muted-2:#80808b;- --gold:#f5c451; --green:#6ee7a8; --blue:#7cc4ff; --violet:#c4a8ff;- --ease:cubic-bezier(.22,1,.36,1);- color-scheme: dark;- }- * { box-sizing:border-box; }- body { margin:0; background:var(--bg); color:var(--ink);- font-family:Inter,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;- -webkit-font-smoothing:antialiased; text-rendering:optimizeLegibility; }- body::before { /* ambient top glow */- content:''; position:fixed; inset:0; pointer-events:none; z-index:0;- background:radial-gradient(900px 500px at 50% -8%, rgba(110,231,168,.10), transparent 60%),- radial-gradient(700px 500px at 85% 0%, rgba(124,196,255,.06), transparent 55%); }- a { color:inherit; text-decoration:none; }- code { font-family:ui-monospace,Menlo,monospace; }- ::selection { background:rgba(110,231,168,.25); }- :focus-visible { outline:2px solid var(--green); outline-offset:3px; border-radius:6px; }-- .ec-wrap { position:relative; z-index:1; max-width:1120px; margin:0 auto; padding:24px 20px 100px; }- .ec-top { display:flex; align-items:center; justify-content:space-between; gap:12px; }- .ec-pill { display:inline-flex; align-items:center; gap:7px; font-size:12.5px; color:var(--muted);- border:1px solid var(--line); border-radius:999px; padding:7px 13px; transition:.18s var(--ease); }- .ec-pill:hover { color:var(--ink); border-color:var(--line-2); transform:translateY(-1px); }- .ec-pill .dot { width:7px; height:7px; border-radius:50%; background:var(--green);- box-shadow:0 0 10px var(--green); animation:ec-pulse 2.4s infinite; }- @keyframes ec-pulse { 0%,100%{opacity:1} 50%{opacity:.35} }-- /* Hero */- .ec-hero { padding:56px 0 8px; text-align:center; }- .ec-badge { display:inline-flex; gap:8px; align-items:center; font-size:11.5px; letter-spacing:.1em;- text-transform:uppercase; color:var(--green); border:1px solid rgba(110,231,168,.25);- background:rgba(110,231,168,.06); border-radius:999px; padding:6px 14px; margin-bottom:20px; }- .ec-h1 { font-size:clamp(34px,6.2vw,60px); line-height:1.02; font-weight:840; letter-spacing:-.035em;- margin:0 0 16px; background:linear-gradient(180deg,#fff 30%,#a9a9b4); -webkit-background-clip:text;- background-clip:text; -webkit-text-fill-color:transparent; }- .ec-lede { color:var(--muted); font-size:clamp(15px,2vw,18px); line-height:1.55; max-width:620px; margin:0 auto; }- .ec-hero-stat { margin:30px auto 4px; display:inline-flex; flex-direction:column; gap:4px;- border:1px solid rgba(110,231,168,.22); background:rgba(110,231,168,.05); border-radius:18px; padding:18px 30px; }- .ec-hero-stat .hs-num { font-size:clamp(30px,5vw,46px); font-weight:850; letter-spacing:-.03em; color:var(--green);- font-variant-numeric:tabular-nums; line-height:1; }- .ec-hero-stat .hs-num .hs-sym { font-size:16px; font-weight:600; color:var(--muted); }- .ec-hero-stat .hs-lbl { font-size:12.5px; color:var(--muted); }- .ec-cta { margin-top:26px; display:flex; gap:11px; justify-content:center; flex-wrap:wrap; }- .ec-btn { font-size:14px; font-weight:600; padding:11px 20px; border-radius:11px; border:1px solid var(--line-2);- background:var(--panel); transition:.16s var(--ease); cursor:pointer; color:var(--ink); }- .ec-btn:hover { transform:translateY(-1px); border-color:#34343f; }- .ec-btn.primary { background:var(--ink); color:#06060a; border-color:var(--ink); font-weight:700; }- .ec-btn.primary:hover { background:#fff; }-- /* Sections */- .ec-section { margin-top:64px; }- .ec-reveal { opacity:0; transform:translateY(16px); transition:opacity .6s var(--ease), transform .6s var(--ease); }- .ec-reveal.in { opacity:1; transform:none; }- .ec-htitle { font-size:13px; text-transform:uppercase; letter-spacing:.12em; color:var(--green); margin:0 0 8px; font-weight:700; }- .ec-h2 { font-size:clamp(22px,3vw,30px); font-weight:780; letter-spacing:-.025em; margin:0 0 8px; }- .ec-desc { color:var(--muted); font-size:14.5px; line-height:1.55; max-width:660px; margin:0 0 22px; }-- /* The Flow */- .ec-flow-shell { position:relative; border:1px solid var(--line); border-radius:20px; overflow:hidden;- background:linear-gradient(180deg,#0c0c11,#090a0d); }- .ec-flow-canvas { display:block; width:100%; height:340px; }- .ec-flow-legend { display:flex; flex-wrap:wrap; gap:14px 22px; padding:14px 18px; border-top:1px solid var(--line);- font-size:12.5px; color:var(--muted); background:rgba(0,0,0,.2); }- .ec-leg { display:inline-flex; align-items:center; gap:7px; }- .ec-leg .sw { width:9px; height:9px; border-radius:50%; }- .ec-flow-note { position:absolute; bottom:62px; left:18px; right:18px; font-size:12px; color:var(--muted-2);- pointer-events:none; }- .ec-flow-pause { position:absolute; top:14px; right:14px; z-index:2; display:inline-flex; align-items:center; gap:6px;- font-size:12px; color:var(--muted); background:rgba(0,0,0,.45); border:1px solid var(--line-2);- border-radius:999px; padding:6px 12px; cursor:pointer; transition:.15s var(--ease); backdrop-filter:blur(6px); }- .ec-flow-pause:hover { color:var(--ink); border-color:#3a3a44; }-- /* Stat band */- .ec-stats { display:grid; gap:13px; grid-template-columns:repeat(auto-fit,minmax(180px,1fr)); }- .ec-stat { border:1px solid var(--line); border-radius:16px; padding:20px;- background:linear-gradient(180deg,var(--panel),var(--panel-2)); position:relative; overflow:hidden; }- .ec-stat::after { content:''; position:absolute; left:0; top:0; height:2px; width:100%;- background:linear-gradient(90deg,transparent,var(--accent,var(--green)),transparent); opacity:.5; }- .ec-stat .v { font-size:28px; font-weight:820; letter-spacing:-.02em; font-variant-numeric:tabular-nums; }- .ec-stat .v .sym { font-size:14px; font-weight:600; color:var(--muted); margin-left:5px; }- .ec-stat .k { color:var(--muted); font-size:12.5px; margin-top:5px; }- .ec-stamp { margin-top:14px; font-size:12px; color:var(--muted-2); display:flex; align-items:center; gap:7px; }- .ec-stamp::before { content:''; width:6px; height:6px; border-radius:50%; background:var(--green); box-shadow:0 0 8px var(--green); }-- /* Verify wallets */- .ec-wallets { display:grid; gap:13px; grid-template-columns:repeat(auto-fit,minmax(260px,1fr)); }- .ec-wallet { display:block; border:1px solid var(--line); border-radius:16px; padding:20px;- background:linear-gradient(180deg,var(--panel),var(--panel-2)); transition:.16s var(--ease); }- a.ec-wallet:hover { transform:translateY(-2px); border-color:var(--accent); box-shadow:0 8px 30px -12px var(--accent-glow); }- .ec-wallet .wlabel { font-size:12.5px; color:var(--muted); display:flex; align-items:center; gap:8px; }- .ec-wallet .wlabel .sw { width:9px; height:9px; border-radius:50%; background:var(--accent); }- .ec-wallet .wbal { font-size:26px; font-weight:820; letter-spacing:-.02em; margin:8px 0 7px; font-variant-numeric:tabular-nums; }- .ec-wallet .wbal .sym { font-size:13px; color:var(--muted); margin-left:5px; font-weight:600; }- .ec-wallet .waddr { font-family:ui-monospace,Menlo,monospace; font-size:11.5px; color:var(--accent); }-- /* Rewards (value returned) + projector */- .ec-reflect { display:grid; gap:16px; grid-template-columns:1.1fr .9fr; align-items:start; }- @media (max-width:760px){ .ec-reflect{ grid-template-columns:1fr; } }- .ec-card { border:1px solid var(--line); border-radius:16px; padding:22px;- background:linear-gradient(180deg,var(--panel),var(--panel-2)); }- .ec-reflect-big { font-size:38px; font-weight:850; letter-spacing:-.025em; color:var(--green);- font-variant-numeric:tabular-nums; }- .ec-reflect-sub { color:var(--muted); font-size:13.5px; margin-top:4px; }- .ec-reflect-table { width:100%; border-collapse:collapse; margin-top:16px; font-size:13px; }- .ec-reflect-table th { text-align:left; font-weight:600; color:var(--muted-2); font-size:11px;- text-transform:uppercase; letter-spacing:.06em; padding:0 0 8px; border-bottom:1px solid var(--line); }- .ec-reflect-table th:last-child { text-align:right; }- .ec-reflect-table td { padding:10px 0; border-bottom:1px solid var(--line); font-variant-numeric:tabular-nums; }- .ec-reflect-table tr:last-child td { border-bottom:none; }- .ec-txlink { color:var(--green); font-weight:600; font-size:12px; }- .ec-txlink:hover { text-decoration:underline; }- .ec-tag { font-size:10.5px; font-weight:700; text-transform:uppercase; letter-spacing:.05em; padding:2px 8px;- border-radius:999px; }- .ec-tag.paid { background:rgba(110,231,168,.12); color:var(--green); }- .ec-tag.planned { background:rgba(139,139,150,.12); color:var(--muted); }- .ec-proj label { font-size:12.5px; color:var(--muted); display:block; margin-bottom:8px; }- .ec-proj input[type=range] { width:100%; accent-color:var(--green); }- .ec-proj-out { margin-top:14px; font-size:14px; line-height:1.6; }- .ec-proj-out b { color:var(--green); font-variant-numeric:tabular-nums; }-- /* Tiers */- .ec-tiers { display:grid; gap:13px; grid-template-columns:repeat(auto-fit,minmax(190px,1fr)); }- .ec-tier { border:1px solid var(--line); border-radius:16px; padding:20px; background:var(--panel);- position:relative; transition:.16s var(--ease); }- .ec-tier:hover { transform:translateY(-3px); border-color:var(--line-2); }- .ec-tier.cur { border-color:var(--green); box-shadow:0 0 0 1px rgba(110,231,168,.3), 0 12px 40px -16px rgba(110,231,168,.4); }- .ec-tier .you { position:absolute; top:-10px; right:14px; font-size:10px; font-weight:800; letter-spacing:.07em;- text-transform:uppercase; color:#06060a; background:var(--green); border-radius:999px; padding:3px 10px; }- .ec-tier .tn { font-size:17px; font-weight:780; }- .ec-tier .tm { color:var(--muted); font-size:12.5px; margin:3px 0 14px; }- .ec-tier ul { list-style:none; margin:0; padding:0; }- .ec-tier li { font-size:12.5px; color:#c9c9d2; padding:5px 0 5px 19px; position:relative;- display:flex; align-items:flex-start; gap:8px; }- .ec-tier li::before { content:''; position:absolute; left:3px; top:11px; width:6px; height:6px; border-radius:50%;- background:var(--green); }- .ec-tier li .pk-label { flex:1; min-width:0; line-height:1.4; }- .ec-tier li.is-planned { color:var(--muted); }- .ec-tier li.is-planned::before { background:var(--muted-2); }- .ec-tier li.pk-free { padding-left:0; }- .ec-tier li.pk-free::before { display:none; }- .pk-tag { flex-shrink:0; margin-top:1px; font-size:9px; font-weight:800; text-transform:uppercase; letter-spacing:.05em;- padding:2px 7px; border-radius:999px; line-height:1.55; }- .pk-tag.pk-live { color:var(--green); background:rgba(110,231,168,.13); }- .pk-tag.pk-planned { color:var(--muted); background:rgba(139,139,150,.14); }- .ec-progress { margin:20px 0 0; }- .ec-progress .bar { height:8px; border-radius:999px; background:var(--line); overflow:hidden; }- .ec-progress .fill { height:100%; border-radius:999px; background:linear-gradient(90deg,var(--green),#a8f0c8);- width:0; transition:width 1s var(--ease); }- .ec-progress .lbl { display:flex; justify-content:space-between; font-size:12.5px; color:var(--muted); margin-top:9px; }- .ec-tier-connect { margin-top:18px; }- .ec-tier-connect .ec-muted { margin:10px 0 0; font-size:12.5px; line-height:1.55; max-width:520px; }-- /* Your access (personal feature matrix) */- .ta-panel { border:1px solid var(--line); border-radius:16px; overflow:hidden;- background:linear-gradient(180deg,var(--panel),var(--panel-2)); }- .ta-head { display:flex; align-items:center; gap:12px; flex-wrap:wrap; padding:18px 20px; border-bottom:1px solid var(--line); }- .ta-tier { display:inline-flex; align-items:center; gap:7px; font-size:14px; font-weight:740; color:var(--muted);- border:1px solid var(--line-2); background:var(--panel); border-radius:999px; padding:7px 13px; }- .ta-tier.t-member { color:#a7a7b2; }- .ta-tier.t-bronze { color:#d8a06a; border-color:rgba(216,160,106,.34); background:rgba(216,160,106,.08); }- .ta-tier.t-silver { color:#cfd6e4; border-color:rgba(207,214,228,.3); background:rgba(207,214,228,.06); }- .ta-tier.t-gold { color:var(--gold); border-color:rgba(245,196,81,.34); background:rgba(245,196,81,.08); }- .ta-tier.t-genesis { color:var(--violet); border-color:rgba(196,168,255,.34); background:rgba(196,168,255,.08); }- .ta-held { font-size:13px; color:var(--muted); font-variant-numeric:tabular-nums; }- .ta-count { margin-left:auto; font-size:12px; color:var(--muted-2); font-variant-numeric:tabular-nums; }- .ta-note { margin:0; padding:11px 20px; font-size:12.5px; color:#f0d488; background:rgba(245,196,81,.06);- border-bottom:1px solid var(--line); }- .ta-rows { list-style:none; margin:0; padding:0; }- .ta-row { display:flex; align-items:center; justify-content:space-between; gap:16px; padding:15px 20px;- border-top:1px solid var(--line); }- .ta-row:first-child { border-top:none; }- .ta-row-info { min-width:0; }- .ta-row-label { display:block; font-size:14px; }- .ta-why { display:block; font-size:12px; color:var(--muted-2); margin-top:3px; line-height:1.45; }- .ta-row-status { display:flex; align-items:center; gap:10px; flex-shrink:0; }- .ta-ppu { font-size:12px; color:var(--muted-2); white-space:nowrap; font-variant-numeric:tabular-nums; }- .ta-pill { display:inline-flex; align-items:center; gap:6px; font-size:12px; font-weight:700; border-radius:999px;- padding:5px 11px; white-space:nowrap; }- .ta-pill--ok { color:var(--green); background:rgba(110,231,168,.1); border:1px solid rgba(110,231,168,.26); }- .ta-pill--lock { color:#f0d488; background:rgba(245,196,81,.09); border:1px solid rgba(245,196,81,.22); }- .ta-pill--soon { color:var(--muted); background:rgba(139,139,150,.12); border:1px solid rgba(139,139,150,.24); }- .ta-row--planned .ta-row-label { color:var(--muted); }- .ta-empty { border:1px dashed var(--line-2); border-radius:16px; padding:34px 24px; text-align:center;- background:linear-gradient(180deg,var(--panel),var(--panel-2)); }- .ta-empty-mark { font-size:30px; color:var(--green); filter:drop-shadow(0 0 12px rgba(110,231,168,.4)); margin-bottom:8px; }- .ta-empty-title { font-size:18px; font-weight:760; margin:0 0 6px; }- .ta-empty-sub { font-size:13.5px; color:var(--muted); margin:0 auto 18px; max-width:420px; line-height:1.55; }- .ta-empty-cta { display:flex; gap:11px; justify-content:center; flex-wrap:wrap; }- .ta-msg { font-size:12.5px; color:#ff9b9b; margin:12px 0 0; }- @media (max-width:560px){- .ta-row{ flex-direction:column; align-items:flex-start; gap:9px; }- .ta-count{ margin-left:0; }- }-- /* Pricing explorer */- .ec-px { display:grid; gap:16px; grid-template-columns:1fr 1fr; }- @media (max-width:760px){ .ec-px{ grid-template-columns:1fr; } }- .ec-px-list { border:1px solid var(--line); border-radius:16px; overflow:hidden; max-height:420px; overflow-y:auto; }- .ec-px-cat { font-size:11px; text-transform:uppercase; letter-spacing:.09em; color:var(--muted-2);- padding:12px 16px 6px; }- .ec-px-item { display:flex; align-items:center; justify-content:space-between; gap:12px; width:100%;- padding:12px 16px; background:none; border:none; border-top:1px solid var(--line); color:var(--ink);- font:inherit; text-align:left; cursor:pointer; transition:background .14s var(--ease); }- .ec-px-item:hover, .ec-px-item.sel { background:rgba(110,231,168,.06); }- .ec-px-item .pl { font-size:13.5px; }- .ec-px-item .pp { font-size:13px; font-weight:700; white-space:nowrap; font-variant-numeric:tabular-nums; }- .ec-px-item .pp.free { color:var(--green); }- .ec-px-item .pp.var { color:var(--muted); font-weight:500; }- .ec-px-detail { border:1px solid var(--line); border-radius:16px; padding:22px;- background:linear-gradient(180deg,var(--panel),var(--panel-2)); align-self:start; position:sticky; top:18px; }- .ec-px-detail .dt { font-size:16px; font-weight:740; }- .ec-px-row { display:flex; justify-content:space-between; padding:11px 0; border-bottom:1px solid var(--line); font-size:14px; }- .ec-px-row:last-child { border-bottom:none; }- .ec-px-row .val { font-weight:700; font-variant-numeric:tabular-nums; }- .ec-px-row .val.save { color:var(--green); }- .ec-px-three { font-size:13px; color:var(--muted); }-- /* Name studio */- .ec-name { display:flex; gap:10px; max-width:520px; }- .ec-name input { flex:1; background:var(--panel); border:1px solid var(--line-2); border-radius:12px;- padding:14px 16px; color:var(--ink); font-size:16px; font-family:ui-monospace,Menlo,monospace; transition:.16s var(--ease); }- .ec-name input:focus { outline:none; border-color:var(--green); box-shadow:0 0 0 3px rgba(110,231,168,.12); }- .ec-name .suffix { align-self:center; color:var(--muted-2); font-family:ui-monospace,Menlo,monospace; font-size:13px; }- .ec-name-out { margin-top:18px; min-height:90px; }- .ec-rare-meter { height:8px; border-radius:999px; background:var(--line); overflow:hidden; margin:14px 0 12px; max-width:520px; }- .ec-rare-fill { height:100%; border-radius:999px; transition:width .5s var(--ease), background .3s; }- .ec-rare-head { display:flex; align-items:center; gap:12px; flex-wrap:wrap; }- .ec-rarity { font-size:11px; font-weight:800; text-transform:uppercase; letter-spacing:.06em; border-radius:999px; padding:4px 11px; }- .r-legendary{background:rgba(196,168,255,.14);color:#d6b8ff} .r-epic{background:rgba(124,196,255,.14);color:#9ed0ff}- .r-rare{background:rgba(110,231,168,.14);color:#8af0c0} .r-uncommon{background:rgba(245,196,81,.14);color:#f0d488}- .r-common{background:rgba(139,139,150,.12);color:#a7a7b2}-- /* Catalog grid (compact, full list) */- .ec-cat { margin-bottom:24px; }- .ec-cat h3 { font-size:12px; text-transform:uppercase; letter-spacing:.09em; color:var(--muted); margin:0 0 11px; }- .ec-items { display:grid; gap:9px; 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 var(--line);- border-radius:12px; padding:13px 15px; background:var(--panel); }- .ec-item .label { font-size:13.5px; }- .ec-item .price { font-size:13.5px; font-weight:700; white-space:nowrap; font-variant-numeric:tabular-nums; }- .ec-item .price.free { color:var(--green); } .ec-item .price.var { color:var(--muted); font-weight:500; }-- /* States */- .ec-skel { background:linear-gradient(90deg,#101015,#191920,#101015); background-size:200% 100%;- animation:ec-sh 1.3s infinite; border-radius:14px; }- @keyframes ec-sh { 0%{background-position:200% 0} 100%{background-position:-200% 0} }- .ec-err { border:1px solid #3a1f1f; background:#160d0d; color:#ff9b9b; border-radius:14px; padding:16px; font-size:13.5px; }- .ec-muted { color:var(--muted); }- .ec-foot { margin-top:64px; padding-top:24px; border-top:1px solid var(--line); color:var(--muted-2);- font-size:12.5px; text-align:center; line-height:1.7; }- .ec-foot code { color:var(--muted); }-- @media (prefers-reduced-motion: reduce){- .ec-skel{animation:none} .ec-pill .dot{animation:none}- .ec-btn:hover,.ec-tier:hover,a.ec-wallet:hover,.ec-pill:hover{transform:none}- }- `;- const el = document.createElement('style');- el.textContent = css;- document.head.appendChild(el);-}--// ── The Flow: live canvas economy visualization ───────────────────────────────-//-// Value enters from the left (a particle per "spend", colored by category), hits-// the protocol splitter, and forks into three beneficiary lanes — treasury (gold),-// holder rewards (green), creators (blue). Reward particles rain onto a row of-// holder dots that pulse on contact. NOTHING is destroyed: there is no burn sink,-// and the note under the canvas says so. Emission rate + lane weights are seeded-// from real /api/three/stats so the picture reflects the actual economy. Pauses-// when offscreen; under reduced-motion it renders a clean static diagram instead.-class FlowViz {- constructor(canvas) {- this.canvas = canvas;- this.ctx = canvas.getContext('2d');- this.particles = [];- this.holders = [];- this.running = false;- this.userPaused = false; // WCAG 2.2.2 — explicit user pause overrides auto start/stop- this.lastEmit = 0;- this.emitInterval = 520; // ms between spends (tuned by activity)- this.weights = { treasury: 0.5, rewards: 0.4, seller: 0.1 };- this.categoryColors = ['#6ee7a8', '#7cc4ff', '#c4a8ff', '#f5c451'];- this._resize = this._resize.bind(this);- this._frame = this._frame.bind(this);- }-- seed(stats) {- const r = stats?.by_role || {};- const t = Number(r.treasury || 0);- const rw = Number(r.rewards || 0);- const s = Number(r.seller || 0);- const sum = t + rw + s;- if (sum > 0) this.weights = { treasury: t / sum, rewards: rw / sum, seller: s / sum };- // Busier economies emit faster (bounded). payment_count drives tempo.- const pc = Number(stats?.payment_count || 0);- this.emitInterval = pc > 0 ? Math.max(220, 620 - Math.min(380, pc * 6)) : 760;- }-- start() {- if (this.running || REDUCED_MOTION || this.userPaused) {- if (REDUCED_MOTION) this._renderStatic();- return;- }- this.running = true;- this._resize();- addEventListener('resize', this._resize, { passive: true });- this._initHolders();- this._raf = requestAnimationFrame(this._frame);- }-- stop() {- this.running = false;- if (this._raf) cancelAnimationFrame(this._raf);- removeEventListener('resize', this._resize);- }-- _resize() {- const dpr = Math.min(2, window.devicePixelRatio || 1);- const rect = this.canvas.getBoundingClientRect();- this.w = rect.width;- this.h = rect.height || 340;- this.canvas.width = Math.round(this.w * dpr);- this.canvas.height = Math.round(this.h * dpr);- this.ctx.setTransform(dpr, 0, 0, dpr, 0, 0);- this.splitX = this.w * 0.42;- this.midY = this.h * 0.5;- this.lanes = {- treasury: this.h * 0.22,- rewards: this.h * 0.5,- seller: this.h * 0.78,- };- this._initHolders();- }-- _initHolders() {- const n = Math.min(26, Math.max(10, Math.floor((this.w || 600) / 34)));- const x0 = this.w * 0.74;- const x1 = this.w - 26;- this.holders = Array.from({ length: n }, (_, i) => ({- x: x0 + ((x1 - x0) * (i % Math.ceil(n / 2))) / Math.max(1, Math.ceil(n / 2) - 1),- y: this.lanes.rewards + 34 + Math.floor(i / Math.ceil(n / 2)) * 22,- pulse: 0,- }));- }-- _emit(now) {- // Pick a beneficiary lane by the real split weights.- const r = Math.random();- let role = 'treasury';- if (r < this.weights.rewards) role = 'rewards';- else if (r < this.weights.rewards + this.weights.seller) role = 'seller';- this.particles.push({- x: -8,- y: this.midY + (Math.random() - 0.5) * 30,- role,- phase: 'in', // in → split → out- t: 0,- cat: this.categoryColors[(Math.random() * this.categoryColors.length) | 0],- speed: 0.6 + Math.random() * 0.5,- targetHolder: role === 'rewards' ? (Math.random() * this.holders.length) | 0 : -1,- });- this.lastEmit = now;- }-- _frame(now) {- if (!this.running) return;- const ctx = this.ctx;- ctx.clearRect(0, 0, this.w, this.h);-- // Static scaffold: source, splitter, lanes.- this._drawScaffold(ctx);-- if (now - this.lastEmit > this.emitInterval) this._emit(now);-- const treasuryC = ROLE.treasury.color,- rewardsC = ROLE.rewards.color,- sellerC = ROLE.seller.color;- for (let i = this.particles.length - 1; i >= 0; i--) {- const p = this.particles[i];- p.t += 0.016 * p.speed;- let alive = true;- if (p.phase === 'in') {- p.x += (this.splitX - p.x) * 0.06 * p.speed;- p.y += (this.midY - p.y) * 0.06;- if (p.x >= this.splitX - 3) {- p.phase = 'out';- p.y = this.midY;- }- } else {- const laneY = this.lanes[p.role];- const endX = p.role === 'rewards' && p.targetHolder >= 0 && this.holders[p.targetHolder]- ? this.holders[p.targetHolder].x- : this.w + 10;- const endY = p.role === 'rewards' && p.targetHolder >= 0 && this.holders[p.targetHolder]- ? this.holders[p.targetHolder].y- : laneY;- p.x += (endX - p.x) * 0.05 * p.speed;- p.y += (endY - p.y) * 0.08;- if (Math.abs(p.x - endX) < 4) {- if (p.role === 'rewards' && this.holders[p.targetHolder]) this.holders[p.targetHolder].pulse = 1;- alive = false;- }- }- const color = p.phase === 'in' ? p.cat : p.role === 'treasury' ? treasuryC : p.role === 'rewards' ? rewardsC : sellerC;- ctx.beginPath();- ctx.arc(p.x, p.y, 2.6, 0, Math.PI * 2);- ctx.fillStyle = color;- ctx.shadowColor = color;- ctx.shadowBlur = 8;- ctx.fill();- ctx.shadowBlur = 0;- if (!alive) this.particles.splice(i, 1);- }-- // Holder dots (rewards recipients) — pulse green on contact.- for (const hh of this.holders) {- hh.pulse *= 0.92;- const rad = 3 + hh.pulse * 4;- ctx.beginPath();- ctx.arc(hh.x, hh.y, rad, 0, Math.PI * 2);- ctx.fillStyle = `rgba(110,231,168,${0.35 + hh.pulse * 0.65})`;- if (hh.pulse > 0.05) {- ctx.shadowColor = ROLE.rewards.color;- ctx.shadowBlur = 10 * hh.pulse;- }- ctx.fill();- ctx.shadowBlur = 0;- }-- // Cap particle count defensively.- if (this.particles.length > 240) this.particles.splice(0, this.particles.length - 240);- this._raf = requestAnimationFrame(this._frame);- }-- _drawScaffold(ctx) {- // Source node (left).- ctx.fillStyle = 'rgba(255,255,255,.04)';- ctx.strokeStyle = 'rgba(255,255,255,.10)';- this._roundRect(ctx, 6, this.midY - 26, 64, 52, 10);- ctx.fill();- ctx.stroke();- ctx.fillStyle = '#8b8b96';- ctx.font = '600 10px Inter, sans-serif';- ctx.textAlign = 'center';- ctx.fillText('SPENDS', 38, this.midY + 3);-- // Splitter node (center).- ctx.beginPath();- ctx.arc(this.splitX, this.midY, 16, 0, Math.PI * 2);- ctx.fillStyle = 'rgba(110,231,168,.10)';- ctx.strokeStyle = 'rgba(110,231,168,.5)';- ctx.lineWidth = 1.5;- ctx.fill();- ctx.stroke();- ctx.fillStyle = '#cfeede';- ctx.font = '700 9px Inter, sans-serif';- ctx.fillText('$THREE', this.splitX, this.midY + 3);-- // Lane labels (right).- ctx.textAlign = 'left';- ctx.font = '600 11px Inter, sans-serif';- const labels = [- ['treasury', ROLE.treasury.color, 'Treasury'],- ['rewards', ROLE.rewards.color, 'Holders'],- ['seller', ROLE.seller.color, 'Creators'],- ];- for (const [k, c, txt] of labels) {- ctx.fillStyle = c;- ctx.globalAlpha = 0.8;- ctx.fillText(txt, this.w * 0.6, this.lanes[k] - 8);- ctx.globalAlpha = 1;- }- }-- _roundRect(ctx, x, y, w, h, r) {- ctx.beginPath();- ctx.moveTo(x + r, y);- ctx.arcTo(x + w, y, x + w, y + h, r);- ctx.arcTo(x + w, y + h, x, y + h, r);- ctx.arcTo(x, y + h, x, y, r);- ctx.arcTo(x, y, x + w, y, r);- ctx.closePath();- }-- // Reduced-motion: a calm, labeled static diagram (no animation).- _renderStatic() {- this._resize();- const ctx = this.ctx;- ctx.clearRect(0, 0, this.w, this.h);- this._drawScaffold(ctx);- ctx.strokeStyle = 'rgba(255,255,255,.12)';- ctx.lineWidth = 1.5;- for (const k of ['treasury', 'rewards', 'seller']) {- ctx.beginPath();- ctx.moveTo(this.splitX + 14, this.midY);- ctx.lineTo(this.w * 0.6, this.lanes[k]);- ctx.stroke();- }- }-}--// ── section renderers ─────────────────────────────────────────────────────────--function statCards(stats) {- const dec = stats?.token?.decimals ?? 6;- const reflected = atomicsToTokens(stats?.reflected?.total_atomics ?? '0', dec);- const treasuryLive = atomicsToTokens(stats?.onchain?.treasury?.balance_atomics ?? '0', dec);- const gross = atomicsToTokens(stats?.gross_atomics ?? '0', dec);- const toCreators = atomicsToTokens(stats?.by_role?.seller ?? '0', dec);- return [- { key: 'gross', v: gross, accent: 'var(--green)', k: 'settled volume', sym: true },- { key: 'reflected', v: reflected, accent: 'var(--green)', k: 'reflected to holders', sym: true },- { key: 'treasury', v: treasuryLive, accent: 'var(--gold)', k: 'in treasury (live)', sym: true },- { key: 'creators', v: toCreators, accent: 'var(--blue)', k: 'earned by creators', sym: true },- { key: 'count', v: Number(stats?.payment_count || 0), accent: 'var(--violet)', k: 'settled payments', sym: false },- ];-}--function onchainHTML(stats) {- const dec = stats?.token?.decimals ?? 6;- const oc = stats?.onchain || {};- const wallet = (w, role) => {- const r = ROLE[role === 'rewards' ? 'rewards' : 'treasury'];- if (!w?.address) {- return `<div class="ec-wallet" style="--accent:${r.color};--accent-glow:${r.glow}"><div class="wlabel"><span class="sw"></span>${esc(r.label)}</div><div class="wbal ec-muted" style="font-size:15px">not yet configured</div></div>`;- }- const bal = fmtCompact(atomicsToTokens(w.balance_atomics ?? '0', dec));- const sub = role === 'rewards' ? 'distributed pro-rata to holders' : 'funds buybacks — never burned';- return `<a class="ec-wallet" style="--accent:${r.color};--accent-glow:${r.glow}" href="${esc(w.explorer)}" target="_blank" rel="noopener">- <div class="wlabel"><span class="sw"></span>${esc(r.label)} · ${esc(sub)}</div>- <div class="wbal">${esc(bal)}<span class="sym">$THREE</span></div>- <div class="waddr">${esc(shortAddr(w.address))} · verify on Solscan ↗</div>- </a>`;- };- return `<div class="ec-wallets">${wallet(oc.treasury, 'treasury')}${wallet(oc.rewards_pool, 'rewards')}</div>`;-}--function reflectedHTML(stats) {- const dec = stats?.token?.decimals ?? 6;- const r = stats?.reflected || { total_atomics: '0', run_count: 0, recent: [] };- const total = fmtCompact(atomicsToTokens(r.total_atomics ?? '0', dec));- let history;- if (!r.recent?.length) {- history = `<p class="ec-muted" style="margin-top:14px;font-size:13px">Distributions begin once the rewards pool funds. Every run will appear here as a row with an on-chain transaction you can open — value returned to holders, never destroyed.</p>`;- } else {- // A real <table> for accessibility + copy/paste; completed runs link to the tx.- const rows = r.recent- .map((d) => {- const amt = fmtCompact(atomicsToTokens(d.distributed_atomics ?? '0', dec));- const when = d.created_at ? new Date(d.created_at).toLocaleDateString('en-US', { month: 'short', day: 'numeric' }) : '';- const paid = d.status === 'completed';- const tx = Array.isArray(d.tx_signatures) && d.tx_signatures[0] ? d.tx_signatures[0] : null;- const verify = tx- ? `<a href="https://solscan.io/tx/${esc(tx)}" target="_blank" rel="noopener" class="ec-txlink">verify ↗</a>`- : `<span class="ec-tag ${paid ? 'paid' : 'planned'}">${paid ? 'paid' : 'planned'}</span>`;- return `<tr><td class="ec-muted">${esc(when)}</td><td>${esc(amt)} $THREE</td><td class="ec-muted">${d.holder_count} holders</td><td style="text-align:right">${verify}</td></tr>`;- })- .join('');- history = `<table class="ec-reflect-table"><thead><tr><th>Date</th><th>Returned</th><th>To</th><th></th></tr></thead><tbody>${rows}</tbody></table>`;- }- return `- <div class="ec-card">- <div class="ec-reflect-big" id="ec-reflect-total">${esc(total)} <span style="font-size:18px;color:var(--muted)">$THREE</span></div>- <div class="ec-reflect-sub">returned to holders across ${r.run_count} distribution${r.run_count === 1 ? '' : 's'} — funded by usage fees, never minted, never burned</div>- ${history}- </div>- <div class="ec-card ec-proj">- <label for="ec-proj-range">If you held this much $THREE…</label>- <input id="ec-proj-range" type="range" min="0" max="6" step="0.1" value="3" aria-label="Amount of $THREE held" />- <div class="ec-proj-out" id="ec-proj-out"></div>- </div>`;-}--// One perk line for a tier card, tagged with whether the perk is enforced ("Live")-// or merely registered ("Planned") — so the ladder never claims an unwired feature-// is available today.-function perkLi(label, enforced) {- const tag = enforced- ? '<span class="pk-tag pk-live">Live</span>'- : '<span class="pk-tag pk-planned">Planned</span>';- return `<li class="${enforced ? 'is-live' : 'is-planned'}"><span class="pk-label">${esc(label)}</span>${tag}</li>`;-}--// A tier's perk list, driven from the LIVE gated-feature matrix (api/three/access)-// grouped by the level that unlocks each feature: the holder fee discount (enforced-// at charge time) leads every paying tier, then each feature it unlocks, marked Live-// or Planned. `byLevel` is null until the matrix loads — until then we show the-// tier's own static copy so the ladder is never empty.-function tierPerksHTML(t, byLevel) {- if (!byLevel) {- return (t.perks || []).slice(0, 4).map((p) => `<li><span class="pk-label">${esc(p)}</span></li>`).join('');- }- const items = [];- if (t.discount_bps > 0) {- items.push(perkLi(`${(t.discount_bps / 100).toFixed(0)}% off all $THREE compute`, true));- }- for (const f of byLevel[t.level] || []) {- items.push(perkLi(f.label, f.enforced !== false));- }- if (!items.length) {- items.push('<li class="pk-free"><span class="pk-label">Everything free-forever — create, discover, embed, social, basic worlds</span></li>');- }- return items.join('');-}--function tiersHTML(tierData, features) {- const ladder = tierData?.ladder || [];- const cur = tierData?.tier?.level ?? null;- // Group the live gated-feature matrix by the tier level that unlocks each feature,- // so every tier card lists exactly what holding to it unlocks. Null until loaded.- let byLevel = null;- if (Array.isArray(features)) {- byLevel = {};- for (const f of features) {- const lvl = Number(f?.required?.level);- if (Number.isFinite(lvl)) (byLevel[lvl] ||= []).push(f);- }- }- const cards = ladder- .map((t) => {- const is = t.level === cur;- return `<div class="ec-tier${is ? ' cur' : ''}">- ${is ? '<span class="you">You</span>' : ''}- <div class="tn">${esc(t.label)}</div>- <div class="tm">${t.min_usd > 0 ? `Hold ${fmtUsd(t.min_usd)}+` : 'Free — everyone'}</div>- <ul>${tierPerksHTML(t, byLevel)}</ul>- </div>`;- })- .join('');- let progress = '';- if (cur != null && tierData?.next) {- const next = tierData.next;- const held = Number(tierData.held_usd || 0);- const prevMin = ladder.find((t) => t.level === cur)?.min_usd || 0;- const pct = Math.max(0, Math.min(100, ((held - prevMin) / Math.max(1, next.min_usd - prevMin)) * 100));- progress = `<div class="ec-progress">- <div class="bar"><div class="fill" id="ec-tier-fill"></div></div>- <div class="lbl"><span>You hold ${fmtUsd(held)}</span><span>${fmtUsd(next.usd_to_go)} to ${esc(next.label)}</span></div>- </div>`;- setTimeout(() => {- const f = document.getElementById('ec-tier-fill');- if (f) f.style.width = `${pct}%`;- }, 80);- } else if (cur == null) {- // No resolved tier yet (no connected wallet, no session). Offer the lowest-friction- // path — connect a wallet and read the tier straight from on-chain $THREE. The- // button is wired in wireTierConnect() after every render.- progress = `<div class="ec-tier-connect">- <button class="ec-btn primary" id="ec-tier-connect" type="button">Connect wallet to see your tier</button>- <p class="ec-muted">Reads your tier straight from your on-chain $THREE — no account needed. Or sign in below to link a wallet and track progress.</p>- </div>`;- }- return `<div class="ec-tiers">${cards}</div>${progress}`;-}--// The signed-out / no-session empty state for the personal access panel — honest and-// actionable (Sign in to resolve a tier, or Get $THREE first), never a dead void.-function accessSignedOutHTML() {- return `<div class="ta-empty">- <div class="ta-empty-mark" aria-hidden="true">◆</div>- <h3 class="ta-empty-title">See what your $THREE unlocks</h3>- <p class="ta-empty-sub">We resolve your holder tier from your on-chain $THREE. Connect a wallet to see your unlocks instantly — no account needed — or sign in to link one.</p>- <div class="ta-empty-cta">- <button class="ec-btn primary" id="ec-access-connect" type="button">Connect wallet</button>- <button class="ec-btn" id="ec-access-signin" type="button">Sign in</button>- <a class="ec-btn" href="/three-token">Get $THREE</a>- </div>- </div>`;-}--// One feature row: label, a status pill, and (when relevant) a sub-line. A feature-// that isn't enforced yet reads "Planned" — never "Unlocked" — even for a holder who-// is over the bar, so the panel never promises a perk the platform can't yet deliver.-// An enforced, locked perk shows the why + a pay-per-use escape hatch when one exists.-function accessRowHTML(f) {- const enforced = f.enforced !== false;- const ok = Boolean(f.eligible);- const required = f.required?.label || 'a higher tier';- let pill;- if (!enforced) {- pill = '<span class="ta-pill ta-pill--soon">Planned</span>';- } else if (ok) {- pill = '<span class="ta-pill ta-pill--ok">Unlocked ✓</span>';- } else {- pill = `<span class="ta-pill ta-pill--lock">Hold to ${esc(required)}</span>`;- }- const ppu =- enforced && !ok && f.pay_per_use && Number(f.pay_per_use.usd) > 0- ? `<span class="ta-ppu">or ${esc(fmtUsd(f.pay_per_use.usd))} / use</span>`- : '';- const sub = !enforced- ? `<span class="ta-why">Unlocks at ${esc(required)} when it ships.</span>`- : !ok && f.why- ? `<span class="ta-why">${esc(f.why)}</span>`- : '';- const cls = !enforced ? ' ta-row--planned' : ok ? ' ta-row--ok' : '';- return `<li class="ta-row${cls}">- <div class="ta-row-info"><span class="ta-row-label">${esc(f.label)}</span>${sub}</div>- <div class="ta-row-status">${pill}${ppu}</div>- </li>`;-}--// The populated matrix: a current-tier chip + how many ENFORCED features it unlocks-// (planned perks are counted separately, never as "unlocked"), then one real list row-// per gated feature. A signed-in user with no linked wallet is read as Member and told-// (once) how to fix it, rather than silently shown an all-locked grid.-function accessMatrixHTML(data) {- const tier = data.tier || { id: 'member', label: 'Member', held_usd: 0 };- const features = Array.isArray(data.features) ? data.features : [];- const live = features.filter((f) => f.enforced !== false);- const unlocked = live.filter((f) => f.eligible).length;- const planned = features.length - live.length;- const held = Number(tier.held_usd) > 0 ? `<span class="ta-held">${esc(fmtUsd(tier.held_usd))} held</span>` : '';- const note =- data.signed_in && !data.wallet_linked- ? `<p class="ta-note">Link a Solana wallet to read your real $THREE — you're seeing the Member view.</p>`- : '';- return `<div class="ta-panel">- <div class="ta-head">- <span class="ta-tier t-${esc(tier.id)}">◆ ${esc(tier.label)}</span>- ${held}- <span class="ta-count">${unlocked} of ${live.length} unlocked${planned > 0 ? ` · ${planned} planned` : ''}</span>- </div>- ${note}- <ul class="ta-rows" role="list">${features.map(accessRowHTML).join('')}</ul>- </div>`;-}--function catalogGroups(actions) {- const byCat = {};- for (const a of actions) (byCat[a.category] ||= []).push(a);- return ['generation', 'data', 'scarcity', 'marketplace']- .filter((c) => byCat[c]?.length)- .map((cat) => ({ cat, label: CATEGORY_LABELS[cat] || cat, items: byCat[cat] }));-}--// ── page ──────────────────────────────────────────────────────────────────────-function shell() {- return `- <div class="ec-wrap">- <div class="ec-top">- <a class="ec-pill" href="/"><span class="dot"></span>three.ws</a>- <a class="ec-pill" href="/three-token">$THREE price ↗</a>- </div>- <!-- Hidden global connect button: initWalletButton() wires it; the "Connect wallet"- CTAs in the ladder + access panel trigger it. The wallet-aware data layer then- re-reads on wallet:changed and highlights the held tier. -->- <button id="connect-wallet-btn" type="button" hidden aria-hidden="true" tabindex="-1"><span data-wallet-label>Connect wallet</span></button>-- <header class="ec-hero ec-reveal">- <span class="ec-badge">◆ $THREE · the only coin · zero burns</span>- <h1 class="ec-h1">An economy you can<br/>watch and verify.</h1>- <p class="ec-lede">You pay in $THREE only for real compute. Hold it for lower fees and bigger perks. <strong style="color:var(--ink)">30% of every compute fee goes straight back to holders</strong> — funded by real usage, never minted, never burned.</p>- <div class="ec-hero-stat" id="ec-hero-stat" aria-live="polite">- <div class="hs-num"><span data-roll>0</span> <span class="hs-sym">$THREE</span></div>- <div class="hs-lbl">returned to holders & counting · 0 burned</div>- </div>- <div class="ec-cta">- <a class="ec-btn primary" href="/three-token" aria-label="Get $THREE — open the token page to buy">Get $THREE</a>- <a class="ec-btn" href="#tiers" aria-label="Jump to the holder tiers section below">See holder tiers</a>- </div>- </header>-- <section class="ec-section ec-reveal" id="flow">- <p class="ec-htitle">The Flow</p>- <h2 class="ec-h2">Where every $THREE goes</h2>- <p class="ec-desc">Live. Each particle is value entering the protocol — it splits to the treasury, to creators, and rains back onto holders. There is no burn lane: nothing is destroyed.</p>- <div class="ec-flow-shell">- <button class="ec-flow-pause" id="ec-flow-pause" type="button" aria-pressed="false" aria-label="Pause the animation">❚❚ Pause</button>- <canvas class="ec-flow-canvas" id="ec-flow" role="img" aria-label="Live visualization of $THREE flowing from spends to treasury, creators, and holders"></canvas>- <div class="ec-flow-note">Lane width reflects the real split of settled volume.</div>- <div class="ec-flow-legend">- <span class="ec-leg"><span class="sw" style="background:var(--gold)"></span>Treasury → buybacks</span>- <span class="ec-leg"><span class="sw" style="background:var(--green)"></span>Holder rewards</span>- <span class="ec-leg"><span class="sw" style="background:var(--blue)"></span>Creators</span>- <span class="ec-leg ec-muted">No burn lane — supply is never destroyed.</span>- </div>- </div>- </section>-- <section class="ec-section ec-reveal" id="stats">- <p class="ec-htitle">Live economy</p>- <h2 class="ec-h2">The numbers, settled on-chain</h2>- <div id="ec-stats" class="ec-stats">${'<div class="ec-stat ec-skel" style="height:96px"></div>'.repeat(5)}</div>- <p class="ec-stamp" id="ec-stamp" aria-live="polite">Loading live figures…</p>- </section>-- <section class="ec-section ec-reveal" id="verify">- <p class="ec-htitle">Don't trust — verify</p>- <h2 class="ec-h2">The real wallets, on Solscan</h2>- <p class="ec-desc">No anonymous "trust us." The treasury and the holder-rewards pool are real Solana accounts. Open them and check the balances against the numbers above.</p>- <div id="ec-onchain"><div class="ec-wallets">${'<div class="ec-wallet ec-skel" style="height:108px"></div>'.repeat(2)}</div></div>- </section>-- <section class="ec-section ec-reveal" id="reflected">- <p class="ec-htitle">Real yield, not burns</p>- <h2 class="ec-h2">Value returned to holders</h2>- <p class="ec-desc">Other tokens burn supply and call it a number. We route real usage fees back to holders pro-rata — never minted, never a tax on your transfers — and record every distribution on-chain. Drag the slider to see what a bag would have earned from past distributions.</p>- <div id="ec-reflected" class="ec-reflect"><div class="ec-card ec-skel" style="height:200px"></div><div class="ec-card ec-skel" style="height:200px"></div></div>- </section>-- <section class="ec-section ec-reveal" id="tiers">- <p class="ec-htitle">Hold to unlock</p>- <h2 class="ec-h2">Holder tiers</h2>- <p class="ec-desc">Holding $THREE — not spending it — lowers your fees and raises your limits. The more you hold, the more you keep.</p>- <div id="ec-tiers"><div class="ec-tiers">${'<div class="ec-tier ec-skel" style="height:170px"></div>'.repeat(5)}</div></div>- </section>-- <section class="ec-section ec-reveal" id="access">- <p class="ec-htitle">Your access</p>- <h2 class="ec-h2">What your $THREE unlocks</h2>- <p class="ec-desc">Your tier, resolved live from your on-chain $THREE — and exactly which holder features it unlocks for you right now.</p>- <div id="ec-access">${'<div class="ec-skel" style="height:62px;margin-bottom:9px;border-radius:12px"></div>'.repeat(4)}</div>- </section>-- <section class="ec-section ec-reveal" id="pricing">- <p class="ec-htitle">What you pay for</p>- <h2 class="ec-h2">Pricing explorer</h2>- <p class="ec-desc">Only real compute and genuinely scarce things cost $THREE. Pick one to see its price — and what your tier discount would make it. Everything else (creating, discovering, embedding, chatting, basic worlds, draft generation) is free forever.</p>- <div class="ec-px">- <div id="ec-px-list" class="ec-px-list">${'<div class="ec-skel" style="height:46px;margin:8px;border-radius:10px"></div>'.repeat(6)}</div>- <div id="ec-px-detail" class="ec-px-detail"><p class="ec-muted">Select an action to see its price.</p></div>- </div>- </section>-- <section class="ec-section ec-reveal" id="names">- <p class="ec-htitle">Scarcity</p>- <h2 class="ec-h2">Rare name studio</h2>- <p class="ec-desc">Common <code>*.threews.sol</code> names mint free. Short, dictionary, and reserved names are rare — priced in $THREE by how rare they are.</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 and price" />- <span class="suffix">.threews.sol</span>- </div>- <div class="ec-name-out" id="ec-name-out"><span class="ec-muted">Type a name to see its rarity and price.</span></div>- </section>-- <section class="ec-section ec-reveal" id="catalog">- <p class="ec-htitle">Full price list</p>- <h2 class="ec-h2">Everything priced in $THREE</h2>- <div id="ec-catalog">${'<div class="ec-skel" style="height:46px;margin-bottom:9px;border-radius:12px"></div>'.repeat(6)}</div>- </section>-- <div class="ec-foot">$THREE is the only coin three.ws references. Contract <code>${MINT}</code>. Prices shown in USD settle in $THREE at the live market price. No burns — ever.</div>- </div>`;-}--// ── interactivity ───────────────────────────────────────────────────────────--let LIVE_PRICE = 0; // $THREE/USD, fetched once for conversions-let DISCOUNT_BPS = 0; // current holder's tier discount-let _accessBound = false; // wallet:changed listener attached once-let _tierData = null; // last /api/three/tier payload (ladder + current tier + progress)-let _accessFeatures = null; // last gated-feature matrix from /api/three/access (Live/Planned)-let _synthTier = false; // true when _tierData was synthesized from a connected wallet (no session)--// Render the holder-tier ladder from whatever we know so far: the ladder + current-// tier from /api/three/tier, and the live gated-feature matrix from /api/three/access-// (which supplies each tier's Live/Planned perks). Either source may arrive first or-// be absent (signed-out / failed call); we fall back to the static ladder so the-// section is never empty. Called by both loaders as their data lands.-function renderTiers() {- const el = document.getElementById('ec-tiers');- if (!el) return;- const td = _tierData?.ladder?.length ? _tierData : { ladder: DEFAULT_LADDER, tier: null, next: null };- el.innerHTML = tiersHTML(td, _accessFeatures);- wireTierConnect();-}--// Wire the "Connect wallet to see your tier" button the ladder renders when no tier is-// resolved yet. It drives the global wallet connect (initWalletButton wired the hidden-// #connect-wallet-btn in init); a successful connect fires wallet:changed, which re-reads-// the wallet-aware matrix and re-highlights the held tier — no reload, no extra fetch.-function wireTierConnect() {- const btn = document.getElementById('ec-tier-connect');- if (!btn || btn.dataset.wired) return;- btn.dataset.wired = '1';- btn.addEventListener('click', () => document.getElementById('connect-wallet-btn')?.click());-}--// Highlight the connected wallet's held tier on the ladder when there's no signed-in-// session to own it. We synthesize the { tier, held_usd, next } shape loadTier would-// produce, deriving the held→next progress from the known ladder thresholds + the-// wallet's held USD — no extra fetch. Reverts to the baseline ladder on disconnect.-function applyTierFromAccess(data) {- if (!data || data.signed_in) return; // a signed-in session: loadTier stays authoritative- if (data.wallet_linked && data.tier) {- const level = Number(data.tier.level) || 0;- const held = Number(data.tier.held_usd) || 0;- const ladder = _tierData?.ladder?.length ? _tierData.ladder : DEFAULT_LADDER;- const cur = ladder.find((t) => t.level === level) || ladder[0];- const next = ladder.find((t) => t.level === level + 1) || null;- _tierData = {- ladder,- tier: { level, id: data.tier.id, label: data.tier.label, discount_bps: cur.discount_bps || 0 },- held_usd: held,- next: next ? { ...next, usd_to_go: Math.max(0, (next.min_usd || 0) - held) } : null,- };- DISCOUNT_BPS = cur.discount_bps || 0;- _synthTier = true;- repriceSelected();- } else if (_synthTier) {- // Wallet disconnected → drop the synthesized highlight, restore the baseline ladder.- _tierData = null;- DISCOUNT_BPS = 0;- _synthTier = false;- repriceSelected();- }-}--// Re-run the selected pricing-explorer row so its tier discount reflects the latest tier.-function repriceSelected() {- const sel = document.querySelector('.ec-px-item.sel');- if (sel) sel.click();-}--function discountedUsd(usd) {- if (!(usd > 0) || DISCOUNT_BPS <= 0) return usd;- return Math.max(0.01, Math.round(usd * (10000 - DISCOUNT_BPS)) / 10000);-}-const usdToThree = (usd) => (LIVE_PRICE > 0 && usd > 0 ? usd / LIVE_PRICE : null);--function renderPriceDetail(action) {- const el = document.getElementById('ec-px-detail');- if (!el) return;- if (action.usd == null) {- el.innerHTML = `<div class="dt">${esc(action.label)}</div>- <p class="ec-muted" style="margin-top:12px">Priced per item — set by the seller (marketplace) or by rarity (scarcity). 90% goes to the creator on a sale; the rest splits to treasury and holder rewards.</p>`;- return;- }- if (action.usd === 0) {- el.innerHTML = `<div class="dt">${esc(action.label)}</div><p style="margin-top:12px;color:var(--green);font-weight:600">Free forever.</p>`;- return;- }- const full = action.usd;- const yours = discountedUsd(full);- const saved = full - yours;- const three = usdToThree(yours);- el.innerHTML = `<div class="dt">${esc(action.label)}</div>- <div class="ec-px-row"><span>List price</span><span class="val">${fmtUsd(full)}</span></div>- <div class="ec-px-row"><span>Your tier price${DISCOUNT_BPS > 0 ? ` <span class="ec-muted">(−${(DISCOUNT_BPS / 100).toFixed(0)}%)</span>` : ''}</span><span class="val${saved > 0 ? ' save' : ''}">${fmtUsd(yours)}</span></div>- ${saved > 0 ? `<div class="ec-px-row"><span>You save</span><span class="val save">${fmtUsd(saved)}</span></div>` : ''}- <div class="ec-px-row"><span>Settles in</span><span class="val ec-px-three">${three != null ? `≈ ${fmtCompact(three)} $THREE` : 'live $THREE'}</span></div>- <p class="ec-muted" style="margin-top:14px;font-size:12.5px">Splits 70% treasury / 30% holder rewards. ${DISCOUNT_BPS > 0 ? 'Your discount is applied automatically at checkout.' : 'Hold $THREE to unlock a tier discount on this.'}</p>`;-}--function wirePricing(actions) {- const list = document.getElementById('ec-px-list');- if (!list) return;- const groups = catalogGroups(actions);- list.innerHTML = groups- .map(- (g) =>- `<div class="ec-px-cat">${esc(g.label)}</div>` +- g.items- .map((a, i) => {- const price =- a.usd == null ? `<span class="pp var">per item</span>` : a.usd === 0 ? `<span class="pp free">Free</span>` : `<span class="pp">${fmtUsd(a.usd)}</span>`;- return `<button class="ec-px-item" data-id="${esc(a.id)}"><span class="pl">${esc(a.label)}</span>${price}</button>`;- })- .join(''),- )- .join('');- const byId = Object.fromEntries(actions.map((a) => [a.id, a]));- const buttons = [...list.querySelectorAll('.ec-px-item')];- const select = (btn) => {- buttons.forEach((b) => b.classList.toggle('sel', b === btn));- renderPriceDetail(byId[btn.dataset.id]);- };- buttons.forEach((b) => b.addEventListener('click', () => select(b)));- // Auto-select the first paid action so the detail panel isn't empty.- const firstPaid = buttons.find((b) => byId[b.dataset.id]?.usd > 0) || buttons[0];- if (firstPaid) select(firstPaid);-}--function wireProjector(stats) {- const range = document.getElementById('ec-proj-range');- const out = document.getElementById('ec-proj-out');- if (!range || !out) return;- const dec = stats?.token?.decimals ?? 6;- const reflectedTotal = atomicsToTokens(stats?.reflected?.total_atomics ?? '0', dec);- // Eligible supply from the most recent run (best estimate of the holder base).- const recent = stats?.reflected?.recent?.[0];- const eligibleSupply = recent ? atomicsToTokens(recent.eligible_supply_atomics ?? '0', dec) : 0;- // Map slider 0–6 to a $THREE bag on a log scale (1 → 1,000,000).- const update = () => {- const v = Number(range.value);- const bag = Math.round(Math.pow(10, v));- const bagUsd = LIVE_PRICE > 0 ? bag * LIVE_PRICE : null;- let earned = null;- if (eligibleSupply > 0 && reflectedTotal > 0) earned = (bag / eligibleSupply) * reflectedTotal;- out.innerHTML = `Holding <b>${fmtCompact(bag)} $THREE</b>${bagUsd != null ? ` <span class="ec-muted">(${fmtUsd(bagUsd)})</span>` : ''}<br/>` +- (earned != null && earned > 0- ? `would have earned <b>≈ ${fmtCompact(earned)} $THREE</b> from past distributions — plus a fee discount on everything you buy. <span class="ec-muted">(historical, not a forecast)</span>`- : `<span class="ec-muted">earns a pro-rata share of every future distribution, plus a fee discount that grows with your tier.</span>`);- };- range.addEventListener('input', update);- update();-}--function wireNameStudio(root) {- const input = root.querySelector('#ec-name-input');- const out = root.querySelector('#ec-name-out');- if (!input || !out) return;- const RANK = { common: 0.18, uncommon: 0.42, rare: 0.64, epic: 0.84, legendary: 1 };- 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 see its rarity and price.</span>';- return;- }- const mine = ++seq;- try {- const q = await getJSON(`${API}/name-quote?name=${encodeURIComponent(name)}`);- if (mine !== seq) return;- const pct = (RANK[q.rarity] || 0.18) * 100;- const color = q.free ? 'var(--muted)' : `var(--${q.rarity === 'legendary' ? 'violet' : q.rarity === 'epic' ? 'blue' : q.rarity === 'rare' ? 'green' : 'gold'})`;- const priceLine = q.free- ? `<span style="color:var(--green);font-weight:700">Free to mint</span> <span class="ec-muted">— common name</span>`- : `<strong>${fmtUsd(q.usd)}</strong> <span class="ec-muted">${q.three ? `≈ ${fmtCompact(q.three.token_amount)} $THREE` : ''}</span>`;- out.innerHTML = `- <div class="ec-rare-head">- <span class="ec-rarity r-${esc(q.rarity)}">${esc(q.rarity_label)}</span>- <strong style="font-family:ui-monospace,Menlo,monospace">${esc(q.full_name)}</strong>- </div>- <div class="ec-rare-meter"><div class="ec-rare-fill" style="width:${pct}%;background:${color}"></div></div>- <div style="font-size:14px">${priceLine}</div>- <div class="ec-muted" style="font-size:12.5px;margin-top:6px">${esc((q.reasons || []).join(' · '))}</div>`;- } catch (e) {- if (mine !== seq) return;- out.innerHTML =- e.code === 'invalid_label'- ? '<div class="ec-err">Use letters, digits, and hyphens only (no leading/trailing hyphen).</div>'- : '<span class="ec-muted">Couldn\'t price that name — try again in a moment.</span>';- }- };- input.addEventListener('input', () => {- clearTimeout(timer);- timer = setTimeout(run, 260);- });-}--// ── load orchestration ─────────────────────────────────────────────────────────-async function load(root) {- const setErr = (id, msg) => {- const el = document.getElementById(id);- if (el) el.innerHTML = `<div class="ec-err">${esc(msg)}</div>`;- };-- // Live $THREE price (for conversions) — best-effort, non-blocking.- getJSON('/api/token/price')- .then((p) => {- LIVE_PRICE = Number(p?.price_usd) || 0;- })- .catch(() => {});-- // Stats drive the flow viz, the stat band, on-chain wallets, reflections + projector.- // Wrapped so a failed first load renders a designed "live figures unavailable" notice- // with a working Retry — never a silent page stuck on "—" placeholders.- function renderStats(s) {- const band = document.getElementById('ec-stats');- if (band) {- band.innerHTML = statCards(s)- .map(- (c) =>- `<div class="ec-stat" style="--accent:${c.accent}"><div class="v" style="--accent:${c.accent}"><span data-roll>0</span>${c.sym ? '<span class="sym">$THREE</span>' : ''}</div><div class="k">${esc(c.k)}</div></div>`,- )- .join('');- const cards = statCards(s);- band.querySelectorAll('[data-roll]').forEach((el, i) => {- rollup(el, cards[i].v, cards[i].sym ? fmtCompact : (n) => Math.round(n).toLocaleString('en-US'));- });- }- // Hero north-star metric: total $THREE returned to holders.- const heroEl = document.querySelector('#ec-hero-stat [data-roll]');- if (heroEl) {- const dec = s?.token?.decimals ?? 6;- rollup(heroEl, atomicsToTokens(s?.reflected?.total_atomics ?? '0', dec), fmtCompact, 1400);- }- const oc = document.getElementById('ec-onchain');- if (oc) oc.innerHTML = onchainHTML(s);- const rf = document.getElementById('ec-reflected');- if (rf) {- rf.innerHTML = reflectedHTML(s);- wireProjector(s);- }- // Trust stamp: when the data is from and where it comes from.- const stamp = document.getElementById('ec-stamp');- if (stamp) {- const when = new Date().toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });- stamp.textContent = `Updated ${when} · source: Solana RPC + settle ledger`;- }- if (window._ecFlow) window._ecFlow.seed(s);- }-- function renderStatsError() {- // One honest, recoverable notice across the stats band, on-chain wallets and- // reflection sections — plus the hero stat + stamp, which would otherwise sit- // silently on their "0"/"Loading…" placeholders forever.- const band = document.getElementById('ec-stats');- if (band) {- band.innerHTML = `<div class="ec-err" style="grid-column:1/-1;display:flex;align-items:center;justify-content:space-between;gap:14px;flex-wrap:wrap">- <span>Live figures are temporarily unavailable. The economy is unchanged — this is a read hiccup.</span>- <button class="ec-btn" id="ec-stats-retry" type="button" aria-label="Retry loading live economy figures">Retry</button>- </div>`;- }- const heroStat = document.getElementById('ec-hero-stat');- if (heroStat) {- const num = heroStat.querySelector('[data-roll]');- if (num) num.textContent = '—';- const lbl = heroStat.querySelector('.hs-lbl');- if (lbl) lbl.textContent = 'live total unavailable — retrying';- }- const stamp = document.getElementById('ec-stamp');- if (stamp) stamp.textContent = 'Live figures unavailable — couldn\'t reach Solana RPC + settle ledger.';- setErr('ec-onchain', 'On-chain data is temporarily unavailable.');- setErr('ec-reflected', 'Reflection history is temporarily unavailable.');- const retry = document.getElementById('ec-stats-retry');- if (retry) {- retry.addEventListener('click', () => {- retry.disabled = true;- retry.textContent = 'Retrying…';- // Restore skeletons so the retry reads as a real reload, not a frozen error.- const b = document.getElementById('ec-stats');- if (b) b.innerHTML = '<div class="ec-stat ec-skel" style="height:96px"></div>'.repeat(5);- const oc = document.getElementById('ec-onchain');- if (oc) oc.innerHTML = '<div class="ec-wallets">' + '<div class="ec-wallet ec-skel" style="height:108px"></div>'.repeat(2) + '</div>';- const rf = document.getElementById('ec-reflected');- if (rf) rf.innerHTML = '<div class="ec-card ec-skel" style="height:200px"></div><div class="ec-card ec-skel" style="height:200px"></div>';- const stamp2 = document.getElementById('ec-stamp');- if (stamp2) stamp2.textContent = 'Loading live figures…';- loadStats();- });- }- }-- function loadStats() {- return getJSON(`${API}/stats`).then(renderStats).catch(renderStatsError);- }- loadStats();-- getJSON(`${API}/catalog`)- .then((c) => {- const actions = c.actions || [];- wirePricing(actions);- const cat = document.getElementById('ec-catalog');- if (cat) {- cat.innerHTML = catalogGroups(actions)- .map(- (g) =>- `<div class="ec-cat"><h3>${esc(g.label)}</h3><div class="ec-items">${g.items- .map((a) => {- const price = a.usd == null ? `<span class="price var">per item</span>` : a.usd === 0 ? `<span class="price free">Free</span>` : `<span class="price">${fmtUsd(a.usd)}</span>`;- return `<div class="ec-item"><span class="label">${esc(a.label)}</span>${price}</div>`;- })- .join('')}</div></div>`,- )- .join('');- }- })- .catch(() => {- setErr('ec-px-list', 'Price catalog is temporarily unavailable.');- setErr('ec-catalog', 'Price catalog is temporarily unavailable.');- });-- // The tier ladder is always-on info content, so render the baseline immediately- // (never an empty/error box), then enhance with the holder's live "current" tier- // + progress (loadTier) and each tier's Live/Planned perks (loadAccess) as they- // land. A signed-out or failed call simply leaves the informative ladder in place.- renderTiers();- loadTier();-- // Personal "Your access" panel: what THIS visitor's $THREE unlocks right now. Renders- // the signed-out empty state for anonymous viewers and the live feature matrix for a- // holder session, and re-fetches whenever a Solana wallet connects/disconnects so the- // panel stays truthful without a reload.- loadAccess();- if (!_accessBound) {- _accessBound = true;- addEventListener('wallet:changed', () => loadAccess());- }-- wireNameStudio(root);-}--// Fetch + render the holder tier ladder and apply the tier discount to the pricing-// explorer. Reusable so a fresh sign-in can refresh it without a full reload. The-// baseline ladder is already on screen, so any failure simply leaves it in place.-function loadTier() {- return getJSON(`${API}/tier`)- .then((t) => {- DISCOUNT_BPS = Number(t?.tier?.discount_bps) || 0;- if (t?.ladder?.length) _tierData = t;- renderTiers();- // Re-render the price detail now that the discount is known.- const sel = document.querySelector('.ec-px-item.sel');- if (sel) sel.click();- })- .catch(() => {- /* keep the baseline ladder — it's informative without auth */- });-}--// Render the personal access panel from /api/three/access. Anonymous → empty state;-// signed-in → the live feature matrix. Degrades to its own error box on failure, so-// the rest of /three (including the always-on ladder above) is unaffected.-function loadAccess() {- const el = document.getElementById('ec-access');- // Wallet-aware read via the shared data layer: a connected wallet (?wallet=) is- // threaded in automatically, so this reflects the wallet in hand — not just the- // session. Returns null on failure (never throws); fresh so a wallet change isn't- // served a stale matrix.- return getAccess(undefined, { fresh: true }).then((data) => {- if (!data) {- if (el) el.innerHTML = '<div class="ec-err">Your access is temporarily unavailable.</div>';- return;- }- // The matrix feeds both the per-tier Live/Planned perks above and the personal- // panel below — one call, two surfaces. Features come back for anonymous callers- // too (all locked), so the ladder enriches regardless.- _accessFeatures = Array.isArray(data.features) ? data.features : null;- // Highlight the connected wallet's held tier on the ladder (loadTier owns the- // highlight for signed-in users — see applyTierFromAccess).- applyTierFromAccess(data);- renderTiers();- if (el) {- // "Known" = a real identity resolved: a signed-in account OR a connected wallet.- // Either way show the live matrix; otherwise the connect / sign-in empty state.- const known = Boolean(data.signed_in || data.wallet_linked);- el.innerHTML = known ? accessMatrixHTML(data) : accessSignedOutHTML();- wireAccessActions();- }- });-}--// Wire the empty-state Sign in button. On success the new session yields the live-// matrix (and refreshes the ladder's "You" chip + the pricing discount); a cancelled-// or failed sign-in restores the button and shows an inline, recoverable message.-function wireAccessActions() {- // Connect a wallet (no account) to reveal the live matrix — drives the same global- // connect button as the ladder; wallet:changed then re-reads and re-renders this panel.- const connect = document.getElementById('ec-access-connect');- if (connect) {- connect.addEventListener('click', () => document.getElementById('connect-wallet-btn')?.click());- }- const signin = document.getElementById('ec-access-signin');- if (!signin) return;- signin.addEventListener('click', async () => {- const label = signin.textContent;- signin.disabled = true;- signin.textContent = 'Signing in…';- try {- const { signInWithWallet } = await import('./wallet-auth.js');- await signInWithWallet();- await loadAccess();- loadTier();- } catch {- signin.disabled = false;- signin.textContent = label;- const cta = signin.closest('.ta-empty-cta');- if (cta && !document.getElementById('ec-access-msg')) {- const msg = document.createElement('p');- msg.id = 'ec-access-msg';- msg.className = 'ta-msg';- msg.setAttribute('role', 'alert');- msg.textContent = 'Sign-in was cancelled or failed. Try again.';- cta.insertAdjacentElement('afterend', msg);- }- }- });-}--// Static ladder shape so a signed-out visitor still sees the tiers (the live-// endpoint returns the authoritative copy; this mirrors api/_lib/three-tier.js).-const DEFAULT_LADDER = [- { level: 0, id: 'member', label: 'Member', min_usd: 0, discount_bps: 0, perks: ['Everything free-forever: create, discover, embed, social, basic worlds'] },- { level: 1, id: 'bronze', label: 'Bronze', min_usd: 25, discount_bps: 500, perks: ['5% off all $THREE compute', '2× free generation quota', 'Bronze profile badge'] },- { level: 2, id: 'silver', label: 'Silver', min_usd: 100, discount_bps: 1000, perks: ['10% off all $THREE compute', '3× free generation quota', 'Private worlds', 'Priority MCP routing'] },- { level: 3, id: 'gold', label: 'Gold', min_usd: 500, discount_bps: 2000, perks: ['20% off all $THREE compute', '5× free generation quota', 'Branded worlds', 'Early access to drops'] },- { level: 4, id: 'genesis', label: 'Genesis', min_usd: 2500, discount_bps: 3000, perks: ['30% off all $THREE compute', '10× free generation quota', 'First dibs on rare names', 'Genesis-only cosmetics'] },-];--function init() {- injectStyles();- document.title = 'The $THREE economy · three.ws';- const root = document.createElement('main');- root.innerHTML = shell();- document.body.appendChild(root);-- // Wire the global wallet connect (hidden #connect-wallet-btn) and auto-connect a- // trusted wallet, so a returning holder's tier highlights with no click. The- // "Connect wallet" CTAs route through this same button; on connect, wallet:changed- // (already bound in load()) re-reads the wallet-aware matrix and re-highlights.- initWalletButton();-- // The Flow: start it, and pause when offscreen to save battery/CPU.- const canvas = document.getElementById('ec-flow');- if (canvas) {- const flow = new FlowViz(canvas);- window._ecFlow = flow;- flow.start();- if (typeof IntersectionObserver === 'function' && !REDUCED_MOTION) {- new IntersectionObserver(- (entries) => {- for (const e of entries) {- if (e.isIntersecting) flow.start();- else flow.stop();- }- },- { threshold: 0.01 },- ).observe(canvas);- }- // WCAG 2.2.2 Pause/Stop/Hide — a control for the perpetual motion.- const pauseBtn = document.getElementById('ec-flow-pause');- if (pauseBtn) {- if (REDUCED_MOTION) pauseBtn.style.display = 'none'; // nothing animating to pause- pauseBtn.addEventListener('click', () => {- flow.userPaused = !flow.userPaused;- pauseBtn.setAttribute('aria-pressed', String(flow.userPaused));- if (flow.userPaused) {- flow.stop();- pauseBtn.innerHTML = '▶ Play';- pauseBtn.setAttribute('aria-label', 'Play the animation');- } else {- pauseBtn.innerHTML = '❚❚ Pause';- pauseBtn.setAttribute('aria-label', 'Pause the animation');- flow.start();- }- });- }- }-- observeReveal(root);- load(root);-}--if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init);-else init();diff --git a/src/three-gate.js b/src/three-gate.jsindex 51e66fe7c..fea5fee38 100644--- a/src/three-gate.js+++ b/src/three-gate.js@@ -33,7 +33,7 @@ import { log } from './shared/log.js';const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';const SOL_MINT = 'So11111111111111111111111111111111111111112';const JUPITER_SWAP_URL = `https://jup.ag/swap/SOL-${THREE_MINT}`;-const ECONOMY_URL = '/three';+const ECONOMY_URL = '/three-token';const SIGN_IN_URL = '/login'; // matches src/three-lock.jsconst LOCK_GLYPH =@@ -289,7 +289,7 @@ class ThreeGate extends HTMLElement {(pay? `<p class="tg-pay">or pay <strong>${fmtUsd(pay.usd)}</strong> per use</p>`: '') +- `<a class="tg-perks" href="${ECONOMY_URL}">See all holder perks →</a>` ++ `<a class="tg-perks" href="${ECONOMY_URL}">Get $THREE →</a>` +`</div>`;this._wireLocked();diff --git a/src/three-lock.js b/src/three-lock.jsindex df4241208..9d2cacc88 100644--- a/src/three-lock.js+++ b/src/three-lock.js@@ -17,7 +17,7 @@// Fully keyboard-navigable (real <a>/<button>), ARIA-labelled, reduced-motion// aware, and responsive. Never throws — a missing target is a no-op.-const ECONOMY_URL = '/three';+const ECONOMY_URL = '/three-token';const SIGN_IN_URL = '/login';const LINK_WALLET_URL = '/dashboard/account#wallets';diff --git a/src/three/gate-modal.js b/src/three/gate-modal.jsindex 166ea0c99..f6a20c356 100644--- a/src/three/gate-modal.js+++ b/src/three/gate-modal.js@@ -16,7 +16,7 @@// { ok:false, reason } on cancel. The server stays the authority — this only shapes// the path back to eligibility, it never grants it.-const ECONOMY_URL = '/three'; // the $THREE economy page — where you get $THREE / see tiers+const ECONOMY_URL = '/three-token'; // the $THREE token page — live price, chart & one-click buylet _active = null; // the single live instance: { overlay, resolve, restoreFocus, onKey }let _stylesInjected = false;@@ -104,7 +104,7 @@ function bodyHTML(snapshot) {${primaryBtn}<button class="tga-btn tga-btn--ghost" data-act="recheck" type="button">Recheck access</button></div>- <a class="tga-tiers" href="${ECONOMY_URL}#tiers" target="_blank" rel="noopener">See holder tiers →</a>+ <a class="tga-tiers" href="${ECONOMY_URL}" target="_blank" rel="noopener">Get $THREE →</a>${ppu}<p class="tga-note" id="tga-note" role="status" aria-live="polite"></p><p class="tga-foot">$THREE is the only coin on three.ws. Draft & Standard generation stay free, forever.</p>`;diff --git a/src/walk.js b/src/walk.jsindex 061b60bf3..306917aaf 100644--- a/src/walk.js+++ b/src/walk.js@@ -1117,7 +1117,7 @@ async function loadAvatar() {buildEmoteTray();// Auto-hide help hints after 5 seconds — fade first, then remove from layout- // so the transition in walk.html's #walk-help { transition: opacity } plays.+ // so the transition in temporary.html's #walk-help { transition: opacity } plays.if (helpEl) {helpAutoHideTimer = setTimeout(() => {helpEl.style.opacity = '0';diff --git a/tests/glb-canonicalize.test.js b/tests/glb-canonicalize.test.jsindex 04a11d837..6166c1f27 100644--- a/tests/glb-canonicalize.test.js+++ b/tests/glb-canonicalize.test.js@@ -95,7 +95,8 @@ describe('canonicalizeBoneName', () => {expect(canonicalizeBoneName('')).toBeNull();expect(canonicalizeBoneName(42)).toBeNull();expect(canonicalizeBoneName('Tail_01')).toBeNull();- expect(canonicalizeBoneName('J_Bip_L_UpperArm')).toBeNull(); // VRM — unmapped+ expect(canonicalizeBoneName('J_Sec_Hair1_01')).toBeNull(); // VRM secondary (hair) — not a body bone+ expect(canonicalizeBoneName('mannequin-root')).toBeNull(); // armature root, not a bone});it('returns canonical exact-match names unchanged', () => {@@ -206,6 +207,91 @@ describe('canonicalizeBoneName', () => {expect(canonicalizeBoneName(input)).toBe(expected);});+ // VRM 0.x / VRoid skeletons (`J_Bip_<C|L|R>_<bone>`). The side is in the+ // prefix; the alias table maps each explicitly, including the "Little" → pinky+ // finger rename, so a VRoid avatar drives the canonical clip library.+ it.each([+ ['J_Bip_C_Hips', 'Hips'],+ ['J_Bip_C_Spine', 'Spine'],+ ['J_Bip_C_Chest', 'Spine1'],+ ['J_Bip_C_UpperChest', 'Spine2'],+ ['J_Bip_C_Neck', 'Neck'],+ ['J_Bip_C_Head', 'Head'],+ ['J_Bip_L_Shoulder', 'LeftShoulder'],+ ['J_Bip_L_UpperArm', 'LeftArm'],+ ['J_Bip_R_LowerArm', 'RightForeArm'],+ ['J_Bip_L_Hand', 'LeftHand'],+ ['J_Bip_L_UpperLeg', 'LeftUpLeg'],+ ['J_Bip_R_LowerLeg', 'RightLeg'],+ ['J_Bip_L_Foot', 'LeftFoot'],+ ['J_Bip_L_ToeBase', 'LeftToeBase'],+ ['J_Bip_R_Toes', 'RightToeBase'],+ ['J_Bip_L_Little1', 'LeftHandPinky1'],+ ['J_Bip_R_Index3', 'RightHandIndex3'],+ ['J_Bip_L_Thumb2', 'LeftHandThumb2'],+ ])('maps VRM/VRoid bones: %s → %s', (input, expected) => {+ expect(canonicalizeBoneName(input)).toBe(expected);+ });++ // VRM 1.0 normalized humanoid names (camelCase, no vendor prefix).+ it.each([+ ['leftUpperArm', 'LeftArm'],+ ['rightLowerArm', 'RightForeArm'],+ ['leftUpperLeg', 'LeftUpLeg'],+ ['rightLowerLeg', 'RightLeg'],+ ['upperChest', 'Spine2'],+ ['chest', 'Spine1'],+ ['leftToes', 'LeftToeBase'],+ ])('maps VRM 1.0 camelCase bones: %s → %s', (input, expected) => {+ expect(canonicalizeBoneName(input)).toBe(expected);+ });++ // Daz3D / Genesis skeletons (`hip`, `abdomen`, `lShldr`, `lThigh`, …),+ // including the Genesis 3+ `…Bend` joints.+ it.each([+ ['hip', 'Hips'],+ ['abdomen', 'Spine'],+ ['lCollar', 'LeftShoulder'],+ ['lShldr', 'LeftArm'],+ ['lShldrBend', 'LeftArm'],+ ['rForeArm', 'RightForeArm'],+ ['lThigh', 'LeftUpLeg'],+ ['lThighBend', 'LeftUpLeg'],+ ['rShin', 'RightLeg'],+ ])('maps Daz/Genesis bones: %s → %s', (input, expected) => {+ expect(canonicalizeBoneName(input)).toBe(expected);+ });++ // MakeHuman / Blender `.L`/`.R` side suffix (the `.` is a separator), sharing+ // stems with the Unreal alias table. Blender's `.001` de-dup is stripped too.+ it.each([+ ['upperarm.L', 'LeftArm'],+ ['lowerarm.R', 'RightForeArm'],+ ['clavicle.L', 'LeftShoulder'],+ ['thigh.L', 'LeftUpLeg'],+ ['shin.R', 'RightLeg'],+ ['foot.L', 'LeftFoot'],+ ['upperarm.L.001', 'LeftArm'], // .L side + Blender .001 de-dup suffix+ ])('maps MakeHuman/Blender .L/.R bones: %s → %s', (input, expected) => {+ expect(canonicalizeBoneName(input)).toBe(expected);+ });++ // Simple / generic 3-joint-limb rigs that put the side as a trailing L/R and+ // name the upper arm "shoulder", forearm "elbow", hand "wrist", etc.+ it.each([+ ['shoulderL', 'LeftArm'],+ ['elbowR', 'RightForeArm'],+ ['wristL', 'LeftHand'],+ ['hipL', 'LeftUpLeg'],+ ['kneeR', 'RightLeg'],+ ['ankleL', 'LeftFoot'],+ ['toeL', 'LeftToeBase'],+ ['chest', 'Spine1'],+ ['pelvis', 'Hips'],+ ])('maps simple/generic side-suffix rigs: %s → %s', (input, expected) => {+ expect(canonicalizeBoneName(input)).toBe(expected);+ });+it('only strips the suffix when the plain form does not already resolve', () => {// A genuinely numbered finger bone must keep its index — the un-stripped// form resolves first, so we never reach the suffix strip.@@ -261,10 +347,12 @@ describe('canonicalizeJointNodes (in-place rewrite)', () => {skins: [{ joints: [0, 1, 2] }],};const { renamed } = canonicalizeJointNodes(json);- expect(renamed).toBe(1); // only Hips+ // Hips (Mixamo) and the VRM upper-arm both canonicalize; the non-humanoid+ // Tail bone has no mapping and is left untouched.+ expect(renamed).toBe(2);expect(json.nodes[0].name).toBe('Hips');expect(json.nodes[1].name).toBe('mixamorig:Tail_01');- expect(json.nodes[2].name).toBe('J_Bip_L_UpperArm');+ expect(json.nodes[2].name).toBe('LeftArm');});});diff --git a/vercel.json b/vercel.jsonindex a9c05b622..7ab1bfbd0 100644--- a/vercel.json+++ b/vercel.json@@ -584,7 +584,10 @@},{"src": "/three/?",- "dest": "/three.html"+ "status": 308,+ "headers": {+ "Location": "/three-token"+ }},{"src": "/go/?",@@ -759,7 +762,7 @@},{"src": "/temporary/?",- "dest": "/walk.html"+ "dest": "/temporary.html"},{"src": "/irl/?",diff --git a/vite.config.js b/vite.config.jsindex 81e597eaa..2e9efeb17 100644--- a/vite.config.js+++ b/vite.config.js@@ -366,7 +366,6 @@ 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'),@@ -389,7 +388,7 @@ const appConfig = {'gallery-picker': resolve(__dirname, 'pages/gallery-picker.html'),status: resolve(__dirname, 'pages/status.html'),xr: resolve(__dirname, 'pages/xr.html'),- walk: resolve(__dirname, 'pages/walk.html'),+ temporary: resolve(__dirname, 'pages/temporary.html'),irl: resolve(__dirname, 'pages/irl.html'),'irl-privacy': resolve(__dirname, 'pages/irl-privacy.html'),communities: resolve(__dirname, 'pages/communities.html'),@@ -778,16 +777,14 @@ 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'),'/three-token/': resolve(root, 'pages/three-token.html'),'/avatar-artifact': resolve(root, 'pages/avatar-artifact.html'),'/avatar-artifact/': resolve(root, 'pages/avatar-artifact.html'),- '/temporary': resolve(root, 'pages/walk.html'),- '/temporary/': resolve(root, 'pages/walk.html'),+ '/temporary': resolve(root, 'pages/temporary.html'),+ '/temporary/': resolve(root, 'pages/temporary.html'),'/irl': resolve(root, 'pages/irl.html'),'/irl/': resolve(root, 'pages/irl.html'),'/irl-privacy': resolve(root, 'pages/irl-privacy.html'),diff --git a/x402-modal-sdk/README.md b/x402-modal-sdk/README.mdnew file mode 100644index 000000000..ee3ffef93--- /dev/null+++ b/x402-modal-sdk/README.md@@ -0,0 +1,306 @@+<div align="center">++# @three-ws/x402-modal++**A drop-in payment modal for any [x402](https://x402.org) paid endpoint.**++One script tag turns an HTTP `402 Payment Required` into a polished checkout:+wallet connect (Phantom on Solana, MetaMask/EVM via EIP-3009), the+`402 → sign → settle` flow, SIWX re-entry, spending caps, and a receipt — all+in **vanilla JS, with no bundler and no framework**.++[](https://www.npmjs.com/package/@three-ws/x402-modal)+[](https://www.npmjs.com/package/@three-ws/x402-modal)++++[Quick start](#quick-start) · [How it works](#how-it-works) · [API](#api) · [Configuration](#configuration) · [Backend](#the-backend) · [Tutorials](./TUTORIAL.md) · [FAQ](#faq)++</div>++---++## Why++[x402](https://x402.org) revives HTTP `402 Payment Required` as a real payment+rail: a server answers a request with a `402` whose body lists what it+`accepts` (asset, amount, network, pay-to), the client pays, and re-sends the+request with an `X-PAYMENT` header. It's perfect for pay-per-call APIs, agent+economies, and content paywalls — but every merchant ends up rebuilding the same+fiddly client: parse the challenge, connect a wallet, sign the right thing for+the right chain, retry, settle, show a receipt.++**This package is that client, done once and done well.** Point it at a `402`+endpoint and it renders the entire flow. The EVM/Base path is 100%+client-side. The Solana path needs one small backend helper (see+[The backend](#the-backend)).++## Quick start++### 1 — One script tag (zero JS)++```html+<script type="module" src="https://unpkg.com/@three-ws/x402-modal/global"></script>++<button+ data-x402-endpoint="https://api.example.com/paid/summarize"+ data-x402-method="POST"+ data-x402-body='{"text":"hello world"}'+ data-x402-merchant="Acme"+ data-x402-action="Summarize">+ Pay & summarize+</button>+```++Clicking the button opens the modal, runs the payment, calls the endpoint, and+fires an `x402:result` event on the button with `{ ok, result, payment, response }`:++```js+document.querySelector('button').addEventListener('x402:result', (e) => {+ console.log('paid + got result:', e.detail.result);+});+```++### 2 — Programmatic (full control)++```js+import { pay } from '@three-ws/x402-modal';++const out = await pay({+ endpoint: '/api/paid/summarize',+ method: 'POST',+ body: { text: 'hello world' },+ merchant: 'Acme',+ action: 'Summarize',+});++console.log(out.result); // the endpoint's response, after settlement+console.log(out.payment); // { network, payer, transaction }+```++`pay()` resolves once the paid call returns `200`, or rejects with an `Error`+whose `.code === 'cancelled'` if the user closes the modal.++### 3 — Self-hosted, fully branded++```html+<script+ type="module"+ src="https://your.cdn/x402.global.js"+ data-x402-api-origin="https://pay.your-company.com"+ data-x402-brand-label="Powered by Acme"+ data-x402-brand-href="https://acme.com"></script>+```++or from JS, before the first `pay()`:++```js+import { configure } from '@three-ws/x402-modal';++configure({+ apiOrigin: 'https://pay.your-company.com', // Solana checkout backend+ brand: { label: 'Powered by Acme', href: 'https://acme.com' },+});+```++> **No dependencies to install.** The ESM build leaves the two optional wallet+> libraries (`@solana/web3.js` for Solana, a keccak for EVM sign-in) as runtime+> CDN imports, fetched only when that wallet path actually runs. The `/global`+> build is a single self-contained file.++## How it works++```+pay({ endpoint })+ │+ ├─ 1. discover GET/POST endpoint → 402 (or 401 + payment-required header)+ │ parse `accepts[]` (asset · amount · network · payTo)+ │+ ├─ 2. connect pick a wallet that can satisfy an accept:+ │ Solana → Phantom EVM → MetaMask / window.ethereum+ │+ ├─ 3. authorize Solana: backend builds the tx → Phantom signs it+ │ EVM: wallet signs an EIP-3009 transferWithAuthorization+ │ (no on-chain tx, no gas for the payer)+ │+ └─ 4. verify re-send the request with `X-PAYMENT` → endpoint runs the work,+ settles on-chain, returns 200 + `x-payment-response` receipt+```++Each step renders as a live row in the modal (spinner → check → error), with a+**Try again** affordance on failure, automatic retry on a `429` upstream+throttle (the payment isn't settled until the work succeeds, so re-sending can't+double-charge), and a receipt with an explorer link on success.++### Networks++| Network | Wallet | Scheme | Needs a backend? |+|---|---|---|---|+| **Base** (`eip155:8453`) | MetaMask / any `window.ethereum` | EIP-3009 `transferWithAuthorization` | **No** — fully client-side |+| Base Sepolia, Arbitrum, Optimism | same | EIP-3009 | No |+| **Solana** (`solana:*`) | Phantom | `exact` (facilitator-settled) | Yes — `prepare`/`encode` helper |++When a `402` advertises more than one network the modal shows a wallet picker;+when it advertises exactly one, it goes straight there.++## API++### `pay(options): Promise<PayResult>`++| option | type | default | notes |+|---------------|-------------------------------|--------------------|-------|+| `endpoint` | `string` | — (**required**) | the x402-protected URL to pay for and call |+| `method` | `string` | `GET` / `POST`* | *POST when a `body` is set |+| `body` | `object \| string` | — | forwarded to the endpoint (object → JSON) |+| `headers` | `Record<string,string>` | — | merged into discovery + paid calls |+| `merchant` | `string` | `Payment` | shown in the modal header |+| `action` | `string` | `Pay-per-call` | shown in the modal header |+| `caps` | `{ maxPerCall, maxPerHour, maxPerDay }` | — | µUSD spending caps (see [Configuration](#configuration)) |+| `autoConnect` | `boolean` | `false` | skip the picker when exactly one wallet is detected |+| `apiOrigin` | `string` | global config | per-call override of the Solana checkout backend |+| `brand` | `{ label, href }` | global config | per-call footer override |++Returns `{ ok: true, result, payment?, siwx?, response }`. `payment` is present+on a fresh payment (`{ network, payer, transaction }`); `siwx` is present when+the user re-entered via sign-in instead of paying.++### `configure(config): config` · `getConfig(): config`++Set global defaults once at startup. See [Configuration](#configuration).++### `init(): void`++Scan the document and bind every `[data-x402-endpoint]` element. The `/global`+build calls this automatically (and re-scans on DOM mutation); call it yourself+only when using the ESM build with declarative buttons.++### DOM events (declarative usage)++Bound elements dispatch bubbling `CustomEvent`s:++- `x402:result` — `detail` is the full `PayResult`.+- `x402:error` — `detail` is `{ error: string }`. (Cancellation does **not** fire this.)+- `x402:siwx-signed` — `detail` is `{ address, network }`, when re-entry was via SIWX.++### `data-*` attributes (declarative usage)++`data-x402-endpoint` (required), `data-x402-method`, `data-x402-body` (JSON),+`data-x402-headers` (JSON), `data-x402-caps` (JSON), `data-x402-api-origin`,+`data-x402-merchant`, `data-x402-action`.++## Configuration++All fields are optional; the defaults reproduce the hosted three.ws modal.++```js+configure({+ // Origin serving the Solana prepare/encode checkout helpers. Only the Solana+ // path uses it; the EVM path needs no backend. null → resolve from the+ // script's own origin; '' → same-origin.+ apiOrigin: 'https://pay.example.com',++ // Footer attribution.+ brand: { label: 'Powered by Acme', href: 'https://acme.com' },++ // ERC-8021 builder-code self-attribution, echoed back only when the 402+ // challenge declares a builder code. null disables the echo.+ builderCode: { wallet: 'acme', service: 'acme_checkout' },++ // Override the on-demand CDN modules (e.g. to self-host under a strict CSP).+ solanaWeb3Url: 'https://esm.sh/@solana/[email protected]?bundle',+ nobleHashesUrl: 'https://esm.sh/@noble/[email protected]/sha3?bundle',+});+```++### Spending caps++Caps are enforced in `localStorage`, bucketed by rolling UTC hour and day, and+survive reloads. Amounts are **micro-USD** (`1_000_000` = `$1`). A failed payment+rolls its reservation back.++```js+await pay({+ endpoint: '/api/paid/x',+ caps: {+ maxPerCall: 1_000_000, // $1.00 per call+ maxPerHour: 10_000_000, // $10/hour+ maxPerDay: 50_000_000, // $50/day+ },+});+```++Stablecoins (USDC, USDT, DAI) are converted to µUSD exactly. Non-stable assets+pass through atomic in the browser (no price feed is fetched to keep the script+dependency-free) — enforce those server-side.++## The backend++**EVM / Base needs no backend.** The payer signs an EIP-3009+`transferWithAuthorization` in their wallet and the modal sends the signed+authorization straight to your merchant endpoint as `X-PAYMENT`. Your x402+server (and its facilitator) verify and settle it.++**Solana needs one tiny helper**, because building a Solana transfer transaction+requires RPC access and the facilitator's fee-payer. The modal expects two+actions at `{apiOrigin}/api/x402-checkout`:++| action | request | response |+|---|---|---|+| `?action=prepare` | `{ accept, buyer }` | `{ tx_base64 }` — an unsigned/partially-signed `VersionedTransaction` |+| `?action=encode` | `{ accept, signed_tx_base64, resource_url, builder_code? }` | `{ x_payment }` — the base64 `X-PAYMENT` value to send to the merchant |++`apiOrigin` defaults to the origin that served the script, so when you self-host+both the script and this helper there is nothing to configure. See+[`docs/BACKEND.md`](./docs/BACKEND.md) for the full contract and a reference+implementation, and [`examples/`](./examples) for runnable code.++## Install++```sh+npm i @three-ws/x402-modal+```++```js+import { pay, configure } from '@three-ws/x402-modal'; // ESM, no side effects+```++or skip the install entirely and use the CDN `/global` build (auto-binds+`[data-x402-endpoint]`, exposes `window.X402`).++## Security notes++- The modal **never holds keys**. Signing happens in the user's wallet; the+ signed payload goes to your endpoint.+- A `429` from the merchant is retried with the *same* signed payment — safe,+ because x402 settles only after the work succeeds.+- Upstream throttle/billing text is never relayed to the buyer verbatim.+- All endpoint-supplied strings are HTML-escaped before rendering.+- For the Solana path, the dynamic CDN import can be blocked by a strict+ Content-Security-Policy; either allow it, repoint it via `solanaWeb3Url`, or+ steer users to the dependency-free Base path.++## FAQ++**Do I need a wallet adapter / WalletConnect?** No. Solana uses the injected+Phantom provider; EVM uses the injected `window.ethereum`.++**Does the payer pay gas?** On EVM, no — EIP-3009 is a gasless signed+authorization your facilitator submits. On Solana the facilitator is the+fee-payer.++**Can I theme it?** It ships a self-contained stylesheet with light/dark+(`prefers-color-scheme`) support. Override the `.x402-*` classes, or set+`brand` for the footer. The header reflects `merchant` / `action`.++**Framework support?** It's framework-agnostic. Import `pay()` and call it from+a React/Vue/Svelte handler, or drop the `/global` script and use `data-*`+buttons.++**Where does this run in production?** This is the same modal that powers+payments on [three.ws](https://three.ws); the package is its standalone,+configurable home.++## License++[Apache-2.0](./LICENSE) © three.ws. Part of the [three.ws](https://three.ws)+platform for building, animating, rigging, and monetizing 3D AI agents.diff --git a/x402-modal-sdk/TUTORIAL.md b/x402-modal-sdk/TUTORIAL.mdnew file mode 100644index 000000000..54d8c9938--- /dev/null+++ b/x402-modal-sdk/TUTORIAL.md@@ -0,0 +1,281 @@+# Tutorials — @three-ws/x402-modal++Hands-on, copy-paste walkthroughs. Each one is self-contained and ends with+something running. Pick the path that matches your stack:++1. [Tutorial 1 — Sell an API call in 5 minutes (Base, no backend)](#tutorial-1--sell-an-api-call-in-5-minutes-base-no-backend)+2. [Tutorial 2 — Programmatic checkout in a SPA](#tutorial-2--programmatic-checkout-in-a-spa)+3. [Tutorial 3 — A content paywall](#tutorial-3--a-content-paywall)+4. [Tutorial 4 — Self-hosting & full branding](#tutorial-4--self-hosting--full-branding)+5. [Tutorial 5 — Adding the Solana path (the backend helper)](#tutorial-5--adding-the-solana-path-the-backend-helper)+6. [Tutorial 6 — Spending caps for autonomous agents](#tutorial-6--spending-caps-for-autonomous-agents)+7. [Troubleshooting](#troubleshooting)++Every tutorial assumes you already have — or are about to build — an x402 server+that answers a protected route with `402 Payment Required`. If you don't, skim+[the backend doc](./docs/BACKEND.md) first; it shows the minimal server side.++---++## Tutorial 1 — Sell an API call in 5 minutes (Base, no backend)++**Goal:** charge USDC on Base for one API call, with zero backend beyond your+existing x402 server. The Base path is fully client-side.++### 1. Have an endpoint that returns 402++Your server should respond to an unpaid request with `402` and an `accepts`+array describing a Base USDC payment. A minimal challenge body looks like:++```json+{+ "x402Version": 2,+ "accepts": [{+ "scheme": "exact",+ "network": "eip155:8453",+ "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",+ "payTo": "0xYourMerchantWallet",+ "amount": "10000",+ "maxTimeoutSeconds": 600,+ "extra": { "name": "USDC", "version": "2", "decimals": 6 }+ }]+}+```++(`amount` is atomic — `10000` = `$0.01` at 6 decimals.)++### 2. Add the modal to your page++```html+<script type="module" src="https://unpkg.com/@three-ws/x402-modal/global"></script>++<button+ data-x402-endpoint="https://api.acme.com/paid/summarize"+ data-x402-method="POST"+ data-x402-body='{"text":"Long article text here..."}'+ data-x402-merchant="Acme AI"+ data-x402-action="Summarize article">+ Summarize for $0.01+</button>+```++### 3. Handle the result++```html+<script>+ document.querySelector('button').addEventListener('x402:result', (e) => {+ const { result, payment } = e.detail;+ document.querySelector('#out').textContent = JSON.stringify(result, null, 2);+ console.log('settled tx:', payment.transaction);+ });+ document.querySelector('button').addEventListener('x402:error', (e) => {+ alert('Payment failed: ' + e.detail.error);+ });+</script>+<pre id="out"></pre>+```++That's the whole integration. Click → MetaMask signs an EIP-3009 authorization+(no gas, no on-chain tx for the user) → your endpoint runs and settles → the+result renders.++---++## Tutorial 2 — Programmatic checkout in a SPA++**Goal:** trigger checkout from your own button in React/Vue/Svelte/vanilla and+get the result back as a promise.++```sh+npm i @three-ws/x402-modal+```++```jsx+// React example+import { pay } from '@three-ws/x402-modal';++function BuyButton({ text }) {+ const [out, setOut] = useState(null);+ const [err, setErr] = useState(null);++ async function onClick() {+ setErr(null);+ try {+ const res = await pay({+ endpoint: '/api/paid/summarize',+ method: 'POST',+ body: { text },+ merchant: 'Acme AI',+ action: 'Summarize',+ });+ setOut(res.result);+ } catch (e) {+ if (e.code === 'cancelled') return; // user closed the modal — not an error+ setErr(e.message);+ }+ }++ return (+ <>+ <button onClick={onClick}>Summarize for $0.01</button>+ {err && <p className="error">{err}</p>}+ {out && <pre>{JSON.stringify(out, null, 2)}</pre>}+ </>+ );+}+```++The ESM import has **no side effects** — it won't scan the DOM or touch+`window`. You control exactly when the modal opens.++---++## Tutorial 3 — A content paywall++**Goal:** blur premium content until the visitor pays, then reveal it.++```html+<script type="module" src="https://unpkg.com/@three-ws/x402-modal/global"></script>++<article id="premium" class="locked">+ <div class="blurred">…premium article body…</div>+ <button+ data-x402-endpoint="https://api.acme.com/paid/article/42"+ data-x402-merchant="Acme Times"+ data-x402-action="Unlock this article">+ Unlock — $0.25+ </button>+</article>++<style>+ .locked .blurred { filter: blur(8px); pointer-events: none; user-select: none; }+ .unlocked .blurred { filter: none; }+</style>++<script>+ const article = document.getElementById('premium');+ article.querySelector('button').addEventListener('x402:result', (e) => {+ // Put the unlocked content from the endpoint into the page, then reveal.+ article.querySelector('.blurred').innerHTML = e.detail.result.html;+ article.classList.replace('locked', 'unlocked');+ // Remember it so a refresh doesn't re-lock (optional).+ localStorage.setItem('unlocked:article:42', '1');+ });+</script>+```++To skip the paywall for returning buyers, check your flag on load — and if your+server supports **SIWX** (sign-in-with-x), the modal will automatically offer+"Already paid? Sign in" so they re-enter by signing instead of paying again.++---++## Tutorial 4 — Self-hosting & full branding++**Goal:** serve the script yourself, point the Solana backend at your own+domain, and replace the footer attribution — without writing JS.++```html+<script+ type="module"+ src="https://cdn.acme.com/x402.global.js"+ data-x402-api-origin="https://pay.acme.com"+ data-x402-brand-label="Powered by Acme Pay"+ data-x402-brand-href="https://acme.com/pay"+ data-x402-builder-wallet="acme"+ data-x402-builder-service="acme_checkout"></script>+```++Grab `x402.global.js` from the package's `dist/` (or build it with+`npm run build`) and host it anywhere static.++Prefer JS? Configure before the first payment:++```js+import { configure } from '@three-ws/x402-modal';++configure({+ apiOrigin: 'https://pay.acme.com',+ brand: { label: 'Powered by Acme Pay', href: 'https://acme.com/pay' },+ builderCode: { wallet: 'acme', service: 'acme_checkout' },+});+```++To drop the footer link entirely, set `data-x402-builder-disable` and a+`brand` with no `href`.++---++## Tutorial 5 — Adding the Solana path (the backend helper)++**Goal:** accept USDC on Solana too. This is the only path that needs a backend,+because building a Solana transfer needs RPC + the facilitator fee-payer.++The modal calls two actions on `{apiOrigin}/api/x402-checkout`:++```+POST /api/x402-checkout?action=prepare+ body: { accept, buyer }+ → { tx_base64 } # a VersionedTransaction the buyer will sign++POST /api/x402-checkout?action=encode+ body: { accept, signed_tx_base64, resource_url, builder_code? }+ → { x_payment } # the base64 X-PAYMENT value to send to the merchant+```++A reference Express handler that delegates to an x402 facilitator SDK lives in+[`examples/server.mjs`](./examples/server.mjs), and the exact field contract is+in [`docs/BACKEND.md`](./docs/BACKEND.md).++Once the helper is live, no client change is needed beyond pointing `apiOrigin`+at it (Tutorial 4). When your `402` advertises **both** a Solana and a Base+`accept`, the modal shows a wallet picker; when it advertises one, it goes+straight there.++---++## Tutorial 6 — Spending caps for autonomous agents++**Goal:** let an agent (or a kiosk, or a shared browser) pay automatically, but+cap how much it can spend per call / hour / day.++```js+import { pay } from '@three-ws/x402-modal';++await pay({+ endpoint: '/api/paid/inference',+ body: { prompt },+ autoConnect: true, // skip the picker when one wallet is present+ caps: {+ maxPerCall: 500_000, // $0.50 max for any single call+ maxPerHour: 5_000_000, // $5.00/hour+ maxPerDay: 20_000_000, // $20.00/day+ },+});+```++Amounts are **micro-USD** (`1_000_000` = `$1`). Caps are tracked per wallet+address in `localStorage`, bucketed by rolling UTC hour and day, and survive+page reloads. A call that would breach a cap is rejected *before* the wallet+prompt with a clear reason; a payment that fails downstream rolls its+reservation back so it doesn't count against the budget.++> Caps are a client-side guardrail, not a trust boundary. For hard limits an+> agent can't bypass, also enforce server-side.++---++## Troubleshooting++| Symptom | Cause / fix |+|---|---|+| **"Endpoint did not return 402 (got 200)"** | The modal was pointed at a free/unprotected URL, or your server didn't send a `402`. Confirm the route is actually gated. |+| **"no `accepts` array could be found"** | Your `402` body (or `payment-required` header) is missing the `accepts` array. See the challenge shape in Tutorial 1. |+| **"NaN USDC" in the price** | Your `accept` used a field other than `amount`/`maxAmountRequired`. The modal normalizes both; anything else needs mapping. |+| **Solana payment errors with "component … was blocked"** | A strict Content-Security-Policy blocked the dynamic `@solana/web3.js` import. Allow the CDN, set `solanaWeb3Url` to a self-hosted copy, or use the Base path (no third-party code). |+| **EVM signature rejected by the facilitator** | Check the USDC `extra.version` in your `accept` matches the deployed contract (Base USDC is `"2"`), and that `payTo`/`asset` are correct. |+| **Modal opens then immediately shows the picker disabled** | No supported wallet detected. Install Phantom (Solana) or MetaMask (EVM), or advertise an `accept` for a chain the visitor's wallet supports. |+| **`pay()` rejected but nothing went wrong** | The user closed the modal: the rejection's `.code === 'cancelled'`. Treat it as a no-op, not an error. |++Still stuck? Open an issue at+<https://github.com/nirholas/three.ws/issues>.diff --git a/x402-modal-sdk/docs/BACKEND.md b/x402-modal-sdk/docs/BACKEND.mdnew file mode 100644index 000000000..ffea634d2--- /dev/null+++ b/x402-modal-sdk/docs/BACKEND.md@@ -0,0 +1,163 @@+# The backend helper++> **TL;DR — EVM/Base needs no backend.** Only the **Solana** payment path uses+> the helper documented here. If you only accept USDC on Base (or any EVM+> chain), you can ignore this file entirely: the payer signs an EIP-3009+> authorization in their wallet and the modal sends it straight to your merchant+> endpoint.++## Why Solana needs a helper++A browser wallet (Phantom) **signs** serialized transactions — it does not+**build** them. Building a Solana SPL transfer requires:++- a Solana RPC connection (to fetch a recent blockhash, resolve associated token+ accounts, etc.), and+- the **facilitator's fee-payer** public key, so the buyer pays no SOL for gas.++Neither belongs in a public browser script. So the modal delegates the *build*+and *encode* steps to a small server endpoint you host, and the wallet only ever+signs the finished transaction.++The EVM path has no equivalent need: EIP-3009 `transferWithAuthorization` is a+typed-data signature the wallet produces locally, with no RPC and no gas.++## The contract++The modal POSTs to **`{apiOrigin}/api/x402-checkout`** with an `action` query+param. `apiOrigin` defaults to the origin that served the script; override it+with `configure({ apiOrigin })` or `data-x402-api-origin`.++### `POST ?action=prepare`++Build the transfer transaction for the buyer to sign.++**Request body**++```jsonc+{+ "accept": {+ "scheme": "exact",+ "network": "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp1aaqr2BSBLY",+ "asset": "<SPL mint address>", // e.g. USDC mint+ "payTo": "<merchant wallet>",+ "amount": "10000", // atomic (6-decimal USDC → 10000 = $0.01)+ "maxTimeoutSeconds": 600,+ "extra": {+ "name": "USDC",+ "decimals": 6,+ "feePayer": "<facilitator fee-payer pubkey>"+ }+ },+ "buyer": "<buyer wallet pubkey>"+}+```++**Response**++```json+{ "network": "solana:5eykt4Us…", "tx_base64": "<base64 VersionedTransaction>" }+```++`tx_base64` is a v0 `VersionedTransaction` whose fee payer is+`accept.extra.feePayer`, carrying the SPL transfer instruction (and the x402+reference / memo your facilitator expects). The buyer's wallet adds its+signature; the facilitator adds the fee-payer signature at settle time.++### `POST ?action=encode`++Wrap the buyer-signed transaction into the `X-PAYMENT` header value.++**Request body**++```jsonc+{+ "accept": { /* same accept as prepare */ },+ "signed_tx_base64": "<base64 of the wallet-signed VersionedTransaction>",+ "resource_url": "https://api.acme.com/paid/route", // the merchant endpoint+ "builder_code": { "a": "…", "s": ["…"], "w": "…" } // optional, echoed from the 402+}+```++**Response**++```json+{ "x_payment": "<base64 x402 paymentPayload>" }+```++The modal then re-sends the original request to `resource_url` with+`X-PAYMENT: <x_payment>`; your x402 merchant middleware verifies and settles it.++## Reference implementation++A production implementation backs three.ws at `api/x402-checkout.js`. Its shape:++```js+// POST /api/x402-checkout?action=prepare|encode+import {+ Connection, PublicKey, TransactionMessage, VersionedTransaction,+} from '@solana/web3.js';+import {+ getAssociatedTokenAddressSync, createTransferCheckedInstruction,+} from '@solana/spl-token';++export default async function handler(req, res) {+ const action = new URL(req.url, 'http://x').searchParams.get('action');+ if (action === 'prepare') return prepare(req, res);+ if (action === 'encode') return encode(req, res);+ return res.status(404).json({ error: 'not_found' });+}++async function prepare(req, res) {+ const { accept, buyer } = await readJson(req);+ const conn = new Connection(process.env.SOLANA_RPC, 'confirmed');+ const mint = new PublicKey(accept.asset);+ const payerKey = new PublicKey(buyer);+ const feePayer = new PublicKey(accept.extra.feePayer);+ const fromAta = getAssociatedTokenAddressSync(mint, payerKey);+ const toAta = getAssociatedTokenAddressSync(mint, new PublicKey(accept.payTo));++ const ix = createTransferCheckedInstruction(+ fromAta, mint, toAta, payerKey, BigInt(accept.amount), accept.extra.decimals,+ );+ // …append the x402 reference account / memo your facilitator requires…++ const { blockhash } = await conn.getLatestBlockhash('confirmed');+ const msg = new TransactionMessage({+ payerKey: feePayer, recentBlockhash: blockhash, instructions: [ix],+ }).compileToV0Message();+ const tx = new VersionedTransaction(msg);++ res.json({ network: accept.network, tx_base64: Buffer.from(tx.serialize()).toString('base64') });+}++async function encode(req, res) {+ const { accept, signed_tx_base64, resource_url, builder_code } = await readJson(req);+ const paymentPayload = {+ x402Version: 2,+ scheme: 'exact',+ network: accept.network,+ resource: { url: resource_url, mimeType: 'application/json' },+ accepted: accept,+ payload: { transaction: signed_tx_base64 },+ ...(builder_code ? { extensions: { 'builder-code': builder_code } } : {}),+ };+ res.json({ x_payment: Buffer.from(JSON.stringify(paymentPayload)).toString('base64') });+}+```++Adapt the instruction list, reference accounts, and `paymentPayload.payload`+shape to whatever your x402 **facilitator** expects (e.g. PayAI, Coinbase CDP).+The modal is agnostic to those details — it only cares that `prepare` returns a+signable `tx_base64` and `encode` returns a ready-to-send `x_payment`.++## Hardening checklist++- **Rate-limit `prepare`** — it fans out to multiple RPC round-trips per call.+- **Validate `accept`** against your own catalog; never trust a client-supplied+ `payTo`, `asset`, or `amount` blindly — re-derive them server-side from the+ resource being purchased.+- **Pin the blockhash freshness** so signed transactions can't be replayed after+ expiry.+- **CORS**: if the script and the helper are on different origins, allow the+ script's origin on `/api/x402-checkout`.diff --git a/x402-modal-sdk/docs/CONFIGURATION.md b/x402-modal-sdk/docs/CONFIGURATION.mdnew file mode 100644index 000000000..dc31b589a--- /dev/null+++ b/x402-modal-sdk/docs/CONFIGURATION.md@@ -0,0 +1,106 @@+# Configuration reference++Three ways to configure, in increasing specificity (later wins):++1. **`data-x402-*` on the `/global` script tag** — declarative, no JS.+2. **`configure({ … })`** — global defaults, set once at startup.+3. **`pay({ … })` options** — per-call overrides.++All defaults reproduce the hosted three.ws modal, so an un-configured drop-in+behaves exactly like `https://three.ws/x402.js`.++---++## `configure(config)` / `getConfig()`++```js+import { configure, getConfig } from '@three-ws/x402-modal';+configure({ apiOrigin: 'https://pay.example.com' });+getConfig(); // → fully-resolved snapshot+```++| field | type | default | purpose |+|---|---|---|---|+| `apiOrigin` | `string \| null` | `null` → script origin | Origin of the Solana `prepare`/`encode` helper. `''` = same-origin. Ignored by the EVM path. |+| `brand` | `{ label?, href? }` | `Powered by three.ws` → `https://three.ws` | Footer attribution. Merge-updated (set only `label` and `href` survives). |+| `builderCode` | `{ wallet?, service? } \| null` | `{ wallet: '3d_agent', service: '3d_agent_modal' }` | ERC-8021 self-attribution echoed when the `402` declares a builder code. `null` disables the echo. Codes must match `^[a-z0-9_]{1,32}$`. |+| `solanaWeb3Url` | `string` | `esm.sh/@solana/[email protected]` | CDN module dynamic-imported on the Solana path. Repoint to self-host under a strict CSP. |+| `nobleHashesUrl` | `string` | `esm.sh/@noble/[email protected]/sha3` | CDN keccak module, used only for EVM SIWX sign-in. |++`configure()` merges: `configure({ brand: { label: 'X' } })` keeps the existing+`href`. Pass `apiOrigin: null` to reset to script-origin resolution; pass+`builderCode: null` to switch the echo off.++---++## `pay(options)`++| option | type | default | notes |+|---|---|---|---|+| `endpoint` | `string` | — (**required**) | the x402-protected URL |+| `method` | `string` | `GET`, or `POST` if `body` set | HTTP method |+| `body` | `object \| string` | — | object is JSON-encoded; string sent as-is |+| `headers` | `Record<string,string>` | — | merged into discovery + paid requests |+| `merchant` | `string` | `Payment` | modal header line 1 |+| `action` | `string` | `Pay-per-call` | modal header line 2 |+| `caps` | `SpendingCaps` | — | per-wallet µUSD caps (below) |+| `autoConnect` | `boolean` | `false` | skip the picker when exactly one wallet is detected |+| `apiOrigin` | `string` | global config | per-call Solana backend override |+| `brand` | `{ label?, href? }` | global config | per-call footer override |++### `SpendingCaps`++```ts+{ maxPerCall?: number|string, maxPerHour?: number|string, maxPerDay?: number|string }+```++Micro-USD (`1_000_000` = `$1`). Tracked per wallet address in `localStorage`,+bucketed by rolling UTC hour and day. Stablecoins convert exactly; non-stable+assets pass through atomic (cap those server-side). A breach is rejected before+the wallet prompt; a downstream failure rolls the reservation back.++---++## `data-x402-*` attributes++### On the `/global` `<script>` tag (global config)++| attribute | maps to |+|---|---|+| `data-x402-api-origin` | `apiOrigin` |+| `data-x402-brand-label` | `brand.label` |+| `data-x402-brand-href` | `brand.href` |+| `data-x402-builder-wallet` | `builderCode.wallet` |+| `data-x402-builder-service` | `builderCode.service` |+| `data-x402-builder-disable` | `builderCode = null` (presence or `"true"`) |+| `data-x402-solana-web3-url` | `solanaWeb3Url` |+| `data-x402-noble-hashes-url` | `nobleHashesUrl` |++### On a clickable element (per-button `pay()` options)++| attribute | maps to |+|---|---|+| `data-x402-endpoint` | `endpoint` (**required** to bind) |+| `data-x402-method` | `method` |+| `data-x402-body` | `body` (JSON parsed; falls back to raw string) |+| `data-x402-headers` | `headers` (JSON) |+| `data-x402-caps` | `caps` (JSON) |+| `data-x402-api-origin` | `apiOrigin` |+| `data-x402-merchant` | `merchant` |+| `data-x402-action` | `action` (defaults to the element's text) |++---++## Theming++The modal injects one stylesheet (`#x402-styles`) scoped to `.x402-*` classes,+with full `prefers-color-scheme` light/dark support and a `prefers-reduced-motion`+-friendly animation. To restyle, override those classes after the script loads:++```css+.x402-modal { border-radius: 8px; }+.x402-pay-btn { background: #6d28d9; }+```++The footer text/link is set by `brand`; the two header lines by+`merchant` / `action`.diff --git a/x402-modal-sdk/docs/PROTOCOL.md b/x402-modal-sdk/docs/PROTOCOL.mdnew file mode 100644index 000000000..50e0036dd--- /dev/null+++ b/x402-modal-sdk/docs/PROTOCOL.md@@ -0,0 +1,102 @@+# The x402 flow, as this modal drives it++A reference for what happens between `pay()` and the resolved receipt. Useful+when debugging an integration or building the server side.++## The four steps++```+┌── 1. DISCOVER ──────────────────────────────────────────────────────────┐+│ The modal sends the request you described (endpoint/method/body/headers) │+│ with NO payment. It expects one of: │+│ • HTTP 402 with a JSON body containing `accepts[]`, or │+│ • HTTP 401 with a base64-JSON `payment-required` header (MCP 2025-06-18)│+│ Anything else (200, etc.) is surfaced as an error — pointing the modal at │+│ a free endpoint must not silently "succeed". │+└───────────────────────────────────────────────────────────────────────────┘+ │ accepts[] = [{ scheme, network, asset,+ │ payTo, amount, extra… }, …]+ ▼+┌── 2. CONNECT ───────────────────────────────────────────────────────────┐+│ The modal picks accepts it can satisfy: │+│ • Solana (`solana:*`) → Phantom (`window.solana` / `window.phantom`) │+│ • EVM (`eip155:*`) → `window.ethereum` (EIP-3009 entries only; │+│ Permit2 siblings are skipped) │+│ >1 viable → wallet picker. Exactly 1 + `autoConnect` → straight through. │+│ Spending caps (if set) are checked here, before any signature prompt. │+└───────────────────────────────────────────────────────────────────────────┘+ ▼+┌── 3. AUTHORIZE ─────────────────────────────────────────────────────────┐+│ Solana: │+│ POST {apiOrigin}/api/x402-checkout?action=prepare {accept,buyer} │+│ → tx_base64 (built server-side; fee payer = facilitator) │+│ Phantom signs the VersionedTransaction │+│ POST …?action=encode {accept, signed_tx_base64, resource_url, …} │+│ → x_payment (base64 paymentPayload) │+│ EVM: │+│ wallet signs an EIP-3009 TransferWithAuthorization (typed data v4) │+│ the modal assembles x_payment locally — no backend, no gas, no tx │+└───────────────────────────────────────────────────────────────────────────┘+ ▼+┌── 4. VERIFY & SETTLE ───────────────────────────────────────────────────┐+│ Re-send the original request with header `X-PAYMENT: <x_payment>`. │+│ The server VERIFIES the payment, RUNS the work, SETTLES on-chain, and │+│ returns 200 with an `x-payment-response` header (base64 receipt: │+│ network, payer, transaction). The modal renders the receipt + result. │+└───────────────────────────────────────────────────────────────────────────┘+```++## Why settlement-after-work makes retries safe++x402 servers verify and *settle* the payment only **after** the protected work+succeeds. So if the merchant returns a transient `429` (an upstream rate-limit+hit *before* settlement), the exact same signed `X-PAYMENT` can be re-sent once+the window resets with **no risk of a double charge**. The modal auto-retries a+`429` up to twice, honoring `Retry-After`, with a live countdown, before falling+back to a manual **Try again**.++## SIWX re-entry (optional)++If the `402` body includes an `extensions['sign-in-with-x']` block, the modal+leads with **"Sign in with wallet"**: a buyer who already paid for this resource+can re-enter by signing a CAIP-122 challenge (submitted via the+`SIGN-IN-WITH-X` header) instead of paying again. If the server responds that+this wallet hasn't actually paid (`401/402` + `siwx_not_paid`), the modal+transparently falls back to the normal payment flow with a one-line notice.++The message string the modal signs is byte-compatible with the+[siwe](https://github.com/spruceid/siwe) (EVM) and SIWS (Solana) formats so the+server's recovered signer matches `payload.address`. See `buildSiwxMessage` in+`src/util.js`.++## ERC-8021 builder codes++When the `402` declares a builder code under+`extensions['builder-code'].info.a`, the modal echoes it back (anti-tamper: the+server checks the echoed `a` equals what it declared) and self-attributes its+own wallet (`w`) and service (`s`) codes from+[`configure({ builderCode })`](./CONFIGURATION.md). Set `builderCode: null` to+disable the echo.++## The `accept` object++| field | meaning |+|---|---|+| `scheme` | payment scheme — `exact` for a fixed price |+| `network` | CAIP-2 id: `solana:<genesis>` or `eip155:<chainId>` |+| `asset` | token: SPL mint (Solana) or ERC-20 address (EVM) |+| `payTo` | recipient wallet |+| `amount` | atomic amount (the modal also reads spec-canonical `maxAmountRequired`) |+| `maxTimeoutSeconds` | EVM EIP-3009 `validBefore` window (default 600) |+| `extra.name` | display + stablecoin detection (`USDC`, `USDT`, `DAI`…) |+| `extra.decimals` | token decimals (default 6) |+| `extra.version` | EVM EIP-712 domain version (Base USDC = `"2"`) |+| `extra.feePayer` | Solana facilitator fee-payer pubkey (Solana only) |+| `extra.assetTransferMethod` | `eip3009` (default) or `permit2` (skipped by this modal) |++## Spec references++- x402 — <https://x402.org>+- CAIP-2 network ids — <https://chainagnostic.org/CAIPs/caip-2>+- EIP-3009 `transferWithAuthorization` — <https://eips.ethereum.org/EIPS/eip-3009>+- CAIP-122 / Sign-In-With-X — <https://chainagnostic.org/CAIPs/caip-122>diff --git a/x402-modal-sdk/examples/index.html b/x402-modal-sdk/examples/index.htmlnew file mode 100644index 000000000..1029dd3c0--- /dev/null+++ b/x402-modal-sdk/examples/index.html@@ -0,0 +1,115 @@+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <title>@three-ws/x402-modal — demo</title>+ <style>+ :root { color-scheme: light dark; }+ * { box-sizing: border-box; }+ body {+ margin: 0; font: 16px/1.6 -apple-system, system-ui, sans-serif;+ background: #0b0c10; color: #e9eaf0;+ min-height: 100vh; padding: 64px 24px 120px;+ }+ main { max-width: 680px; margin: 0 auto; }+ h1 { font-size: 36px; line-height: 1.1; margin: 0 0 8px; letter-spacing: -0.02em; }+ .lede { font-size: 18px; color: #aab; margin: 0 0 36px; }+ h2 { font-size: 20px; margin: 40px 0 10px; }+ p { color: #c7c9d6; }+ code { background: #15161e; padding: 2px 6px; border-radius: 6px; font-size: 14px; }+ .card {+ background: #12131b; border: 1px solid #23252f; border-radius: 16px;+ padding: 22px; margin: 16px 0;+ }+ button.cta {+ cursor: pointer; border: none; border-radius: 12px;+ background: linear-gradient(135deg, #0a84ff, #0066d6); color: #fff;+ padding: 13px 20px; font: inherit; font-weight: 700; letter-spacing: -0.01em;+ }+ button.cta:hover { filter: brightness(1.08); }+ pre {+ background: #0e0f16; border: 1px solid #23252f; border-radius: 12px;+ padding: 14px; overflow: auto; font-size: 13px; color: #cfd2e3;+ margin-top: 14px; white-space: pre-wrap; word-break: break-word;+ }+ .muted { color: #7b7f93; font-size: 13px; }+ .err { color: #f87171; }+ </style>+</head>+<body>+ <main>+ <h1>@three-ws/x402-modal</h1>+ <p class="lede">A drop-in payment modal for any x402 paid endpoint. Two ways to wire it, both below.</p>++ <h2>1 — Declarative (<code>data-x402-*</code>)</h2>+ <p>The button below is bound automatically by the global script. Point+ <code>data-x402-endpoint</code> at your own x402 route to try it live.</p>+ <div class="card">+ <button+ class="cta"+ id="declarative"+ data-x402-endpoint="https://three.ws/api/x402/dance-tip?dancer=1&dance=rumba"+ data-x402-merchant="three.ws"+ data-x402-action="Tip a dancer">+ Pay & tip+ </button>+ <pre id="declarative-out" class="muted">result will appear here…</pre>+ </div>++ <h2>2 — Programmatic (<code>pay()</code>)</h2>+ <p>Call <code>pay()</code> from your own handler and await the result.</p>+ <div class="card">+ <button class="cta" id="programmatic">Pay with pay()</button>+ <pre id="programmatic-out" class="muted">result will appear here…</pre>+ </div>++ <p class="muted">+ This page loads the local build at <code>../dist/x402.global.js</code>.+ Run <code>npm run build</code> in the package root first, then serve this+ folder (e.g. <code>npx serve</code>) and open it. The demo endpoint is a+ live three.ws x402 route; swap it for your own.+ </p>+ </main>++ <!-- Local build. In production, use the CDN:+ <script type="module" src="https://unpkg.com/@three-ws/x402-modal/global"></script> -->+ <script type="module" src="../dist/x402.global.js"></script>++ <script type="module">+ import { pay } from '../dist/x402-modal.mjs';++ // Declarative button → listen for the DOM events the global build fires.+ const dEl = document.getElementById('declarative');+ const dOut = document.getElementById('declarative-out');+ dEl.addEventListener('x402:result', (e) => {+ dOut.classList.remove('muted', 'err');+ dOut.textContent = JSON.stringify(e.detail.result, null, 2);+ });+ dEl.addEventListener('x402:error', (e) => {+ dOut.classList.add('err');+ dOut.textContent = 'Error: ' + e.detail.error;+ });++ // Programmatic button → await pay().+ const pOut = document.getElementById('programmatic-out');+ document.getElementById('programmatic').addEventListener('click', async () => {+ pOut.className = 'muted';+ pOut.textContent = 'opening modal…';+ try {+ const out = await pay({+ endpoint: 'https://three.ws/api/x402/dance-tip?dancer=1&dance=rumba',+ merchant: 'three.ws',+ action: 'Tip a dancer',+ });+ pOut.className = '';+ pOut.textContent = JSON.stringify({ result: out.result, payment: out.payment }, null, 2);+ } catch (e) {+ if (e.code === 'cancelled') { pOut.className = 'muted'; pOut.textContent = 'cancelled.'; return; }+ pOut.className = 'err';+ pOut.textContent = 'Error: ' + e.message;+ }+ });+ </script>+</body>+</html>diff --git a/x402-modal-sdk/examples/server.mjs b/x402-modal-sdk/examples/server.mjsnew file mode 100644index 000000000..fd9ccd89b--- /dev/null+++ b/x402-modal-sdk/examples/server.mjs@@ -0,0 +1,144 @@+// examples/server.mjs — reference Solana checkout helper for @three-ws/x402-modal.+//+// The EVM/Base payment path is fully client-side and needs NO backend. This+// helper exists only for the Solana path, which must build a transfer+// transaction (RPC + facilitator fee-payer) for Phantom to sign.+//+// It implements the two actions the modal calls:+// POST /api/x402-checkout?action=prepare { accept, buyer }+// → { network, tx_base64 }+// POST /api/x402-checkout?action=encode { accept, signed_tx_base64, resource_url, builder_code? }+// → { x_payment }+//+// Run it:+// npm i @solana/web3.js @solana/spl-token+// SOLANA_RPC="https://api.mainnet-beta.solana.com" node examples/server.mjs+//+// Then point the modal at it:+// configure({ apiOrigin: 'http://localhost:8787' })+//+// In production, validate `accept` against your own catalog (never trust a+// client-supplied payTo/asset/amount), rate-limit `prepare`, and shape+// `payload` to whatever your x402 facilitator expects. See ../docs/BACKEND.md.++import { createServer } from 'node:http';+import {+ Connection,+ PublicKey,+ TransactionMessage,+ VersionedTransaction,+} from '@solana/web3.js';+import {+ getAssociatedTokenAddressSync,+ createTransferCheckedInstruction,+} from '@solana/spl-token';++const PORT = Number(process.env.PORT || 8787);+const RPC = process.env.SOLANA_RPC || 'https://api.mainnet-beta.solana.com';+const connection = new Connection(RPC, 'confirmed');++function isSolana(net) {+ return typeof net === 'string' && (net === 'solana' || net.startsWith('solana:'));+}++async function readJson(req) {+ const chunks = [];+ for await (const c of req) chunks.push(c);+ return JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');+}++function json(res, status, body) {+ const payload = JSON.stringify(body);+ res.writeHead(status, {+ 'content-type': 'application/json',+ // Allow cross-origin use when the script is served from another origin.+ 'access-control-allow-origin': '*',+ 'access-control-allow-headers': 'content-type',+ 'access-control-allow-methods': 'POST, OPTIONS',+ });+ res.end(payload);+}++async function handlePrepare(req, res) {+ const { accept, buyer } = await readJson(req);+ if (!isSolana(accept?.network)) {+ return json(res, 400, {+ error: 'wrong_network',+ error_description: 'prepare only builds Solana transactions; EVM clients sign EIP-3009 locally.',+ });+ }++ const mint = new PublicKey(accept.asset);+ const buyerKey = new PublicKey(buyer);+ const payTo = new PublicKey(accept.payTo);+ const feePayer = new PublicKey(accept.extra.feePayer);+ const decimals = Number(accept.extra.decimals ?? 6);+ const amount = BigInt(accept.amount);++ const fromAta = getAssociatedTokenAddressSync(mint, buyerKey);+ const toAta = getAssociatedTokenAddressSync(mint, payTo);++ const ix = createTransferCheckedInstruction(+ fromAta, mint, toAta, buyerKey, amount, decimals,+ );+ // Append the x402 reference account your facilitator watches for settlement.+ // Many facilitators expect a read-only reference pubkey on the transfer ix:+ if (accept.extra.reference) {+ ix.keys.push({ pubkey: new PublicKey(accept.extra.reference), isSigner: false, isWritable: false });+ }++ const { blockhash } = await connection.getLatestBlockhash('confirmed');+ const message = new TransactionMessage({+ payerKey: feePayer,+ recentBlockhash: blockhash,+ instructions: [ix],+ }).compileToV0Message();+ const tx = new VersionedTransaction(message);++ return json(res, 200, {+ network: accept.network,+ tx_base64: Buffer.from(tx.serialize()).toString('base64'),+ });+}++async function handleEncode(req, res) {+ const { accept, signed_tx_base64, resource_url, builder_code } = await readJson(req);+ if (!signed_tx_base64 || !resource_url) {+ return json(res, 400, { error: 'bad_request', error_description: 'signed_tx_base64 and resource_url are required' });+ }++ // Standard Solana exact-scheme payload. Adapt `payload` to your facilitator.+ const paymentPayload = {+ x402Version: 2,+ scheme: 'exact',+ network: accept.network,+ resource: { url: resource_url, mimeType: 'application/json' },+ accepted: accept,+ payload: { transaction: signed_tx_base64 },+ ...(builder_code ? { extensions: { 'builder-code': builder_code } } : {}),+ };++ return json(res, 200, {+ x_payment: Buffer.from(JSON.stringify(paymentPayload), 'utf8').toString('base64'),+ });+}++const server = createServer(async (req, res) => {+ try {+ if (req.method === 'OPTIONS') return json(res, 204, {});+ const url = new URL(req.url, `http://${req.headers.host}`);+ if (req.method === 'POST' && url.pathname === '/api/x402-checkout') {+ const action = url.searchParams.get('action');+ if (action === 'prepare') return await handlePrepare(req, res);+ if (action === 'encode') return await handleEncode(req, res);+ return json(res, 404, { error: 'not_found', error_description: `unknown action: ${action ?? '(none)'}` });+ }+ return json(res, 404, { error: 'not_found' });+ } catch (err) {+ return json(res, 500, { error: 'server_error', error_description: String(err?.message || err) });+ }+});++server.listen(PORT, () => {+ console.log(`x402-checkout helper on http://localhost:${PORT} (RPC: ${RPC})`);+});diff --git a/x402-payment-modal/README.md b/x402-payment-modal/README.mdnew file mode 100644index 000000000..d3cce980b--- /dev/null+++ b/x402-payment-modal/README.md@@ -0,0 +1,308 @@+# @three-ws/x402-payment-modal++**A drop-in payment modal for any [x402](https://x402.org) paid endpoint.** One ES+module, zero runtime dependencies. It turns an HTTP `402 Payment Required`+challenge into a polished checkout: wallet connect (Phantom on Solana, MetaMask /+any EVM wallet on Base via EIP-3009), the `402 → sign → settle` flow, optional+SIWX re-entry, client-side spending caps, and a receipt — vanilla JS, no bundler+required.++```html+<script type="module" src="https://unpkg.com/@three-ws/x402-payment-modal"></script>++<button+ data-x402-endpoint="https://api.example.com/paid/summarize"+ data-x402-method="POST"+ data-x402-body='{"text":"hello"}'+ data-x402-merchant="Acme"+ data-x402-action="Summarize">+ Pay & Run+</button>+```++That's the whole integration. Clicking the button opens the modal, runs the+payment, calls your endpoint with the signed `X-PAYMENT` header, and fires an+`x402:result` event with the response.++---++## Why++x402 lets any HTTP endpoint charge a micropayment per call: the server answers an+unpaid request with `402` and a list of accepted payments; the client pays and+retries with an `X-PAYMENT` header. The protocol is simple — the *wallet UX* is+not. This package is the missing front end: a single, framework-agnostic modal+that handles wallet detection, chain switching, signing, settlement, errors,+throttle retries, and the receipt, so you ship a paid endpoint in minutes.++- **Zero dependencies, zero build.** Plain ES module. Drop in a `<script>` tag or+ `import` it. The Solana/EVM crypto helpers are loaded lazily from a CDN *only*+ when a payment is actually attempted.+- **Solana + EVM.** Phantom (Solana USDC) and any injected EVM wallet (Base USDC+ via EIP-3009 `transferWithAuthorization`). The modal picks the right path from+ the 402 challenge.+- **SIWX re-entry.** If a wallet already paid for a resource, it can sign back in+ instead of paying again. See [docs/siwx.md](docs/siwx.md).+- **Spending caps.** Optional per-call / hourly / daily caps enforced in the+ browser. See [docs/spending-caps.md](docs/spending-caps.md).+- **Themeable.** Light + automatic dark mode, all classes overridable. See+ [docs/theming.md](docs/theming.md).+- **Accessible.** Focus management, `aria-modal`, keyboard `Esc` to close.++---++## Install++**Via CDN (no build step):**++```html+<script type="module" src="https://unpkg.com/@three-ws/x402-payment-modal"></script>+```++**Via npm (bundler / framework):**++```bash+npm install @three-ws/x402-payment-modal+```++```js+import { pay, configure } from '@three-ws/x402-payment-modal';+```++For Solana payments you also run a tiny server endpoint — install the optional+peer deps there:++```bash+npm install @solana/web3.js @solana/spl-token+```++> EVM-only sites need **nothing** server-side: the wallet signs EIP-3009+> typed-data entirely in the browser.++---++## Quick start++### 1. Declarative (HTML attributes)++Any element with `data-x402-endpoint` is auto-bound on load and re-scanned as the+DOM changes:++```html+<button+ data-x402-endpoint="/api/paid/translate"+ data-x402-method="POST"+ data-x402-body='{"text":"bonjour","to":"en"}'+ data-x402-merchant="Acme Translate"+ data-x402-action="Translate">+ Translate ($0.01)+</button>++<script type="module" src="https://unpkg.com/@three-ws/x402-payment-modal"></script>++<script>+ document.querySelector('button').addEventListener('x402:result', (e) => {+ console.log('paid + result:', e.detail.result);+ });+</script>+```++### 2. Programmatic++```js+import { pay } from '@three-ws/x402-payment-modal';++try {+ const { result, payment } = await pay({+ endpoint: '/api/paid/translate',+ method: 'POST',+ body: { text: 'bonjour', to: 'en' },+ merchant: 'Acme Translate',+ action: 'Translate',+ });+ console.log(result, 'tx:', payment?.transaction);+} catch (err) {+ if (err.code !== 'cancelled') console.error(err);+}+```++See the runnable [examples/](examples/) — plain HTML, React, and an Express+server.++---++## How it works++```+ click ──▶ GET/POST endpoint+ │+ ▼ HTTP 402 { accepts: [ {network, amount, asset, payTo, ...} ] }+ ┌─────────────┐+ │ discover │ modal shows price + network+ └─────────────┘+ │+ ▼+ ┌─────────────┐+ │ connect │ Phantom (Solana) or EVM wallet (Base)+ └─────────────┘+ │+ ┌────┴───────────────────────────────────────┐+ ▼ Solana ▼ EVM+ POST /api/x402-checkout?action=prepare sign EIP-3009+ Phantom signTransaction transferWithAuthorization+ POST /api/x402-checkout?action=encode (browser only — no server)+ └────┬───────────────────────────────────────┘+ ▼+ ┌─────────────┐+ │ verify │ retry endpoint with `X-PAYMENT: <base64>`+ └─────────────┘ (auto-retries once on a 429 throttle)+ │+ ▼ 200 + `X-PAYMENT-RESPONSE` settlement header+ receipt + result+```++Full walkthrough in [docs/architecture.md](docs/architecture.md).++---++## Client API++| Export | Signature | Purpose |+| --- | --- | --- |+| `pay` | `pay(opts) => Promise<PayResult>` | Open the modal and run a payment. |+| `configure` | `configure(opts) => Config` | Set checkout origin, branding, builder-code, CDN URLs. |+| `init` | `init() => void` | Bind `[data-x402-endpoint]` elements (auto-called). |+| `version` | `string` | Library version. |++Also exposed as `window.X402.{ pay, init, configure, version }` for inline+scripts.++**`pay(opts)`** — `opts`:++| Field | Type | Notes |+| --- | --- | --- |+| `endpoint` | `string` | **Required.** The paid (x402) URL. |+| `method` | `string` | Default `GET`, or `POST` when `body` is set. |+| `body` | `object \| string` | Objects are JSON-stringified. |+| `headers` | `object` | Extra headers merged into the paid call. |+| `merchant` | `string` | Shown in the modal header. |+| `action` | `string` | Shown in the modal header. |+| `autoConnect` | `boolean` | Skip the picker when exactly one wallet is detected. |+| `caps` | `SpendingCaps` | `{ maxPerCall, maxPerHour, maxPerDay }` in atomic micro-USD. |++Resolves to `PayResult`: `{ ok: true, result, payment?: { network, transaction,+payer }, siwx?: { address, network }, response: { status, headers } }`. Rejects+with an `Error` whose `.code === 'cancelled'` when the user closes the modal.++**DOM events** (bubbling `CustomEvent`s on the clicked element):+`x402:result` (`detail` = `PayResult`), `x402:error` (`detail` = `{ error }`),+`x402:siwx-signed` (`detail` = `{ address, network }`).++Full reference: [docs/api-reference.md](docs/api-reference.md).++---++## Configuration++Defaults work out of the box. Override host-specific bits with `configure()`:++```js+import { configure } from '@three-ws/x402-payment-modal';++configure({+ checkoutOrigin: 'https://pay.acme.com', // where your Solana checkout endpoint lives+ brand: { name: 'Acme', url: 'https://acme.com' },+ footerNote: 'Acme Pay',+});+```++…or with `data-*` attributes on the script tag (no inline module needed):++```html+<script type="module"+ src="https://unpkg.com/@three-ws/x402-payment-modal"+ data-x402-checkout-origin="https://pay.acme.com"+ data-x402-brand-name="Acme"+ data-x402-brand-url="https://acme.com"></script>+```++| Option | `data-*` attribute | Default |+| --- | --- | --- |+| `checkoutOrigin` | `data-x402-checkout-origin` | the script's own origin |+| `checkoutPath` | `data-x402-checkout-path` | `/api/x402-checkout` |+| `footerNote` | `data-x402-footer-note` | `x402 · onchain settled` |+| `brand.name` / `brand.url` | `data-x402-brand-name` / `-brand-url` | `three.ws` |+| `builderCode.wallet` / `.service` | `data-x402-builder-wallet` / `-builder-service` | three.ws codes |+| `esm.solanaWeb3` / `esm.nobleHashesSha3` | — | pinned esm.sh URLs |++Repoint `esm.*` at a self-hosted mirror if a strict Content-Security-Policy+blocks `esm.sh`. (The EVM/Base path needs no third-party code at all.)++---++## Server (Solana only)++Phantom signs serialized transactions but doesn't build instructions, so the+Solana path needs a tiny endpoint to build the SPL transfer and wrap the signed+tx into the `X-PAYMENT` envelope. The package ships it.++**Express:**++```js+import express from 'express';+import { x402CheckoutRouter } from '@three-ws/x402-payment-modal/server/express';++const app = express();+app.use(express.json());+app.use('/api/x402-checkout', x402CheckoutRouter({ rpcUrl: process.env.SOLANA_RPC_URL }));+app.listen(3000);+```++**Vercel / Next.js** — `api/x402-checkout.js`:++```js+export { default } from '@three-ws/x402-payment-modal/server/vercel';+```++Lower-level helpers (`prepareSolanaCheckout`, `encodeX402Payment`,+`handleCheckout`, `CheckoutError`) are exported from+`@three-ws/x402-payment-modal/server`. Full guide:+[docs/server-setup.md](docs/server-setup.md).++---++## Documentation++- [Architecture](docs/architecture.md) — the full payment lifecycle.+- [Client API reference](docs/api-reference.md)+- [Server setup](docs/server-setup.md)+- [Theming](docs/theming.md)+- [SIWX re-entry](docs/siwx.md)+- [Spending caps](docs/spending-caps.md)+- [Tutorial](TUTORIAL.md) — build a paid endpoint end-to-end.++---++## Browser support++Modern evergreen browsers (ES2020, `BigInt`, dynamic `import()`, `fetch`,+`crypto.getRandomValues`). The Solana wallet path requires+[Phantom](https://phantom.app); the EVM path requires an injected wallet+(`window.ethereum`).++## Security++- Payments are signed in the user's wallet — this package never sees a private+ key. The Solana checkout server only builds an unsigned transaction and base64-+ wraps the user-signed one; it cannot move funds.+- Spending caps are a **client-side guardrail**, not a security boundary — a user+ can clear `localStorage`. Enforce real limits server-side.+- Pin the script to a version or self-host it for production.++## License++[Apache-2.0](LICENSE) © three.ws++> Maintained inside the [three.ws](https://three.ws) monorepo and published as a+> standalone package. Issues and PRs:+> <https://github.com/nirholas/three.ws/issues>.diff --git a/x402-payment-modal/TUTORIAL.md b/x402-payment-modal/TUTORIAL.mdnew file mode 100644index 000000000..4cbe207bf--- /dev/null+++ b/x402-payment-modal/TUTORIAL.md@@ -0,0 +1,188 @@+# Tutorial: ship a paid endpoint with x402++This walks you from an empty folder to a working page where a user pays USDC to+call your API — using `@three-ws/x402-payment-modal` for the front end. It takes+about 15 minutes.++By the end you'll have:++1. A paid HTTP endpoint that answers `402` until it sees a valid payment.+2. A button that opens the payment modal and runs the call.+3. The Solana checkout endpoint the modal needs (skip this if you only take EVM).++> **Prerequisites:** Node 18+, and a browser with [Phantom](https://phantom.app)+> (Solana) and/or an EVM wallet like MetaMask. You'll need a little USDC on Base+> or Solana to test a real payment end-to-end.++---++## Part 1 — The front end (5 minutes)++Create `index.html`:++```html+<!doctype html>+<html>+ <head>+ <meta charset="utf-8" />+ <title>Paid endpoint demo</title>+ </head>+ <body>+ <h1>Summarize anything — $0.01</h1>++ <button+ id="summarize"+ data-x402-endpoint="https://api.example.com/paid/summarize"+ data-x402-method="POST"+ data-x402-body='{"text":"The quick brown fox..."}'+ data-x402-merchant="Acme AI"+ data-x402-action="Summarize">+ Pay & Summarize+ </button>++ <pre id="out"></pre>++ <script type="module" src="https://unpkg.com/@three-ws/x402-payment-modal"></script>+ <script>+ const out = document.getElementById('out');+ const btn = document.getElementById('summarize');+ btn.addEventListener('x402:result', (e) => {+ out.textContent = JSON.stringify(e.detail.result, null, 2);+ });+ btn.addEventListener('x402:error', (e) => {+ out.textContent = 'Error: ' + e.detail.error;+ });+ </script>+ </body>+</html>+```++Open it in a browser and click the button. The modal appears, reads the price+from the endpoint's `402` response, and walks the user through paying. (Pointing+at `api.example.com` won't actually settle — we build a real endpoint next.)++That's the entire client integration. Everything below is the *server* you're+charging for.++---++## Part 2 — A paid endpoint (5 minutes)++A paid endpoint follows the x402 contract:++1. **No `X-PAYMENT` header →** respond `402` with a challenge describing what you+ accept.+2. **Valid `X-PAYMENT` header →** verify + settle it with an x402 facilitator,+ do the work, and return `200` with an `X-PAYMENT-RESPONSE` header.++Here's the challenge half (the part the modal reads). Create `server.js`:++```js+import express from 'express';++const app = express();+app.use(express.json());++// Atomic USDC is 6-decimal: 10000 = $0.01.+const PRICE_ATOMIC = '10000';++function challenge(req) {+ const url = `${req.protocol}://${req.get('host')}${req.originalUrl}`;+ return {+ x402Version: 2,+ error: 'X-PAYMENT header is required',+ resource: { url, description: 'Summarize text', mimeType: 'application/json' },+ accepts: [+ {+ scheme: 'exact',+ network: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp', // Solana mainnet+ amount: PRICE_ATOMIC,+ asset: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', // USDC mint+ payTo: 'REPLACE_WITH_YOUR_SOLANA_ADDRESS',+ maxTimeoutSeconds: 60,+ extra: {+ name: 'USDC',+ decimals: 6,+ // The facilitator sponsor that pays the SOL network fee so the buyer+ // needs only USDC. Provided by your x402 facilitator.+ feePayer: 'REPLACE_WITH_FACILITATOR_FEE_PAYER',+ },+ },+ ],+ };+}++app.post('/paid/summarize', (req, res) => {+ const xPayment = req.get('X-PAYMENT');+ if (!xPayment) {+ return res.status(402).json(challenge(req));+ }++ // 1. Verify + settle `xPayment` with your x402 facilitator here.+ // (See the x402 spec — facilitator /verify and /settle.)+ // 2. Do the actual work:+ const summary = `Summary of: ${String(req.body?.text || '').slice(0, 40)}…`;++ // 3. Return the result. Attach the base64 settlement as X-PAYMENT-RESPONSE.+ res.json({ summary });+});++app.listen(3000, () => console.log('http://localhost:3000'));+```++> Verifying and settling the `X-PAYMENT` payload against a facilitator is the+> server's responsibility and is beyond this modal's scope — see the+> [x402 spec](https://x402.org). The modal's job is everything on the client.++Point your button's `data-x402-endpoint` at `http://localhost:3000/paid/summarize`+and the modal will read your real price.++---++## Part 3 — The Solana checkout endpoint (5 minutes)++EVM payments are signed entirely in the browser, so if you only accept Base/EVM+USDC you can **stop here**. For Solana, Phantom can sign but not *build*+transactions, so the modal calls a small endpoint to build the transfer and wrap+the signed tx. The package ships it — mount it in the same server:++```bash+npm install @solana/web3.js @solana/spl-token+```++```js+import { x402CheckoutRouter } from '@three-ws/x402-payment-modal/server/express';++app.use(+ '/api/x402-checkout',+ x402CheckoutRouter({ rpcUrl: process.env.SOLANA_RPC_URL }),+);+```++The modal automatically POSTs to `/api/x402-checkout?action=prepare` and+`?action=encode` on the same origin as the script. If your checkout lives on a+different origin, tell the modal:++```js+import { configure } from '@three-ws/x402-payment-modal';+configure({ checkoutOrigin: 'https://pay.acme.com' });+```++Set a reliable RPC (a public endpoint is rate-limited):++```bash+SOLANA_RPC_URL="https://your-rpc-provider/..." node server.js+```++That's it — a full paid endpoint with a polished checkout.++---++## Where to go next++- **Brand the modal** → [docs/theming.md](docs/theming.md)+- **Let repeat buyers skip paying** → [docs/siwx.md](docs/siwx.md)+- **Cap how much a user can spend** → [docs/spending-caps.md](docs/spending-caps.md)+- **React / framework usage** → [examples/react/](examples/react/)+- **A runnable server** → [examples/server-express/](examples/server-express/)+- **The full lifecycle** → [docs/architecture.md](docs/architecture.md)diff --git a/x402-payment-modal/docs/api-reference.md b/x402-payment-modal/docs/api-reference.mdnew file mode 100644index 000000000..bd358d2e6--- /dev/null+++ b/x402-payment-modal/docs/api-reference.md@@ -0,0 +1,227 @@+# Client API reference++The browser entry point. Import it as an ES module, or drop the bundle on a page+and use `window.X402`. For how these pieces fit together see+[architecture](./architecture.md); for the Solana backend see+[server setup](./server-setup.md).++```js+import { pay, configure, init, version } from '@three-ws/x402-payment-modal';+```++When loaded as a script, the same functions are available as+`window.X402.{ pay, init, configure, version }`. The module also auto-binds+`[data-x402-endpoint]` elements on load (and re-binds new ones via a+`MutationObserver`).++```html+<script type="module" src="https://unpkg.com/@three-ws/x402-payment-modal"></script>+```++---++## `pay(opts) => Promise<PayResult>`++Opens the modal and drives the full pay flow against one endpoint. Resolves once+the merchant settles and returns a result. Rejects with an `Error` whose+`.code === 'cancelled'` if the user closes the modal.++```js+try {+ const res = await pay({+ endpoint: 'https://api.example.com/premium',+ method: 'POST',+ body: { prompt: 'Summarize this article' },+ merchant: 'Example API',+ action: 'Generate summary',+ autoConnect: true,+ });+ console.log(res.result); // the paid endpoint's response+ console.log(res.payment); // { network, transaction, payer }+} catch (err) {+ if (err.code === 'cancelled') return; // user closed the modal+ throw err;+}+```++### PayOptions++| Field | Type | Required | Description |+|---------------|---------------------------|----------|-----------------------------------------------------------------------------|+| `endpoint` | `string` | yes | The x402-protected URL to call. |+| `method` | `string` | no | HTTP method. Defaults to `GET` (or `POST` when a `body` is supplied). |+| `body` | `object \| string` | no | Request body. An object is JSON-stringified; a string is sent as-is. |+| `headers` | `object` | no | Extra request headers merged into both the probe and retry requests. |+| `merchant` | `string` | no | Merchant name shown in the modal header. |+| `action` | `string` | no | Short action label shown in the modal header (e.g. "Generate summary"). |+| `autoConnect` | `boolean` | no | Skip the wallet picker when exactly one wallet is detected. |+| `caps` | [`SpendingCaps`](./spending-caps.md) | no | Client-side spending limits, atomic micro-USD. |++### PayResult++```ts+{+ ok: true,+ result: unknown, // parsed JSON, or text, from the paid endpoint+ payment?: {+ network: string,+ transaction: string, // tx hash / signature+ payer: string, // payer address+ },+ siwx?: { // present when re-entry used Sign-In-With-X+ address: string,+ network: string,+ },+ response: {+ status: number,+ headers: Record<string, string>,+ },+}+```++---++## `configure(opts) => Config`++Sets global defaults. All fields are optional; nested objects are+**shallow-merged** into the current config. Returns the resulting config.++```js+import { configure } from '@three-ws/x402-payment-modal';++configure({+ checkoutOrigin: 'https://pay.example.com',+ checkoutPath: '/api/x402-checkout',+ brand: { name: 'Example', url: 'https://example.com' },+ footerNote: 'Secured by x402',+ builderCode: { wallet: 'examplewallet', service: 'example_api' },+ esm: {+ solanaWeb3: 'https://esm.sh/@solana/[email protected]',+ nobleHashesSha3: 'https://esm.sh/@noble/hashes@1/sha3',+ },+});+```++| Field | Type | Description |+|------------------|---------------------------------------|-----------------------------------------------------------------------------------------------|+| `checkoutOrigin` | `string \| null` | Origin serving the Solana checkout endpoint. `null` resolves it from the script `src` or page origin. |+| `checkoutPath` | `string` | Checkout path. Default `'/api/x402-checkout'`. |+| `brand` | `{ name, url }` | Footer attribution. |+| `footerNote` | `string` | Text on the left side of the footer. |+| `builderCode` | `{ wallet, service }` | ERC-8021 builder-code echo. Each value lowercase `[a-z0-9_]{1,32}`. |+| `esm` | `{ solanaWeb3, nobleHashesSha3 }` | CDN URLs for crypto helpers loaded on demand. Repoint for strict CSP / self-hosting. |++> The `checkoutOrigin` / `checkoutPath` settings only matter for the Solana rail.+> EVM-only sites can ignore them.++---++## `init()`++Re-scans the document and binds every `[data-x402-endpoint]` element. This is+called automatically on load and whenever the `MutationObserver` sees new+matching elements, so you rarely need it — call it after injecting markup into a+context the observer doesn't cover (e.g. inside a shadow root you control).++```js+import { init } from '@three-ws/x402-payment-modal';+init();+```++---++## `version`++The package version string.++```js+import { version } from '@three-ws/x402-payment-modal';+console.log(version); // "1.0.0"+```++---++## HTML data attributes++You can drive the modal declaratively without writing JavaScript. Add attributes+to any clickable element and the auto-binder wires the click handler.++### On a clickable element++| Attribute | Maps to | Notes |+|------------------------|--------------------|--------------------------------|+| `data-x402-endpoint` | `endpoint` | **Required.** |+| `data-x402-method` | `method` | |+| `data-x402-body` | `body` | JSON string. |+| `data-x402-headers` | `headers` | JSON string. |+| `data-x402-merchant` | `merchant` | |+| `data-x402-action` | `action` | |++```html+<button+ data-x402-endpoint="https://api.example.com/premium"+ data-x402-method="POST"+ data-x402-body='{"prompt":"Summarize this article"}'+ data-x402-headers='{"X-Client":"web"}'+ data-x402-merchant="Example API"+ data-x402-action="Generate summary">+ Unlock for 0.05 USDC+</button>+```++### On the `<script>` tag (read once at load)++These configure global defaults from the script element that loads the module —+equivalent to calling `configure()`.++| Attribute | Maps to |+|-------------------------------|--------------------------|+| `data-x402-checkout-origin` | `checkoutOrigin` |+| `data-x402-checkout-path` | `checkoutPath` |+| `data-x402-footer-note` | `footerNote` |+| `data-x402-brand-name` | `brand.name` |+| `data-x402-brand-url` | `brand.url` |+| `data-x402-builder-wallet` | `builderCode.wallet` |+| `data-x402-builder-service` | `builderCode.service` |++```html+<script+ type="module"+ src="https://unpkg.com/@three-ws/x402-payment-modal"+ data-x402-checkout-origin="https://pay.example.com"+ data-x402-checkout-path="/api/x402-checkout"+ data-x402-brand-name="Example"+ data-x402-brand-url="https://example.com"+ data-x402-footer-note="Secured by x402"+ data-x402-builder-wallet="examplewallet"+ data-x402-builder-service="example_api"></script>+```++---++## DOM events++The modal dispatches bubbling `CustomEvent`s on the **clicked element** — useful+for declarative integrations where you never called `pay()` directly.++| Event | `detail` | When |+|--------------------|---------------------------------------|---------------------------------------|+| `x402:result` | the [`PayResult`](#payresult) | Payment settled and result returned. |+| `x402:error` | `{ error: string }` | The flow failed (not on cancellation).|+| `x402:siwx-signed` | `{ address, network }` | A [SIWX](./siwx.md) sign-in succeeded.|++```js+const btn = document.querySelector('[data-x402-endpoint]');++btn.addEventListener('x402:result', (e) => {+ console.log('paid result:', e.detail.result);+});++btn.addEventListener('x402:error', (e) => {+ console.error('payment failed:', e.detail.error);+});++btn.addEventListener('x402:siwx-signed', (e) => {+ console.log('re-entered via SIWX:', e.detail.address, e.detail.network);+});+```diff --git a/x402-payment-modal/docs/architecture.md b/x402-payment-modal/docs/architecture.mdnew file mode 100644index 000000000..8c2644437--- /dev/null+++ b/x402-payment-modal/docs/architecture.md@@ -0,0 +1,169 @@+# Architecture++`@three-ws/x402-payment-modal` is a single zero-dependency vanilla-JS ES module+that turns any [x402](https://x402.org)-protected HTTP endpoint into a one-click+checkout. It owns the entire client lifecycle: discovering the payment challenge,+connecting a wallet, signing the payment, retrying the request with proof, and+rendering a receipt plus the endpoint's result.++This document explains how the modal works end to end. For the public surface,+see the [API reference](./api-reference.md). For the Solana checkout backend, see+[server setup](./server-setup.md).++## The x402 flow in one sentence++> The merchant answers an unpaid request with **HTTP 402** describing what it+> wants; the modal makes the user **sign** a payment matching that description;+> the modal **retries** the same request with an `X-PAYMENT` header; the merchant+> **settles** the payment and returns the real result.++The package never holds funds and never moves money on its own. It only produces+a signed payment authorization and hands it back to the merchant, who settles it+through an x402 facilitator.++## Lifecycle++```+discover → connect → authorize → verify (retry + settle) → receipt+```++These map directly to the four visible modal steps:++| Step | Modal label | What happens |+|-------------|----------------------|------------------------------------------------------------------------------|+| `discover` | Confirming price | Probe the endpoint, parse the 402 challenge, render price + network. |+| `connect` | Connect wallet | Detect Phantom / EVM wallet, let the user pick and connect one. |+| `authorize` | Authorize payment | Produce a signed payment (EVM EIP-3009 typed-data, or Solana signed tx). |+| `verify` | Verify & complete | Re-send the request with `X-PAYMENT`; merchant settles; show receipt. |++Each step is rendered as a `.x402-step` element and carries `.x402-active`,+`.x402-done`, or `.x402-error` modifiers as it progresses. See+[theming](./theming.md) for styling hooks.++## Challenge discovery++When `pay()` first calls the endpoint (using the configured `method`, `body`, and+`headers`), it inspects the response for a payment challenge. It accepts any of:++1. **HTTP 402** with a JSON body describing the accepted payment(s).+2. **HTTP 402** with a `payment-required` response header (the body-less form).+3. **MCP-style HTTP 401** with a `payment-required` header — used by Model+ Context Protocol servers that gate tools behind payment.++The parsed challenge contains one or more `accepts` entries. Each entry names a+`network` (e.g. an EVM chain like Base, or a Solana network), an asset, an+amount, the pay-to address, and protocol `extra`/`extensions` metadata. If the+challenge advertises [SIWX](./siwx.md), the modal can offer sign-in re-entry+instead of a fresh payment.++If the very first response is **not** a payment challenge (e.g. an immediate+`200`), the modal short-circuits: there is nothing to pay, so it resolves with+that response as the result.++## Two signing paths++x402 supports multiple settlement rails. The modal implements two, and which one+runs is decided entirely by the `network` in the selected `accepts` entry.++### EVM path — browser-only (EIP-3009)++EVM stablecoin payments (e.g. USDC on Base) use **EIP-3009** "transfer with+authorization." The browser wallet (MetaMask or any injected EIP-1193 provider)+signs an EIP-712 typed-data authorization. This is a pure signature — **no funds+move at signing time and no server call is made.** The signed authorization+becomes the `X-PAYMENT` header; the merchant's facilitator submits it on-chain+when it settles.++Because the signature is generated entirely in the browser, **EVM-only sites need+nothing on the server side** of this package.++### Solana path — server-assisted (prepare / encode + Phantom)++Phantom signs *serialized transactions*, not arbitrary typed data, so the Solana+path needs a small backend to build the transaction the wallet will sign. The+flow:++1. Client posts the selected `accepts` entry and the buyer's address to the+ checkout server: `POST /api/x402-checkout?action=prepare`.+2. The server builds a partially-signed SPL `transferChecked` v0 transaction.+ The **fee payer is a facilitator sponsor account** (`accept.extra.feePayer`),+ so the buyer needs only USDC — no SOL for gas.+3. The server returns `tx_base64` + `recent_blockhash`.+4. Phantom signs the transaction (`signTransaction`).+5. Client posts the signed tx to `?action=encode`; the server wraps it into a+ base64 x402 v2 payment envelope and returns `x_payment`.+6. That envelope becomes the `X-PAYMENT` header on the retry.++See [server setup](./server-setup.md) for mounting `prepare`/`encode`.++## Retry, settle, and the 429 auto-retry++Once a signed payment exists, the modal re-issues the original request with the+`X-PAYMENT` header attached. Outcomes:++- **2xx** — the merchant accepted and settled the payment. The modal parses the+ body (JSON or text), extracts any `payment`/receipt metadata from the response,+ renders the receipt + result, and resolves the `pay()` promise.+- **HTTP 429 (throttled)** — the facilitator was rate-limited. **Payment is not+ settled until the merchant call actually succeeds**, so it is safe to re-send+ the *same* signed payment. The modal auto-retries up to **2 additional times**+ with the identical `X-PAYMENT` payload before surfacing an error.+- **Other 4xx/5xx** — surfaced as an error in the modal (and via the+ `x402:error` event), with the reservation rolled back if+ [spending caps](./spending-caps.md) were in play.++This retry-on-429 is why the modal keeps the signed payment in memory rather than+re-prompting the wallet: re-signing is unnecessary and would annoy the user.++## Sequence diagram++```+ User Modal Merchant Checkout server Wallet+ | | | | |+ | click | | | |+ |----------->| pay(opts) | | |+ | | GET/POST endpoint | | |+ | |------------------->| | |+ | | 402 + accepts | | |+ | |<-------------------| | |+ | | [discover] price | | |+ | | | | |+ | | [connect] pick wallet ------------------------------------>|+ | |<----------------------------------------------- address |+ | | | | |+ | == EVM path (browser-only) == | | |+ | | sign EIP-3009 typed data ----------------------------------->|+ | |<-------------------------------------------- signature |+ | | | | |+ | == Solana path (server-assisted) == | |+ | | POST ?action=prepare ------------------->| |+ | |<------------------ tx_base64, blockhash --| |+ | | signTransaction ------------------------------------------>|+ | |<-------------------------------- signed tx |+ | | POST ?action=encode --------------------->| |+ | |<------------------------- x_payment ------| |+ | | | | |+ | | [verify] retry with X-PAYMENT | |+ | |------------------->| | |+ | | (429? re-send same payment, up to 2x) | |+ | | 200 + result + receipt | |+ | |<-------------------| | |+ | receipt | | | |+ |<-----------| resolve PayResult | | |+```++## Cancellation++If the user closes the modal at any point, `pay()` rejects with an `Error` whose+`.code === 'cancelled'`. Any spending-cap reservation made for the attempt is+rolled back. Callers should treat `cancelled` as a no-op, not a failure.++## Distribution shape++- **Client:** one ES module (`src/index.js`), also shipped minified+ (`dist/x402.min.js`). It self-registers `window.X402` and auto-binds+ `[data-x402-endpoint]` elements. Crypto helpers (`@solana/web3.js`,+ noble hashes) are loaded on demand from CDN ESM and can be repointed for+ strict CSP via [`configure`](./api-reference.md#configure).+- **Server:** optional, only for the Solana rail. Exposed at+ `@three-ws/x402-payment-modal/server` with Express and Vercel adapters.diff --git a/x402-payment-modal/docs/server-setup.md b/x402-payment-modal/docs/server-setup.mdnew file mode 100644index 000000000..ad8963c28--- /dev/null+++ b/x402-payment-modal/docs/server-setup.md@@ -0,0 +1,239 @@+# Server setup++The server module exists for **one reason: the Solana payment rail.** It exposes+`prepare`/`encode` endpoints that build and wrap the SPL transaction Phantom+signs. If your endpoint only accepts EVM stablecoins (e.g. USDC on Base), you do+**not** need any of this — see why below.++For the full request lifecycle, see [architecture](./architecture.md). For the+client side, see the [API reference](./api-reference.md).++```js+import {+ prepareSolanaCheckout,+ encodeX402Payment,+ handleCheckout,+ CheckoutError,+ isSolanaNetwork,+ X402_VERSION, // 2+ NETWORK_SOLANA_MAINNET,+ NETWORK_SOLANA_DEVNET,+} from '@three-ws/x402-payment-modal/server';+```++## Why EVM needs no server, but Solana does++- **EVM (EIP-3009):** the browser wallet signs an EIP-712 typed-data+ authorization entirely client-side. No funds move at signing time, and no+ server is contacted. The signature becomes the `X-PAYMENT` header directly.+- **Solana:** Phantom only signs *serialized transactions*, not arbitrary typed+ data. Something has to build that transaction. The server builds a partially+ signed `transferChecked` v0 transaction (`prepare`), the buyer signs it, then+ the server wraps the signed tx into the x402 v2 envelope (`encode`). The fee+ payer is a facilitator sponsor account, so the buyer needs only USDC — no SOL+ for gas.++## Install the peer dependencies++The Solana helpers require these **optional** peer deps. Install them only if you+mount the Solana checkout:++```bash+npm install @solana/web3.js@^1.95 @solana/spl-token@^0.4+```++EVM-only sites can skip this entirely.++## Environment variables++| Variable | Purpose |+|-------------------|---------------------------------------------------------------|+| `SOLANA_RPC_URL` | Mainnet RPC endpoint used to build/serialize the transaction. |++You may also pass `rpcUrl` (and `devnetRpcUrl`) explicitly to the adapters or to+`prepareSolanaCheckout`; explicit options take precedence over the env var.++## Mounting with Express++```js+import express from 'express';+import { x402CheckoutRouter } from '@three-ws/x402-payment-modal/server/express';++const app = express();+app.use(express.json());++app.use(+ '/api/x402-checkout',+ x402CheckoutRouter({+ rpcUrl: process.env.SOLANA_RPC_URL,+ // devnetRpcUrl: 'https://api.devnet.solana.com',+ // origin: 'https://yourapp.com', // CORS allow-origin (default '*')+ })+);++app.listen(3000);+```++`x402CheckoutRouter({ rpcUrl?, devnetRpcUrl?, origin? })` returns an Express+`RequestHandler`. It sets permissive CORS by default (`origin: '*'`), answers+`OPTIONS` preflight, and requires `POST` for the actual calls.++## Mounting with Vercel / Next.js (pages API)++Create `api/x402-checkout.js` (or `pages/api/x402-checkout.js`) and re-export the+handler:++```js+// api/x402-checkout.js+import { createVercelCheckoutHandler } from '@three-ws/x402-payment-modal/server/vercel';++export default createVercelCheckoutHandler({+ rpcUrl: process.env.SOLANA_RPC_URL,+ // devnetRpcUrl: process.env.SOLANA_DEVNET_RPC_URL,+ // origin: 'https://yourapp.com',+});+```++`createVercelCheckoutHandler()` is also the module's default export, so the+zero-config form works too:++```js+// api/x402-checkout.js+export { default } from '@three-ws/x402-payment-modal/server/vercel';+```++Like the Express adapter, it applies permissive CORS by default, handles+`OPTIONS`, and requires `POST`.++> Point the client at this endpoint with `configure({ checkoutOrigin, checkoutPath })`+> or the `data-x402-checkout-origin` / `data-x402-checkout-path` script+> attributes. See the [API reference](./api-reference.md#configure).++## From scratch with Node `http` + `handleCheckout`++`handleCheckout` is the framework-agnostic router. Pass it the `action`+(`'prepare'` or `'encode'`), the parsed JSON `body`, and optional `options`. It+returns `{ status, body }`, mapping a thrown `CheckoutError` to its `.status` and+any unexpected error to `502`. It accepts both camelCase and snake_case body+fields (`signed_tx_base64`/`signedTxBase64`, `resource_url`/`resourceUrl`,+`builder_code`/`builderCode`).++```js+import { createServer } from 'node:http';+import { handleCheckout } from '@three-ws/x402-payment-modal/server';++const server = createServer((req, res) => {+ const url = new URL(req.url, 'http://localhost');+ const action = url.searchParams.get('action'); // 'prepare' | 'encode'++ if (req.method === 'OPTIONS') {+ res.writeHead(204, cors).end();+ return;+ }+ if (req.method !== 'POST') {+ res.writeHead(405, cors).end();+ return;+ }++ let raw = '';+ req.on('data', (c) => (raw += c));+ req.on('end', async () => {+ const body = raw ? JSON.parse(raw) : {};+ const { status, body: out } = await handleCheckout({+ action,+ body,+ options: { rpcUrl: process.env.SOLANA_RPC_URL },+ });+ res.writeHead(status, { 'content-type': 'application/json', ...cors });+ res.end(JSON.stringify(out));+ });+});++const cors = {+ 'access-control-allow-origin': '*',+ 'access-control-allow-methods': 'POST, OPTIONS',+ 'access-control-allow-headers': 'content-type',+};++server.listen(3000);+```++## CORS notes++Both adapters default to `origin: '*'` so a paywall served from one domain can+talk to a checkout server on another. For production, pass your site's origin:++```js+x402CheckoutRouter({ rpcUrl: process.env.SOLANA_RPC_URL, origin: 'https://yourapp.com' });+```++## Request / response shapes++### `?action=prepare`++`prepareSolanaCheckout({ accept, buyer, rpcUrl?, devnetRpcUrl? })` builds a+partially signed v0 transaction whose fee payer is `accept.extra.feePayer`.++Request:++```json+{+ "accept": {+ "network": "solana",+ "asset": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",+ "maxAmountRequired": "50000",+ "payTo": "So111SyntheticMerchantPlaceholder1111111111",+ "extra": { "feePayer": "So111SyntheticFeePayerPlaceholder11111111" }+ },+ "buyer": "So111SyntheticBuyerPlaceholder111111111111"+}+```++Response:++```json+{+ "network": "solana",+ "tx_base64": "AQAB...base64-serialized-v0-tx...",+ "recent_blockhash": "9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin"+}+```++> `asset` above is the real Solana USDC mint (`EPjFW…Dt1v`). All other addresses+> are synthetic placeholders. Substitute your own facilitator and merchant+> accounts.++### `?action=encode`++`encodeX402Payment({ accept, signedTxBase64, resourceUrl, builderCode? })` wraps+the buyer-signed transaction into a base64 x402 v2 envelope (`X402_VERSION === 2`).++Request:++```json+{+ "accept": { "network": "solana", "asset": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" },+ "signed_tx_base64": "AQAB...signed...",+ "resource_url": "https://api.example.com/premium",+ "builder_code": { "wallet": "examplewallet", "service": "example_api" }+}+```++Response:++```json+{ "x_payment": "eyJ4NDAyVmVyc2lvbiI6Mn0...base64-envelope..." }+```++The client puts `x_payment` into the `X-PAYMENT` header and retries the original+request.++## Helpers++| Export | Description |+|----------------------------|------------------------------------------------------------------------|+| `CheckoutError` | `Error` subclass with `.status` and `.code`; mapped to HTTP by router. |+| `isSolanaNetwork(network)` | `true` for Solana mainnet/devnet network identifiers. |+| `X402_VERSION` | `2` — the x402 envelope version produced by `encode`. |+| `NETWORK_SOLANA_MAINNET` | Canonical Solana mainnet network id. |+| `NETWORK_SOLANA_DEVNET` | Canonical Solana devnet network id. |diff --git a/x402-payment-modal/docs/siwx.md b/x402-payment-modal/docs/siwx.mdnew file mode 100644index 000000000..5fba6f3db--- /dev/null+++ b/x402-payment-modal/docs/siwx.md@@ -0,0 +1,116 @@+# SIWX — Sign-In-With-X re-entry++SIWX ("Sign-In-With-X", standardized as [CAIP-122](https://chainagnostic.org/CAIPs/caip-122))+lets a wallet that **already paid** for an endpoint get back in by **signing a+challenge instead of paying again**. It is the difference between a one-time+purchase and being charged on every page load.++This package implements the **client** side of SIWX. The server endpoint must+issue the challenge and verify the signed proof — see+[Server responsibilities](#server-responsibilities).++For the overall flow, see [architecture](./architecture.md).++## Why it matters++x402 charges per call. Without SIWX, a user who paid for `/premium` would pay+again the next time they hit it. With SIWX, the merchant can recognize a wallet+that has an active entitlement: the wallet proves ownership with a cheap,+gasless, off-chain signature, and the merchant grants access without a new+payment.++## How the server advertises SIWX++When the endpoint returns its **HTTP 402** challenge, it advertises SIWX support+by including an extension entry in the challenge body:++```json+{+ "x402Version": 2,+ "accepts": [+ {+ "network": "base",+ "asset": "0xUSDC...synthetic",+ "maxAmountRequired": "50000",+ "payTo": "0xMerchant...synthetic",+ "extensions": {+ "sign-in-with-x": {+ "domain": "api.example.com",+ "statement": "Sign in to re-enter your paid session.",+ "nonce": "synthetic-nonce-abc123"+ }+ }+ }+ ]+}+```++The exact challenge fields are defined by the x402 SIWX spec; the modal only+needs `extensions['sign-in-with-x']` to be present to offer sign-in.++## How the client submits proof++When the user signs the challenge, the modal sends the signed CAIP-122 proof back+to the endpoint as a base64-encoded JSON value in the **`SIGN-IN-WITH-X`**+request header, then retries the original request. If the merchant accepts the+proof, it returns the result with no payment required.++## Modal behavior++The modal adapts its layout to what the challenge offers:++1. **SIWX advertised + a compatible wallet present** — the modal **leads with+ "Sign in with wallet"** as the primary (`.x402-pay-btn`) action and **demotes+ pay to secondary** (`.x402-pay-secondary`). Signing in is cheaper, so it's the+ default.+2. **User signs in** — on success the modal resolves [`PayResult`](./api-reference.md#payresult)+ with the `siwx` field populated (`{ address, network }`) and **no `payment`+ field**, and fires the [`x402:siwx-signed`](#the-x402siwx-signed-event) event.+3. **Sign-in rejected (`siwx_not_paid`)** — if the server answers the SIWX+ attempt with a `401`/`402` carrying a `siwx_not_paid` reason (the wallet has+ no active entitlement), the modal **falls back to the normal pay flow** and+ shows a notice explaining that payment is required.+4. **SIWX not advertised** — the modal behaves as a plain pay modal; nothing+ changes.++## The `x402:siwx-signed` event++A successful SIWX re-entry dispatches a bubbling `x402:siwx-signed`+`CustomEvent` on the clicked element:++```js+const btn = document.querySelector('[data-x402-endpoint]');++btn.addEventListener('x402:siwx-signed', (e) => {+ const { address, network } = e.detail;+ console.log(`re-entered as ${address} on ${network}`);+});+```++You also get the same data programmatically from the resolved result:++```js+const res = await pay({ endpoint: 'https://api.example.com/premium' });++if (res.siwx) {+ console.log('re-entered via SIWX:', res.siwx.address);+} else if (res.payment) {+ console.log('paid:', res.payment.transaction);+}+```++## Server responsibilities++This package does not store entitlements or verify signatures. Your endpoint+must:++1. **Advertise** the SIWX extension in the 402 challenge (see above).+2. **Verify** the CAIP-122 proof from the `SIGN-IN-WITH-X` header — check the+ nonce, domain, expiry, and signature against the claimed address.+3. **Authorize** the request if that address has an active paid entitlement;+ otherwise respond `401`/`402` with `siwx_not_paid` so the client falls back to+ paying.++Implement these against the x402 SIWX specification. The modal handles+everything on the browser side: detecting the offer, prompting the signature,+encoding the header, retrying, and falling back.diff --git a/x402-payment-modal/docs/spending-caps.md b/x402-payment-modal/docs/spending-caps.mdnew file mode 100644index 000000000..ecdf6339e--- /dev/null+++ b/x402-payment-modal/docs/spending-caps.md@@ -0,0 +1,92 @@+# Spending caps++Spending caps are client-side guardrails that stop a wallet from spending more+than you allow through the modal — per call, per hour, and per day. They make+unattended or agentic usage safer by bounding the blast radius of a bug or a+runaway loop.++They are passed to [`pay()`](./api-reference.md#payopts) via the `caps` option.++## Shape++```ts+interface SpendingCaps {+ maxPerCall?: string | number;+ maxPerHour?: string | number;+ maxPerDay?: string | number;+}+```++All amounts are **atomic micro-USD** — i.e. millionths of a dollar+(`1_000_000` = 1 USDC). Strings are accepted to avoid floating-point loss on+large numbers.++| Field | Meaning |+|--------------|--------------------------------------------------------|+| `maxPerCall` | Maximum a single payment may cost. |+| `maxPerHour` | Maximum total across the current UTC hour bucket. |+| `maxPerDay` | Maximum total across the current UTC day bucket. |++## How enforcement works++- Spend is tracked in **`localStorage`, per wallet address.**+- Totals are **bucketed by UTC hour and UTC day**, so the windows roll over+ cleanly and survive a page reload.+- Before a payment is signed, the modal **reserves** the amount against the+ relevant buckets. If any cap would be exceeded, the payment is blocked and the+ user sees an error explaining which limit was hit.+- If the payment **fails or is cancelled**, the reservation is **rolled back** so+ a failed attempt never counts against the user's budget. (Cancellation is the+ `pay()` rejection with `.code === 'cancelled'`.)++## Important caveat: stablecoins only++The drop-in script stays **zero-dependency and does not fetch live prices.** That+means it can only reason about value when 1 token ≈ 1 USD — i.e. **stablecoins+(USDC / USDT / DAI).** For those, atomic micro-USD caps are meaningful directly.++For **non-stable assets**, the modal cannot convert an amount to USD without a+price feed, so browser caps do **not** meaningfully bound spend. **Enforce caps+for non-stable assets on the server side**, where you can price the asset at+settlement time.++## Not a security boundary++Client-side caps are **advisory guardrails, not a security control.** They live in+`localStorage`, which a determined user can clear or edit, and they only cover+flows that go through this modal. Treat them as a convenience and a safety net for+honest usage. **Real spending limits belong on the server**, enforced where the+payment is verified and settled.++## Worked example++```js+import { pay } from '@three-ws/x402-payment-modal';++// USDC, so atomic micro-USD caps apply directly:+// 0.10 USDC per call, 2.00 USDC/hour, 10.00 USDC/day+const res = await pay({+ endpoint: 'https://api.example.com/premium',+ method: 'POST',+ body: { prompt: 'Summarize this article' },+ merchant: 'Example API',+ action: 'Generate summary',+ caps: {+ maxPerCall: 100_000, // 0.10 USDC+ maxPerHour: 2_000_000, // 2.00 USDC+ maxPerDay: 10_000_000, // 10.00 USDC+ },+});++console.log(res.result);+```++If a call would push the current UTC-hour total over `maxPerHour`, the modal+blocks it before any wallet prompt and surfaces the reason; nothing is reserved.++## See also++- [API reference](./api-reference.md) — where `caps` fits in `PayOptions`.+- [Architecture](./architecture.md) — where the reservation/rollback sits in the+ lifecycle.+- [Server setup](./server-setup.md) — for enforcing real limits server-side.diff --git a/x402-payment-modal/docs/theming.md b/x402-payment-modal/docs/theming.mdnew file mode 100644index 000000000..82cec1288--- /dev/null+++ b/x402-payment-modal/docs/theming.md@@ -0,0 +1,124 @@+# Theming++The modal ships its own styles so it looks finished out of the box, then gives+you clean hooks to skin it to your brand. There is no build step and no CSS file+to import — styles are injected at runtime.++For the markup these classes wrap, see the step model in+[architecture](./architecture.md).++## How styles are injected++On first use, the modal injects a single `<style id="x402-styles">` block into+the document head. It is injected **once**; subsequent opens reuse it.++To override it, do one of:++1. Define your own rules with **higher specificity** in a stylesheet loaded+ **after** the module runs (so your rules win on equal specificity, or beat+ the injected ones).+2. Use `!important` on the specific declarations you want to force.+3. Override the exposed **CSS custom property** (`--x402-z`) where one exists.++The modal is **light by default** and includes a built-in dark theme via+`@media (prefers-color-scheme: dark)` — it follows the OS setting automatically.++## CSS classes++| Class | Element / role |+|------------------------|---------------------------------------------------------------------|+| `.x402-overlay` | Root overlay. Holds `--x402-z` (z-index, default `2147483600`). |+| `.x402-modal` | The modal card container. |+| `.x402-head` | Header region (merchant/action/close). |+| `.x402-merchant` | Merchant block in the header. |+| `.x402-name` | Merchant name text. |+| `.x402-action` | Action label text (from `action`). |+| `.x402-close` | Close button. |+| `.x402-price-row` | Row holding price + network. |+| `.x402-price` | Numeric price. |+| `.x402-currency` | Currency label (e.g. USDC). |+| `.x402-network` | Network badge (e.g. Base / Solana). |+| `.x402-body` | Main content area. |+| `.x402-step` | A lifecycle step row. Modifiers below. |+| `.x402-step.x402-active` | The step currently in progress. |+| `.x402-step.x402-done` | A completed step. |+| `.x402-step.x402-error`| A step that failed. |+| `.x402-wallet-btn` | A wallet choice button (Phantom / EVM). |+| `.x402-pay-btn` | Primary pay / confirm button. |+| `.x402-pay-secondary` | Secondary action button (e.g. demoted pay under SIWX). |+| `.x402-error-box` | Error message container. |+| `.x402-receipt` | Settled-payment receipt block. |+| `.x402-result` | The paid endpoint's returned result. |+| `.x402-foot` | Footer (brand attribution + footer note). |++The four `.x402-step` rows correspond to the discover / connect / authorize /+verify lifecycle described in [architecture](./architecture.md).++## Overriding the z-index++The overlay z-index is a custom property so you can lower it under your own+top-layer UI (or raise it) without touching the rest of the stylesheet:++```css+.x402-overlay {+ --x402-z: 9999;+}+```++Default is `2147483600` (just under the 32-bit max) so the modal sits above most+app chrome.++## Dark mode++Dark styling is automatic via `prefers-color-scheme: dark`. To force a single+theme regardless of OS, override the relevant classes. For example, to force the+light look everywhere:++```css+@media (prefers-color-scheme: dark) {+ .x402-modal { background: #ffffff; color: #111111; }+}+```++## Worked example: brand the pay button and modal radius++Load this **after** the module so it wins:++```html+<script type="module" src="https://unpkg.com/@three-ws/x402-payment-modal"></script>+<style>+ /* Rounder card */+ .x402-modal {+ border-radius: 18px;+ }++ /* Brand-colored primary button with a hover lift */+ .x402-pay-btn {+ background: #4f46e5; /* indigo */+ color: #fff;+ border: none;+ transition: transform 120ms ease, background 120ms ease;+ }+ .x402-pay-btn:hover {+ background: #4338ca;+ transform: translateY(-1px);+ }+ .x402-pay-btn:active {+ transform: translateY(0);+ }+ .x402-pay-btn:focus-visible {+ outline: 2px solid #818cf8;+ outline-offset: 2px;+ }++ /* Tone down the secondary action */+ .x402-pay-secondary {+ background: transparent;+ color: #4f46e5;+ }+</style>+```++If a rule still loses to the injected stylesheet, raise specificity (e.g.+`.x402-overlay .x402-pay-btn`) or add `!important` to the individual+declarations.diff --git a/x402-payment-modal/examples/README.md b/x402-payment-modal/examples/README.mdnew file mode 100644index 000000000..3df4f499a--- /dev/null+++ b/x402-payment-modal/examples/README.md@@ -0,0 +1,22 @@+# Examples++Runnable examples for [`@three-ws/x402-payment-modal`](https://www.npmjs.com/package/@three-ws/x402-payment-modal)+— a zero-dependency, vanilla-JS payment modal for any x402 paid HTTP endpoint.++| Example | What it shows | Fastest way to try it |+| --- | --- | --- |+| [`plain-html/`](./plain-html) | No build step. Declarative `data-x402-*` buttons, a programmatic `pay()` call, and `x402:result` / `x402:error` event handling — all from a single CDN `<script>`. | Open `plain-html/index.html` in a browser (or serve the folder, e.g. `npx serve plain-html`). |+| [`react/`](./react) | A reusable `<X402Button>` component that wraps `pay()` with a dynamic import, so it is SSR-safe. | Copy `react/X402Button.jsx` into your app — see [`react/README.md`](./react/README.md). |+| [`server-express/`](./server-express) | A complete Express server that mounts the Solana checkout router and serves a demo paid endpoint returning a real x402 v2 challenge. | `cd server-express && npm install && npm start`, then open http://localhost:3000 |++## Which do I need?++- **EVM payments** sign in the browser (EIP-3009) — the **plain-html** or+ **react** client is all you need.+- **Solana payments** also require the **server-express** checkout endpoint to+ build and settle the transfer. See+ [`../docs/server-setup.md`](../docs/server-setup.md).++> The client examples point at placeholder endpoints+> (`https://api.example.com/...`). Swap in a real x402-enabled endpoint to take+> an actual payment.diff --git a/x402-payment-modal/examples/plain-html/index.html b/x402-payment-modal/examples/plain-html/index.htmlnew file mode 100644index 000000000..9c228f583--- /dev/null+++ b/x402-payment-modal/examples/plain-html/index.html@@ -0,0 +1,232 @@+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <title>x402 Payment Modal — Plain HTML demo</title>++ <!--+ ─────────────────────────────────────────────────────────────────────────+ DEMO ONLY++ This page shows three ways to use @three-ws/x402-payment-modal with no+ build step at all — just an ES module loaded from a CDN.++ (a) Declarative: a button annotated with data-x402-* attributes. The+ library auto-binds these on load — zero JavaScript required.+ (b) Programmatic: a button wired in an inline module that imports pay().+ (c) Events: x402:result / x402:error bubble from the clicked element;+ we listen and render the outcome into #outcome below.++ The endpoint below (https://api.example.com/...) is a PLACEHOLDER. To+ actually take a payment, point data-x402-endpoint / pay({ endpoint }) at a+ REAL x402-enabled HTTP endpoint that responds with HTTP 402 + an x402+ challenge. The modal handles the 402 → connect wallet → sign → settle flow.++ Self-hosting: instead of the unpkg URL you can serve the module yourself,+ e.g. <script type="module" src="/vendor/x402.min.js" ...>. The data-x402-*+ config attributes work the same way on a self-hosted <script> tag.+ ─────────────────────────────────────────────────────────────────────────+ -->++ <style>+ :root {+ --bg: #0b0c10;+ --card: #15171e;+ --border: #262a35;+ --text: #e7e9ee;+ --muted: #9aa1b1;+ --accent: #6c8cff;+ --accent-press: #5476f5;+ --ok: #3ddc97;+ --err: #ff6b6b;+ }+ * { box-sizing: border-box; }+ html, body { height: 100%; }+ body {+ margin: 0;+ background: radial-gradient(1200px 600px at 50% -10%, #1a1d27 0%, var(--bg) 60%);+ color: var(--text);+ font: 15px/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;+ display: grid;+ place-items: center;+ padding: 32px 16px;+ }+ .card {+ width: 100%;+ max-width: 520px;+ background: var(--card);+ border: 1px solid var(--border);+ border-radius: 16px;+ padding: 28px;+ box-shadow: 0 24px 60px rgba(0, 0, 0, 0.45);+ }+ h1 { font-size: 20px; margin: 0 0 4px; letter-spacing: -0.01em; }+ p.lede { margin: 0 0 22px; color: var(--muted); }+ h2 {+ font-size: 12px;+ text-transform: uppercase;+ letter-spacing: 0.08em;+ color: var(--muted);+ margin: 22px 0 8px;+ }+ .row { display: flex; gap: 10px; flex-wrap: wrap; align-items: center; }+ button {+ appearance: none;+ border: 0;+ border-radius: 10px;+ padding: 11px 18px;+ font: inherit;+ font-weight: 600;+ color: #fff;+ background: var(--accent);+ cursor: pointer;+ transition: transform 0.08s ease, background 0.15s ease, box-shadow 0.15s ease;+ }+ button:hover { background: var(--accent-press); }+ button:active { transform: translateY(1px); }+ button:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }+ button[disabled] { opacity: 0.55; cursor: progress; }+ .hint { color: var(--muted); font-size: 13px; }+ code {+ background: #0c0e14;+ border: 1px solid var(--border);+ border-radius: 6px;+ padding: 1px 6px;+ font-size: 12px;+ }+ #outcome {+ margin-top: 22px;+ min-height: 44px;+ border: 1px dashed var(--border);+ border-radius: 12px;+ padding: 14px 16px;+ color: var(--muted);+ font-size: 13px;+ white-space: pre-wrap;+ word-break: break-word;+ transition: border-color 0.2s ease;+ }+ #outcome.ok { border-color: var(--ok); color: var(--ok); }+ #outcome.err { border-color: var(--err); color: var(--err); }+ .footer { margin-top: 20px; color: var(--muted); font-size: 12px; }+ a { color: var(--accent); }+ </style>++ <!--+ (a) Declarative usage.++ Loading the module runs init() automatically: any element carrying a+ data-x402-endpoint attribute becomes a pay trigger. Config that applies to+ the whole page (brand, where the Solana checkout endpoint lives) rides on+ THIS script tag as data-x402-* attributes.+ -->+ <script+ type="module"+ src="https://unpkg.com/@three-ws/x402-payment-modal"+ data-x402-brand-name="Acme Summaries"+ data-x402-brand-url="https://example.com"+ data-x402-checkout-origin="https://example.com"+ data-x402-footer-note="Payments settle in USDC. Powered by x402."+ ></script>+</head>++<body>+ <main class="card">+ <h1>x402 Payment Modal</h1>+ <p class="lede">Pay any x402 endpoint in one click — no wallet integration code.</p>++ <!-- (a) Zero-JS declarative button. The attributes describe the request. -->+ <h2>Declarative (no JavaScript)</h2>+ <div class="row">+ <button+ id="declarative-pay"+ data-x402-endpoint="https://api.example.com/paid/summarize"+ data-x402-method="POST"+ data-x402-body='{"url":"https://en.wikipedia.org/wiki/x402"}'+ data-x402-merchant="Acme Summaries"+ data-x402-action="Summarize article"+ >+ Summarize for 0.01 USDC+ </button>+ <span class="hint">Driven entirely by <code>data-x402-*</code> attributes.</span>+ </div>++ <!-- (b) Programmatic button — wired by the inline module below. -->+ <h2>Programmatic (inline module)</h2>+ <div class="row">+ <button id="programmatic-pay">Translate for 0.01 USDC</button>+ <span class="hint">Calls <code>pay()</code> from a <code><script type="module"></code>.</span>+ </div>++ <!-- (c) Outcome surface — populated by the x402:result / x402:error listeners. -->+ <h2>Outcome</h2>+ <div id="outcome" role="status" aria-live="polite">No payment attempted yet.</div>++ <p class="footer">+ Endpoints above are placeholders — swap in a real x402 endpoint to take a payment.+ You can also self-host the module instead of unpkg.+ </p>+ </main>++ <script type="module">+ // (b) Programmatic usage: import pay() straight from the CDN module.+ // In a self-hosted setup, import from your own URL instead, e.g.+ // import { pay } from '/vendor/x402.min.js';+ import { pay } from 'https://unpkg.com/@three-ws/x402-payment-modal';++ const button = document.getElementById('programmatic-pay');++ button.addEventListener('click', async () => {+ button.disabled = true;+ const original = button.textContent;+ button.textContent = 'Processing…';+ try {+ const result = await pay({+ endpoint: 'https://api.example.com/paid/translate',+ method: 'POST',+ body: { text: 'Hello, world', to: 'es' },+ merchant: 'Acme Translate',+ action: 'Translate text',+ });+ // result = { ok, result, payment?, siwx?, response }+ console.log('Payment result:', result);+ } catch (err) {+ // The modal rejects with err.code === 'cancelled' when dismissed.+ if (err && err.code === 'cancelled') {+ console.log('User cancelled the payment.');+ } else {+ console.error('Payment failed:', err);+ }+ } finally {+ button.disabled = false;+ button.textContent = original;+ }+ });++ // (c) Event listeners. x402:result and x402:error bubble from the element+ // that triggered the payment, so a single document-level listener covers+ // both the declarative and programmatic buttons.+ const outcome = document.getElementById('outcome');++ document.addEventListener('x402:result', (event) => {+ const detail = event.detail; // PayResult: { ok, result, payment?, siwx?, response }+ outcome.className = 'ok';+ const payer = detail.payment?.payer ? `\nPayer: ${detail.payment.payer}` : '';+ const tx = detail.payment?.transaction ? `\nTx: ${detail.payment.transaction}` : '';+ outcome.textContent = `Paid ✓ (${detail.payment?.network ?? 'settled'})${payer}${tx}`;+ });++ document.addEventListener('x402:error', (event) => {+ const error = event.detail?.error;+ if (error && error.code === 'cancelled') {+ outcome.className = '';+ outcome.textContent = 'Payment cancelled.';+ return;+ }+ outcome.className = 'err';+ outcome.textContent = `Payment failed: ${error?.message ?? String(error)}`;+ });+ </script>+</body>+</html>diff --git a/x402-payment-modal/examples/react/README.md b/x402-payment-modal/examples/react/README.mdnew file mode 100644index 000000000..5dc5a0c3e--- /dev/null+++ b/x402-payment-modal/examples/react/README.md@@ -0,0 +1,69 @@+# React example — `<X402Button>`++A drop-in React component that wraps `pay()` from+[`@three-ws/x402-payment-modal`](https://www.npmjs.com/package/@three-ws/x402-payment-modal).++## Install++```bash+npm i @three-ws/x402-payment-modal+```++## Use it++Copy [`X402Button.jsx`](./X402Button.jsx) into your project, then:++```jsx+import X402Button from './X402Button';++export default function Demo() {+ return (+ <X402Button+ endpoint="https://api.example.com/paid/summarize"+ method="POST"+ body={{ url: 'https://en.wikipedia.org/wiki/x402' }}+ merchant="Acme Summaries"+ action="Summarize article"+ label="Summarize for 0.01 USDC"+ onResult={(r) => console.log('paid', r.payment)}+ onError={(e) => console.error('payment failed', e)}+ />+ );+}+```++### Props++| Prop | Type | Notes |+| ---------- | ---------- | ---------------------------------------------------------- |+| `endpoint` | `string` | Required. The x402-enabled HTTP endpoint to call. |+| `method` | `string` | HTTP method (default `GET`). |+| `body` | `object` | Request body (sent as JSON). |+| `merchant` | `string` | Display name shown in the modal. |+| `action` | `string` | Short description of what the user is paying for. |+| `label` | `string` | Button text (default `Pay`). `children` overrides it. |+| `onResult` | `function` | Called with the `PayResult` on success. |+| `onError` | `function` | Called on failure. **Not** called when the user cancels. |++`onResult` receives `{ ok, result, payment?, siwx?, response }`.++## SSR safety++The package is browser-only (it renders a modal and connects to a wallet), so+`X402Button` imports it lazily **inside the click handler**:++```js+const { pay } = await import('@three-ws/x402-payment-modal');+```++Nothing from the package runs during render or on the server, so the component+is safe in Next.js, Remix, and other SSR frameworks without `dynamic`/`ssr:false`+wrappers.++## Solana payments need a server++EVM payments sign in the browser (EIP-3009) and need no backend. **Solana+payments require a checkout endpoint** that builds and settles the transfer.+Stand one up before going live — see+[`../../docs/server-setup.md`](../../docs/server-setup.md) and the runnable+[`examples/server-express`](../server-express) server.diff --git a/x402-payment-modal/examples/react/X402Button.jsx b/x402-payment-modal/examples/react/X402Button.jsxnew file mode 100644index 000000000..ac5db4907--- /dev/null+++ b/x402-payment-modal/examples/react/X402Button.jsx@@ -0,0 +1,84 @@+/**+ * <X402Button> — a thin React wrapper around @three-ws/x402-payment-modal.+ *+ * The package is a browser-only ES module (it renders a modal and talks to a+ * wallet), so we dynamically import it INSIDE the click handler. That keeps the+ * component SSR-safe: nothing from the package is touched during render or on+ * the server.+ *+ * Usage:+ *+ * import X402Button from './X402Button';+ *+ * <X402Button+ * endpoint="https://api.example.com/paid/summarize"+ * method="POST"+ * body={{ url: 'https://en.wikipedia.org/wiki/x402' }}+ * merchant="Acme Summaries"+ * action="Summarize article"+ * label="Summarize for 0.01 USDC"+ * onResult={(r) => console.log('paid', r)}+ * onError={(e) => console.error(e)}+ * />+ *+ * For Solana payments your app must also run the server checkout endpoint+ * (see ../../docs/server-setup.md and examples/server-express). EVM payments+ * sign in-browser and need no server.+ */++import { useCallback, useState } from 'react';++export default function X402Button({+ endpoint,+ method = 'GET',+ body,+ merchant,+ action,+ label = 'Pay',+ onResult,+ onError,+ children,+ ...rest+}) {+ const [processing, setProcessing] = useState(false);++ const handleClick = useCallback(async () => {+ if (processing) return;+ setProcessing(true);++ try {+ // Dynamic import keeps the browser-only module out of the SSR bundle.+ const { pay } = await import('@three-ws/x402-payment-modal');++ const result = await pay({+ endpoint,+ method,+ body,+ merchant,+ action,+ });++ // result = { ok, result, payment?, siwx?, response }+ onResult?.(result);+ } catch (err) {+ // The modal rejects with err.code === 'cancelled' when the user dismisses+ // it. That is not an error — stay silent so we don't flash a failure.+ if (err && err.code === 'cancelled') return;+ onError?.(err);+ } finally {+ setProcessing(false);+ }+ }, [processing, endpoint, method, body, merchant, action, onResult, onError]);++ return (+ <button+ type="button"+ onClick={handleClick}+ disabled={processing}+ aria-busy={processing}+ {...rest}+ >+ {processing ? 'Processing…' : children ?? label}+ </button>+ );+}diff --git a/x402-payment-modal/examples/server-express/package.json b/x402-payment-modal/examples/server-express/package.jsonnew file mode 100644index 000000000..0b006afbf--- /dev/null+++ b/x402-payment-modal/examples/server-express/package.json@@ -0,0 +1,16 @@+{+ "name": "x402-checkout-example",+ "private": true,+ "version": "1.0.0",+ "description": "Runnable Express server that mounts the @three-ws/x402-payment-modal Solana checkout router and serves a demo paid endpoint.",+ "type": "module",+ "scripts": {+ "start": "node server.js"+ },+ "dependencies": {+ "@solana/spl-token": "*",+ "@solana/web3.js": "*",+ "@three-ws/x402-payment-modal": "*",+ "express": "*"+ }+}diff --git a/x402-payment-modal/examples/server-express/public/index.html b/x402-payment-modal/examples/server-express/public/index.htmlnew file mode 100644index 000000000..b60a12e06--- /dev/null+++ b/x402-payment-modal/examples/server-express/public/index.html@@ -0,0 +1,89 @@+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <title>x402 Express checkout demo</title>+ <style>+ body {+ margin: 0;+ min-height: 100vh;+ display: grid;+ place-items: center;+ background: #0b0c10;+ color: #e7e9ee;+ font: 15px/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;+ }+ .card {+ background: #15171e;+ border: 1px solid #262a35;+ border-radius: 16px;+ padding: 28px;+ max-width: 460px;+ text-align: center;+ box-shadow: 0 24px 60px rgba(0, 0, 0, 0.45);+ }+ h1 { font-size: 20px; margin: 0 0 6px; }+ p { color: #9aa1b1; margin: 0 0 20px; }+ button {+ border: 0;+ border-radius: 10px;+ padding: 11px 18px;+ font: inherit;+ font-weight: 600;+ color: #fff;+ background: #6c8cff;+ cursor: pointer;+ }+ button:hover { background: #5476f5; }+ button[disabled] { opacity: 0.55; cursor: progress; }+ #out {+ margin-top: 18px;+ min-height: 22px;+ font-size: 13px;+ color: #9aa1b1;+ white-space: pre-wrap;+ word-break: break-word;+ }+ </style>+</head>+<body>+ <main class="card">+ <h1>x402 Express checkout demo</h1>+ <p>Click to pay the local <code>/api/paid/hello</code> endpoint in USDC.</p>+ <button id="pay">Say hello for 0.01 USDC</button>+ <div id="out" role="status" aria-live="polite"></div>+ </main>++ <script type="module">+ // Loaded from the CDN for the demo; bundle it locally for production.+ import { pay, configure } from 'https://unpkg.com/@three-ws/x402-payment-modal';++ // Tell the modal where this server's Solana checkout endpoint lives.+ configure({+ checkoutOrigin: window.location.origin,+ checkoutPath: '/api/x402-checkout',+ brand: { name: 'x402 Express demo', url: window.location.origin },+ });++ const out = document.getElementById('out');+ document.getElementById('pay').addEventListener('click', async (e) => {+ e.target.disabled = true;+ try {+ const result = await pay({+ endpoint: '/api/paid/hello',+ merchant: 'x402 Express demo',+ action: 'Say hello',+ });+ out.textContent = `Paid ✓ ${JSON.stringify(result.result ?? result.ok)}`;+ } catch (err) {+ out.textContent = err?.code === 'cancelled'+ ? 'Cancelled.'+ : `Failed: ${err?.message ?? err}`;+ } finally {+ e.target.disabled = false;+ }+ });+ </script>+</body>+</html>diff --git a/x402-payment-modal/examples/server-express/server.js b/x402-payment-modal/examples/server-express/server.jsnew file mode 100644index 000000000..35c6245c9--- /dev/null+++ b/x402-payment-modal/examples/server-express/server.js@@ -0,0 +1,97 @@+// Runnable Express server for @three-ws/x402-payment-modal.+//+// What it does:+// 1. Mounts the Solana checkout router at /api/x402-checkout. The browser+// modal posts here to build and settle Solana USDC transfers. (EVM+// payments sign in-browser and never hit this server.)+// 2. Serves a trivial static page from ./public so you can click through the+// flow in a real browser.+// 3. Exposes ONE demo paid endpoint, GET /api/paid/hello, that returns a+// correct x402 v2 challenge so you can see the 402 → pay loop end to end.+//+// Run:+// npm install+// SOLANA_RPC_URL="https://your-rpc" npm start+// open http://localhost:3000++import express from 'express';+import { fileURLToPath } from 'node:url';+import { dirname, join } from 'node:path';+import { x402CheckoutRouter } from '@three-ws/x402-payment-modal/server/express';++const __dirname = dirname(fileURLToPath(import.meta.url));+const PORT = process.env.PORT || 3000;++// A public Solana mainnet RPC works for a quick try, but it is rate-limited.+// Use a dedicated RPC (Helius, Triton, QuickNode, …) for anything real.+const SOLANA_RPC_URL =+ process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';++const app = express();++// Required by the checkout router — it reads JSON request bodies.+app.use(express.json());++// The checkout endpoint the browser modal talks to for Solana payments.+app.use('/api/x402-checkout', x402CheckoutRouter({ rpcUrl: SOLANA_RPC_URL }));++// ── Demo paid endpoint ─────────────────────────────────────────────────────+//+// A real x402 resource answers with HTTP 402 + a challenge until it receives a+// valid X-PAYMENT header, then serves the content. Here we only implement the+// challenge half so you can watch the modal react to a 402.+//+// IMPORTANT: verifying and settling the X-PAYMENT payload against an x402+// facilitator is OUT OF SCOPE for this demo. In production you would verify the+// payment proof (and idempotency) before returning 200. See the docs:+// https://github.com/three-ws/x402-payment-modal/tree/main/docs+//+// Synthetic placeholders below — replace payTo / feePayer with YOUR addresses.+const DEMO_PAY_TO = 'So11111111111111111111111111111111111111112'; // replace me+const DEMO_FEE_PAYER = 'So11111111111111111111111111111111111111112'; // replace me++app.get('/api/paid/hello', (req, res) => {+ const hasPayment = Boolean(req.get('X-PAYMENT'));++ if (!hasPayment) {+ // No payment yet → answer with the x402 v2 challenge.+ return res.status(402).json({+ x402Version: 2,+ error: 'Payment required',+ resource: {+ url: `${req.protocol}://${req.get('host')}/api/paid/hello`,+ description: 'A friendly hello, paid for in USDC.',+ mimeType: 'application/json',+ },+ accepts: [+ {+ scheme: 'exact',+ // Solana mainnet, in CAIP-2 form.+ network: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',+ amount: '10000', // 0.01 USDC (USDC has 6 decimals → 10000 = 0.01)+ asset: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', // USDC mint+ payTo: DEMO_PAY_TO,+ maxTimeoutSeconds: 60,+ extra: {+ name: 'USDC',+ decimals: 6,+ feePayer: DEMO_FEE_PAYER,+ },+ },+ ],+ });+ }++ // A real implementation verifies the X-PAYMENT proof here before responding.+ return res.json({ message: 'Hello — thanks for paying with USDC!' });+});++// Static demo page (examples/server-express/public/index.html).+app.use(express.static(join(__dirname, 'public')));++app.listen(PORT, () => {+ console.log(`x402 checkout example running at http://localhost:${PORT}`);+ console.log(` checkout router → /api/x402-checkout`);+ console.log(` demo paid route → /api/paid/hello`);+ console.log(` Solana RPC → ${SOLANA_RPC_URL}`);+});