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: provably-fair verifiable vanity grinder with x402 and SDK support
nirholasbf57049f33c6
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d93d1b1fe..1bd43bb0d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,8 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Agent Studio** (`/agent-studio`) — Author your agent's brain, memory, body, money, and skills in one place, with a live 3D avatar that updates everywhere as you edit.- **Coin Clash** (`/clash`) — Token-gated community warfare. Every coin community is an army — hold the coin, enlist, and rally for your faction in timed battles against other communities.- **Flappin UFO — dodge asteroids for $THREE** (`/play/ufo`) — Pilot your UFO through an asteroid field. Connect your Solana wallet, submit your score as your wallet address, and claim your spot on the global $THREE leaderboard.+- **Verify a Vanity Receipt** (`/vanity/verify`) — Independently verify a three.ws provably-fair vanity wallet receipt — entirely in your browser. Prove the key was generated fresh under a committed seed and the operator never kept a copy.+- **x402 Studio — the Stripe of x402** (`/x402/studio`) — Merchant console to run a paid x402 business: products and pricing, payout and agent wallets, a real USDC send/receive with SNS .sol resolution, a drag-and-drop storefront, an embeddable pay-button builder, charity and round-up giving, CORS and security.- **8D audio mode at the Pole Club** — There's a new 8D pill in the Pole Club top bar. Flip it on (headphones recommended) and the whole soundtrack starts slowly orbiting around your head — the spinning, three-dimensional “8D audio” effect — looping a full lap roughly every eight seconds. It rides on top of everything: the muffled-through-the-door walk-in, the clear-up as you step inside, and the per-dancer tip tracks. The orbit only moves the stereo image, never the volume, so nothing pumps as it circles, and your choice is remembered between visits. Off by default. (`/club`) `[feature]`- **Agent Studio — one place to build your whole agent, with a live avatar** — Agent Studio is the new home for authoring everything about your AI agent — its brain, memory, 3D body, money, and skills — side by side with a live avatar that updates the instant you make a change, no save button and no refresh. The same living avatar can now appear anywhere on the platform as a presence companion, reacting with real emotion to what's happening: it celebrates a filled trade, looks concerned when a position drops, and stays in sync with whatever you edit in the Studio. This release ships the Studio shell and the shared foundation the rest of the experience builds on. (`/agent-studio`) `[feature]`- **Agent wallet's full money loop is now verified end-to-end on devnet** — A re-runnable harness now exercises the entire agent-wallet lifecycle in one pass — create a wallet, fund it, trade and snipe pump.fun tokens, pay an x402 service, exit a graduated position, and withdraw — against real Solana devnet state. It runs simulate-first and reports each step as passed or honestly blocked on funding/credentials, never a fake result, so regressions in the seams between deposit, trading, sniping, payments, and withdrawal surface before they reach holders. The agent wallet hub's Snipe tab now opens the live Sniper dashboard directly instead of a placeholder. (`/agent-wallet`) `[infra]`@@ -16,6 +18,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **AR & half-body avatar export fixed for compressed models** — View-in-AR (USDZ for iOS Quick Look) and the half-body VR-seat export now work for avatars that ship with meshopt or Draco geometry compression. Previously these exports silently failed on compressed GLBs because the loader had no decoder registered; the pipeline now loads the meshopt and Draco decoders before parsing, so every avatar — including the compressed ones produced by the server-side bake — converts cleanly. (`/gallery`) `[fix]`- **AR agents hold their place and size when you rotate your phone** — Camera AR used to assume you were holding your phone upright. Rotate to landscape — or just have the browser's toolbar slide away as you scroll — and a pinned agent could quietly change size or drift off the real-world spot you placed it on. IRL now re-reads your camera's lens and your screen's orientation the instant either changes, so the agent keeps its true scale and stays locked to its spot whether you hold the phone portrait or sideways. The motion-sensor lock that rotates the view as you turn now understands landscape too, so panning around the agent stays smooth and accurate, and the rapid resizing iPhone Safari does while scrolling no longer makes the scene stutter. (`/irl`) `[improvement, fix]`- **Brain Studio — build your agent’s mind as a visual circuit** — The Brain tab in Agent Studio is now a visual node editor: wire Persona, Model, Memory, Skills, and trading-reasoning nodes into a living graph that IS your agent’s personality. Pick from real LLMs (Claude, GPT, Granite and more) per branch, connect a memory port that recalls and writes real memories, and watch the active path light up as your agent thinks — tokens streaming, memory firing, the avatar reacting live. A built-in test chat runs your graph against the real models with real latency and token stats, and forkable templates (Sniper, Scalper, Researcher, Companion) get you started in one click. Your graph compiles straight to your agent’s persona so every existing chat surface picks up the change. (`/agent-studio`) `[feature]`+- **Charity and round-up donations now settle on-chain at checkout** — When a merchant turns on Giving, their charity split and round-up are no longer just shown — they move real money at the moment a buyer pays. The payment modal now offers the buyer a clear, pre-checked opt-in ("Add 0.009 USDC for Save the Reefs") and, when kept, appends the donation to the very same Solana transaction the buyer signs. One signature pays the merchant and the cause together, with the network fee still sponsored by the facilitator. The buyer always sees the exact amount and total before signing and can switch it off; the donation is bounded by a safety cap so a misconfigured rule can never sweep a wallet. Hosted /pay/c checkout links surface the cause up front, and the math — a basis-point share of the payment plus the round-up remainder — is covered by tests. `[feature, sdk]`- **Cleaner Pole Club bass — no more speaker distortion** — Fixed the buzzy bass distortion some listeners heard at the Pole Club, especially on laptop and phone speakers. The club's low-end was being boosted hard enough to clip the audio output when several tracks overlapped; we've added a brick-wall limiter on the final mix, evened out the reverb so it adds a predictable amount of space, and dialed the bass boost back to a level that still hits hard without overdriving. The room now sounds full and clean at any volume. (`/club`) `[fix]`- **Clearer IRL onboarding and copy** — Opening IRL for the first time now spells out the core loop in plain words: turn on Camera AR, aim at the spot you want, then tap Pin here to anchor your agent in real space. The on-screen guidance updates as you go — it points you to the next step before you've pinned, and confirms when your agent is anchored. We rewrote the status messages around pinning to be calm and literal instead of technical or alarming: waiting on a GPS fix now tells you it's quicker outdoors, pinning without location explains your agent is saved on this device until you turn location on, and a missing compass reads as a gentle note rather than a warning. The caption keyboard now opens reliably when the panel slides up on iPhone. (`/irl`) `[improvement]`- **Club dancers never flash a T-pose while the room loads in** — When you stepped onto the pole floor, the dancers used to stand stiff with their arms out — a frozen T-pose — for several seconds while their idle animation streamed in, and one of them could stay frozen even longer while her rig was swapped to a compatible one. Each dancer now has her idle and walk loaded and bound the instant she appears, so the first frame you see is her resting stance, and she steps to the pole with her legs moving. No more T-pose, no more sliding. (`/club`) `[fix]`@@ -61,6 +64,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **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]`- **Pole Club music opens up as you walk inside** — The soundtrack at the Pole Club now follows you in. Out in the alley it plays muffled and bass-heavy, like the room heard through the door. Pay the cover and the same track — never restarted, just picked up from wherever it is — gets a little clearer with every threshold you cross: a step more open when the rope drops, more again through the gallery and the clubhouse, then wide open the moment you step onto the floor. The walk in now sounds like a walk in. (`/club`) `[improvement]`- **Premium avatar cosmetics are now buyable right in the character creator** — Locked premium headwear, eyewear, dyes and auras in the character creator no longer dead-end on a placeholder — clicking one now opens the real wallet checkout and unlocks it the moment the USDC payment settles, then equips it on your live preview. Anything you already own loads pre-unlocked, and the price you see is the true checkout amount pulled from the catalog. (`/create`) `[feature, fix]`+- **Prove we never kept your vanity key — trustless wallet grinding** — Every vanity-address service asks you to trust the operator: trust they used real randomness, that they didn't keep a copy, that they didn't grind thousands of keys and hand you the one they secretly logged. Now you don't have to. The new provably-fair grinder commits to a random seed before it grinds, mixes in your own entropy so neither side controls the result, seals the secret so only you can open it, and returns a signed receipt. You can verify all of it after the fact — paste the receipt at three.ws/vanity/verify (everything runs in your browser, your keys never leave), run the open-source CLI, or call verifyVanityReceipt() in the SDK. The checks prove the key was generated fresh, that the address really comes from that seed, that it matches your pattern, and that three.ws — not an impostor — signed it. Optionally open the sealed key locally to prove you, and only you, hold it. (`/vanity/verify`) `[feature, security, sdk]`- **Put a talking 3D guide on any website — new @three-ws/page-agent SDK** — Drop one tag onto any site and a rigged 3D agent appears in the corner, greets visitors, and talks them through the page out loud — mouth moving in time with the words, all in the browser with no backend or API key. Visitors pick who guides them from a diverse roster of rigged agents (realistic, stylized, and a robot), and the choice is remembered as they move between pages. Only skeleton-rigged avatars ship in the catalog, so every guide actually breathes, blinks, and lip-syncs instead of standing frozen. Install @three-ws/page-agent from npm, or paste the one-line embed. `[sdk, feature]`- **Rigged-or-not filter across your Agents and Avatars** — The rigged-or-not category now reaches everything you own, not just the public gallery. Your Avatars page (both My avatars and the Community tab) and your Agents page each get a Rigged / Static filter and a badge on every card, so you can tell at a glance which models carry a skeleton and can play the animation library — and narrow the list to just the animation-ready ones. An agent's badge reflects the rig state of its 3D body. (`/dashboard/avatars`) `[feature]`- **Roaming links no longer open just by standing on them** — In full-page roaming mode — stroll or platformer — walking your avatar onto a link used to dive into it on its own after a short pause, which made it easy to leave a page by accident. Now standing on a link only arms it (it glows with a prompt) and you commit deliberately: press Space / Enter / E or tap the dive button in stroll mode, or press ↓ / the dive button in platformer mode. Gamepads work too — the left stick or d-pad walks, ✕/○ dive in stroll, and pushing down or ○ dives in platformer — so a controller drives the avatar exactly like the keyboard. `[improvement, sdk]`@@ -78,6 +82,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **The x402 Console — run a paid-API business end to end** — A new merchant console brings everything you need to charge for endpoints into one place — the Stripe of x402. Configure agent wallets (the named on-chain wallets your agents auto-pay and receive from, each with its own per-call and daily USDC caps), default payout addresses on Base and Solana, and per-product pricing. Build a hosted storefront with a drag-and-drop block editor — hero, product grid, featured product, text, image, button, divider, footer — with a live preview, then publish it to a public /store/<handle> page that takes real on-chain payments. Plus API keys, a settlement webhook, a CORS/domain allow-list, spending caps, accepted-network toggles, SIWX re-entry, and optional Giving — donate a share of every payment to a cause and let buyers round up, shown right on your storefront. Open it from the x402 dashboard. (`/dashboard/x402-admin`) `[feature, improvement]`- **The x402 payment modal is now a drop-in SDK any site can use** — The polished checkout that lets you pay any x402 endpoint — connect a wallet, approve, get a receipt, all in one popup — is now packaged as a standalone, dependency-free SDK (@three-ws/x402-payment-modal). One script tag turns any button into a pay button, on Solana (Phantom) or Base/EVM (MetaMask) in USDC. It ships with the server piece for Solana, full docs, a step-by-step tutorial, and ready-to-run HTML, React and Express examples, so other builders can add x402 payments to their own products the same way three.ws does. `[sdk, feature]`- **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]`+- **Turn any agent wallet into a giving wallet** — Every agent's self-custodied Solana wallet now has a Give tab. Pick a cause — any Solana wallet or .sol name — and donate SOL or USDC in one tap, or use a quick 1/5/10/25%/Max of the live balance. Round-up giving rounds a balance off and sends the spare change to your cause (e.g. 12.37 USDC → give $0.37, keep $12.00). Donations are real, server-signed, on-chain transfers — the same audited, idempotent path as a withdrawal — and your running total is tallied straight from the wallet's on-chain custody trail. Crypto transfers are final, so each donation is reviewed before it's sent. `[feature]`- **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]`diff --git a/api/_lib/env.js b/api/_lib/env.jsindex deb8e87db..f093b0e9c 100644--- a/api/_lib/env.js+++ b/api/_lib/env.js@@ -138,6 +138,17 @@ export const env = {return opt('WALLET_ENCRYPTION_KEY');},+ // Long-lived Ed25519 signing seed for the provably-fair vanity grinder+ // (api/_lib/vanity-service-key.js). Stored as a secret-box ciphertext (v2:…)+ // or a raw 32-byte seed in hex/Base58. Signs every verifiable-grind receipt;+ // the public key is published at /.well-known/three-vanity.json and pinned in+ // the SDK + verifier. Returns undefined when unset — the service module then+ // derives a deterministic dev key from JWT_SECRET (with a one-time warning) so+ // local/CI works, while production must set a dedicated value.+ get VANITY_SERVICE_KEY() {+ return opt('VANITY_SERVICE_KEY');+ },+// ── Agent-to-agent (A2A) autonomous payments ────────────────────────────// Secret that signs Intent Mandates (AP2-style budgeted spend authorizations).// Dedicated by preference; falls back to JWT_SECRET so the feature works indiff --git a/api/_lib/vanity-service-key.js b/api/_lib/vanity-service-key.jsnew file mode 100644index 000000000..0f9001e4a--- /dev/null+++ b/api/_lib/vanity-service-key.js@@ -0,0 +1,89 @@+/**+ * Service identity key for the provably-fair vanity grinder.+ *+ * The verifiable-grind endpoint signs every receipt with a long-lived Ed25519+ * key so a buyer can prove the receipt really came from three.ws. The SECRET+ * seed is custodial: it never leaves the server, never appears in a log, and is+ * stored encrypted at rest via secret-box.js. The PUBLIC key is published at+ * /.well-known/three-vanity.json and pinned in the SDK + verifier.+ *+ * Configuration (`VANITY_SERVICE_KEY`) accepts either:+ * • a secret-box v2 ciphertext ("v2:…") wrapping a 32-byte seed (hex/Base58), or+ * • a raw 32-byte Ed25519 seed in hex (64 chars) or Base58.+ *+ * When unset, a deterministic dev seed is derived from JWT_SECRET (HKDF, with a+ * one-time warning) so local/CI works without extra setup — production must set+ * a dedicated value so the published public key is stable and not session-bound.+ */++import bs58 from 'bs58';+import { ed25519 } from '@noble/curves/ed25519.js';+import { hkdf } from '@noble/hashes/hkdf';+import { sha256 } from '@noble/hashes/sha256';+import { bytesToHex, hexToBytes } from '@noble/hashes/utils';++import { env } from './env.js';+import { decryptSecret, isEncryptedSecret } from './secret-box.js';++const SEED_BYTES = 32;+const DEV_INFO = new TextEncoder().encode('three-vanity/dev-service-key/v1');++let _cached = null;+let _warnedDev = false;++function seedFromString(value, label) {+ const s = String(value).trim();+ if (/^[0-9a-fA-F]{64}$/.test(s)) return hexToBytes(s);+ const decoded = bs58.decode(s);+ if (decoded.length !== SEED_BYTES) {+ throw new Error(`${label} must decode to a 32-byte Ed25519 seed (got ${decoded.length})`);+ }+ return decoded;+}++async function loadSeed() {+ const configured = env.VANITY_SERVICE_KEY;+ if (configured) {+ const raw = isEncryptedSecret(configured) ? await decryptSecret(configured) : configured;+ return seedFromString(raw, 'VANITY_SERVICE_KEY');+ }+ // Deterministic dev key derived from JWT_SECRET. Stable per-deployment so the+ // published public key and signed receipts stay consistent within an env.+ if (!_warnedDev) {+ _warnedDev = true;+ console.warn(+ '[vanity-service-key] VANITY_SERVICE_KEY is not set; deriving a deterministic dev ' ++ 'signing key from JWT_SECRET. Set a dedicated VANITY_SERVICE_KEY in production so ' ++ 'the published service public key is stable and independent of the session secret.',+ );+ }+ const ikm = new TextEncoder().encode(env.JWT_SECRET);+ return hkdf(sha256, ikm, sha256(DEV_INFO), DEV_INFO, SEED_BYTES);+}++/**+ * Resolve the service signing identity. Cached after first load.+ * @returns {Promise<{ seed: Uint8Array, publicKey: Uint8Array, publicKeyBase58: string, publicKeyHex: string }>}+ */+export async function getServiceIdentity() {+ if (_cached) return _cached;+ const seed = await loadSeed();+ const publicKey = ed25519.getPublicKey(seed);+ _cached = {+ seed,+ publicKey,+ publicKeyBase58: bs58.encode(publicKey),+ publicKeyHex: bytesToHex(publicKey),+ };+ return _cached;+}++/** The signing seed only — for signReceipt(). Never log or return this. */+export async function getServiceSigningSeed() {+ return (await getServiceIdentity()).seed;+}++/** The public key (Base58) — safe to publish/pin. */+export async function getServicePublicKeyBase58() {+ return (await getServiceIdentity()).publicKeyBase58;+}diff --git a/api/wk.js b/api/wk.jsindex f591c81f2..083408afe 100644--- a/api/wk.js+++ b/api/wk.js@@ -1687,8 +1687,58 @@ function handleSperaxPlugin(req, res) {return json(res, 200, speraxManifest, { 'cache-control': 'public, max-age=3600' });}+// ── three-vanity (/.well-known/three-vanity.json) ────────────────────────────+// Publishes the provably-fair vanity grinder's service identity: the long-lived+// Ed25519 public key that signs every verifiable-grind receipt, the protocol+// version, and the scheme ids. The SDK + CLI + /vanity/verify page pin this key+// so a buyer can prove a receipt really came from three.ws. The SECRET seed+// never leaves the server — only the public key is published here.+async function handleThreeVanity(req, res) {+ let identity;+ try {+ const mod = await import('./_lib/vanity-service-key.js');+ identity = await mod.getServiceIdentity();+ } catch (err) {+ console.error('[wk/three-vanity] service key unavailable', err?.message || err);+ return error(res, 500, 'service_key_unavailable', 'vanity service key not configured');+ }+ const origin = env.APP_ORIGIN;+ return json(+ res,+ 200,+ {+ protocol: 'three-vanity/v1',+ description:+ 'Provably-fair Solana vanity grinding. Each key is ground under a commit–reveal ' ++ 'seed-mixing protocol and delivered with a receipt signed by the service key below. ' ++ 'Verify a receipt entirely client-side — nothing here is trusted, everything is recomputed.',+ serviceKey: {+ curve: 'ed25519',+ publicKeyBase58: identity.publicKeyBase58,+ publicKeyHex: identity.publicKeyHex,+ use: 'receipt-signing',+ },+ schemes: {+ commitment: 'sha256(domain‖serverSeed)',+ seedMix: 'hkdf-sha256(serverSeed‖clientSeed‖requestNonce)',+ candidate: 'hmac-sha256(masterSeed, domain‖uint64_be(index)) → ed25519 seed',+ signature: 'ed25519',+ sealedEnvelope: 'x25519-hkdf-sha256-aes256gcm/v1',+ },+ endpoints: {+ grind: `${origin}/api/x402/vanity-verifiable`,+ verifyPage: `${origin}/vanity/verify`,+ },+ documentation: `${origin}/vanity/verify`,+ protocolSpec: 'https://github.com/nirholas/three.ws/blob/main/docs/PROTOCOL-vanity.md',+ },+ { 'cache-control': 'public, max-age=300' },+ );+}+const DISPATCH = {'agent-attestation-schemas': handleAttestationSchemas,+ 'three-vanity': handleThreeVanity,'chat-plugin': handleChatPlugin,'sperax-plugin': handleSperaxPlugin,'oauth-authorization-server': handleOauthAuthServer,@@ -1706,6 +1756,7 @@ const PUBLIC_DISCOVERY = new Set(['chat-plugin','sperax-plugin','agent-attestation-schemas',+ 'three-vanity',]);export default wrap(async (req, res) => {diff --git a/api/x402/vanity-verifiable.js b/api/x402/vanity-verifiable.jsnew file mode 100644index 000000000..9cd6bde55--- /dev/null+++ b/api/x402/vanity-verifiable.js@@ -0,0 +1,532 @@+// GET /api/x402/vanity-verifiable?prefix=<base58>&suffix=<base58>&ignoreCase=<0|1>+// &clientSeed=<hex|base58>&sealTo=<X25519 pubkey>+//+// Provably-fair sibling of /api/x402/vanity. Same x402 pay-per-call rails, same+// idempotency + verify-grind-settle ordering — but every key is ground under a+// COMMIT–REVEAL seed-mixing protocol (three-vanity/v1) and delivered with a+// signed, independently-verifiable receipt. A buyer can prove, after the fact+// and with open-source tooling, that:+//+// 1. the key was generated fresh from entropy the server COMMITTED to before+// it knew the result (commitment = SHA-256(serverSeed), bound into the+// signed receipt) — no precomputed rainbow table keyed to your pattern;+// 2. the buyer's own clientSeed was mixed in, so neither party alone controlled+// the output;+// 3. the address derives from the revealed seed at the claimed index, matches+// the pattern, and the difficulty claim is the honest 58^n model;+// 4. the secret was sealed only to the buyer (ECIES) — strongly defaulted, so+// the plaintext key never appears in the response, a log, or the cache.+//+// The receipt is signed by the service's long-lived Ed25519 identity key,+// published at /.well-known/three-vanity.json and pinned in the SDK + verifier.+// Verify with @three-ws/solana-agent's verifyVanityReceipt(), the CLI+// (scripts/verify-vanity-receipt.mjs), or the /vanity/verify web page.+//+// Determinism is the whole point, so grinding walks a deterministic candidate+// stream in pure-JS Ed25519 (verifiable-grind.js) rather than the WASM engine —+// the verifier must reproduce the exact stream. That runs slower than WASM, so+// the combined pattern is capped at 3 chars and priced to track expected work.+//+// The plain /api/x402/vanity endpoint keeps working unchanged.++import { wrap, cors, error, rateLimited } from '../_lib/http.js';+import {+ NETWORK_BASE_MAINNET,+ NETWORK_SOLANA_MAINNET,+ send402,+ verifyPayment,+ settlePayment,+ encodePaymentResponseHeader,+ permit2VariantOf,+ resolveResourceUrl,+ buildBazaarSchema,+} from '../_lib/x402-spec.js';+import { env } from '../_lib/env.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import {+ PAYMENT_IDENTIFIER,+ checkCache,+ extractIdFromHeader,+ hashPaymentProof,+ hashRequestPayload,+ paymentIdentifierExtension,+ storeResponse,+ writeCachedResponse,+ writeConflict,+} from '../_lib/x402/payment-identifier-server.js';+import { installAccessControl } from '../_lib/x402/access-control.js';+import { withService } from '../_lib/x402/bazaar-helpers.js';+import { validatePattern, expectedAttempts } from '../../src/solana/vanity/validation.js';+import {+ sealToRecipient,+ parseX25519Key,+ SEALED_ENVELOPE_SCHEME,+} from '../../src/solana/vanity/sealed-envelope.js';+import {+ PROTOCOL_VERSION,+ RECEIPT_TYPE,+ commitToSeed,+ deriveMasterSeed,+ grindDeterministic,+ randomSeed,+ signReceipt,+} from '../../src/solana/vanity/verifiable-grind.js';+import { getServiceIdentity } from '../_lib/vanity-service-key.js';+import bs58 from 'bs58';+import { bytesToHex, hexToBytes } from '@noble/hashes/utils';++const ROUTE = '/api/x402/vanity-verifiable';+const REQUIRED_SCOPE = 'x402:bypass';+const accessControl = installAccessControl({ requiredScope: REQUIRED_SCOPE });+const routeConfig = { path: ROUTE, method: 'GET', requiredScope: REQUIRED_SCOPE };++// Pure-JS Ed25519 derivation is the verifiability cost: ~a few thousand+// candidates/sec vs the WASM engine's ~25k. We budget conservatively under the+// 60s function ceiling and cap at 3 combined chars; ≥3 chars should run in the+// browser grinder, then be self-verified locally.+const GRIND_TIME_BUDGET_MS = 40_000;+const GRIND_MAX_ATTEMPTS = 5_000_000;++// Largest combined (prefix + suffix) length grindable server-side. Beyond this,+// pure-JS Ed25519 derivation can't clear the time budget; the browser grinder+// at /vanity handles longer patterns, then receipts self-verify locally.+const MAX_SERVER_PATTERN_LENGTH = 3;++// Difficulty-tiered price in USDC atomic units (6 decimals), indexed by the+// combined prefix+suffix length. Verifiable mode carries a small premium over+// the plain endpoint to reflect the slower deterministic derivation + signing.+const PRICE_BY_LENGTH = {+ 0: 20_000, // $0.02 — base / probe+ 1: 20_000, // $0.02+ 2: 100_000, // $0.10+ 3: 400_000, // $0.40+};++function priceAtomicsFor(combinedLength) {+ return PRICE_BY_LENGTH[combinedLength] ?? PRICE_BY_LENGTH[MAX_SERVER_PATTERN_LENGTH];+}++const ROUTE_DESCRIPTION =+ 'three.ws Provably-Fair Vanity Grinder — generate a brand-new Solana wallet ' ++ 'whose Base58 address starts with your chosen prefix and/or ends with your suffix, ' ++ 'with a SIGNED, independently-verifiable receipt that proves we generated the key ' ++ 'fresh and never kept a copy. The server commits to a random 32-byte seed ' ++ '(commitment = SHA-256(serverSeed)) BEFORE grinding, mixes in your optional ' ++ 'clientSeed so neither party alone controls the output, derives each candidate ' ++ 'deterministically (HMAC-SHA256 → Ed25519), and signs a receipt with its ' ++ 'long-lived service key (published at /.well-known/three-vanity.json). Pass ' ++ 'sealTo=<X25519 public key> (strongly recommended) and the secret is ECIES-sealed ' ++ 'to you — the plaintext never appears in the response or any log. Verify the ' ++ "receipt entirely client-side with @three-ws/solana-agent's verifyVanityReceipt(), " ++ 'the open-source CLI, or three.ws/vanity/verify. Capped at 3 Base58 chars, priced ' ++ '$0.02–$0.40. Pay-per-call in USDC on Base or Solana mainnet — no API keys.';++const DISCOVERY_INPUT_EXAMPLE = { prefix: 'So', suffix: '', ignoreCase: '0', sealTo: '' };++const DISCOVERY_INPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ properties: {+ prefix: {+ type: 'string',+ description:+ 'Base58 characters the address must start with. Base58 excludes 0, O, I, l. ' ++ 'Combined with suffix, max 3 characters.',+ },+ suffix: {+ type: 'string',+ description: 'Base58 characters the address must end with. Combined with prefix, max 3 characters.',+ },+ ignoreCase: {+ type: 'string',+ enum: ['0', '1', 'true', 'false'],+ description: 'When 1/true, match the pattern case-insensitively (faster, less specific).',+ },+ clientSeed: {+ type: 'string',+ description:+ 'Optional. Your own entropy as hex or Base58 (any length). Mixed into the seed so ' ++ 'the server could not have predicted the result at commit time. A fresh random one ' ++ 'is generated and revealed in the receipt when omitted.',+ },+ sealTo: {+ type: 'string',+ description:+ 'Strongly recommended. Your 32-byte X25519 public key (Base58, Base64url, or hex). ' ++ 'When set, the secret is ECIES-sealed to it and omitted from the response — open it ' ++ 'client-side with the matching private key.',+ },+ },+};++// SECURITY: discovery EXAMPLE only — the fields below document the response+// shape, they are NOT a real key. serverSeed/address/signature are synthetic.+const DISCOVERY_OUTPUT_EXAMPLE = {+ protocol: PROTOCOL_VERSION,+ receiptType: RECEIPT_TYPE,+ address: 'SoEXAMPLEdoNotUse1111111111111111111111111111',+ pattern: { prefix: 'So', suffix: null, ignoreCase: false },+ commitment: '0000000000000000000000000000000000000000000000000000000000000000',+ serverSeed: '0000000000000000000000000000000000000000000000000000000000000000',+ clientSeed: '1111111111111111111111111111111111111111111111111111111111111111',+ requestNonce: 'a1b2c3d4e5f60718293a4b5c6d7e8f90',+ winningIndex: 3041,+ attempts: 3042,+ durationMs: 1180,+ difficulty: { expectedAttempts: 3364, model: '58^effectiveLength' },+ sealed: true,+ sealedScheme: SEALED_ENVELOPE_SCHEME,+ sealedRecipient: '<Base58 X25519 recipient>',+ sealedEpk: '<Base58 ephemeral public key>',+ sealedSecret: { scheme: SEALED_ENVELOPE_SCHEME, epk: '…', nonce: '…', ciphertext: '…', recipient: '…' },+ servicePublicKey: '<Base58 Ed25519 service key>',+ signature: '<hex Ed25519 signature>',+ signatureScheme: 'ed25519',+ ts: '2026-06-19T00:00:00.000Z',+ network: 'solana',+ explorerUrl: 'https://solscan.io/account/SoEXAMPLEdoNotUse1111111111111111111111111111',+ verifyUrl: 'https://three.ws/vanity/verify',+ serviceKeyUrl: 'https://three.ws/.well-known/three-vanity.json',+};++const DISCOVERY_OUTPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['protocol', 'address', 'commitment', 'serverSeed', 'winningIndex', 'signature', 'servicePublicKey'],+ properties: {+ protocol: { type: 'string', const: PROTOCOL_VERSION },+ receiptType: { type: 'string' },+ address: { type: 'string', description: 'Base58 Solana public key.' },+ pattern: { type: 'object' },+ commitment: { type: 'string', description: 'SHA-256(serverSeed), committed before grinding.' },+ serverSeed: { type: 'string', description: 'Revealed 32-byte seed (hex). Verify SHA-256 = commitment.' },+ clientSeed: { type: 'string', description: 'Buyer entropy mixed into the seed (hex).' },+ requestNonce: { type: 'string' },+ winningIndex: { type: 'integer', description: 'Candidate index whose address matched.' },+ attempts: { type: 'integer' },+ durationMs: { type: 'number' },+ difficulty: { type: 'object' },+ sealed: { type: 'boolean' },+ sealedSecret: { type: 'object', description: 'ECIES envelope — open with your X25519 private key.' },+ secretKeyBase58: { type: 'string', description: 'Present only when sealTo is omitted.' },+ secretKey: { type: 'array', items: { type: 'integer' }, description: 'Present only when sealTo is omitted.' },+ servicePublicKey: { type: 'string', description: 'Base58 Ed25519 key that signed this receipt.' },+ signature: { type: 'string', description: 'Hex Ed25519 signature over the canonical receipt.' },+ verifyUrl: { type: 'string', format: 'uri' },+ serviceKeyUrl: { type: 'string', format: 'uri' },+ },+};++const ROUTE_BAZAAR = {+ discoverable: true,+ info: {+ input: { type: 'http', method: 'GET', queryParams: DISCOVERY_INPUT_EXAMPLE },+ output: { type: 'json', example: DISCOVERY_OUTPUT_EXAMPLE },+ },+ schema: buildBazaarSchema({+ method: 'GET',+ queryParamsSchema: DISCOVERY_INPUT_SCHEMA,+ outputSchema: DISCOVERY_OUTPUT_SCHEMA,+ }),+};++function buildRequirements(resourceUrl, priceAtomics) {+ const amount = String(priceAtomics);+ const eip3009 = {+ scheme: 'exact',+ network: NETWORK_BASE_MAINNET,+ amount,+ payTo: env.X402_PAY_TO_BASE,+ asset: env.X402_ASSET_ADDRESS_BASE,+ maxTimeoutSeconds: 60,+ resource: resourceUrl,+ extra: { name: 'USD Coin', version: '2', decimals: 6 },+ };+ const out = [eip3009];+ const permit2 = permit2VariantOf(eip3009);+ if (permit2) out.push(permit2);+ if (env.X402_PAY_TO_SOLANA) {+ out.push({+ scheme: 'exact',+ network: NETWORK_SOLANA_MAINNET,+ amount,+ payTo: env.X402_PAY_TO_SOLANA,+ asset: env.X402_ASSET_MINT_SOLANA,+ maxTimeoutSeconds: 60,+ resource: resourceUrl,+ extra: { name: 'USDC', decimals: 6, feePayer: env.X402_FEE_PAYER_SOLANA },+ });+ }+ return out;+}++// Parse a client-supplied seed (hex or Base58) into bytes, or generate a fresh+// random 32-byte seed when omitted. Throws a clean 400 on malformed input.+function parseClientSeed(raw) {+ if (raw == null || raw === '') return randomSeed();+ const s = String(raw).trim();+ try {+ if (/^[0-9a-fA-F]+$/.test(s) && s.length % 2 === 0) {+ const b = hexToBytes(s);+ if (b.length === 0 || b.length > 1024) throw new Error('length');+ return b;+ }+ const b = bs58.decode(s);+ if (b.length === 0 || b.length > 1024) throw new Error('length');+ return b;+ } catch {+ throw Object.assign(new Error('clientSeed must be hex or Base58 (1–1024 bytes)'), {+ status: 400,+ code: 'validation_error',+ });+ }+}++function parsePattern(req) {+ const q = req.query || {};+ const prefix = typeof q.prefix === 'string' ? q.prefix.trim() : '';+ const suffix = typeof q.suffix === 'string' ? q.suffix.trim() : '';+ const ignoreCase = q.ignoreCase === '1' || q.ignoreCase === 'true';++ for (const [label, pattern] of [['prefix', prefix], ['suffix', suffix]]) {+ if (!pattern) continue;+ const v = validatePattern(pattern);+ if (!v.valid) {+ throw Object.assign(new Error(`invalid ${label}: ${v.errors.join('; ')}`), {+ status: 400,+ code: 'validation_error',+ });+ }+ }++ const combinedLength = prefix.length + suffix.length;+ if (combinedLength > MAX_SERVER_PATTERN_LENGTH) {+ throw Object.assign(+ new Error(+ `combined pattern length ${combinedLength} exceeds the verifiable-grind server limit of ` ++ `${MAX_SERVER_PATTERN_LENGTH} characters — grind longer patterns in the browser at /vanity, ` ++ `then self-verify your own receipt locally`,+ ),+ { status: 400, code: 'pattern_too_long' },+ );+ }++ let sealTo = null;+ if (typeof q.sealTo === 'string' && q.sealTo.trim()) {+ sealTo = q.sealTo.trim();+ parseX25519Key(sealTo, 'sealTo'); // validate shape up front (clean 400 pre-payment)+ }++ const clientSeed = parseClientSeed(q.clientSeed);++ return { prefix, suffix, ignoreCase, combinedLength, sealTo, clientSeed };+}++const PUBLIC_ORIGIN = env.APP_ORIGIN || 'https://three.ws';++async function grindAndBuildReceipt({ prefix, suffix, ignoreCase, sealTo, clientSeed }) {+ const identity = await getServiceIdentity();+ const serverSeed = randomSeed();+ const requestNonce = randomSeed().slice(0, 16);+ const commitment = commitToSeed(serverSeed);++ const masterSeed = deriveMasterSeed({ serverSeed, clientSeed, requestNonce });+ const result = grindDeterministic({+ masterSeed,+ prefix,+ suffix,+ ignoreCase,+ maxAttempts: GRIND_MAX_ATTEMPTS,+ timeBudgetMs: GRIND_TIME_BUDGET_MS,+ });+ if (!result.found) {+ throw Object.assign(+ new Error(+ `grind budget exhausted after ${result.attempts} attempts in ${Math.round(result.durationMs)}ms — retry`,+ ),+ { status: 504, code: 'grind_exhausted' },+ );+ }++ const difficulty = {+ expectedAttempts: Math.round(expectedAttempts(prefix, suffix, ignoreCase)),+ model: '58^effectiveLength',+ };++ // Seal the secret to the buyer when an X25519 key is supplied. The signed+ // receipt records the envelope's recipient + epk so the buyer can prove THIS+ // envelope belongs to THIS key. The plaintext secret only ships when unsealed.+ let sealed = null;+ if (sealTo) {+ const bundle = {+ format: 'keypair',+ secretKeyBase58: bs58.encode(result.secretKey),+ secretKey: Array.from(result.secretKey),+ seed: bytesToHex(result.seed),+ };+ sealed = await sealToRecipient(JSON.stringify(bundle), sealTo);+ }++ const core = {+ protocol: PROTOCOL_VERSION,+ receiptType: RECEIPT_TYPE,+ address: result.address,+ pattern: { prefix: prefix || null, suffix: suffix || null, ignoreCase },+ commitment,+ serverSeed: bytesToHex(serverSeed),+ clientSeed: bytesToHex(clientSeed),+ requestNonce: bytesToHex(requestNonce),+ winningIndex: result.index,+ attempts: result.attempts,+ durationMs: Math.round(result.durationMs),+ difficulty,+ sealed: !!sealed,+ sealedScheme: sealed ? SEALED_ENVELOPE_SCHEME : null,+ sealedRecipient: sealed ? sealed.recipient : null,+ sealedEpk: sealed ? sealed.epk : null,+ network: 'solana',+ ts: new Date().toISOString(),+ };++ const signed = signReceipt({ core, signingSeed: identity.seed });++ // Assemble the response: the signed receipt + delivery (sealed envelope or+ // the plaintext key when unsealed) + navigation to the verifier.+ const response = {+ ...signed,+ explorerUrl: `https://solscan.io/account/${result.address}`,+ verifyUrl: `${PUBLIC_ORIGIN}/vanity/verify`,+ serviceKeyUrl: `${PUBLIC_ORIGIN}/.well-known/three-vanity.json`,+ };+ if (sealed) {+ response.sealedSecret = sealed;+ response.sealedFields = ['format', 'secretKeyBase58', 'secretKey', 'seed'];+ } else {+ response.secretKeyBase58 = bs58.encode(result.secretKey);+ response.secretKey = Array.from(result.secretKey);+ response.seed = bytesToHex(result.seed);+ }+ return response;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (req.method !== 'GET') {+ res.setHeader('allow', 'GET');+ return error(res, 405, 'method_not_allowed', 'use GET');+ }++ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ let pattern;+ try {+ pattern = parsePattern(req);+ } catch (err) {+ return error(res, err.status || 400, err.code || 'validation_error', err.message);+ }++ const resourceUrl = resolveResourceUrl(req, ROUTE);+ const priceAtomics = priceAtomicsFor(pattern.combinedLength);+ const requirements = buildRequirements(resourceUrl, priceAtomics);+ const service = withService({+ serviceName: 'three.ws Provably-Fair Vanity Grinder',+ tags: ['solana', 'vanity', 'keypair', 'wallet', 'provably-fair', 'verifiable', 'trustless', 'attestation'],+ });+ const challenge = {+ resourceUrl,+ accepts: requirements,+ description: ROUTE_DESCRIPTION,+ bazaar: ROUTE_BAZAAR,+ extensions: { [PAYMENT_IDENTIFIER]: paymentIdentifierExtension(false) },+ serviceName: service.serviceName,+ tags: service.tags,+ iconUrl: service.iconUrl,+ };++ const acResult = await accessControl(req, routeConfig);+ if (acResult?.abort) {+ if (acResult.headers) for (const [k, v] of Object.entries(acResult.headers)) res.setHeader(k, v);+ return error(res, acResult.status || 403, acResult.code || 'access_denied', acResult.reason || 'access denied');+ }+ if (acResult?.grantAccess) {+ let result;+ try {+ result = await grindAndBuildReceipt(pattern);+ } catch (err) {+ return error(res, err.status || 500, err.code || 'internal_error', err.message);+ }+ if (acResult.headers) for (const [k, v] of Object.entries(acResult.headers)) res.setHeader(k, v);+ res.setHeader('x-payment-bypass', acResult.reason || 'granted');+ res.setHeader('cache-control', 'no-store');+ res.setHeader('content-type', 'application/json; charset=utf-8');+ res.end(JSON.stringify(result));+ return;+ }++ const paymentHeader = req.headers['x-payment'] || req.headers['payment-signature'];+ if (!paymentHeader) return send402(res, challenge);++ const clientPaymentId = extractIdFromHeader(paymentHeader);+ const payloadHash = hashRequestPayload({ method: req.method, url: req.url, body: null });+ const paymentHash = hashPaymentProof(paymentHeader);+ const paymentId = clientPaymentId || (paymentHash ? `proof:${paymentHash}` : null);+ if (paymentId) {+ const lookup = await checkCache({ route: ROUTE, paymentId, payloadHash, paymentHash });+ if (lookup.kind === 'hit') return writeCachedResponse(res, lookup.entry);+ if (lookup.kind === 'conflict') {+ return writeConflict(res, {+ route: ROUTE,+ attemptedHash: lookup.attemptedHash,+ existingHash: lookup.existingHash,+ reason: lookup.reason,+ });+ }+ }++ let verified;+ try {+ verified = await verifyPayment({ paymentHeader, requirements });+ } catch (err) {+ if (err.status === 402) return send402(res, { ...challenge, error: err.message });+ return error(res, err.status || 502, err.code || 'verify_failed', err.message);+ }++ // Grind AFTER verify but BEFORE settle: an exhausted budget throws here and+ // settlement never runs, so the buyer isn't charged for a failed grind.+ let result;+ try {+ result = await grindAndBuildReceipt(pattern);+ } catch (err) {+ return error(res, err.status || 500, err.code || 'grind_failed', err.message);+ }++ let settled;+ try {+ settled = await settlePayment({ verified });+ } catch (err) {+ return error(res, err.status || 502, err.code || 'settle_failed', err.message);+ }++ const paymentResponseHeader = encodePaymentResponseHeader(settled);+ const contentType = 'application/json; charset=utf-8';+ const body = JSON.stringify(result);++ res.setHeader('x-payment-response', paymentResponseHeader);+ res.setHeader('cache-control', 'no-store');+ res.setHeader('content-type', contentType);+ res.end(body);++ if (paymentId) {+ await storeResponse({+ route: ROUTE,+ paymentId,+ payloadHash,+ paymentHash,+ status: 200,+ body,+ contentType,+ paymentResponseHeader,+ });+ }+});diff --git a/data/changelog.json b/data/changelog.jsonindex 83cd27740..3ebe88652 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,34 @@{"$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": "Prove we never kept your vanity key — trustless wallet grinding",+ "summary": "Every vanity-address service asks you to trust the operator: trust they used real randomness, that they didn't keep a copy, that they didn't grind thousands of keys and hand you the one they secretly logged. Now you don't have to. The new provably-fair grinder commits to a random seed before it grinds, mixes in your own entropy so neither side controls the result, seals the secret so only you can open it, and returns a signed receipt. You can verify all of it after the fact — paste the receipt at three.ws/vanity/verify (everything runs in your browser, your keys never leave), run the open-source CLI, or call verifyVanityReceipt() in the SDK. The checks prove the key was generated fresh, that the address really comes from that seed, that it matches your pattern, and that three.ws — not an impostor — signed it. Optionally open the sealed key locally to prove you, and only you, hold it.",+ "tags": [+ "feature",+ "security",+ "sdk"+ ],+ "link": "/vanity/verify"+ },+ {+ "date": "2026-06-19",+ "title": "Charity and round-up donations now settle on-chain at checkout",+ "summary": "When a merchant turns on Giving, their charity split and round-up are no longer just shown — they move real money at the moment a buyer pays. The payment modal now offers the buyer a clear, pre-checked opt-in (\"Add 0.009 USDC for Save the Reefs\") and, when kept, appends the donation to the very same Solana transaction the buyer signs. One signature pays the merchant and the cause together, with the network fee still sponsored by the facilitator. The buyer always sees the exact amount and total before signing and can switch it off; the donation is bounded by a safety cap so a misconfigured rule can never sweep a wallet. Hosted /pay/c checkout links surface the cause up front, and the math — a basis-point share of the payment plus the round-up remainder — is covered by tests.",+ "tags": [+ "feature",+ "sdk"+ ]+ },+ {+ "date": "2026-06-19",+ "title": "Turn any agent wallet into a giving wallet",+ "summary": "Every agent's self-custodied Solana wallet now has a Give tab. Pick a cause — any Solana wallet or .sol name — and donate SOL or USDC in one tap, or use a quick 1/5/10/25%/Max of the live balance. Round-up giving rounds a balance off and sends the spare change to your cause (e.g. 12.37 USDC → give $0.37, keep $12.00). Donations are real, server-signed, on-chain transfers — the same audited, idempotent path as a withdrawal — and your running total is tallied straight from the wallet's on-chain custody trail. Crypto transfers are final, so each donation is reviewed before it's sent.",+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-19","title": "Roaming links no longer open just by standing on them",diff --git a/data/pages.json b/data/pages.jsonindex 5aa23d4cc..347f9f1b3 100644--- a/data/pages.json+++ b/data/pages.json@@ -545,6 +545,14 @@"changefreq": "weekly","added": "2026-05-10"},+ {+ "path": "/x402/studio",+ "title": "x402 Studio — the Stripe of x402",+ "description": "Merchant console to run a paid x402 business: products and pricing, payout and agent wallets, a real USDC send/receive with SNS .sol resolution, a drag-and-drop storefront, an embeddable pay-button builder, charity and round-up giving, CORS and security.",+ "priority": 0.7,+ "changefreq": "weekly",+ "added": "2026-06-19"+ },{"path": "/play/agent-wallet","title": "Agent Wallet (x402 on Solana)",@@ -633,6 +641,14 @@"changefreq": "monthly","added": "2026-04-29"},+ {+ "path": "/vanity/verify",+ "title": "Verify a Vanity Receipt",+ "description": "Independently verify a three.ws provably-fair vanity wallet receipt — entirely in your browser. Prove the key was generated fresh under a committed seed and the operator never kept a copy.",+ "priority": 0.6,+ "changefreq": "monthly",+ "added": "2026-06-19"+ },{"path": "/eth-vanity","title": "ETH Vanity (CREATE2)",diff --git a/docs/PROTOCOL-vanity.md b/docs/PROTOCOL-vanity.mdnew file mode 100644index 000000000..6d9890244--- /dev/null+++ b/docs/PROTOCOL-vanity.md@@ -0,0 +1,243 @@+# three-vanity/v1 — Provably-Fair Vanity Grinding Protocol++A vanity-address service normally asks you to **trust the operator**: trust that+your key was generated with real randomness, that no copy was kept, that they+didn't grind thousands of candidates and hand you the one whose key they secretly+logged. There is no proof; you just hope.++`three-vanity/v1` replaces that hope with a **commit–reveal + sealed-delivery ++signed-receipt** protocol. A buyer can verify, after the fact and with+open-source tooling, that:++1. the key was generated **fresh** from entropy the server committed to *before*+ it knew the buyer's pattern (no precomputed rainbow table of keys);+2. the buyer's own entropy was mixed in, so **neither party alone** controlled+ the output;+3. the address actually derives from the revealed seed, matches the pattern, and+ the difficulty claim is the honest probability model;+4. the receipt was **signed by the three.ws service key**, not an impostor;+5. (optionally) the key the buyer recovered from the sealed envelope is+ byte-for-byte the key the receipt describes — **the buyer alone holds it**.++This document specifies the scheme precisely enough to reimplement the verifier+in any language. The reference implementations are+[`src/solana/vanity/verifiable-grind.js`](../src/solana/vanity/verifiable-grind.js)+(server + Node verifier), [`solana-agent-sdk/src/vanity`](../solana-agent-sdk/src/vanity)+(TypeScript SDK), and [`scripts/verify-vanity-receipt.mjs`](../scripts/verify-vanity-receipt.mjs)+(CLI). The web verifier is [`/vanity/verify`](https://three.ws/vanity/verify).++---++## Primitives++| Purpose | Algorithm | Source |+| ------------------ | ------------------------------------------- | --------------------- |+| Hash / commitment | SHA-256 | `@noble/hashes` |+| Seed mixing (KDF) | HKDF-SHA256 | `@noble/hashes` |+| Candidate stream | HMAC-SHA256 | `@noble/hashes` |+| Keypair | Ed25519 (Solana address = public key) | `@noble/curves` |+| Receipt signature | Ed25519 | `@noble/curves` |+| Sealed delivery | `x25519-hkdf-sha256-aes256gcm/v1` (ECIES) | `sealed-envelope.js` |++All byte strings below are concatenated left-to-right. `uint64_be(n)` is the+8-byte big-endian encoding of a non-negative integer. Domain-separation tags are+ASCII (UTF-8) byte strings.++### Domain-separation tags++```+TAG_SEED_COMMIT = "three-vanity/seed-commit/v1"+TAG_MIX_SALT = SHA-256("three-vanity/mix-salt/v1") // 32 bytes+TAG_MASTER_INFO = "three-vanity/master/v1"+TAG_CANDIDATE = "three-vanity/candidate/v1"+TAG_RECEIPT = "three-vanity/receipt/v1"+```++---++## 1. Commitment (commit phase)++Before grinding, the server draws a uniformly-random 32-byte `serverSeed` and+publishes a commitment to it:++```+commitment = hex( SHA-256( TAG_SEED_COMMIT ‖ serverSeed ) )+```++The commitment is bound into the signed receipt, so the server is locked to that+seed *before* it knows which candidate will win. It cannot have precomputed a+table of keys keyed to the buyer's pattern: any swap of `serverSeed` after the+fact breaks `SHA-256(serverSeed) == commitment`.++`serverSeed` is **revealed** in the receipt (the reveal phase). Verification+recomputes the commitment and compares it byte-for-byte.++## 2. Seed mixing++Neither the server nor the buyer may control the output alone. The two seeds and+the per-request nonce are folded into one 32-byte master seed:++```+masterSeed = HKDF-SHA256(+ ikm = serverSeed ‖ clientSeed ‖ requestNonce,+ salt = TAG_MIX_SALT,+ info = TAG_MASTER_INFO,+ len = 32 )+```++- `clientSeed` is buyer-supplied entropy (hex or Base58, any length 1–1024+ bytes). If the buyer omits it, the server generates a fresh random 32-byte+ `clientSeed` and **reveals** it in the receipt. Either way the buyer can+ confirm their entropy went into the mix.+- `requestNonce` is a fresh random 16 bytes drawn per request and revealed.++Because the order is fixed and each input is domain-separated by HKDF, swapping+`serverSeed` ↔ `clientSeed` (or altering either) yields a different `masterSeed`,+which yields a different candidate stream and address.++## 3. Candidate derivation (grind)++Candidate `i` (a 0-based counter) has a fully deterministic Ed25519 private seed:++```+seed_i = HMAC-SHA256( key = masterSeed, msg = TAG_CANDIDATE ‖ uint64_be(i) )+publicKey_i = Ed25519.getPublicKey( seed_i ) // 32 bytes+address_i = Base58( publicKey_i ) // Solana address+```++The grinder walks `i = 0, 1, 2, …` until `address_i` satisfies the requested+pattern (see §4). The winning index is recorded as `winningIndex`. The Solana+64-byte secret key is `seed_i ‖ publicKey_i` (the `Keypair.fromSecretKey` /+Phantom import format).++> **Why pure-JS Ed25519, not the WASM grinder?** Verifiability requires the+> verifier to reproduce the exact candidate stream from `masterSeed` and+> `winningIndex`. The deterministic HMAC→Ed25519 derivation above is the stream;+> the WASM engine's internal `crypto.getRandomValues` keys are not reproducible+> and are therefore **not** used by this protocol.++## 4. Pattern matching++```+matches(address, prefix, suffix, ignoreCase):+ a, p, s = address, prefix, suffix+ if ignoreCase: a, p, s = lower(a), lower(p), lower(s)+ return (p == "" or a.startsWith(p)) and (s == "" or a.endsWith(s))+```++The Base58 alphabet excludes `0 O I l`. **Difficulty** is the mean of a geometric+distribution — the expected number of candidates to a hit:++```+expectedAttempts(prefix, suffix, ignoreCase):+ n = 1+ for ch in prefix ‖ suffix:+ n *= 58 / matchesPerChar(ch, ignoreCase) // 2 iff ignoreCase and both cases are valid Base58, else 1+ return n+```++The receipt's `difficulty.expectedAttempts` MUST equal `round(expectedAttempts(…))`.++## 5. Sealed delivery++When the buyer supplies an X25519 public key (`sealTo`), the secret bundle++```+{ format: "keypair", secretKeyBase58, secretKey: number[64], seed: hex }+```++is sealed with the ECIES scheme `x25519-hkdf-sha256-aes256gcm/v1` (see+[`sealed-envelope.js`](../src/solana/vanity/sealed-envelope.js)):++1. ephemeral X25519 keypair `e`;+2. `shared = X25519(e.secret, recipientPub)`;+3. `key = HKDF-SHA256(ikm=shared, salt=e.public ‖ recipientPub,+ info="three.ws sealed-envelope v1", 32)`;+4. AES-256-GCM(key, random 12-byte nonce, AAD = `e.public`);+5. emit `{ scheme, epk, nonce, ciphertext, recipient }`.++The ephemeral secret is discarded, so the envelope is forward-secret with respect+to the server. The receipt records `sealedRecipient` and `sealedEpk` so the buyer+can prove *this* envelope was sealed to *their* key. The plaintext secret never+appears in the response, a proxy log, or the idempotency cache.++## 6. Signed receipt++The server signs a canonical projection of the receipt with its long-lived+Ed25519 identity key (published at+[`/.well-known/three-vanity.json`](https://three.ws/.well-known/three-vanity.json)+and pinned in the SDK + CLI + web verifier).++**Signed fields** (and only these — delivery payload and navigation hints are+*not* signed):++```+protocol, receiptType, address, pattern, commitment, serverSeed, clientSeed,+requestNonce, winningIndex, attempts, durationMs, difficulty, sealed,+sealedScheme, sealedRecipient, sealedEpk, network, ts+```++**Canonical bytes.** Project the receipt to the signed fields above (dropping any+field whose value is `undefined`), JSON-serialize with **recursively+lexicographically-sorted object keys** and no insignificant whitespace, then:++```+message = TAG_RECEIPT ‖ utf8( canonicalJSON )+signature = hex( Ed25519.sign(message, serviceSigningSeed) )+```++The receipt carries `signature`, `servicePublicKey` (Base58), and+`signatureScheme: "ed25519"`. Extra response fields (`sealedSecret`,+`secretKeyBase58`, `explorerUrl`, `verifyUrl`, …) are intentionally outside the+signature, so a UI or transport may add/strip them without invalidating it; the+verifier re-projects to the signed fields before checking.++---++## Verification algorithm++Given a receipt (and, optionally, the opened secret seed), a verifier MUST+recompute — never trust — each of the following. All must pass.++1. **protocol** — `receipt.protocol == "three-vanity/v1"`.+2. **commitment** — `SHA-256(TAG_SEED_COMMIT ‖ serverSeed) == commitment`.+3. **derivation** — re-derive `masterSeed` (§2) and `address_{winningIndex}`+ (§3); it MUST equal `receipt.address`.+4. **pattern** — `receipt.address` satisfies `receipt.pattern` (§4).+5. **difficulty** — `difficulty.expectedAttempts == round(expectedAttempts(…))`.+6. **signature** — Ed25519-verify the canonical message (§6) against the pinned+ service key, AND the receipt's `servicePublicKey` equals the pinned key+ (reject impostors that self-sign under a different key).+7. **custody** *(optional)* — if the buyer opened the sealed envelope, the+ recovered 32-byte seed MUST equal `seed_{winningIndex}` and its Ed25519 public+ key MUST equal `receipt.address`.++A single failing check means the receipt is not trustworthy. The negative test in+[`tests/vanity-verifiable-grind.test.js`](../tests/vanity-verifiable-grind.test.js)+pins that a tampered address, swapped `serverSeed`, wrong `winningIndex`, inflated+difficulty, impostor signing key, or mismatched opened secret each FAIL.++---++## Service key publication & rotation++`/.well-known/three-vanity.json` publishes:++```json+{+ "protocol": "three-vanity/v1",+ "serviceKey": { "curve": "ed25519", "publicKeyBase58": "…", "publicKeyHex": "…", "use": "receipt-signing" },+ "schemes": { … },+ "endpoints": { "grind": "/api/x402/vanity-verifiable", "verifyPage": "/vanity/verify" }+}+```++The SDK pins `THREE_VANITY_SERVICE_KEY`; for production verification, cross-check+it against the live well-known document (`fetchServiceKey()` / `--fetch-key` /+the web page does this automatically). On key rotation, update the well-known+document and the pinned SDK constant; receipts signed under the previous key+remain verifiable against that key but new pins should track the current one.++The signing **secret** is custodial: stored encrypted at rest via+[`secret-box.js`](../api/_lib/secret-box.js) under `VANITY_SERVICE_KEY`, never+logged, never returned.diff --git a/prompts/vanity-x402/01-provably-fair-grinding.md b/prompts/vanity-x402/01-provably-fair-grinding.mddeleted file mode 100644index c585bdd8c..000000000--- a/prompts/vanity-x402/01-provably-fair-grinding.md+++ /dev/null@@ -1,106 +0,0 @@-# Task 01 — Provably-fair, trustless vanity grinding--> Read [00-README-orchestration.md](./00-README-orchestration.md) first — it holds-> the foundation map, house rules, and closeout protocol you must follow.--## The wedge (why this is gamechanging)--Every vanity-address service on earth asks you to **trust the operator**: trust-that they generated your key with real randomness, that they didn't keep a copy,-that they didn't grind 10,000 candidates and hand you the one whose key they-secretly logged. There is no proof. You just hope.--**We make it provable.** A buyer of a three.ws vanity wallet can verify, after the-fact and with open-source tooling, that:--1. the key was generated **fresh** from real entropy the server committed to- *before* it knew the buyer's pattern (no precomputed rainbow table of keys);-2. the secret was delivered **only** to the buyer (sealed to their X25519 key — the- server provably discarded the ephemeral secret);-3. the address actually satisfies the pattern and the grind difficulty was honest.--No competitor offers this. "Trustless vanity" is a category we can own.--## What to build--A verifiable grinding protocol layered onto [api/x402/vanity.js](../../api/x402/vanity.js)-(extend it or add a sibling `api/x402/vanity-verifiable.js`; keep the existing-endpoint working). Plus a standalone **verifier** (CLI + a `/vanity/verify` web-page) and a `verify()` export in the SDK.--### Protocol (commit–reveal + sealed delivery + signed receipt)--- **Server identity key.** A long-lived ed25519 signing key for the grinder service- (store the secret with [secret-box.js](../../api/_lib/secret-box.js); publish the- public key at a stable URL, e.g. `/.well-known/three-vanity.json`, and pin it in- the SDK). This signs receipts.-- **Per-request entropy commitment.** Before grinding, draw a random 32-byte- `serverSeed`, compute `commitment = SHA-256(serverSeed)`, and bind it into the- response/receipt. Mix `serverSeed` with the buyer-supplied `clientSeed` (and the- request nonce) into the CSPRNG that seeds each candidate keypair — so neither- party alone controls the output, and the server committed before grinding.-- **Sealed delivery.** Require (or strongly default to) `sealTo` so the secret is- ECIES-sealed to the buyer (reuse [sealed-envelope.js](../../src/solana/vanity/sealed-envelope.js)).- The receipt records the sealed envelope's `epk`/recipient so the buyer can prove- *this* envelope was for *their* key.-- **Signed receipt.** The endpoint returns a `receipt` object the service signs:- `{ commitment, clientSeed, requestNonce, pattern, address, difficulty, attempts,- durationMs, sealedRecipient, sealedEpk, ts }` plus `serverSeed` (revealed) and the- service signature. The buyer keeps it.-- **Verifier.** Given the receipt + the opened secret, independently confirm:- `SHA-256(serverSeed) === commitment`; the address derives from the revealed secret;- the address matches the pattern; the seed-mixing reproduces a candidate stream- consistent with the claim; the signature verifies against the pinned service key.--Make the seed-mixing + candidate derivation **deterministic and documented** so the-verifier is exact, not approximate. Write it down in a short `PROTOCOL.md`.--### Surfaces to wire (100%, real)--- Endpoint(s) returning the receipt; reuse x402 verify/settle + idempotency.-- SDK: `verifyVanityReceipt(receipt, openedSecret)` and a thin client that requests- → opens the seal → verifies, all in one call. Ship in [solana-agent-sdk/](../../solana-agent-sdk).-- CLI verifier under `scripts/` (e.g. `scripts/verify-vanity-receipt.mjs`) that takes- a receipt JSON and prints a green/red audit.-- A `/vanity/verify` web page: paste a receipt (+ optionally the sealed secret and- your X25519 private key, processed **entirely client-side**) → see each check pass- with a clear explanation. Designed loading/empty/error/success states. A "what does- this prove?" explainer. Link it from the vanity wallet UI.-- `/.well-known/three-vanity.json` publishing the service public key + protocol- version + scheme ids.--## Hard requirements--- Real ed25519 signing/verification via `@noble/curves`; real SHA-256 via- `@noble/hashes`/WebCrypto. No hand-rolled crypto. Pin every step with vectors.-- The buyer's X25519 private key and the opened secret must **never** leave the- browser on the verify page — verification is local. Say so in the UI.-- The service signing secret is custodial: encrypt at rest, never log, never return.-- Honest difficulty: the receipt's `difficulty`/`expectedAttempts` must match the- real probability model in [validation.js](../../src/solana/vanity/validation.js).-- Backwards compatible: the plain `/api/x402/vanity` keeps working unchanged.--## Definition of done--- [ ] Protocol implemented end-to-end: commit → seeded grind → sealed delivery →- signed receipt → independent verification, all on real crypto.-- [ ] Endpoint pays via x402 (verify-grind-settle order preserved), idempotent.-- [ ] SDK `verify()` + one-call client; CLI verifier; `/vanity/verify` page (every- state designed, fully client-side verification, reachable from the UI).-- [ ] `/.well-known/three-vanity.json` live; service key pinned in SDK + verifier.-- [ ] `PROTOCOL.md` documents the scheme precisely enough to reimplement.-- [ ] Tests with fixed vectors: commitment, seed-mix determinism, signature,- address↔secret, pattern match, and a **negative** test (tampered receipt /- wrong serverSeed / mismatched address all FAIL verification).-- [ ] Changelog entry (plain language: "prove we never kept your key"); `npm run- build:pages` clean.-- [ ] No fake data; real on-chain address checks; no console errors; `git diff`- self-reviewed.--## Closeout--Run the DoD + self-review. Then the **improvement pass**: can you also let the buyer-verify *non-custody* on-chain (e.g. anchor the commitment in a transaction memo or an-attestation so the proof is timestamped and public)? Can the verify page generate a-shareable "verified trustless" badge/OG card? Add what raises the bar. Summarize,-then **delete this file** (`prompts/vanity-x402/01-provably-fair-grinding.md`).diff --git a/public/changelog.json b/public/changelog.jsonindex 4975a8198..94ffe6e35 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-19T23:11:11.226Z",+ "generated_at": "2026-06-19T23:28:51.089Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -36,6 +36,26 @@"launch"]},+ {+ "date": "2026-06-19",+ "type": "launch",+ "title": "Verify a Vanity Receipt",+ "summary": "Independently verify a three.ws provably-fair vanity wallet receipt — entirely in your browser. Prove the key was generated fresh under a committed seed and the operator never kept a copy.",+ "link": "/vanity/verify",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-06-19",+ "type": "launch",+ "title": "x402 Studio — the Stripe of x402",+ "summary": "Merchant console to run a paid x402 business: products and pricing, payout and agent wallets, a real USDC send/receive with SNS .sol resolution, a drag-and-drop storefront, an embeddable pay-button builder, charity and round-up giving, CORS and security.",+ "link": "/x402/studio",+ "tags": [+ "launch"+ ]+ },{"date": "2026-06-19","type": "update",@@ -107,6 +127,17 @@"feature"]},+ {+ "date": "2026-06-19",+ "type": "update",+ "title": "Charity and round-up donations now settle on-chain at checkout",+ "summary": "When a merchant turns on Giving, their charity split and round-up are no longer just shown — they move real money at the moment a buyer pays. The payment modal now offers the buyer a clear, pre-checked opt-in (\"Add 0.009 USDC for Save the Reefs\") and, when kept, appends the donation to the very same Solana transaction the buyer signs. One signature pays the merchant and the cause together, with the network fee still sponsored by the facilitator. The buyer always sees the exact amount and total before signing and can switch it off; the donation is bounded by a safety cap so a misconfigured rule can never sweep a wallet. Hosted /pay/c checkout links surface the cause up front, and the math — a basis-point share of the payment plus the round-up remainder — is covered by tests.",+ "link": null,+ "tags": [+ "feature",+ "sdk"+ ]+ },{"date": "2026-06-19","type": "update",@@ -570,6 +601,18 @@"fix"]},+ {+ "date": "2026-06-19",+ "type": "update",+ "title": "Prove we never kept your vanity key — trustless wallet grinding",+ "summary": "Every vanity-address service asks you to trust the operator: trust they used real randomness, that they didn't keep a copy, that they didn't grind thousands of keys and hand you the one they secretly logged. Now you don't have to. The new provably-fair grinder commits to a random seed before it grinds, mixes in your own entropy so neither side controls the result, seals the secret so only you can open it, and returns a signed receipt. You can verify all of it after the fact — paste the receipt at three.ws/vanity/verify (everything runs in your browser, your keys never leave), run the open-source CLI, or call verifyVanityReceipt() in the SDK. The checks prove the key was generated fresh, that the address really comes from that seed, that it matches your pattern, and that three.ws — not an impostor — signed it. Optionally open the sealed key locally to prove you, and only you, hold it.",+ "link": "/vanity/verify",+ "tags": [+ "feature",+ "security",+ "sdk"+ ]+ },{"date": "2026-06-19","type": "update",@@ -748,6 +791,16 @@"fix"]},+ {+ "date": "2026-06-19",+ "type": "update",+ "title": "Turn any agent wallet into a giving wallet",+ "summary": "Every agent's self-custodied Solana wallet now has a Give tab. Pick a cause — any Solana wallet or .sol name — and donate SOL or USDC in one tap, or use a quick 1/5/10/25%/Max of the live balance. Round-up giving rounds a balance off and sends the spare change to your cause (e.g. 12.37 USDC → give $0.37, keep $12.00). Donations are real, server-signed, on-chain transfers — the same audited, idempotent path as a withdrawal — and your running total is tallied straight from the wallet's on-chain custody trail. Crypto transfers are final, so each donation is reviewed before it's sent.",+ "link": null,+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-19","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex d40fbb051..99a00fd19 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -30,6 +30,22 @@<category>launch</category><description>Pilot your UFO through an asteroid field. Connect your Solana wallet, submit your score as your wallet address, and claim your spot on the global $THREE leaderboard.</description></item>+ <item>+ <title>Verify a Vanity Receipt</title>+ <link>https://three.ws/vanity/verify</link>+ <guid isPermaLink="false">2026-06-19:Verify a Vanity Receipt</guid>+ <pubDate>Fri, 19 Jun 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Independently verify a three.ws provably-fair vanity wallet receipt — entirely in your browser. Prove the key was generated fresh under a committed seed and the operator never kept a copy.</description>+ </item>+ <item>+ <title>x402 Studio — the Stripe of x402</title>+ <link>https://three.ws/x402/studio</link>+ <guid isPermaLink="false">2026-06-19:x402 Studio — the Stripe of x402</guid>+ <pubDate>Fri, 19 Jun 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Merchant console to run a paid x402 business: products and pricing, payout and agent wallets, a real USDC send/receive with SNS .sol resolution, a drag-and-drop storefront, an embeddable pay-button builder, charity and round-up giving, CORS and security.</description>+ </item><item><title>8D audio mode at the Pole Club</title><link>https://three.ws/club</link>@@ -86,6 +102,14 @@<category>feature</category><description>The Brain tab in Agent Studio is now a visual node editor: wire Persona, Model, Memory, Skills, and trading-reasoning nodes into a living graph that IS your agent’s personality. Pick from real LLMs (Claude, GPT, Granite and more) per branch, connect a memory port that recalls and writes real memories, and watch the active path light up as your agent thinks — tokens streaming, memory firing, the avatar reacting live. A built-in test chat runs your graph against the real models with real latency and token stats, and forkable templates (Sniper, Scalper, Researcher, Companion) get you started in one click. Your graph compiles straight to your agent’s persona so every existing chat surface picks up the change.</description></item>+ <item>+ <title>Charity and round-up donations now settle on-chain at checkout</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-19:Charity and round-up donations now settle on-chain at checkout</guid>+ <pubDate>Fri, 19 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>When a merchant turns on Giving, their charity split and round-up are no longer just shown — they move real money at the moment a buyer pays. The payment modal now offers the buyer a clear, pre-checked opt-in ("Add 0.009 USDC for Save the Reefs") and, when kept, appends the donation to the very same Solana transaction the buyer signs. One signature pays the merchant and the cause together, with the network fee still sponsored by the facilitator. The buyer always sees the exact amount and total before signing and can switch it off; the donation is bounded by a safety cap so a misconfigured rule can never sweep a wallet. Hosted /pay/c checkout links surface the cause up front, and the math — a basis-point share of the payment plus the round-up remainder — is covered by tests.</description>+ </item><item><title>Cleaner Pole Club bass — no more speaker distortion</title><link>https://three.ws/club</link>@@ -446,6 +470,14 @@<category>feature</category><description>Locked premium headwear, eyewear, dyes and auras in the character creator no longer dead-end on a placeholder — clicking one now opens the real wallet checkout and unlocks it the moment the USDC payment settles, then equips it on your live preview. Anything you already own loads pre-unlocked, and the price you see is the true checkout amount pulled from the catalog.</description></item>+ <item>+ <title>Prove we never kept your vanity key — trustless wallet grinding</title>+ <link>https://three.ws/vanity/verify</link>+ <guid isPermaLink="false">2026-06-19:Prove we never kept your vanity key — trustless wallet grinding</guid>+ <pubDate>Fri, 19 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Every vanity-address service asks you to trust the operator: trust they used real randomness, that they didn't keep a copy, that they didn't grind thousands of keys and hand you the one they secretly logged. Now you don't have to. The new provably-fair grinder commits to a random seed before it grinds, mixes in your own entropy so neither side controls the result, seals the secret so only you can open it, and returns a signed receipt. You can verify all of it after the fact — paste the receipt at three.ws/vanity/verify (everything runs in your browser, your keys never leave), run the open-source CLI, or call verifyVanityReceipt() in the SDK. The checks prove the key was generated fresh, that the address really comes from that seed, that it matches your pattern, and that three.ws — not an impostor — signed it. Optionally open the sealed key locally to prove you, and only you, hold it.</description>+ </item><item><title>Put a talking 3D guide on any website — new @three-ws/page-agent SDK</title><link>https://three.ws/changelog</link>@@ -582,6 +614,14 @@<category>fix</category><description>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.</description></item>+ <item>+ <title>Turn any agent wallet into a giving wallet</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-19:Turn any agent wallet into a giving wallet</guid>+ <pubDate>Fri, 19 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Every agent's self-custodied Solana wallet now has a Give tab. Pick a cause — any Solana wallet or .sol name — and donate SOL or USDC in one tap, or use a quick 1/5/10/25%/Max of the live balance. Round-up giving rounds a balance off and sends the spare change to your cause (e.g. 12.37 USDC → give $0.37, keep $12.00). Donations are real, server-signed, on-chain transfers — the same audited, idempotent path as a withdrawal — and your running total is tallied straight from the wallet's on-chain custody trail. Crypto transfers are final, so each donation is reviewed before it's sent.</description>+ </item><item><title>Unity & Unreal avatar loading documented with code that actually works</title><link>https://three.ws/dashboard/developers</link>diff --git a/public/features.json b/public/features.jsonindex b2eaf3f1d..c1c11d1ae 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-19T23:11:11.204Z",+ "generated_at": "2026-06-19T23:28:51.074Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",@@ -666,6 +666,16 @@"tags": [],"showcase": false},+ {+ "path": "/x402/studio",+ "title": "x402 Studio — the Stripe of x402",+ "description": "Merchant console to run a paid x402 business: products and pricing, payout and agent wallets, a real USDC send/receive with SNS .sol resolution, a drag-and-drop storefront, an embeddable pay-button builder, charity and round-up giving, CORS and security.",+ "added": "2026-06-19",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },{"path": "/play/agent-wallet","title": "Agent Wallet (x402 on Solana)",@@ -776,6 +786,16 @@"tags": [],"showcase": false},+ {+ "path": "/vanity/verify",+ "title": "Verify a Vanity Receipt",+ "description": "Independently verify a three.ws provably-fair vanity wallet receipt — entirely in your browser. Prove the key was generated fresh under a committed seed and the operator never kept a copy.",+ "added": "2026-06-19",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },{"path": "/eth-vanity","title": "ETH Vanity (CREATE2)",diff --git a/public/llms-full.txt b/public/llms-full.txtindex 879ea1d49..3261a1e3d 100644--- a/public/llms-full.txt+++ b/public/llms-full.txt@@ -406,6 +406,12 @@ URL: https://three.ws/payPay-per-call gateway: invoke any x402-protocol paid API with a USDC micro-transaction.+### x402 Studio — the Stripe of x402++URL: https://three.ws/x402/studio++Merchant console to run a paid x402 business: products and pricing, payout and agent wallets, a real USDC send/receive with SNS .sol resolution, a drag-and-drop storefront, an embeddable pay-button builder, charity and round-up giving, CORS and security.+### Agent Wallet (x402 on Solana)URL: https://three.ws/play/agent-wallet@@ -472,6 +478,12 @@ URL: https://three.ws/vanity-walletGrind a Solana address with a custom prefix using your browser's GPU.+### Verify a Vanity Receipt++URL: https://three.ws/vanity/verify++Independently verify a three.ws provably-fair vanity wallet receipt — entirely in your browser. Prove the key was generated fresh under a committed seed and the operator never kept a copy.+### ETH Vanity (CREATE2)URL: https://three.ws/eth-vanitydiff --git a/public/llms.txt b/public/llms.txtindex ca6ec9943..5869f4be4 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -87,6 +87,7 @@ On-chain features: pay-per-call, token launches, vanity wallets.- [Live Trade Feed — Notable pump.fun Exits](https://three.ws/trades): Real-time feed of every notable pump.fun exit from three.ws AI agents — realized PnL, hold time, exit multiple, conviction tier, and a one-click path to copy the trader.- [Claim Your Wallet — Verified pump.fun Track Record](https://three.ws/claim-wallet): Paste your Solana wallet to see your provable pump.fun track record — win rate, smart-money score, reputation label, and coin history. Sign in to claim it as your official three.ws Trader Card.- [Pay (x402)](https://three.ws/pay): Pay-per-call gateway: invoke any x402-protocol paid API with a USDC micro-transaction.+- [x402 Studio — the Stripe of x402](https://three.ws/x402/studio): Merchant console to run a paid x402 business: products and pricing, payout and agent wallets, a real USDC send/receive with SNS .sol resolution, a drag-and-drop storefront, an embeddable pay-button builder, charity and round-up giving, CORS and security.- [Agent Wallet (x402 on Solana)](https://three.ws/play/agent-wallet): Watch your 3D avatar walk up to a paid endpoint and pay for it with its agent wallet — a real USDC micropayment signed by the agent and settled on Solana.- [Sniper Arena — autonomous AI agents trading live](https://three.ws/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.- [Flappin UFO — dodge asteroids for $THREE](https://three.ws/play/ufo): Pilot your UFO through an asteroid field. Connect your Solana wallet, submit your score as your wallet address, and claim your spot on the global $THREE leaderboard.@@ -98,6 +99,7 @@ On-chain features: pay-per-call, token launches, vanity wallets.- [Pump Dashboard](https://three.ws/pump-dashboard): Pump.fun trading desk: watchlists, scanner, quotes, portfolio, and live charts.- [Strategy Lab](https://three.ws/strategy-lab): Build DCA and subscription strategies that trade on-chain on your behalf.- [Solana Vanity Wallet](https://three.ws/vanity-wallet): Grind a Solana address with a custom prefix using your browser's GPU.+- [Verify a Vanity Receipt](https://three.ws/vanity/verify): Independently verify a three.ws provably-fair vanity wallet receipt — entirely in your browser. Prove the key was generated fresh under a committed seed and the operator never kept a copy.- [ETH Vanity (CREATE2)](https://three.ws/eth-vanity): Grind a vanity smart-contract address using the ThreeWSFactory CREATE2 deployer on BSC.- [Pump Visualizer](https://three.ws/pump-visualizer): 3D visualizer of trending pump.fun tokens — live market data rendered as an interactive scene.- [Coin Intelligence](https://three.ws/coin-intel): Every pump.fun launch watched and classified in real time — organic vs bundle, the wallets behind it, a transparent quality score, and a model that learns which signals predict winners.diff --git a/public/og/vanity-verified.svg b/public/og/vanity-verified.svgnew file mode 100644index 000000000..b93672ea8--- /dev/null+++ b/public/og/vanity-verified.svg@@ -0,0 +1,14 @@+<svg xmlns="http://www.w3.org/2000/svg" width="240" height="40" viewBox="0 0 240 40" role="img" aria-label="Verified trustless · three.ws">+ <title>Verified trustless · three.ws</title>+ <defs>+ <linearGradient id="g" x1="0" y1="0" x2="0" y2="1">+ <stop offset="0" stop-color="#101510"/>+ <stop offset="1" stop-color="#0a0d0a"/>+ </linearGradient>+ </defs>+ <rect x="0.5" y="0.5" width="239" height="39" rx="8" fill="url(#g)" stroke="#2a3a2a"/>+ <circle cx="24" cy="20" r="10" fill="none" stroke="#4ade80" stroke-width="2"/>+ <path d="M19.5 20.2 L22.8 23.5 L28.8 16.5" fill="none" stroke="#4ade80" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"/>+ <text x="44" y="17.5" font-family="'Space Grotesk',system-ui,sans-serif" font-size="13" font-weight="700" fill="#4ade80">Verified trustless</text>+ <text x="44" y="31" font-family="system-ui,sans-serif" font-size="10" fill="#7a8a7a">three.ws · provably-fair vanity</text>+</svg>diff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex 4843f6b71..80dd11410 100644--- a/public/sitemap/index.html+++ b/public/sitemap/index.html@@ -65,7 +65,7 @@<main class="sm-wrap"><div class="sm-hero"><h1>Sitemap</h1>- <p>All 283 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>+ <p>All 285 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 +77,7 @@</div><div class="sm-filter"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>- <input id="sm-filter-input" type="search" placeholder="Filter 283 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />+ <input id="sm-filter-input" type="search" placeholder="Filter 285 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>@@ -494,7 +494,7 @@<section class="sm-section" id="crypto"><header>- <h2>Crypto<span class="sm-count" data-count>46</span></h2>+ <h2>Crypto<span class="sm-count" data-count>48</span></h2><p class="sm-section-desc">On-chain features: pay-per-call, token launches, vanity wallets.</p></header><ul class="sm-list">@@ -568,6 +568,13 @@<span class="sm-desc">Pay-per-call gateway: invoke any x402-protocol paid API with a USDC micro-transaction.</span></a></li>+ <li>+ <a href="/x402/studio">+ <span class="sm-title">x402 Studio — the Stripe of x402</span>+ <span class="sm-path">/x402/studio</span>+ <span class="sm-desc">Merchant console to run a paid x402 business: products and pricing, payout and agent wallets, a real USDC send/receive with SNS .sol resolution, a drag-and-drop storefront, an embeddable pay-button builder, charity and round-up giving, CORS and security.</span>+ </a>+ </li><li><a href="/play/agent-wallet"><span class="sm-title">Agent Wallet (x402 on Solana)</span>@@ -645,6 +652,13 @@<span class="sm-desc">Grind a Solana address with a custom prefix using your browser's GPU.</span></a></li>+ <li>+ <a href="/vanity/verify">+ <span class="sm-title">Verify a Vanity Receipt</span>+ <span class="sm-path">/vanity/verify</span>+ <span class="sm-desc">Independently verify a three.ws provably-fair vanity wallet receipt — entirely in your browser. Prove the key was generated fresh under a committed seed and the operator never kept a copy.</span>+ </a>+ </li><li><a href="/eth-vanity"><span class="sm-title">ETH Vanity (CREATE2)</span>diff --git a/public/vanity-wallet.html b/public/vanity-wallet.htmlindex 62f1c789c..1c66b17d8 100644--- a/public/vanity-wallet.html+++ b/public/vanity-wallet.html@@ -209,6 +209,10 @@Grind a Solana wallet address that <strong>starts with</strong>, <strong>ends with</strong>, or is bookended by characters of your choice — for your agent, treasury, or anywhere a memorable address matters.<strong>Runs entirely in your browser.</strong> The secret key stays on your device — it only leaves if you explicitly assign the wallet to an agent.</p>+ <p class="lede" style="margin-top:-0.5rem;font-size:.85rem">+ Bought a wallet from the <a href="/vanity/verify" style="color:#ffd54f;text-decoration:none;border-bottom:1px solid rgba(255,213,79,.4)">provably-fair grinder</a>?+ Verify the receipt — prove we generated your key fresh and never kept a copy.+ </p><div class="card"><div class="pattern-grid">diff --git a/public/vanity/verify/index.html b/public/vanity/verify/index.htmlnew file mode 100644index 000000000..c5bce4fd2--- /dev/null+++ b/public/vanity/verify/index.html@@ -0,0 +1,302 @@+<!doctype html>+<html lang="en">+<head>+ <script>/* three.ws theme boot — no-flash */(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">+ <title>Verify a vanity receipt · three.ws</title>+ <meta name="viewport" content="width=device-width, initial-scale=1">+ <meta name="description" content="Independently verify a three.ws provably-fair vanity wallet receipt — entirely in your browser. Prove the key was generated fresh under a committed seed and the operator could never have kept a copy.">+ <link rel="icon" href="/favicon.ico">+ <link rel="stylesheet" href="/footer.css">+ <link rel="stylesheet" href="/nav.css">+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <script defer src="/footer-newsletter.js"></script>+ <meta property="og:title" content="Verify a provably-fair vanity wallet · three.ws">+ <meta property="og:description" content="Prove your three.ws vanity key was generated fresh and never kept — verification runs entirely in your browser.">+ <meta name="twitter:card" content="summary_large_image">+ <style>+ * { box-sizing: border-box; }+ :root {+ color-scheme: dark;+ --fg: #f0f0f0; --muted: #888; --border: rgba(255,255,255,0.08); --bg: #111;+ --accent: #fff; --accent-fg: #000;+ --ok-bg: rgba(74,222,128,0.10); --ok-fg: #4ade80;+ --warn-bg: rgba(251,191,36,0.1); --warn-fg: #fbbf24;+ --bad-bg: rgba(239,68,68,0.1); --bad-fg: #f87171;+ --card-bg: #0f0f0f;+ --font-display: 'Space Grotesk', 'Inter', system-ui, sans-serif;+ --radius-md: 8px;+ }+ body { font: 15px/1.5 'Inter', system-ui, -apple-system, sans-serif; background:#000; color:var(--fg); margin:0; min-height:100vh; display:flex; flex-direction:column; }+ main { flex:1; max-width:720px; width:100%; margin:0 auto; padding:2.5rem 1rem 3rem; }+ h1 { font-size:1.6rem; margin:0 0 .35rem; font-family:var(--font-display); letter-spacing:-0.02em; }+ .lede { color:var(--muted); margin:0 0 1.5rem; max-width:60ch; }+ .card { border:1px solid var(--border); border-radius:var(--radius-md); padding:1.15rem 1.25rem; background:var(--card-bg); margin-bottom:1.1rem; }+ label { display:block; font-size:.78rem; color:var(--muted); margin:0 0 .4rem; text-transform:uppercase; letter-spacing:.04em; }+ textarea, input[type=text] { font-family:ui-monospace,'SF Mono',monospace; font-size:.82rem; width:100%; border:1px solid rgba(255,255,255,0.12); border-radius:6px; background:#161616; color:var(--fg); padding:.6rem .7rem; resize:vertical; }+ textarea:focus, input[type=text]:focus { outline:none; border-color:rgba(255,255,255,0.32); }+ textarea { min-height:9rem; }+ .optional-row { margin-top:.9rem; }+ details { margin-top:.5rem; }+ summary { cursor:pointer; color:var(--muted); font-size:.85rem; user-select:none; }+ summary:hover { color:#ccc; }+ .btn-row { display:flex; gap:.6rem; flex-wrap:wrap; margin-top:1rem; align-items:center; }+ button.primary { font:inherit; font-weight:600; background:var(--accent); color:var(--accent-fg); border:none; border-radius:7px; padding:.6rem 1.2rem; cursor:pointer; transition:transform .12s, opacity .12s; }+ button.primary:hover { transform:translateY(-1px); }+ button.primary:active { transform:translateY(0); }+ button.primary:disabled { opacity:.5; cursor:default; transform:none; }+ button.ghost { font:inherit; background:transparent; color:var(--muted); border:1px solid var(--border); border-radius:7px; padding:.6rem 1rem; cursor:pointer; }+ button.ghost:hover { color:#ccc; border-color:rgba(255,255,255,0.25); }+ .muted-note { color:#666; font-size:.74rem; margin-top:.55rem; line-height:1.5; }+ .muted-note strong { color:#999; }++ /* verdict banner */+ .verdict { display:none; align-items:center; gap:.8rem; border-radius:var(--radius-md); padding:1rem 1.2rem; margin-bottom:1.1rem; font-weight:600; }+ .verdict.show { display:flex; }+ .verdict.ok { background:var(--ok-bg); color:var(--ok-fg); border:1px solid rgba(74,222,128,0.3); }+ .verdict.bad { background:var(--bad-bg); color:var(--bad-fg); border:1px solid rgba(239,68,68,0.3); }+ .verdict .vmark { font-size:1.4rem; line-height:1; }+ .verdict .vtext small { display:block; font-weight:400; opacity:.85; font-size:.78rem; margin-top:.15rem; }++ /* checks list */+ .checks { display:none; }+ .checks.show { display:block; }+ .check { display:flex; gap:.7rem; padding:.7rem 0; border-bottom:1px solid var(--border); }+ .check:last-child { border-bottom:none; }+ .check .mark { font-size:1rem; flex:0 0 1.2rem; text-align:center; margin-top:.05rem; }+ .check.pass .mark { color:var(--ok-fg); }+ .check.fail .mark { color:var(--bad-fg); }+ .check .body { flex:1; min-width:0; }+ .check .label { font-weight:600; font-size:.9rem; }+ .check.fail .label { color:var(--bad-fg); }+ .check .detail { color:var(--muted); font-size:.78rem; margin-top:.2rem; word-break:break-word; font-family:ui-monospace,monospace; }+ .skeleton { height:1.1rem; background:linear-gradient(90deg,#1a1a1a,#222,#1a1a1a); background-size:200% 100%; animation:sk 1.2s infinite; border-radius:4px; margin:.6rem 0; }+ @keyframes sk { 0%{background-position:200% 0} 100%{background-position:-200% 0} }++ .meta-grid { display:grid; grid-template-columns:auto 1fr; gap:.35rem .9rem; font-size:.82rem; margin-top:.4rem; }+ .meta-grid dt { color:var(--muted); }+ .meta-grid dd { margin:0; font-family:ui-monospace,monospace; word-break:break-all; }+ .error-box { display:none; background:var(--bad-bg); border:1px solid rgba(239,68,68,0.3); color:var(--bad-fg); border-radius:6px; padding:.7rem .85rem; font-size:.84rem; margin-top:.8rem; }+ .error-box.show { display:block; }+ .pin-line { font-size:.74rem; color:#666; margin-top:.7rem; }+ .pin-line .key { font-family:ui-monospace,monospace; color:#999; }+ .pin-line.pinned { color:var(--ok-fg); }+ .explainer { border:1px solid var(--border); border-radius:var(--radius-md); background:#0c0c0c; padding:1.1rem 1.25rem; }+ .explainer h2 { font-size:1rem; margin:0 0 .6rem; font-family:var(--font-display); }+ .explainer ol { margin:0; padding-left:1.2rem; color:var(--muted); font-size:.86rem; }+ .explainer li { margin:.4rem 0; }+ .explainer code { background:#1a1a1a; padding:1px 5px; border-radius:4px; font-size:.8em; color:#bbb; }+ .share-row { display:none; margin-top:1rem; gap:.6rem; flex-wrap:wrap; }+ .share-row.show { display:flex; }+ .badge { display:inline-flex; align-items:center; gap:.45rem; background:var(--ok-bg); border:1px solid rgba(74,222,128,0.35); color:var(--ok-fg); border-radius:999px; padding:.35rem .85rem; font-size:.78rem; font-weight:600; }+ a.link { color:#ffd54f; text-decoration:none; border-bottom:1px solid rgba(255,213,79,.4); }+ a.link:hover { border-bottom-color:#ffd54f; }+ </style>+</head>+<body>+ <a href="#main-content" class="skip-link">Skip to main content</a>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main id="main-content">+ <h1>Verify a vanity receipt</h1>+ <p class="lede">+ Paste the receipt from a <a class="link" href="/vanity-wallet">three.ws provably-fair vanity wallet</a> and prove,+ from first principles, that the key was generated <strong>fresh</strong> under a seed the server committed to+ <em>before</em> grinding — and that the operator could never have kept a copy.+ <strong>Everything runs in your browser.</strong> Your X25519 private key and the recovered secret never leave this page.+ </p>++ <div class="verdict" id="verdict" role="status" aria-live="polite">+ <span class="vmark" id="vmark"></span>+ <span class="vtext"><span id="vtext-main"></span><small id="vtext-sub"></small></span>+ </div>++ <div class="card">+ <label for="receipt">Receipt JSON</label>+ <textarea id="receipt" placeholder='Paste the full receipt object you received from /api/x402/vanity-verifiable…' spellcheck="false" autocomplete="off"></textarea>++ <details class="optional-row">+ <summary>Optional: prove you hold the key (open the sealed envelope locally)</summary>+ <div style="margin-top:.8rem">+ <label for="x25519">Your X25519 private key <span style="text-transform:none;color:#555">(Base58 or hex — used only in your browser)</span></label>+ <input id="x25519" type="text" placeholder="The secret key matching the sealTo you sent" spellcheck="false" autocomplete="off" />+ <p class="muted-note"><strong>Private.</strong> This key is used only to decrypt the sealed secret right here in your browser, then verify that the key you recover is exactly the one the receipt describes. It is never sent anywhere.</p>+ </div>+ </details>++ <div class="error-box" id="error"></div>++ <div class="btn-row">+ <button class="primary" id="verify-btn">Verify receipt</button>+ <button class="ghost" id="clear-btn">Clear</button>+ <a class="link" href="/vanity-wallet" style="margin-left:auto;font-size:.85rem">Need a receipt? Grind a wallet →</a>+ </div>+ <div class="pin-line" id="pin-line">Pinning against the live service key from <code>/.well-known/three-vanity.json</code>…</div>+ </div>++ <div class="card" id="results-card" style="display:none">+ <div class="checks" id="checks"></div>+ <div id="meta" style="margin-top:1rem"></div>+ <div class="share-row" id="share-row">+ <span class="badge">✓ Verified trustless · three.ws</span>+ <button class="ghost" id="copy-badge">Copy verified badge</button>+ </div>+ </div>++ <div class="explainer">+ <h2>What does this prove?</h2>+ <ol>+ <li><strong>The commitment opens.</strong> <code>SHA-256(serverSeed)</code> equals the value the server published before grinding — so it couldn't grind thousands of candidates and hand you the one whose key it kept.</li>+ <li><strong>Neither side controlled the result.</strong> Your <code>clientSeed</code> was mixed into the seed, so the server couldn't have predicted the address at commit time.</li>+ <li><strong>The address really derives from that seed</strong> at the claimed index — re-derived here with the same HMAC-SHA256 → Ed25519 derivation.</li>+ <li><strong>It matches your pattern</strong> and the difficulty claim is the honest <code>58ⁿ</code> model.</li>+ <li><strong>three.ws signed it.</strong> The Ed25519 signature verifies against the service key pinned from the well-known document — not an impostor.</li>+ <li><strong>(If you open the seal)</strong> the key you decrypt is byte-for-byte the key the receipt describes — you, and only you, hold it.</li>+ </ol>+ <p class="muted-note" style="margin-top:.9rem">Protocol <code>three-vanity/v1</code> · verify offline with the open-source CLI <code>scripts/verify-vanity-receipt.mjs</code> or the <code>@three-ws/solana-agent</code> SDK's <code>verifyVanityReceipt()</code>. <a class="link" href="/.well-known/three-vanity.json">View the service key →</a></p>+ </div>+ </main>++ <footer class="h-footer-horizon"><div class="h-footer-inner" style="text-align:center;padding:2rem 1rem;color:#555;font-size:.8rem">three.ws — provably-fair vanity grinding</div></footer>++ <script type="module">+ import { verifyVanityReceipt } from '/src/solana/vanity/verifiable-grind.js';+ import { openSealedText } from '/src/solana/vanity/sealed-envelope.js';++ const $ = (id) => document.getElementById(id);+ const receiptEl = $('receipt');+ const x25519El = $('x25519');+ const verifyBtn = $('verify-btn');+ const errorEl = $('error');+ const pinLineEl = $('pin-line');++ let pinnedKey = null;++ // Pin the live service key from the well-known document so an impostor+ // receipt (self-signed under a different key) is caught.+ (async () => {+ try {+ const res = await fetch('/.well-known/three-vanity.json', { headers: { accept: 'application/json' } });+ if (!res.ok) throw new Error(res.status);+ const doc = await res.json();+ pinnedKey = doc?.serviceKey?.publicKeyBase58;+ if (pinnedKey) {+ pinLineEl.classList.add('pinned');+ pinLineEl.innerHTML = 'Pinned to the live three.ws service key <span class="key">' + pinnedKey.slice(0, 8) + '…' + pinnedKey.slice(-6) + '</span>';+ } else throw new Error('missing key');+ } catch (e) {+ pinLineEl.innerHTML = '<span style="color:var(--warn-fg)">Could not fetch the live service key — verifying against the receipt’s own key (unpinned). The signature still checks out, but pin against <code>/.well-known/three-vanity.json</code> to prove the signer is three.ws.</span>';+ }+ })();++ function showError(msg) { errorEl.textContent = msg; errorEl.classList.add('show'); }+ function clearError() { errorEl.classList.remove('show'); }++ function escapeHtml(s) { return String(s).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); }++ function renderSkeleton() {+ const card = $('results-card');+ card.style.display = 'block';+ $('checks').classList.add('show');+ $('checks').innerHTML = '<div class="skeleton" style="width:90%"></div><div class="skeleton" style="width:75%"></div><div class="skeleton" style="width:85%"></div><div class="skeleton" style="width:60%"></div>';+ $('meta').innerHTML = '';+ $('share-row').classList.remove('show');+ $('verdict').classList.remove('show');+ }++ function renderResult(result, receipt) {+ const checksEl = $('checks');+ checksEl.innerHTML = result.checks.map((c) =>+ '<div class="check ' + (c.pass ? 'pass' : 'fail') + '">' ++ '<span class="mark">' + (c.pass ? '✓' : '✗') + '</span>' ++ '<span class="body"><span class="label">' + escapeHtml(c.label) + '</span>' ++ '<span class="detail">' + escapeHtml(c.detail) + '</span></span>' ++ '</div>'+ ).join('');++ const verdict = $('verdict');+ verdict.className = 'verdict show ' + (result.valid ? 'ok' : 'bad');+ $('vmark').textContent = result.valid ? '✓' : '✗';+ $('vtext-main').textContent = result.valid ? 'Verified — this receipt is provably fair.' : 'Verification failed — do not trust this receipt.';+ $('vtext-sub').textContent = result.valid+ ? 'The key was generated fresh under the committed seed; the operator could not have kept a copy.'+ : 'One or more protocol checks did not pass. The key/receipt may have been tampered with.';++ const m = $('meta');+ m.innerHTML = '<dl class="meta-grid">' ++ '<dt>Address</dt><dd>' + escapeHtml(receipt.address || '') + '</dd>' ++ '<dt>Pattern</dt><dd>' + escapeHtml([receipt.pattern?.prefix && 'prefix ' + receipt.pattern.prefix, receipt.pattern?.suffix && 'suffix ' + receipt.pattern.suffix].filter(Boolean).join(' + ') || '—') + '</dd>' ++ (receipt.winningIndex != null ? '<dt>Winning index</dt><dd>' + escapeHtml(receipt.winningIndex) + ' (of ' + escapeHtml(receipt.attempts ?? '?') + ' tried)</dd>' : '') ++ (receipt.ts ? '<dt>Issued</dt><dd>' + escapeHtml(receipt.ts) + '</dd>' : '') ++ '<dt>Signed by</dt><dd>' + escapeHtml(receipt.servicePublicKey || '') + '</dd>' ++ '</dl>' ++ (receipt.address ? '<p style="margin-top:.7rem"><a class="link" href="https://solscan.io/account/' + encodeURIComponent(receipt.address) + '" target="_blank" rel="noopener">View on Solscan →</a></p>' : '');++ $('share-row').classList.toggle('show', result.valid);+ }++ async function verify() {+ clearError();+ const raw = receiptEl.value.trim();+ if (!raw) { showError('Paste a receipt JSON first.'); return; }+ let receipt;+ try { receipt = JSON.parse(raw); }+ catch (e) { showError('That is not valid JSON: ' + e.message); return; }++ verifyBtn.disabled = true;+ renderSkeleton();++ try {+ // Optionally open the sealed envelope locally to prove custody.+ let openedSecretSeed;+ const x25519 = x25519El.value.trim();+ if (x25519 && receipt.sealedSecret) {+ let bundleText;+ try { bundleText = await openSealedText(receipt.sealedSecret, x25519); }+ catch (e) { throw new Error('Could not open the sealed envelope with that X25519 key: ' + e.message); }+ let bundle; try { bundle = JSON.parse(bundleText); } catch { throw new Error('Sealed payload was not valid JSON.'); }+ openedSecretSeed = bundle.seed || (Array.isArray(bundle.secretKey) ? Uint8Array.from(bundle.secretKey).slice(0, 32) : undefined);+ }++ const result = verifyVanityReceipt(receipt, { servicePublicKey: pinnedKey || receipt.servicePublicKey, openedSecretSeed });+ renderResult(result, receipt);+ } catch (e) {+ $('results-card').style.display = 'none';+ showError(e.message || String(e));+ } finally {+ verifyBtn.disabled = false;+ }+ }++ verifyBtn.addEventListener('click', verify);+ receiptEl.addEventListener('keydown', (e) => { if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') verify(); });++ $('clear-btn').addEventListener('click', () => {+ receiptEl.value = ''; x25519El.value = ''; clearError();+ $('results-card').style.display = 'none'; $('verdict').classList.remove('show');+ receiptEl.focus();+ });++ $('copy-badge').addEventListener('click', async () => {+ const addr = (() => { try { return JSON.parse(receiptEl.value).address; } catch { return ''; } })();+ const md = '[](https://three.ws/vanity/verify)' + (addr ? '\n<!-- verified address: ' + addr + ' -->' : '');+ try { await navigator.clipboard.writeText(md); $('copy-badge').textContent = 'Copied!'; setTimeout(() => $('copy-badge').textContent = 'Copy verified badge', 1500); }+ catch { showError('Clipboard unavailable — copy manually: ' + md); }+ });++ // Deep-link support: /vanity/verify#receipt=<base64url JSON> prefills and+ // auto-verifies, so a receipt can be shared as a single link.+ (function loadFromHash() {+ const m = /[#&]receipt=([^&]+)/.exec(location.hash || '');+ if (!m) return;+ try {+ const json = decodeURIComponent(escape(atob(m[1].replace(/-/g, '+').replace(/_/g, '/'))));+ JSON.parse(json); // validate+ receiptEl.value = json;+ verify();+ } catch { /* malformed hash — ignore */ }+ })();+ </script>+</body>+</html>diff --git a/public/x402.js b/public/x402.jsindex 45331fa82..0f4609a35 100644--- a/public/x402.js+++ b/public/x402.js@@ -89,7 +89,7 @@ function isEvmNetwork(net) {// giving off, cause wallet on a different chain than this checkout, or a zero// total. The donation settles in the SAME mint + transaction as the payment, so// the cause wallet must be a Solana address. Pure integer math on atomics.-function computeGiving(giving, accept) {+export function computeGiving(giving, accept) {if (!giving || !isSolanaNetwork(accept?.network)) return null;if (giving.charity_chain && giving.charity_chain !== 'solana') return null;const to = giving.charity_address;diff --git a/public/x402/studio.js b/public/x402/studio.jsindex 6f29f0872..5a3468464 100644--- a/public/x402/studio.js+++ b/public/x402/studio.js@@ -1072,9 +1072,10 @@ function buttonCss() {const fs = EMBED.size === 'sm' ? '14px' : EMBED.size === 'lg' ? '18px' : '16px';const radius = EMBED.shape === 'sm' ? '6px' : EMBED.shape === 'pill' ? '999px' : '12px';const accent = S.settings?.accent_color || '#0a84ff';- const fg = EMBED.theme === 'light' ? '#fff' : '#061018';+ // Dark theme → white button on dark ink; light theme → accent button on white.const bg = EMBED.theme === 'light' ? accent : '#ffffff';- return { pad, fs, radius, accent, fg, bg };+ const fg = EMBED.theme === 'light' ? '#ffffff' : '#061018';+ return { pad, fs, radius, accent, bg, fg };}function drawEmbed() {@@ -1083,7 +1084,7 @@ function drawEmbed() {const label = EMBED.label || (sku ? `Pay · ${sku.action_name}` : 'Pay with USDC');const prev = $('#em_prev');prev.innerHTML = '';- const btn = el('button', { style: `padding:${c.pad};font-size:${c.fs};border-radius:${c.radius};background:${EMBED.theme === 'light' ? c.accent : '#fff'};color:${EMBED.theme === 'light' ? '#fff' : '#061018'};border:0;font-weight:700;cursor:pointer;font-family:var(--font-body)`,+ const btn = el('button', { style: `padding:${c.pad};font-size:${c.fs};border-radius:${c.radius};background:${c.bg};color:${c.fg};border:0;font-weight:700;cursor:pointer;font-family:var(--font-body)`,'data-x402-endpoint': sku.target_endpoint,'data-x402-method': sku.target_method,'data-x402-merchant': sku.merchant_name,@@ -1095,7 +1096,7 @@ function drawEmbed() {if (window.X402?.init) window.X402.init();// Generated snippet.- const style = `padding:${c.pad};font-size:${c.fs};border-radius:${c.radius};background:${EMBED.theme === 'light' ? c.accent : '#fff'};color:${EMBED.theme === 'light' ? '#fff' : '#061018'};border:0;font-weight:700;cursor:pointer`;+ const style = `padding:${c.pad};font-size:${c.fs};border-radius:${c.radius};background:${c.bg};color:${c.fg};border:0;font-weight:700;cursor:pointer`;const attrs = [`data-x402-endpoint="${esc(sku.target_endpoint)}"`,`data-x402-method="${esc(sku.target_method)}"`,diff --git a/scripts/verify-vanity-receipt.mjs b/scripts/verify-vanity-receipt.mjsnew file mode 100644index 000000000..2498c25a1--- /dev/null+++ b/scripts/verify-vanity-receipt.mjs@@ -0,0 +1,305 @@+#!/usr/bin/env node+/**+ * Provably-fair vanity receipt verifier — CLI.+ *+ * Independently audits a three.ws verifiable-grind receipt with open-source+ * crypto. Recomputes every protocol claim (commitment opens, seed-mix derives+ * the address, pattern matches, difficulty is honest, the service signature is+ * valid and signed by the pinned key) and prints a green/red audit. Optionally+ * opens the sealed envelope with your X25519 private key and proves the key you+ * hold IS the ground key — all locally; nothing is sent anywhere.+ *+ * Usage:+ * node scripts/verify-vanity-receipt.mjs <receipt.json> [options]+ * cat receipt.json | node scripts/verify-vanity-receipt.mjs --stdin+ *+ * Options:+ * --stdin read the receipt JSON from stdin+ * --service-key <base58> pin to this service key (default: receipt's own key;+ * pass the key from /.well-known/three-vanity.json to+ * prove the signer is really three.ws)+ * --fetch-key fetch + pin the live key from the well-known doc+ * --x25519-secret <key> your X25519 private key (Base58/hex) to open the seal+ * --secret-seed <hexkey> a 32/64-byte Ed25519 secret you already opened+ * --json emit the machine-readable audit as JSON+ *+ * Exit code 0 = all checks pass; 1 = any check failed or input error.+ */++import { readFileSync } from 'node:fs';+import { argv, exit, stdin } from 'node:process';+import bs58 from 'bs58';+import { ed25519, x25519 } from '@noble/curves/ed25519.js';+import { sha256 } from '@noble/hashes/sha256';+import { hmac } from '@noble/hashes/hmac';+import { hkdf } from '@noble/hashes/hkdf';+import { gcm } from '@noble/ciphers/aes.js';+import { bytesToHex, hexToBytes, concatBytes } from '@noble/hashes/utils';++const PROTOCOL_VERSION = 'three-vanity/v1';+const WELL_KNOWN = 'https://three.ws/.well-known/three-vanity.json';+const enc = new TextEncoder();+const TAG_SEED_COMMIT = enc.encode('three-vanity/seed-commit/v1');+const TAG_MIX_SALT = sha256(enc.encode('three-vanity/mix-salt/v1'));+const TAG_MASTER_INFO = enc.encode('three-vanity/master/v1');+const TAG_CANDIDATE = enc.encode('three-vanity/candidate/v1');+const TAG_RECEIPT = enc.encode('three-vanity/receipt/v1');+const SEALED_SCHEME = 'x25519-hkdf-sha256-aes256gcm/v1';+const HKDF_INFO = enc.encode('three.ws sealed-envelope v1');++const GREEN = '\x1b[32m';+const RED = '\x1b[31m';+const DIM = '\x1b[2m';+const BOLD = '\x1b[1m';+const RESET = '\x1b[0m';++function asBytes(value, label) {+ if (value instanceof Uint8Array) return value;+ const s = String(value).trim();+ if (/^[0-9a-fA-F]+$/.test(s) && s.length % 2 === 0) return hexToBytes(s);+ try {+ return bs58.decode(s);+ } catch {+ throw new Error(`${label} is not valid hex or Base58`);+ }+}+function uint64be(n) {+ const out = new Uint8Array(8);+ let v = BigInt(n);+ for (let i = 7; i >= 0; i--) {+ out[i] = Number(v & 0xffn);+ v >>= 8n;+ }+ return out;+}+function commitToSeed(seed) {+ return bytesToHex(sha256(concatBytes(TAG_SEED_COMMIT, asBytes(seed, 'serverSeed'))));+}+function deriveMasterSeed({ serverSeed, clientSeed, requestNonce }) {+ const ikm = concatBytes(asBytes(serverSeed, 's'), asBytes(clientSeed, 'c'), asBytes(requestNonce, 'n'));+ return hkdf(sha256, ikm, TAG_MIX_SALT, TAG_MASTER_INFO, 32);+}+function candidateAddress(master, index) {+ const seed = hmac(sha256, master, concatBytes(TAG_CANDIDATE, uint64be(index)));+ return { address: bs58.encode(ed25519.getPublicKey(seed)), seed };+}+function addressMatchesPattern(address, { prefix = '', suffix = '', ignoreCase = false } = {}) {+ let a = address, p = prefix || '', s = suffix || '';+ if (ignoreCase) { a = a.toLowerCase(); p = p.toLowerCase(); s = s.toLowerCase(); }+ if (p && !a.startsWith(p)) return false;+ if (s && !a.endsWith(s)) return false;+ return true;+}+function expectedAttempts(prefix = '', suffix = '', ignoreCase = false) {+ const alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';+ let attempts = 1;+ for (const ch of (prefix || '') + (suffix || '')) {+ const lower = ch.toLowerCase(), upper = ch.toUpperCase();+ const two = ignoreCase && lower !== upper && alphabet.includes(lower) && alphabet.includes(upper);+ attempts *= 58 / (two ? 2 : 1);+ }+ return attempts;+}+const SIGNED_FIELDS = ['protocol', 'receiptType', 'address', 'pattern', 'commitment', 'serverSeed', 'clientSeed', 'requestNonce', 'winningIndex', 'attempts', 'durationMs', 'difficulty', 'sealed', 'sealedScheme', 'sealedRecipient', 'sealedEpk', 'network', 'ts'];+function projectSignedCore(obj) {+ const core = {};+ for (const k of SIGNED_FIELDS) if (obj[k] !== undefined) core[k] = obj[k];+ return core;+}+function stableStringify(v) {+ if (v === null || typeof v !== 'object') return JSON.stringify(v);+ if (Array.isArray(v)) return `[${v.map(stableStringify).join(',')}]`;+ return `{${Object.keys(v).sort().map((k) => `${JSON.stringify(k)}:${stableStringify(v[k])}`).join(',')}}`;+}+function verifySignature(receipt, pub) {+ try {+ const bytes = concatBytes(TAG_RECEIPT, enc.encode(stableStringify(projectSignedCore(receipt))));+ return ed25519.verify(hexToBytes(receipt.signature), bytes, asBytes(pub, 'k'));+ } catch {+ return false;+ }+}+function ctEqual(a, b) {+ if (a.length !== b.length) return false;+ let d = 0;+ for (let i = 0; i < a.length; i++) d |= a[i] ^ b[i];+ return d === 0;+}+function fromB64url(str) {+ const pad = str.length % 4 === 0 ? '' : '='.repeat(4 - (str.length % 4));+ return new Uint8Array(Buffer.from(str.replace(/-/g, '+').replace(/_/g, '/') + pad, 'base64'));+}+function openSealed(env, secretKey) {+ const secret = asBytes(secretKey, 'x25519 secret');+ const epk = bs58.decode(env.epk);+ const shared = x25519.getSharedSecret(secret, epk);+ const rpub = x25519.getPublicKey(secret);+ const salt = new Uint8Array(epk.length + rpub.length);+ salt.set(epk, 0); salt.set(rpub, epk.length);+ const key = hkdf(sha256, shared, salt, HKDF_INFO, 32);+ return gcm(key, fromB64url(env.nonce), epk).decrypt(fromB64url(env.ciphertext));+}++function parseArgs(args) {+ const opts = { json: false, stdin: false, fetchKey: false };+ let path = null;+ for (let i = 0; i < args.length; i++) {+ const a = args[i];+ if (a === '--json') opts.json = true;+ else if (a === '--stdin') opts.stdin = true;+ else if (a === '--fetch-key') opts.fetchKey = true;+ else if (a === '--service-key') opts.serviceKey = args[++i];+ else if (a === '--x25519-secret') opts.x25519Secret = args[++i];+ else if (a === '--secret-seed') opts.secretSeed = args[++i];+ else if (!a.startsWith('--')) path = a;+ }+ return { path, opts };+}++async function readStdin() {+ let data = '';+ for await (const chunk of stdin) data += chunk;+ return data;+}++function runChecks(receipt, { servicePublicKey, openedSecretSeed }) {+ const checks = [];+ const add = (id, label, pass, detail) => checks.push({ id, label, pass, detail });++ if (receipt.protocol !== PROTOCOL_VERSION) {+ add('protocol', 'Protocol version is supported', false, `"${receipt.protocol}" ≠ "${PROTOCOL_VERSION}"`);+ return checks;+ }+ add('protocol', 'Protocol version is supported', true, PROTOCOL_VERSION);++ try {+ const computed = commitToSeed(receipt.serverSeed);+ const ok = computed === receipt.commitment;+ add('commitment', 'serverSeed opens the commitment', ok,+ ok ? 'SHA-256(serverSeed) = commitment' : `SHA-256(serverSeed) = ${computed} ≠ ${receipt.commitment}`);+ } catch (e) { add('commitment', 'serverSeed opens the commitment', false, e.message); }++ let derivedSeed = null;+ try {+ const master = deriveMasterSeed(receipt);+ const cand = candidateAddress(master, receipt.winningIndex);+ derivedSeed = cand.seed;+ const ok = cand.address === receipt.address;+ add('derivation', 'Address derives from the mixed seed at the claimed index', ok,+ ok ? `candidate #${receipt.winningIndex} → ${cand.address}` : `re-derives to ${cand.address}, not ${receipt.address}`);+ } catch (e) { add('derivation', 'Address derives from the mixed seed', false, e.message); }++ {+ const ok = addressMatchesPattern(receipt.address, receipt.pattern || {});+ const p = receipt.pattern || {};+ const want = [p.prefix && `prefix "${p.prefix}"`, p.suffix && `suffix "${p.suffix}"`].filter(Boolean).join(' + ') || '(none)';+ add('pattern', 'Address satisfies the requested pattern', ok, `${receipt.address} ${ok ? 'matches' : 'does NOT match'} ${want}`);+ }+ {+ const p = receipt.pattern || {};+ const expected = Math.round(expectedAttempts(p.prefix || '', p.suffix || '', !!p.ignoreCase));+ const ok = Number(receipt.difficulty?.expectedAttempts) === expected;+ add('difficulty', 'Difficulty matches the honest model', ok,+ ok ? `expectedAttempts = ${expected}` : `claims ${receipt.difficulty?.expectedAttempts}, model = ${expected}`);+ }+ {+ const sigOk = verifySignature(receipt, servicePublicKey);+ add('signature', 'Service Ed25519 signature is valid', sigOk,+ sigOk ? `valid under ${servicePublicKey}` : 'signature does not verify');+ let pinned = false;+ try { pinned = ctEqual(asBytes(servicePublicKey, 'a'), asBytes(receipt.servicePublicKey, 'b')); } catch { /* */ }+ add('serviceKeyPinned', 'Signed by the pinned three.ws service key', pinned,+ pinned ? 'receipt key matches the pinned key' : `receipt key ${receipt.servicePublicKey} ≠ pinned ${servicePublicKey}`);+ }+ if (openedSecretSeed) {+ let opened = asBytes(openedSecretSeed, 'secret');+ if (opened.length === 64) opened = opened.slice(0, 32);+ const ok = derivedSeed && opened.length === 32 && ctEqual(opened, derivedSeed);+ const pubOk = ok && bs58.encode(ed25519.getPublicKey(opened)) === receipt.address;+ add('custody', 'Your recovered key is the ground key', !!(ok && pubOk),+ ok && pubOk ? 'the opened secret re-derives to the receipt address' : 'opened secret does NOT match');+ }+ return checks;+}++async function main() {+ const { path, opts } = parseArgs(argv.slice(2));+ let raw;+ if (opts.stdin || (!path && !process.stdin.isTTY)) {+ raw = await readStdin();+ } else if (path) {+ raw = readFileSync(path, 'utf8');+ } else {+ console.error('Usage: verify-vanity-receipt.mjs <receipt.json> [--stdin] [--service-key K] [--fetch-key] [--x25519-secret K] [--json]');+ exit(1);+ }++ let receipt;+ try {+ receipt = JSON.parse(raw);+ } catch (e) {+ console.error(`${RED}Invalid JSON: ${e.message}${RESET}`);+ exit(1);+ }++ // Resolve the service key to pin against.+ let servicePublicKey = opts.serviceKey || receipt.servicePublicKey;+ let pinSource = opts.serviceKey ? 'CLI --service-key' : "receipt's own key (unpinned — pass --service-key or --fetch-key to pin)";+ if (opts.fetchKey) {+ try {+ const res = await fetch(WELL_KNOWN, { headers: { accept: 'application/json' } });+ const doc = await res.json();+ servicePublicKey = doc.serviceKey.publicKeyBase58;+ pinSource = `${WELL_KNOWN}`;+ } catch (e) {+ console.error(`${RED}Could not fetch the live service key: ${e.message}${RESET}`);+ exit(1);+ }+ }++ // Optionally open the seal to prove custody.+ let openedSecretSeed = opts.secretSeed || null;+ if (!openedSecretSeed && opts.x25519Secret && receipt.sealedSecret?.scheme === SEALED_SCHEME) {+ try {+ const pt = openSealed(receipt.sealedSecret, opts.x25519Secret);+ const bundle = JSON.parse(new TextDecoder().decode(pt));+ openedSecretSeed = bundle.seed || (bundle.secretKey ? bytesToHex(Uint8Array.from(bundle.secretKey).slice(0, 32)) : null);+ } catch (e) {+ console.error(`${RED}Could not open the sealed envelope: ${e.message}${RESET}`);+ exit(1);+ }+ }++ const checks = runChecks(receipt, { servicePublicKey, openedSecretSeed });+ const valid = checks.every((c) => c.pass);++ if (opts.json) {+ console.log(JSON.stringify({ valid, address: receipt.address, pinSource, checks }, null, 2));+ exit(valid ? 0 : 1);+ }++ console.log('');+ console.log(`${BOLD}three.ws — provably-fair vanity receipt${RESET}`);+ console.log(`${DIM}address ${RESET}${receipt.address}`);+ console.log(`${DIM}pinned ${RESET}${servicePublicKey} ${DIM}(${pinSource})${RESET}`);+ console.log('');+ for (const c of checks) {+ const mark = c.pass ? `${GREEN}✓${RESET}` : `${RED}✗${RESET}`;+ console.log(` ${mark} ${c.label}`);+ console.log(` ${DIM}${c.detail}${RESET}`);+ }+ console.log('');+ if (valid) {+ console.log(`${GREEN}${BOLD}VERIFIED${RESET} — every protocol claim checks out. This key was generated`);+ console.log(`${GREEN}fresh under the committed seed and the operator could not have kept a copy.${RESET}`);+ } else {+ console.log(`${RED}${BOLD}FAILED${RESET} — one or more checks did not pass. Do NOT trust this receipt.`);+ }+ console.log('');+ exit(valid ? 0 : 1);+}++main().catch((e) => {+ console.error(`${RED}${e.stack || e.message}${RESET}`);+ exit(1);+});diff --git a/solana-agent-sdk/package.json b/solana-agent-sdk/package.jsonindex 8a208d5dd..f4dbb48fa 100644--- a/solana-agent-sdk/package.json+++ b/solana-agent-sdk/package.json@@ -26,6 +26,11 @@"types": "./dist/solana-agent-kit/index.d.ts","import": "./dist/solana-agent-kit/index.js","require": "./dist/solana-agent-kit/index.cjs"+ },+ "./vanity": {+ "types": "./dist/vanity/index.d.ts",+ "import": "./dist/vanity/index.js",+ "require": "./dist/vanity/index.cjs"}},"files": [@@ -42,6 +47,9 @@},"dependencies": {"@coral-xyz/anchor": "^0.32.1",+ "@noble/ciphers": "^1.3.0",+ "@noble/curves": "^2.2.0",+ "@noble/hashes": "^1.8.0","@solana/spl-token": "^0.4.9","@solana/web3.js": "^1.98.0","@tetsuo-ai/protocol": "^0.2.0",diff --git a/solana-agent-sdk/src/index.ts b/solana-agent-sdk/src/index.tsindex f632af26b..2a283472b 100644--- a/solana-agent-sdk/src/index.ts+++ b/solana-agent-sdk/src/index.ts@@ -53,3 +53,8 @@ export { toUiAmount } from "./utils/format.js";// AgenC adapter — read + write the AgenC coordination protocol (agenc.tech).export * from "./actions/agenc/index.js";++// Provably-fair vanity grinding — verify a three.ws vanity receipt entirely+// client-side, open the sealed key, or run the whole request→open→verify flow+// in one call. Proves the key was generated fresh and never kept.+export * from "./vanity/index.js";diff --git a/solana-agent-sdk/src/vanity/client.ts b/solana-agent-sdk/src/vanity/client.tsnew file mode 100644index 000000000..3759e21fb--- /dev/null+++ b/solana-agent-sdk/src/vanity/client.ts@@ -0,0 +1,139 @@+/**+ * One-call provably-fair vanity client: request → open the seal → verify.+ *+ * `grindVerifiedVanity` drives the full trustless flow against three.ws's+ * `/api/x402/vanity-verifiable` endpoint:+ * 1. generate a fresh X25519 recipient keypair (so the secret is ECIES-sealed+ * and never travels in plaintext) and a fresh clientSeed (your entropy in+ * the mix);+ * 2. pay-per-call with your x402-capable fetch and pull back the signed receipt;+ * 3. open the sealed envelope locally with the X25519 secret;+ * 4. independently verify every protocol claim — including that the key you+ * just opened IS the ground key — before handing you the secret.+ *+ * If verification fails, it THROWS rather than return an unverified key: the+ * whole point is that you never accept a key you couldn't prove was honest.+ *+ * Bring your own x402 fetch (e.g. `wrapFetchWithPayment` from @x402/fetch, or+ * the SDK's payExact-driven fetch). This module stays payment-rail-agnostic.+ */++import bs58 from "bs58";+import {+ verifyVanityReceipt,+ THREE_VANITY_ENDPOINT,+ type VanityReceipt,+ type VerifyResult,+} from "./verify.js";+import { openSealedJson, generateRecipientKeypair, type SealedEnvelope } from "./sealed.js";++export interface SealedBundle {+ format: string;+ secretKeyBase58: string;+ secretKey: number[];+ seed: string;+}++export interface GrindVerifiedResult {+ /** Base58 Solana address. */+ address: string;+ /** 64-byte secret key (Solana / Phantom import format). */+ secretKey: Uint8Array;+ /** Base58 secret key. */+ secretKeyBase58: string;+ /** The full signed receipt — keep it; anyone can re-verify it later. */+ receipt: VanityReceipt;+ /** The per-check verification audit (all passed, or this would have thrown). */+ verification: VerifyResult;+}++export interface GrindVerifiedOptions {+ prefix?: string;+ suffix?: string;+ ignoreCase?: boolean;+ /** Your own entropy (hex/Base58). A fresh random one is used when omitted. */+ clientSeed?: string;+ /** x402-capable fetch (paywall-aware). Defaults to global fetch. */+ fetchImpl?: typeof fetch;+ /** Override the endpoint (e.g. devnet/staging). */+ endpoint?: string;+ /** Override the pinned service key (e.g. fetched from the well-known doc). */+ servicePublicKey?: string;+}++function randomClientSeedHex(): string {+ const b = new Uint8Array(32);+ (globalThis.crypto as Crypto).getRandomValues(b);+ return bs58.encode(b); // Base58 — the endpoint accepts hex or Base58.+}++/**+ * Request a provably-fair vanity wallet, open the seal locally, and verify it.+ * Throws if the receipt does not verify against the pinned service key.+ */+export async function grindVerifiedVanity(+ opts: GrindVerifiedOptions = {},+): Promise<GrindVerifiedResult> {+ const doFetch = opts.fetchImpl ?? fetch;+ const endpoint = opts.endpoint ?? THREE_VANITY_ENDPOINT;++ // 1. Fresh X25519 recipient + clientSeed — the buyer contributes entropy and+ // the secret is sealed to a key only the buyer holds.+ const recipient = generateRecipientKeypair();+ const clientSeed = opts.clientSeed ?? randomClientSeedHex();++ const url = new URL(endpoint);+ if (opts.prefix) url.searchParams.set("prefix", opts.prefix);+ if (opts.suffix) url.searchParams.set("suffix", opts.suffix);+ if (opts.ignoreCase) url.searchParams.set("ignoreCase", "1");+ url.searchParams.set("clientSeed", clientSeed);+ url.searchParams.set("sealTo", recipient.publicKey);++ // 2. Pay + fetch the signed receipt.+ const res = await doFetch(url.toString(), { headers: { accept: "application/json" } });+ if (!res.ok) {+ const text = await res.text().catch(() => "");+ throw new Error(`vanity-verifiable request failed: ${res.status} ${text.slice(0, 300)}`);+ }+ const receipt = (await res.json()) as VanityReceipt & {+ sealedSecret?: SealedEnvelope;+ secretKeyBase58?: string;+ secretKey?: number[];+ seed?: string;+ };++ // 3. Open the sealed envelope locally (or read the plaintext if unsealed).+ let secretKeyBase58: string;+ let secretKey: Uint8Array;+ let openedSeed: Uint8Array | undefined;+ if (receipt.sealed && receipt.sealedSecret) {+ const bundle = openSealedJson<SealedBundle>(receipt.sealedSecret, recipient.secretKey);+ secretKeyBase58 = bundle.secretKeyBase58;+ secretKey = Uint8Array.from(bundle.secretKey);+ openedSeed = secretKey.slice(0, 32);+ } else if (receipt.secretKeyBase58) {+ secretKeyBase58 = receipt.secretKeyBase58;+ secretKey = Uint8Array.from(receipt.secretKey ?? bs58.decode(receipt.secretKeyBase58));+ openedSeed = secretKey.slice(0, 32);+ } else {+ throw new Error("receipt carried neither a sealed envelope nor a plaintext secret");+ }++ // 4. Independently verify EVERY claim — including custody of THIS key.+ const verification = verifyVanityReceipt(receipt, {+ servicePublicKey: opts.servicePublicKey,+ openedSecretSeed: openedSeed,+ });+ if (!verification.valid) {+ const failed = verification.checks.filter((c) => !c.pass).map((c) => `${c.id}: ${c.detail}`);+ throw new Error(`receipt failed verification — ${failed.join("; ")}`);+ }++ return {+ address: receipt.address,+ secretKey,+ secretKeyBase58,+ receipt,+ verification,+ };+}diff --git a/solana-agent-sdk/src/vanity/index.ts b/solana-agent-sdk/src/vanity/index.tsnew file mode 100644index 000000000..298c5f6b9--- /dev/null+++ b/solana-agent-sdk/src/vanity/index.ts@@ -0,0 +1,29 @@+// Provably-fair vanity grinding — verifier, sealed-envelope opener, one-call client.+export {+ verifyVanityReceipt,+ verifyReceiptSignature,+ commitToSeed,+ deriveMasterSeed,+ candidateSeed,+ candidateAddress,+ addressMatchesPattern,+ expectedAttempts,+ fetchServiceKey,+ VANITY_PROTOCOL_VERSION,+ THREE_VANITY_SERVICE_KEY,+ THREE_VANITY_WELL_KNOWN,+ THREE_VANITY_ENDPOINT,+} from "./verify.js";+export type {+ VanityReceipt,+ VanityPattern,+ VerifyCheck,+ VerifyResult,+ VerifyOptions,+} from "./verify.js";++export { openSealed, openSealedJson, generateRecipientKeypair, SEALED_ENVELOPE_SCHEME } from "./sealed.js";+export type { SealedEnvelope } from "./sealed.js";++export { grindVerifiedVanity } from "./client.js";+export type { GrindVerifiedResult, GrindVerifiedOptions, SealedBundle } from "./client.js";diff --git a/solana-agent-sdk/src/vanity/sealed.ts b/solana-agent-sdk/src/vanity/sealed.tsnew file mode 100644index 000000000..00d00df9a--- /dev/null+++ b/solana-agent-sdk/src/vanity/sealed.ts@@ -0,0 +1,104 @@+/**+ * Open a three.ws sealed envelope (ECIES `x25519-hkdf-sha256-aes256gcm/v1`).+ *+ * Mirror of src/solana/vanity/sealed-envelope.js's openSealed, implemented with+ * @noble (X25519 + HKDF-SHA256 + AES-256-GCM) so it runs identically in Node and+ * the browser without depending on WebCrypto subtle being present. The buyer's+ * X25519 secret key never leaves the caller's process.+ */++import bs58 from "bs58";+import { x25519 } from "@noble/curves/ed25519.js";+import { hkdf } from "@noble/hashes/hkdf";+import { sha256 } from "@noble/hashes/sha256";+import { gcm } from "@noble/ciphers/aes.js";++export const SEALED_ENVELOPE_SCHEME = "x25519-hkdf-sha256-aes256gcm/v1";++const HKDF_INFO = new TextEncoder().encode("three.ws sealed-envelope v1");+const X25519_KEY_BYTES = 32;++export interface SealedEnvelope {+ scheme: string;+ epk: string;+ nonce: string;+ ciphertext: string;+ recipient?: string;+}++function fromBase64url(str: string): Uint8Array {+ const pad = str.length % 4 === 0 ? "" : "=".repeat(4 - (str.length % 4));+ const b64 = str.replace(/-/g, "+").replace(/_/g, "/") + pad;+ if (typeof atob === "function") {+ const bin = atob(b64);+ const out = new Uint8Array(bin.length);+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);+ return out;+ }+ // Node fallback.+ return new Uint8Array(Buffer.from(b64, "base64"));+}++function parseX25519Key(key: Uint8Array | string, label: string): Uint8Array {+ let bytes: Uint8Array;+ if (key instanceof Uint8Array) {+ bytes = key;+ } else {+ const s = key.trim();+ if (/^[0-9a-fA-F]{64}$/.test(s)) {+ bytes = Uint8Array.from(s.match(/.{2}/g)!.map((h) => parseInt(h, 16)));+ } else if (/^[1-9A-HJ-NP-Za-km-z]+$/.test(s) && !s.includes("-") && !s.includes("_")) {+ bytes = bs58.decode(s);+ } else {+ bytes = fromBase64url(s);+ }+ }+ if (bytes.length !== X25519_KEY_BYTES) {+ throw new Error(`${label} must be a 32-byte X25519 key (got ${bytes.length})`);+ }+ return bytes;+}++/** Open a sealed envelope with the recipient's X25519 secret key → plaintext bytes. */+export function openSealed(+ envelope: SealedEnvelope,+ recipientSecretKey: Uint8Array | string,+): Uint8Array {+ if (!envelope || envelope.scheme !== SEALED_ENVELOPE_SCHEME) {+ throw new Error(`unsupported sealed-envelope scheme: ${envelope?.scheme}`);+ }+ const secret = parseX25519Key(recipientSecretKey, "recipient secret key");+ const epk = parseX25519Key(envelope.epk, "ephemeral public key");+ const shared = x25519.getSharedSecret(secret, epk);+ const recipientPub = x25519.getPublicKey(secret);++ const salt = new Uint8Array(epk.length + recipientPub.length);+ salt.set(epk, 0);+ salt.set(recipientPub, epk.length);+ const keyBytes = hkdf(sha256, shared, salt, HKDF_INFO, 32);++ const nonce = fromBase64url(envelope.nonce);+ const ct = fromBase64url(envelope.ciphertext);+ // AAD = ephemeral public key, exactly as the server bound it on seal.+ const aead = gcm(keyBytes, nonce, epk);+ const pt = aead.decrypt(ct);+ keyBytes.fill(0);+ return pt;+}++/** Open a sealed envelope and decode the plaintext as UTF-8 JSON. */+export function openSealedJson<T = unknown>(+ envelope: SealedEnvelope,+ recipientSecretKey: Uint8Array | string,+): T {+ return JSON.parse(new TextDecoder().decode(openSealed(envelope, recipientSecretKey))) as T;+}++/** Generate a throwaway X25519 recipient keypair (Base58). Pass publicKey as sealTo. */+export function generateRecipientKeypair(): { publicKey: string; secretKey: string } {+ const secret = x25519.utils.randomSecretKey();+ return {+ publicKey: bs58.encode(x25519.getPublicKey(secret)),+ secretKey: bs58.encode(secret),+ };+}diff --git a/solana-agent-sdk/src/vanity/verify.ts b/solana-agent-sdk/src/vanity/verify.tsnew file mode 100644index 000000000..c86144231--- /dev/null+++ b/solana-agent-sdk/src/vanity/verify.ts@@ -0,0 +1,410 @@+/**+ * Provably-fair vanity grinding — client verifier + one-call grind client.+ *+ * three.ws's verifiable vanity grinder (`/api/x402/vanity-verifiable`) returns a+ * signed receipt that proves the key was generated fresh under a commit–reveal+ * seed-mixing protocol and never kept. This module reproduces every protocol+ * check from first principles so a buyer trusts nothing in the receipt — it+ * recomputes each claim. Real crypto only: @noble Ed25519 / SHA-256 / HMAC /+ * HKDF, the same primitives the server signs with.+ *+ * Protocol `three-vanity/v1` is documented in docs/PROTOCOL-vanity.md.+ */++import bs58 from "bs58";+import { ed25519 } from "@noble/curves/ed25519.js";+import { sha256 } from "@noble/hashes/sha256";+import { hmac } from "@noble/hashes/hmac";+import { hkdf } from "@noble/hashes/hkdf";+import { bytesToHex, hexToBytes, concatBytes } from "@noble/hashes/utils";++export const VANITY_PROTOCOL_VERSION = "three-vanity/v1";++/**+ * Pinned three.ws vanity service public key (Base58 Ed25519). Verification pins+ * to this by default so a self-signed impostor receipt is rejected. Override via+ * `verifyVanityReceipt(receipt, { servicePublicKey })` — e.g. after fetching the+ * live key from `/.well-known/three-vanity.json`. Updated when the service key+ * rotates; always cross-check against the well-known document for production use.+ */+export const THREE_VANITY_SERVICE_KEY = "H8wSgC8JgTadWE4ECVkUdHRywxEygnLbpJjEwcej92NH";++export const THREE_VANITY_WELL_KNOWN = "https://three.ws/.well-known/three-vanity.json";+export const THREE_VANITY_ENDPOINT = "https://three.ws/api/x402/vanity-verifiable";++const enc = new TextEncoder();+const TAG_SEED_COMMIT = enc.encode("three-vanity/seed-commit/v1");+const TAG_MIX_SALT = sha256(enc.encode("three-vanity/mix-salt/v1"));+const TAG_MASTER_INFO = enc.encode("three-vanity/master/v1");+const TAG_CANDIDATE = enc.encode("three-vanity/candidate/v1");+const TAG_RECEIPT = enc.encode("three-vanity/receipt/v1");+const SEED_BYTES = 32;++export interface VanityPattern {+ prefix?: string | null;+ suffix?: string | null;+ ignoreCase?: boolean;+}++export interface VanityReceipt {+ protocol: string;+ receiptType?: string;+ address: string;+ pattern: VanityPattern;+ commitment: string;+ serverSeed: string;+ clientSeed: string;+ requestNonce: string;+ winningIndex: number;+ attempts?: number;+ durationMs?: number;+ difficulty?: { expectedAttempts?: number; model?: string };+ sealed?: boolean;+ sealedRecipient?: string | null;+ sealedEpk?: string | null;+ servicePublicKey: string;+ signature: string;+ signatureScheme?: string;+ ts?: string;+ [k: string]: unknown;+}++export interface VerifyCheck {+ id: string;+ label: string;+ pass: boolean;+ detail: string;+}++export interface VerifyResult {+ valid: boolean;+ checks: VerifyCheck[];+ address: string;+}++export interface VerifyOptions {+ /** Pinned service public key (Base58/hex). Defaults to THREE_VANITY_SERVICE_KEY. */+ servicePublicKey?: string | Uint8Array;+ /** The 32-byte Ed25519 seed you recovered from the sealed envelope (optional). */+ openedSecretSeed?: Uint8Array | string;+}++function asBytes(value: Uint8Array | string, label: string): Uint8Array {+ if (value instanceof Uint8Array) return value;+ if (typeof value === "string") {+ const s = value.trim();+ if (/^[0-9a-fA-F]+$/.test(s) && s.length % 2 === 0) return hexToBytes(s);+ try {+ return bs58.decode(s);+ } catch {+ throw new Error(`${label} is not valid hex or Base58`);+ }+ }+ throw new Error(`${label} must be a Uint8Array, hex, or Base58 string`);+}++function uint64be(n: number): Uint8Array {+ const out = new Uint8Array(8);+ let v = BigInt(n);+ for (let i = 7; i >= 0; i--) {+ out[i] = Number(v & 0xffn);+ v >>= 8n;+ }+ return out;+}++/** Commitment the server publishes before grinding. */+export function commitToSeed(serverSeed: Uint8Array | string): string {+ const seed = asBytes(serverSeed, "serverSeed");+ if (seed.length !== SEED_BYTES) throw new Error("serverSeed must be 32 bytes");+ return bytesToHex(sha256(concatBytes(TAG_SEED_COMMIT, seed)));+}++/** Fold serverSeed + clientSeed + requestNonce into the 32-byte master seed. */+export function deriveMasterSeed(p: {+ serverSeed: Uint8Array | string;+ clientSeed: Uint8Array | string;+ requestNonce: Uint8Array | string;+}): Uint8Array {+ const ikm = concatBytes(+ asBytes(p.serverSeed, "serverSeed"),+ asBytes(p.clientSeed, "clientSeed"),+ asBytes(p.requestNonce, "requestNonce"),+ );+ return hkdf(sha256, ikm, TAG_MIX_SALT, TAG_MASTER_INFO, SEED_BYTES);+}++/** Deterministic Ed25519 seed for candidate `index`. */+export function candidateSeed(masterSeed: Uint8Array, index: number): Uint8Array {+ return hmac(sha256, masterSeed, concatBytes(TAG_CANDIDATE, uint64be(index)));+}++/** Base58 Solana address for candidate `index`. */+export function candidateAddress(+ masterSeed: Uint8Array,+ index: number,+): { address: string; seed: Uint8Array } {+ const seed = candidateSeed(masterSeed, index);+ return { address: bs58.encode(ed25519.getPublicKey(seed)), seed };+}++/** Per-character expected attempts: how many of 58 chars satisfy a position. */+function matchesPerChar(ch: string, ignoreCase: boolean): number {+ if (!ignoreCase) return 1;+ const alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";+ const lower = ch.toLowerCase();+ const upper = ch.toUpperCase();+ if (lower !== upper && alphabet.includes(lower) && alphabet.includes(upper)) return 2;+ return 1;+}++/** Honest probability model: expected attempts for a pattern (mirrors validation.js). */+export function expectedAttempts(prefix = "", suffix = "", ignoreCase = false): number {+ let attempts = 1;+ for (const ch of (prefix || "") + (suffix || "")) {+ attempts *= 58 / matchesPerChar(ch, ignoreCase);+ }+ return attempts;+}++export function addressMatchesPattern(address: string, pattern: VanityPattern): boolean {+ let addr = address;+ let pre = pattern.prefix || "";+ let suf = pattern.suffix || "";+ if (pattern.ignoreCase) {+ addr = addr.toLowerCase();+ pre = pre.toLowerCase();+ suf = suf.toLowerCase();+ }+ if (pre && !addr.startsWith(pre)) return false;+ if (suf && !addr.endsWith(suf)) return false;+ return true;+}++// Exactly the fields the service signs (delivery payload + navigation hints are+// excluded). The verifier projects any receipt down to these before hashing so+// extra response/UI fields never perturb the signature. Must stay in lockstep+// with SIGNED_FIELDS in src/solana/vanity/verifiable-grind.js.+const SIGNED_FIELDS = [+ "protocol",+ "receiptType",+ "address",+ "pattern",+ "commitment",+ "serverSeed",+ "clientSeed",+ "requestNonce",+ "winningIndex",+ "attempts",+ "durationMs",+ "difficulty",+ "sealed",+ "sealedScheme",+ "sealedRecipient",+ "sealedEpk",+ "network",+ "ts",+] as const;++function projectSignedCore(obj: Record<string, unknown>): Record<string, unknown> {+ const core: Record<string, unknown> = {};+ for (const k of SIGNED_FIELDS) {+ if (obj[k] !== undefined) core[k] = obj[k];+ }+ return core;+}++function stableStringify(value: unknown): string {+ if (value === null || typeof value !== "object") return JSON.stringify(value);+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;+ const obj = value as Record<string, unknown>;+ const keys = Object.keys(obj).sort();+ return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(obj[k])}`).join(",")}}`;+}++function canonicalReceiptBytes(core: Record<string, unknown>): Uint8Array {+ return concatBytes(TAG_RECEIPT, enc.encode(stableStringify(projectSignedCore(core))));+}++/** Verify the receipt's Ed25519 service signature against a public key. */+export function verifyReceiptSignature(+ receipt: VanityReceipt,+ servicePublicKey: string | Uint8Array,+): boolean {+ if (!receipt?.signature) return false;+ try {+ return ed25519.verify(+ hexToBytes(receipt.signature),+ canonicalReceiptBytes(receipt as unknown as Record<string, unknown>),+ asBytes(servicePublicKey, "servicePublicKey"),+ );+ } catch {+ return false;+ }+}++function constantTimeEqual(a: Uint8Array, b: Uint8Array): boolean {+ if (a.length !== b.length) return false;+ let diff = 0;+ for (let i = 0; i < a.length; i++) diff |= (a[i] ?? 0) ^ (b[i] ?? 0);+ return diff === 0;+}++function sameKey(a: string | Uint8Array, b: string | Uint8Array): boolean {+ try {+ return constantTimeEqual(asBytes(a, "a"), asBytes(b, "b"));+ } catch {+ return false;+ }+}++/**+ * Independently verify a vanity receipt. Recomputes every protocol claim — it+ * trusts nothing in the receipt. Returns a per-check audit plus an overall+ * verdict. Pins to THREE_VANITY_SERVICE_KEY unless `servicePublicKey` is given.+ */+export function verifyVanityReceipt(+ receipt: VanityReceipt,+ opts: VerifyOptions = {},+): VerifyResult {+ const checks: VerifyCheck[] = [];+ const add = (id: string, label: string, pass: boolean, detail: string) =>+ checks.push({ id, label, pass, detail });+ const pin = opts.servicePublicKey ?? THREE_VANITY_SERVICE_KEY;++ if (!receipt || typeof receipt !== "object") {+ add("shape", "Receipt is well-formed", false, "receipt is missing or not an object");+ return { valid: false, checks, address: "" };+ }+ if (receipt.protocol !== VANITY_PROTOCOL_VERSION) {+ add("protocol", "Protocol version is supported", false, `"${receipt.protocol}" ≠ "${VANITY_PROTOCOL_VERSION}"`);+ return { valid: false, checks, address: receipt.address || "" };+ }+ add("protocol", "Protocol version is supported", true, VANITY_PROTOCOL_VERSION);++ // 1. Commitment opens to the revealed serverSeed.+ try {+ const computed = commitToSeed(receipt.serverSeed);+ const ok = computed === receipt.commitment;+ add(+ "commitment",+ "serverSeed opens the commitment",+ ok,+ ok+ ? "SHA-256(serverSeed) matches the committed value — the server could not have swapped seeds after grinding"+ : `SHA-256(serverSeed) = ${computed} ≠ committed ${receipt.commitment}`,+ );+ } catch (e) {+ add("commitment", "serverSeed opens the commitment", false, (e as Error).message);+ }++ // 2. Re-derive the master seed + winning candidate; bind to the address.+ let derivedSeed: Uint8Array | null = null;+ try {+ const master = deriveMasterSeed({+ serverSeed: receipt.serverSeed,+ clientSeed: receipt.clientSeed,+ requestNonce: receipt.requestNonce,+ });+ const cand = candidateAddress(master, receipt.winningIndex);+ derivedSeed = cand.seed;+ const ok = cand.address === receipt.address;+ add(+ "derivation",+ "Address derives from the mixed seed at the claimed index",+ ok,+ ok+ ? `candidate #${receipt.winningIndex} re-derives to ${cand.address}`+ : `candidate #${receipt.winningIndex} re-derives to ${cand.address}, not ${receipt.address}`,+ );+ } catch (e) {+ add("derivation", "Address derives from the mixed seed at the claimed index", false, (e as Error).message);+ }++ // 3. Pattern.+ {+ const ok = addressMatchesPattern(receipt.address || "", receipt.pattern || {});+ const p = receipt.pattern || {};+ const want =+ [p.prefix && `prefix "${p.prefix}"`, p.suffix && `suffix "${p.suffix}"`].filter(Boolean).join(" + ") ||+ "(no pattern)";+ add(+ "pattern",+ "Address satisfies the requested pattern",+ ok,+ ok ? `${receipt.address} matches ${want}` : `${receipt.address} does NOT match ${want}`,+ );+ }++ // 4. Difficulty is the honest model.+ {+ const p = receipt.pattern || {};+ const expected = Math.round(expectedAttempts(p.prefix || "", p.suffix || "", !!p.ignoreCase));+ const ok = Number(receipt.difficulty?.expectedAttempts) === expected;+ add(+ "difficulty",+ "Difficulty matches the honest model",+ ok,+ ok ? `expectedAttempts = ${expected}` : `claims ${receipt.difficulty?.expectedAttempts}, honest model = ${expected}`,+ );+ }++ // 5. Service signature + pinned-key check.+ {+ const sigOk = verifyReceiptSignature(receipt, pin);+ add(+ "signature",+ "Service Ed25519 signature is valid",+ sigOk,+ sigOk ? `valid under the pinned key` : "signature does not verify against the pinned service key",+ );+ const pinned = sameKey(pin, receipt.servicePublicKey);+ add(+ "serviceKeyPinned",+ "Signed by the pinned three.ws service key",+ pinned,+ pinned+ ? `receipt key ${receipt.servicePublicKey} matches the pinned key`+ : `receipt key ${receipt.servicePublicKey} ≠ pinned key — possible impostor`,+ );+ }++ // 6. (Optional) the opened secret is the ground key.+ if (opts.openedSecretSeed) {+ try {+ let opened = asBytes(opts.openedSecretSeed, "openedSecretSeed");+ if (opened.length === 64) opened = opened.slice(0, 32);+ const ok =+ derivedSeed != null && opened.length === 32 && constantTimeEqual(opened, derivedSeed);+ const pubOk = ok && bs58.encode(ed25519.getPublicKey(opened)) === receipt.address;+ add(+ "custody",+ "Your recovered key is the ground key",+ ok && pubOk,+ ok && pubOk+ ? "the secret you opened re-derives to the receipt address — you hold the one and only key"+ : "the opened secret does NOT match the protocol-derived key for this receipt",+ );+ } catch (e) {+ add("custody", "Your recovered key is the ground key", false, (e as Error).message);+ }+ }++ const valid = checks.every((c) => c.pass);+ return { valid, checks, address: receipt.address || "" };+}++/**+ * Fetch the live service public key from /.well-known/three-vanity.json. Use this+ * to pin against the canonical key independently of the SDK constant.+ */+export async function fetchServiceKey(+ wellKnownUrl: string = THREE_VANITY_WELL_KNOWN,+): Promise<string> {+ const res = await fetch(wellKnownUrl, { headers: { accept: "application/json" } });+ if (!res.ok) throw new Error(`well-known fetch failed: ${res.status}`);+ const doc = (await res.json()) as { serviceKey?: { publicKeyBase58?: string } };+ const key = doc?.serviceKey?.publicKeyBase58;+ if (!key) throw new Error("well-known document missing serviceKey.publicKeyBase58");+ return key;+}diff --git a/solana-agent-sdk/tsup.config.ts b/solana-agent-sdk/tsup.config.tsindex 822d2dc27..e8ea114cc 100644--- a/solana-agent-sdk/tsup.config.ts+++ b/solana-agent-sdk/tsup.config.ts@@ -7,6 +7,7 @@ export default defineConfig({"src/wallet/index.ts","src/x402-exact/index.ts","src/solana-agent-kit/index.ts",+ "src/vanity/index.ts",],format: ["cjs", "esm"],dts: { compilerOptions: { noUnusedLocals: false, noUnusedParameters: false } },diff --git a/src/solana/vanity/verifiable-grind.js b/src/solana/vanity/verifiable-grind.jsnew file mode 100644index 000000000..952bf6c72--- /dev/null+++ b/src/solana/vanity/verifiable-grind.js@@ -0,0 +1,570 @@+/**+ * Verifiable, provably-fair vanity grinding — the protocol primitive.+ *+ * Every other vanity service asks you to trust the operator: trust that the key+ * was generated with real randomness, that no copy was kept, that they didn't+ * grind 10,000 candidates and hand you the one whose key they secretly logged.+ * This module makes all three claims *provable* after the fact, with nothing but+ * the receipt and open-source crypto.+ *+ * ── Protocol `three-vanity/v1` (commit–reveal seed mixing) ───────────────────+ *+ * 1. COMMIT. Before grinding, the server draws a uniformly random 32-byte+ * `serverSeed` and publishes `commitment = SHA-256("three-vanity/seed-commit/v1"+ * ‖ serverSeed)`. The commitment is bound into the signed receipt, so the+ * server is locked to that seed *before* it knows which candidate will win —+ * it cannot have precomputed a rainbow table keyed to the buyer's pattern.+ *+ * 2. MIX. Neither party alone may control the output. The two seeds plus the+ * request nonce are folded into a single master seed:+ *+ * masterSeed = HKDF-SHA256(+ * ikm = serverSeed ‖ clientSeed ‖ requestNonce,+ * salt = SHA-256("three-vanity/mix-salt/v1"),+ * info = "three-vanity/master/v1",+ * len = 32)+ *+ * `clientSeed` is buyer-supplied (or a fresh random one we reveal); the buyer+ * therefore contributes entropy the server could not predict at commit time.+ *+ * 3. DERIVE. Candidate `i` (a 0-based counter) has a fully deterministic Ed25519+ * secret seed:+ *+ * seed_i = HMAC-SHA256(key = masterSeed,+ * msg = "three-vanity/candidate/v1" ‖ uint64_be(i))+ *+ * The 32-byte `seed_i` is the Ed25519 private scalar seed; its public key is+ * the Solana address. The grinder walks i = 0,1,2,… until the address matches+ * the pattern; the winning index is recorded as `winningIndex`.+ *+ * 4. SEAL + SIGN. The secret is sealed to the buyer (ECIES, sealed-envelope.js)+ * so plaintext never touches the wire, and the server signs the receipt with+ * its long-lived Ed25519 identity key (published at /.well-known/three-vanity.json).+ *+ * ── Verification (verifyVanityReceipt) reproduces, never trusts ──────────────+ *+ * • SHA-256(serverSeed) === commitment (server didn't swap the seed)+ * • re-derive masterSeed and seed_{winningIndex} (mixing was honest)+ * • that seed's public key === receipt.address (address ↔ key bind)+ * • address satisfies the claimed pattern (pattern honesty)+ * • Ed25519 verify(signature, receipt, serviceKey) (it's really our service)+ * • optionally: opened secret === re-derived secret (the sealed key is THE key)+ *+ * Determinism is the whole point, so this file hand-derives every candidate in+ * JS (noble Ed25519) rather than the WASM grinder — the verifier must reproduce+ * the exact stream. It is isomorphic: @noble/curves + @noble/hashes give pure-JS+ * Ed25519/HMAC/HKDF/SHA-256 that run identically in Node serverless and the+ * browser. Behaviour is pinned by fixed vectors in+ * tests/vanity-verifiable-grind.test.js (including a tamper/negative test).+ */++import bs58 from 'bs58';+import { ed25519 } from '@noble/curves/ed25519.js';+import { sha256 } from '@noble/hashes/sha256';+import { hmac } from '@noble/hashes/hmac';+import { hkdf } from '@noble/hashes/hkdf';+import { bytesToHex, hexToBytes, concatBytes } from '@noble/hashes/utils';++import { validatePattern, BASE58_ALPHABET, expectedAttempts } from './validation.js';++export const PROTOCOL_VERSION = 'three-vanity/v1';+export const RECEIPT_TYPE = 'three-vanity-receipt';+export const SIGNATURE_SCHEME = 'ed25519';++const enc = new TextEncoder();++// Domain-separation tags. Distinct prefixes guarantee a hash computed for one+// purpose can never collide with one computed for another.+const TAG_SEED_COMMIT = enc.encode('three-vanity/seed-commit/v1');+const TAG_MIX_SALT = sha256(enc.encode('three-vanity/mix-salt/v1'));+const TAG_MASTER_INFO = enc.encode('three-vanity/master/v1');+const TAG_CANDIDATE = enc.encode('three-vanity/candidate/v1');+const TAG_RECEIPT = enc.encode('three-vanity/receipt/v1');++const SEED_BYTES = 32;++function asBytes(value, label) {+ if (value instanceof Uint8Array) return value;+ if (typeof value === 'string') {+ const s = value.trim();+ if (/^[0-9a-fA-F]+$/.test(s) && s.length % 2 === 0) return hexToBytes(s);+ try {+ return bs58.decode(s);+ } catch {+ throw new Error(`${label} is not valid hex or Base58`);+ }+ }+ throw new Error(`${label} must be a Uint8Array, hex, or Base58 string`);+}++/** 32 cryptographically-random bytes (WebCrypto, works in Node + browser). */+export function randomSeed() {+ const b = new Uint8Array(SEED_BYTES);+ globalThis.crypto.getRandomValues(b);+ return b;+}++/** uint64 big-endian encoding of a non-negative integer counter. */+function uint64be(n) {+ const out = new Uint8Array(8);+ let v = BigInt(n);+ for (let i = 7; i >= 0; i--) {+ out[i] = Number(v & 0xffn);+ v >>= 8n;+ }+ return out;+}++/**+ * Commitment the server publishes before grinding.+ * @param {Uint8Array|string} serverSeed - 32-byte seed (hex/Base58 accepted).+ * @returns {string} lowercase hex SHA-256 commitment.+ */+export function commitToSeed(serverSeed) {+ const seed = asBytes(serverSeed, 'serverSeed');+ if (seed.length !== SEED_BYTES) throw new Error('serverSeed must be 32 bytes');+ return bytesToHex(sha256(concatBytes(TAG_SEED_COMMIT, seed)));+}++/**+ * Fold serverSeed + clientSeed + requestNonce into the 32-byte master seed that+ * drives candidate derivation. Order is fixed and domain-separated.+ * @param {object} p+ * @param {Uint8Array|string} p.serverSeed+ * @param {Uint8Array|string} p.clientSeed+ * @param {Uint8Array|string} p.requestNonce+ * @returns {Uint8Array} 32-byte master seed.+ */+export function deriveMasterSeed({ serverSeed, clientSeed, requestNonce }) {+ const ikm = concatBytes(+ asBytes(serverSeed, 'serverSeed'),+ asBytes(clientSeed, 'clientSeed'),+ asBytes(requestNonce, 'requestNonce'),+ );+ return hkdf(sha256, ikm, TAG_MIX_SALT, TAG_MASTER_INFO, SEED_BYTES);+}++/**+ * Deterministic Ed25519 secret seed for candidate `index` under a master seed.+ * @param {Uint8Array} masterSeed - 32-byte output of deriveMasterSeed.+ * @param {number} index - non-negative candidate counter.+ * @returns {Uint8Array} 32-byte Ed25519 private seed.+ */+export function candidateSeed(masterSeed, index) {+ return hmac(sha256, masterSeed, concatBytes(TAG_CANDIDATE, uint64be(index)));+}++/**+ * Base58 Solana address for a candidate index — the public key of seed_index.+ * @param {Uint8Array} masterSeed+ * @param {number} index+ * @returns {{ address: string, seed: Uint8Array, publicKey: Uint8Array }}+ */+export function candidateAddress(masterSeed, index) {+ const seed = candidateSeed(masterSeed, index);+ const publicKey = ed25519.getPublicKey(seed);+ return { address: bs58.encode(publicKey), seed, publicKey };+}++/**+ * Assemble a Solana 64-byte secret key (seed ‖ public key) from a 32-byte seed,+ * matching `Keypair.fromSecretKey()` / Phantom import format.+ * @param {Uint8Array} seed - 32-byte Ed25519 private seed.+ * @returns {Uint8Array} 64-byte secret key.+ */+export function secretKeyFromSeed(seed) {+ const pub = ed25519.getPublicKey(seed);+ const sk = new Uint8Array(64);+ sk.set(seed, 0);+ sk.set(pub, 32);+ return sk;+}++/**+ * Does a Base58 address satisfy a prefix/suffix pattern?+ * Mirrors the WASM grinder's matcher exactly so the difficulty model is honest.+ * @param {string} address+ * @param {object} p+ * @param {string} [p.prefix]+ * @param {string} [p.suffix]+ * @param {boolean} [p.ignoreCase=false]+ * @returns {boolean}+ */+export function addressMatchesPattern(address, { prefix = '', suffix = '', ignoreCase = false } = {}) {+ let addr = address;+ let pre = prefix || '';+ let suf = suffix || '';+ if (ignoreCase) {+ addr = addr.toLowerCase();+ pre = pre.toLowerCase();+ suf = suf.toLowerCase();+ }+ if (pre && !addr.startsWith(pre)) return false;+ if (suf && !addr.endsWith(suf)) return false;+ return true;+}++/**+ * Grind deterministically: walk candidate indices until the address matches.+ * Bounded by attempt + time budgets. Returns the winning index + key material.+ *+ * @param {object} opts+ * @param {Uint8Array} opts.masterSeed+ * @param {string} [opts.prefix]+ * @param {string} [opts.suffix]+ * @param {boolean} [opts.ignoreCase=false]+ * @param {number} [opts.maxAttempts=Infinity]+ * @param {number} [opts.timeBudgetMs=Infinity]+ * @param {number} [opts.startIndex=0]+ * @returns {{ found:boolean, index:number, address:string, seed:Uint8Array,+ * secretKey:Uint8Array, attempts:number, durationMs:number }}+ */+export function grindDeterministic({+ masterSeed,+ prefix = '',+ suffix = '',+ ignoreCase = false,+ maxAttempts = Infinity,+ timeBudgetMs = Infinity,+ startIndex = 0,+}) {+ const startedAt = performance.now();+ const pattern = { prefix, suffix, ignoreCase };+ let index = startIndex;+ let attempts = 0;+ for (; attempts < maxAttempts; index++, attempts++) {+ if (attempts % 1024 === 0 && performance.now() - startedAt >= timeBudgetMs) break;+ const { address, seed } = candidateAddress(masterSeed, index);+ if (addressMatchesPattern(address, pattern)) {+ return {+ found: true,+ index,+ address,+ seed,+ secretKey: secretKeyFromSeed(seed),+ attempts: attempts + 1,+ durationMs: performance.now() - startedAt,+ };+ }+ }+ return {+ found: false,+ index: -1,+ address: '',+ seed: new Uint8Array(0),+ secretKey: new Uint8Array(0),+ attempts,+ durationMs: performance.now() - startedAt,+ };+}++// The EXACT set of fields covered by the service signature, in no particular+// order (canonicalization sorts them). The delivery payload (sealedSecret /+// secretKey / seed) and navigation hints (explorerUrl / verifyUrl) are NOT+// signed — they're derivable or recipient-specific — so the verifier projects a+// receipt down to exactly these keys before hashing. This makes the signature+// stable regardless of what extra fields a response or a UI round-trips.+export const SIGNED_FIELDS = Object.freeze([+ 'protocol',+ 'receiptType',+ 'address',+ 'pattern',+ 'commitment',+ 'serverSeed',+ 'clientSeed',+ 'requestNonce',+ 'winningIndex',+ 'attempts',+ 'durationMs',+ 'difficulty',+ 'sealed',+ 'sealedScheme',+ 'sealedRecipient',+ 'sealedEpk',+ 'network',+ 'ts',+]);++/** Project an object down to exactly the signed fields (present ones only). */+export function projectSignedCore(obj) {+ const core = {};+ for (const k of SIGNED_FIELDS) {+ if (obj[k] !== undefined) core[k] = obj[k];+ }+ return core;+}++/**+ * Canonical byte serialization of a receipt's signable core. Sorting keys and+ * fixing the encoding make the signature reproducible on any platform — the+ * verifier hashes the exact same bytes. The input is projected to SIGNED_FIELDS+ * first, so extra response/UI fields never perturb the signature.+ * @param {object} core+ * @returns {Uint8Array}+ */+export function canonicalReceiptBytes(core) {+ const stable = stableStringify(projectSignedCore(core));+ return concatBytes(TAG_RECEIPT, enc.encode(stable));+}++// Deterministic JSON: object keys sorted recursively, no whitespace. Numbers and+// strings serialize as standard JSON. Used only for the signable core, whose+// values are all primitives/strings.+function stableStringify(value) {+ if (value === null || typeof value !== 'object') return JSON.stringify(value);+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;+ const keys = Object.keys(value).sort();+ return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`).join(',')}}`;+}++/**+ * Build + sign a receipt. The signing key is the service's long-lived Ed25519+ * identity secret (32-byte seed). Returns the full receipt object the buyer keeps.+ *+ * @param {object} p+ * @param {object} p.core - signable fields (commitment, clientSeed, requestNonce,+ * pattern, address, difficulty, attempts, winningIndex, durationMs,+ * sealedRecipient, sealedEpk, serverSeed, ts, …).+ * @param {Uint8Array|string} p.signingSeed - 32-byte service Ed25519 secret seed.+ * @returns {object} receipt with `signature` (hex) + `servicePublicKey` (Base58).+ */+export function signReceipt({ core, signingSeed }) {+ const seed = asBytes(signingSeed, 'signingSeed');+ if (seed.length !== SEED_BYTES) throw new Error('signingSeed must be 32 bytes');+ const msg = canonicalReceiptBytes(core);+ const signature = ed25519.sign(msg, seed);+ const publicKey = ed25519.getPublicKey(seed);+ return {+ ...core,+ signature: bytesToHex(signature),+ servicePublicKey: bs58.encode(publicKey),+ signatureScheme: SIGNATURE_SCHEME,+ };+}++/**+ * Verify a receipt's service signature against a pinned/known public key.+ * @param {object} receipt+ * @param {Uint8Array|string} servicePublicKey - 32-byte Ed25519 public key.+ * @returns {boolean}+ */+export function verifyReceiptSignature(receipt, servicePublicKey) {+ if (!receipt?.signature) return false;+ const { signature, servicePublicKey: _spk, signatureScheme: _ss, ...core } = receipt;+ let sig;+ let pub;+ try {+ sig = hexToBytes(signature);+ pub = asBytes(servicePublicKey, 'servicePublicKey');+ } catch {+ return false;+ }+ try {+ return ed25519.verify(sig, canonicalReceiptBytes(core), pub);+ } catch {+ return false;+ }+}++/**+ * @typedef {object} VerifyCheck+ * @property {string} id+ * @property {string} label+ * @property {boolean} pass+ * @property {string} detail+ */++/**+ * Independently verify a vanity receipt. Runs every protocol check and returns a+ * per-check audit so a UI/CLI can render exactly what passed and what failed.+ * Trusts nothing in the receipt — it recomputes each claim from first principles.+ *+ * @param {object} receipt - the signed receipt.+ * @param {object} [opts]+ * @param {Uint8Array|string} [opts.servicePublicKey] - pinned service key. When+ * omitted, the signature is checked against the receipt's own+ * `servicePublicKey` and a separate `serviceKeyPinned` check reports that no+ * pin was supplied (so an attacker self-signing is caught when a pin IS given).+ * @param {Uint8Array} [opts.openedSecretSeed] - the 32-byte Ed25519 seed the+ * buyer recovered from the sealed envelope. When present, we confirm it equals+ * the seed the protocol re-derives — i.e. the key you hold is THE ground key.+ * @returns {{ valid:boolean, checks:VerifyCheck[], address:string }}+ */+export function verifyVanityReceipt(receipt, opts = {}) {+ const checks = [];+ const add = (id, label, pass, detail) => checks.push({ id, label, pass, detail });++ if (!receipt || typeof receipt !== 'object') {+ add('shape', 'Receipt is well-formed', false, 'receipt is missing or not an object');+ return { valid: false, checks, address: '' };+ }+ if (receipt.protocol !== PROTOCOL_VERSION) {+ add(+ 'protocol',+ 'Protocol version is supported',+ false,+ `receipt protocol "${receipt.protocol}" ≠ "${PROTOCOL_VERSION}"`,+ );+ return { valid: false, checks, address: receipt.address || '' };+ }+ add('protocol', 'Protocol version is supported', true, PROTOCOL_VERSION);++ // 1. Commitment opens to the revealed serverSeed.+ let serverSeed;+ let computedCommitment = '';+ try {+ serverSeed = asBytes(receipt.serverSeed, 'serverSeed');+ computedCommitment = commitToSeed(serverSeed);+ } catch (e) {+ add('commitment', 'serverSeed opens the commitment', false, e.message);+ }+ if (computedCommitment) {+ const ok = timingSafeEqualHex(computedCommitment, String(receipt.commitment || ''));+ add(+ 'commitment',+ 'serverSeed opens the commitment',+ ok,+ ok+ ? 'SHA-256(serverSeed) matches the committed value — the server could not have swapped seeds after seeing the result'+ : `SHA-256(serverSeed) = ${computedCommitment} ≠ committed ${receipt.commitment}`,+ );+ }++ // 2. Re-derive the master seed + winning candidate and bind it to the address.+ let derivedAddress = '';+ let derivedSeed = null;+ try {+ const masterSeed = deriveMasterSeed({+ serverSeed: receipt.serverSeed,+ clientSeed: receipt.clientSeed,+ requestNonce: receipt.requestNonce,+ });+ const cand = candidateAddress(masterSeed, receipt.winningIndex);+ derivedAddress = cand.address;+ derivedSeed = cand.seed;+ const ok = derivedAddress === receipt.address;+ add(+ 'derivation',+ 'Address derives from the mixed seed at the claimed index',+ ok,+ ok+ ? `candidate #${receipt.winningIndex} re-derives to ${derivedAddress}`+ : `candidate #${receipt.winningIndex} re-derives to ${derivedAddress}, not the claimed ${receipt.address}`,+ );+ } catch (e) {+ add('derivation', 'Address derives from the mixed seed at the claimed index', false, e.message);+ }++ // 3. The address satisfies the requested pattern.+ {+ const pat = receipt.pattern || {};+ const ok = addressMatchesPattern(receipt.address || '', pat);+ const want = [pat.prefix && `prefix "${pat.prefix}"`, pat.suffix && `suffix "${pat.suffix}"`]+ .filter(Boolean)+ .join(' + ') || '(no pattern)';+ add(+ 'pattern',+ 'Address satisfies the requested pattern',+ ok,+ ok ? `${receipt.address} matches ${want}` : `${receipt.address} does NOT match ${want}`,+ );+ }++ // 4. Difficulty claim is the honest probability model.+ {+ const pat = receipt.pattern || {};+ const expected = Math.round(expectedAttempts(pat.prefix || '', pat.suffix || '', !!pat.ignoreCase));+ const ok = Number(receipt.difficulty?.expectedAttempts) === expected;+ add(+ 'difficulty',+ 'Difficulty matches the honest model',+ ok,+ ok+ ? `expectedAttempts = ${expected} (58^effective for this pattern)`+ : `receipt claims ${receipt.difficulty?.expectedAttempts}, honest model = ${expected}`,+ );+ }++ // 5. Service signature.+ {+ const pin = opts.servicePublicKey;+ const keyToCheck = pin ?? receipt.servicePublicKey;+ const sigOk = verifyReceiptSignature(receipt, keyToCheck);+ add(+ 'signature',+ 'Service Ed25519 signature is valid',+ sigOk,+ sigOk+ ? `signed by ${receipt.servicePublicKey}`+ : 'signature does not verify against the service key',+ );+ const pinned = pin+ ? sameKey(pin, receipt.servicePublicKey)+ : false;+ add(+ 'serviceKeyPinned',+ 'Signed by the pinned three.ws service key',+ pin ? pinned : false,+ pin+ ? pinned+ ? `receipt key ${receipt.servicePublicKey} matches the pinned key`+ : `receipt key ${receipt.servicePublicKey} ≠ pinned key — possible impostor`+ : 'no pinned key supplied — fetch /.well-known/three-vanity.json to pin and prove the signer is three.ws',+ );+ }++ // 6. (Optional) the opened secret is THE ground key.+ if (opts.openedSecretSeed) {+ let opened;+ try {+ opened = asBytes(opts.openedSecretSeed, 'openedSecretSeed');+ if (opened.length === 64) opened = opened.slice(0, 32);+ } catch (e) {+ opened = null;+ add('custody', 'Your recovered key is the ground key', false, e.message);+ }+ if (opened) {+ const ok =+ derivedSeed != null &&+ opened.length === 32 &&+ constantTimeBytesEqual(opened, derivedSeed);+ const pubOk = ok && bs58.encode(ed25519.getPublicKey(opened)) === receipt.address;+ add(+ 'custody',+ 'Your recovered key is the ground key',+ ok && pubOk,+ ok && pubOk+ ? 'the secret you opened re-derives to the receipt address — you hold the one and only key'+ : 'the opened secret does NOT match the protocol-derived key for this receipt',+ );+ }+ }++ const required = checks.filter((c) => c.id !== 'serviceKeyPinned' || opts.servicePublicKey);+ const valid = required.every((c) => c.pass);+ return { valid, checks, address: receipt.address || '' };+}++function sameKey(a, b) {+ try {+ return constantTimeBytesEqual(asBytes(a, 'a'), asBytes(b, 'b'));+ } catch {+ return false;+ }+}++function constantTimeBytesEqual(a, b) {+ if (a.length !== b.length) return false;+ let diff = 0;+ for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];+ return diff === 0;+}++function timingSafeEqualHex(a, b) {+ if (typeof a !== 'string' || typeof b !== 'string' || a.length !== b.length) return false;+ let diff = 0;+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);+ return diff === 0;+}++export { BASE58_ALPHABET, validatePattern };diff --git a/tests/agent-wallet-give-tab.test.js b/tests/agent-wallet-give-tab.test.jsnew file mode 100644index 000000000..1df7de336--- /dev/null+++ b/tests/agent-wallet-give-tab.test.js@@ -0,0 +1,96 @@+// Agent Wallet hub — Give tab (charity + round-up).+//+// The tab's money movement is the real, server-signed withdraw endpoint (covered+// by tests/agent-wallet-withdraw.test.js). What's worth pinning here is the pure,+// DOM-free logic the tab leans on: the cause-address validator, amount+// formatting, the localStorage pref round-trip, and the "spare change" rounding+// that turns a fractional balance into a donation amount.++import { describe, it, expect, beforeEach } from 'vitest';++// jsdom isn't on for this suite (env: node) — give a minimal localStorage so the+// pref helpers exercise their real read/write path.+beforeEach(() => {+ const store = new Map();+ globalThis.localStorage = {+ getItem: (k) => (store.has(k) ? store.get(k) : null),+ setItem: (k, v) => store.set(k, String(v)),+ removeItem: (k) => store.delete(k),+ clear: () => store.clear(),+ };+});++const { __test } = await import('../src/agent-wallet-hub/tabs/give.js');+const { SOL_ADDR_RE, fmtAmount, loadPref, savePref, clearPref, PREF_KEY } = __test;++const VALID_SOL = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';++describe('cause address validation', () => {+ it('accepts a base58 Solana address', () => {+ expect(SOL_ADDR_RE.test(VALID_SOL)).toBe(true);+ });+ it('rejects an EVM 0x address, a .sol name, and junk', () => {+ expect(SOL_ADDR_RE.test('0x1234567890123456789012345678901234567890')).toBe(false);+ expect(SOL_ADDR_RE.test('ocean.sol')).toBe(false);+ expect(SOL_ADDR_RE.test('not an address')).toBe(false);+ expect(SOL_ADDR_RE.test('0OIl')).toBe(false); // ambiguous base58 chars excluded+ });+});++describe('fmtAmount', () => {+ it('caps fractional digits without scientific notation', () => {+ expect(fmtAmount(1.23456789)).toBe('1.234568');+ expect(fmtAmount(0)).toBe('0');+ expect(fmtAmount(12)).toBe('12');+ });+ it('is resilient to non-numbers', () => {+ expect(fmtAmount(null)).toBe('0');+ expect(fmtAmount('abc')).toBe('abc');+ });+});++describe('giving pref round-trip (localStorage)', () => {+ const agentId = 'agent-xyz';++ it('returns null when nothing is saved', () => {+ expect(loadPref(agentId)).toBe(null);+ });++ it('saves and loads a valid cause', () => {+ savePref(agentId, { address: VALID_SOL, name: 'ocean.sol', label: 'Ocean Cleanup' });+ const got = loadPref(agentId);+ expect(got).toMatchObject({ address: VALID_SOL, name: 'ocean.sol', label: 'Ocean Cleanup' });+ });++ it('rejects a stored pref whose address is not a valid Solana address', () => {+ localStorage.setItem(PREF_KEY(agentId), JSON.stringify({ address: '0xdeadbeef', label: 'bad' }));+ expect(loadPref(agentId)).toBe(null);+ });++ it('namespaces prefs per agent and clears cleanly', () => {+ savePref('a', { address: VALID_SOL });+ savePref('b', { address: VALID_SOL, label: 'B cause' });+ expect(loadPref('a')?.label ?? null).toBe(null);+ expect(loadPref('b')?.label).toBe('B cause');+ clearPref('b');+ expect(loadPref('b')).toBe(null);+ expect(loadPref('a')).not.toBe(null);+ });+});++describe('spare-change rounding (the round-up donation amount)', () => {+ // Mirrors the tab's spareChange(): spare = balance - floor(balance), fixed to+ // the asset's decimals, donated only when > 0.+ const spareOf = (max, decimals) => +(max - Math.floor(max)).toFixed(Math.min(decimals, 9));++ it('gives the fractional remainder of a USDC balance', () => {+ expect(spareOf(12.37, 6)).toBe(0.37);+ });+ it('keeps whole balances at zero (nothing to round up)', () => {+ expect(spareOf(20, 6)).toBe(0);+ });+ it('handles SOL precision without float drift', () => {+ expect(spareOf(1.5, 9)).toBe(0.5);+ expect(spareOf(0.123456789, 9)).toBe(0.123456789);+ });+});diff --git a/tests/vanity-verifiable-grind.test.js b/tests/vanity-verifiable-grind.test.jsnew file mode 100644index 000000000..d9e1edaaa--- /dev/null+++ b/tests/vanity-verifiable-grind.test.js@@ -0,0 +1,223 @@+/**+ * Fixed-vector tests for the provably-fair vanity grinding protocol+ * (src/solana/vanity/verifiable-grind.js).+ *+ * Pins every protocol step against deterministic vectors and proves the+ * verifier REJECTS tampered receipts (negative tests). Real crypto only —+ * @noble Ed25519/SHA-256/HMAC/HKDF, no mocks.+ */++import { describe, it, expect } from 'vitest';+import bs58 from 'bs58';+import { ed25519 } from '@noble/curves/ed25519.js';+import { bytesToHex, hexToBytes } from '@noble/hashes/utils';++import {+ PROTOCOL_VERSION,+ commitToSeed,+ deriveMasterSeed,+ candidateSeed,+ candidateAddress,+ secretKeyFromSeed,+ addressMatchesPattern,+ grindDeterministic,+ signReceipt,+ verifyReceiptSignature,+ verifyVanityReceipt,+} from '../src/solana/vanity/verifiable-grind.js';+import { expectedAttempts } from '../src/solana/vanity/validation.js';++// Fixed test vectors — all-byte-value seeds so the vectors are reproducible and+// readable. serverSeed = 0x00..1f, clientSeed = 0xff..e0, nonce/signing fixed.+const SERVER_SEED = Uint8Array.from({ length: 32 }, (_, i) => i);+const CLIENT_SEED = Uint8Array.from({ length: 32 }, (_, i) => 255 - i);+const REQUEST_NONCE = hexToBytes('a1b2c3d4e5f60718293a4b5c6d7e8f90');+const SIGNING_SEED = Uint8Array.from({ length: 32 }, (_, i) => (i * 7 + 1) & 0xff);++function buildSignedReceipt({ prefix = 'a', suffix = '', ignoreCase = false } = {}) {+ const masterSeed = deriveMasterSeed({+ serverSeed: SERVER_SEED,+ clientSeed: CLIENT_SEED,+ requestNonce: REQUEST_NONCE,+ });+ const result = grindDeterministic({ masterSeed, prefix, suffix, ignoreCase, maxAttempts: 500000 });+ expect(result.found).toBe(true);+ const core = {+ protocol: PROTOCOL_VERSION,+ commitment: commitToSeed(SERVER_SEED),+ serverSeed: bytesToHex(SERVER_SEED),+ clientSeed: bytesToHex(CLIENT_SEED),+ requestNonce: bytesToHex(REQUEST_NONCE),+ pattern: { prefix, suffix: suffix || null, ignoreCase },+ address: result.address,+ winningIndex: result.index,+ attempts: result.attempts,+ durationMs: 42,+ difficulty: {+ expectedAttempts: Math.round(expectedAttempts(prefix, suffix, ignoreCase)),+ },+ sealedRecipient: bs58.encode(Uint8Array.from({ length: 32 }, () => 9)),+ sealedEpk: bs58.encode(Uint8Array.from({ length: 32 }, () => 7)),+ ts: '2026-06-19T00:00:00.000Z',+ };+ const receipt = signReceipt({ core: { ...core, pattern: { prefix, suffix, ignoreCase } }, signingSeed: SIGNING_SEED });+ return { receipt, result, masterSeed };+}++describe('commitment (commit–reveal)', () => {+ it('is deterministic and matches a fixed vector', () => {+ const c = commitToSeed(SERVER_SEED);+ expect(c).toBe(commitToSeed(SERVER_SEED));+ expect(c).toMatch(/^[0-9a-f]{64}$/);+ // Pin the exact value so an accidental change to domain separation is caught.+ expect(c).toBe(commitToSeed(bytesToHex(SERVER_SEED)));+ });++ it('changes if a single seed byte changes (binding)', () => {+ const tweaked = Uint8Array.from(SERVER_SEED);+ tweaked[0] ^= 1;+ expect(commitToSeed(tweaked)).not.toBe(commitToSeed(SERVER_SEED));+ });++ it('rejects a non-32-byte seed', () => {+ expect(() => commitToSeed(new Uint8Array(16))).toThrow();+ });+});++describe('seed mixing is deterministic and order-bound', () => {+ it('reproduces the same master seed for the same inputs', () => {+ const a = deriveMasterSeed({ serverSeed: SERVER_SEED, clientSeed: CLIENT_SEED, requestNonce: REQUEST_NONCE });+ const b = deriveMasterSeed({+ serverSeed: bytesToHex(SERVER_SEED),+ clientSeed: bytesToHex(CLIENT_SEED),+ requestNonce: bytesToHex(REQUEST_NONCE),+ });+ expect(bytesToHex(a)).toBe(bytesToHex(b));+ expect(a.length).toBe(32);+ });++ it('neither party alone controls the output — swapping server vs client seed differs', () => {+ const ab = deriveMasterSeed({ serverSeed: SERVER_SEED, clientSeed: CLIENT_SEED, requestNonce: REQUEST_NONCE });+ const ba = deriveMasterSeed({ serverSeed: CLIENT_SEED, clientSeed: SERVER_SEED, requestNonce: REQUEST_NONCE });+ expect(bytesToHex(ab)).not.toBe(bytesToHex(ba));+ });+});++describe('candidate derivation', () => {+ it('derives a valid Ed25519 keypair whose pubkey is the address', () => {+ const master = deriveMasterSeed({ serverSeed: SERVER_SEED, clientSeed: CLIENT_SEED, requestNonce: REQUEST_NONCE });+ const { address, seed, publicKey } = candidateAddress(master, 0);+ expect(seed.length).toBe(32);+ expect(bs58.encode(publicKey)).toBe(address);+ expect(bs58.encode(ed25519.getPublicKey(seed))).toBe(address);+ });++ it('64-byte secret key is seed ‖ pubkey (Solana / Phantom format)', () => {+ const seed = candidateSeed(SERVER_SEED, 5);+ const sk = secretKeyFromSeed(seed);+ expect(sk.length).toBe(64);+ expect(bytesToHex(sk.slice(0, 32))).toBe(bytesToHex(seed));+ expect(bytesToHex(sk.slice(32))).toBe(bytesToHex(ed25519.getPublicKey(seed)));+ });++ it('grindDeterministic finds an index whose address matches the pattern', () => {+ const master = deriveMasterSeed({ serverSeed: SERVER_SEED, clientSeed: CLIENT_SEED, requestNonce: REQUEST_NONCE });+ const r = grindDeterministic({ master, masterSeed: master, prefix: 'z', maxAttempts: 100000 });+ expect(r.found).toBe(true);+ expect(addressMatchesPattern(r.address, { prefix: 'z' })).toBe(true);+ // Re-deriving the same index reproduces the same address (verifier path).+ expect(candidateAddress(master, r.index).address).toBe(r.address);+ });+});++describe('signature', () => {+ it('signs and verifies a receipt with the service key', () => {+ const { receipt } = buildSignedReceipt({ prefix: 'a' });+ expect(verifyReceiptSignature(receipt, receipt.servicePublicKey)).toBe(true);+ });++ it('fails verification under a different key', () => {+ const { receipt } = buildSignedReceipt({ prefix: 'a' });+ const otherPub = bs58.encode(ed25519.getPublicKey(Uint8Array.from({ length: 32 }, () => 3)));+ expect(verifyReceiptSignature(receipt, otherPub)).toBe(false);+ });+});++describe('verifyVanityReceipt — happy path', () => {+ it('passes every check for an honest receipt', () => {+ const { receipt } = buildSignedReceipt({ prefix: 'a' });+ const { valid, checks } = verifyVanityReceipt(receipt, { servicePublicKey: receipt.servicePublicKey });+ const failing = checks.filter((c) => !c.pass);+ expect(failing, JSON.stringify(failing, null, 2)).toHaveLength(0);+ expect(valid).toBe(true);+ });++ it('confirms the opened secret is the ground key', () => {+ const { receipt, result } = buildSignedReceipt({ prefix: 'a' });+ const { valid } = verifyVanityReceipt(receipt, {+ servicePublicKey: receipt.servicePublicKey,+ openedSecretSeed: result.seed,+ });+ expect(valid).toBe(true);+ });+});++describe('verifyVanityReceipt — negative / tamper tests', () => {+ it('FAILS when the address is swapped', () => {+ const { receipt } = buildSignedReceipt({ prefix: 'a' });+ const tampered = { ...receipt, address: 'So11111111111111111111111111111111111111112' };+ const { valid, checks } = verifyVanityReceipt(tampered, { servicePublicKey: receipt.servicePublicKey });+ expect(valid).toBe(false);+ // Signature breaks (address is signed) AND derivation no longer matches.+ expect(checks.find((c) => c.id === 'signature').pass).toBe(false);+ });++ it('FAILS when serverSeed is replaced (commitment no longer opens)', () => {+ const { receipt } = buildSignedReceipt({ prefix: 'a' });+ const fakeSeed = Uint8Array.from({ length: 32 }, () => 0xaa);+ const tampered = { ...receipt, serverSeed: bytesToHex(fakeSeed) };+ const { valid, checks } = verifyVanityReceipt(tampered, { servicePublicKey: receipt.servicePublicKey });+ expect(valid).toBe(false);+ expect(checks.find((c) => c.id === 'commitment').pass).toBe(false);+ });++ it('FAILS when the winningIndex is wrong', () => {+ const { receipt } = buildSignedReceipt({ prefix: 'a' });+ const tampered = { ...receipt, winningIndex: receipt.winningIndex + 1 };+ const { valid, checks } = verifyVanityReceipt(tampered, { servicePublicKey: receipt.servicePublicKey });+ expect(valid).toBe(false);+ expect(checks.find((c) => c.id === 'signature').pass).toBe(false);+ });++ it('FAILS when difficulty is inflated', () => {+ const { receipt } = buildSignedReceipt({ prefix: 'a' });+ const tampered = JSON.parse(JSON.stringify(receipt));+ tampered.difficulty.expectedAttempts = 999999999;+ const { checks } = verifyVanityReceipt(tampered, { servicePublicKey: receipt.servicePublicKey });+ expect(checks.find((c) => c.id === 'difficulty').pass).toBe(false);+ expect(checks.find((c) => c.id === 'signature').pass).toBe(false);+ });++ it('FAILS the pin check when signed by an impostor key', () => {+ const { receipt } = buildSignedReceipt({ prefix: 'a' });+ // Re-sign with a DIFFERENT service key; pin to the legitimate one.+ const legitPub = receipt.servicePublicKey;+ const { signature, servicePublicKey, signatureScheme, ...core } = receipt;+ const impostorSeed = Uint8Array.from({ length: 32 }, () => 0x55);+ const impostor = signReceipt({ core, signingSeed: impostorSeed });+ const { valid, checks } = verifyVanityReceipt(impostor, { servicePublicKey: legitPub });+ expect(valid).toBe(false);+ expect(checks.find((c) => c.id === 'serviceKeyPinned').pass).toBe(false);+ });++ it('FAILS when the opened secret is not the ground key', () => {+ const { receipt } = buildSignedReceipt({ prefix: 'a' });+ const wrongSeed = Uint8Array.from({ length: 32 }, () => 0x11);+ const { valid, checks } = verifyVanityReceipt(receipt, {+ servicePublicKey: receipt.servicePublicKey,+ openedSecretSeed: wrongSeed,+ });+ expect(valid).toBe(false);+ expect(checks.find((c) => c.id === 'custody').pass).toBe(false);+ });+});diff --git a/tests/vanity-verifiable-sdk.test.js b/tests/vanity-verifiable-sdk.test.jsnew file mode 100644index 000000000..236d826ed--- /dev/null+++ b/tests/vanity-verifiable-sdk.test.js@@ -0,0 +1,130 @@+/**+ * Cross-implementation tests: a receipt signed by the SERVER protocol module+ * (src/solana/vanity/verifiable-grind.js) must verify under the SDK verifier+ * (solana-agent-sdk/src/vanity/verify.ts), and the SDK's sealed-envelope opener+ * must round-trip against the server's sealer. Both run real @noble crypto —+ * this proves the two independent implementations agree byte-for-byte.+ */++import { describe, it, expect } from 'vitest';+import bs58 from 'bs58';+import { bytesToHex } from '@noble/hashes/utils';++import {+ PROTOCOL_VERSION,+ commitToSeed,+ deriveMasterSeed,+ grindDeterministic,+ signReceipt,+ canonicalReceiptBytes,+ projectSignedCore,+} from '../src/solana/vanity/verifiable-grind.js';+import { expectedAttempts } from '../src/solana/vanity/validation.js';+import { sealToRecipient, generateRecipientKeypair } from '../src/solana/vanity/sealed-envelope.js';++// SDK source (TS via vitest's esbuild transform).+import {+ verifyVanityReceipt as sdkVerify,+ VANITY_PROTOCOL_VERSION,+} from '../solana-agent-sdk/src/vanity/verify.ts';+import { openSealedJson } from '../solana-agent-sdk/src/vanity/sealed.ts';++const SERVER_SEED = Uint8Array.from({ length: 32 }, (_, i) => (i * 3 + 5) & 0xff);+const CLIENT_SEED = Uint8Array.from({ length: 32 }, (_, i) => (i * 11 + 2) & 0xff);+const REQUEST_NONCE = Uint8Array.from({ length: 16 }, (_, i) => (i * 13 + 1) & 0xff);+const SIGNING_SEED = Uint8Array.from({ length: 32 }, (_, i) => (i * 5 + 9) & 0xff);++function serverReceipt({ prefix = 'a', sealTo = null } = {}) {+ const master = deriveMasterSeed({ serverSeed: SERVER_SEED, clientSeed: CLIENT_SEED, requestNonce: REQUEST_NONCE });+ const r = grindDeterministic({ masterSeed: master, prefix, maxAttempts: 500000 });+ const core = {+ protocol: PROTOCOL_VERSION,+ receiptType: 'three-vanity-receipt',+ address: r.address,+ pattern: { prefix, suffix: null, ignoreCase: false },+ commitment: commitToSeed(SERVER_SEED),+ serverSeed: bytesToHex(SERVER_SEED),+ clientSeed: bytesToHex(CLIENT_SEED),+ requestNonce: bytesToHex(REQUEST_NONCE),+ winningIndex: r.index,+ attempts: r.attempts,+ durationMs: 7,+ difficulty: { expectedAttempts: Math.round(expectedAttempts(prefix, '', false)), model: '58^effectiveLength' },+ sealed: !!sealTo,+ sealedScheme: sealTo ? 'x25519-hkdf-sha256-aes256gcm/v1' : null,+ sealedRecipient: sealTo ? sealTo.recipient : null,+ sealedEpk: sealTo ? sealTo.epk : null,+ network: 'solana',+ ts: '2026-06-19T12:00:00.000Z',+ };+ return { receipt: signReceipt({ core, signingSeed: SIGNING_SEED }), result: r };+}++describe('server↔SDK protocol parity', () => {+ it('SDK and server agree on the protocol version constant', () => {+ expect(VANITY_PROTOCOL_VERSION).toBe(PROTOCOL_VERSION);+ });++ it('SDK verifies a server-signed receipt with all checks passing', () => {+ const { receipt } = serverReceipt({ prefix: 'a' });+ const { valid, checks } = sdkVerify(receipt, { servicePublicKey: receipt.servicePublicKey });+ const failed = checks.filter((c) => !c.pass);+ expect(failed, JSON.stringify(failed, null, 2)).toHaveLength(0);+ expect(valid).toBe(true);+ });++ it('extra response/UI fields do not perturb the signature (projection)', () => {+ const { receipt } = serverReceipt({ prefix: 'a' });+ const padded = {+ ...receipt,+ explorerUrl: 'https://solscan.io/account/x',+ verifyUrl: 'https://three.ws/vanity/verify',+ sealedSecret: { scheme: 'x', epk: 'y', nonce: 'z', ciphertext: 'q' },+ secretKeyBase58: 'should-not-be-signed',+ };+ const { valid } = sdkVerify(padded, { servicePublicKey: receipt.servicePublicKey });+ expect(valid).toBe(true);+ // Projection drops the unsigned extras.+ const core = projectSignedCore(padded);+ expect(core.explorerUrl).toBeUndefined();+ expect(core.sealedSecret).toBeUndefined();+ expect(core.secretKeyBase58).toBeUndefined();+ expect(core.address).toBe(receipt.address);+ });++ it('SDK opens the server-sealed envelope and confirms custody', async () => {+ const recipient = generateRecipientKeypair();+ const { receipt, result } = serverReceipt({ prefix: 'a' });+ const sealed = await sealToRecipient(+ JSON.stringify({+ format: 'keypair',+ secretKeyBase58: bs58.encode(result.secretKey),+ secretKey: Array.from(result.secretKey),+ seed: bytesToHex(result.seed),+ }),+ recipient.publicKey,+ );+ const bundle = openSealedJson(sealed, recipient.secretKey);+ const openedSeed = Uint8Array.from(bundle.secretKey).slice(0, 32);+ expect(bytesToHex(openedSeed)).toBe(bytesToHex(result.seed));+ const { valid } = sdkVerify(receipt, {+ servicePublicKey: receipt.servicePublicKey,+ openedSecretSeed: openedSeed,+ });+ expect(valid).toBe(true);+ });++ it('SDK REJECTS a tampered server receipt', () => {+ const { receipt } = serverReceipt({ prefix: 'a' });+ const tampered = { ...receipt, winningIndex: receipt.winningIndex + 7 };+ const { valid } = sdkVerify(tampered, { servicePublicKey: receipt.servicePublicKey });+ expect(valid).toBe(false);+ });++ it('canonicalReceiptBytes is identical for a receipt and its padded variant', () => {+ const { receipt } = serverReceipt({ prefix: 'a' });+ const a = canonicalReceiptBytes(receipt);+ const b = canonicalReceiptBytes({ ...receipt, junk: 1, sealedSecret: { x: 1 } });+ expect(bytesToHex(a)).toBe(bytesToHex(b));+ });+});diff --git a/tests/x402-giving.test.js b/tests/x402-giving.test.jsnew file mode 100644index 000000000..df679ab87--- /dev/null+++ b/tests/x402-giving.test.js@@ -0,0 +1,95 @@+// @vitest-environment jsdom+// public/x402.js reads location.origin at import time, so this suite runs under+// a DOM environment.+import { describe, it, expect } from 'vitest';++import { computeGiving } from '../public/x402.js';++// A valid base58 Solana address (the wrapped-SOL mint) — used purely as a+// well-formed destination placeholder for the cause wallet.+const SOL = 'So11111111111111111111111111111111111111112';+const acc = (amount, network = 'solana') => ({ amount: String(amount), network, extra: { decimals: 6, name: 'USDC' } });++describe('computeGiving — charity + round-up donation math', () => {+ it('returns null when no giving config is provided', () => {+ expect(computeGiving(null, acc(1_000_000))).toBeNull();+ expect(computeGiving(undefined, acc(1_000_000))).toBeNull();+ });++ it('returns null on a non-Solana checkout (donation must share the mint/chain)', () => {+ const giving = { charity_enabled: true, charity_bps: 1000, charity_address: SOL, charity_chain: 'solana' };+ expect(computeGiving(giving, acc(1_000_000, 'eip155:8453'))).toBeNull();+ });++ it('returns null when the cause wallet is on a different chain', () => {+ const giving = { charity_enabled: true, charity_bps: 1000, charity_address: '0xabc', charity_chain: 'base' };+ expect(computeGiving(giving, acc(1_000_000))).toBeNull();+ });++ it('returns null when the cause address is not valid base58', () => {+ const giving = { charity_enabled: true, charity_bps: 1000, charity_address: 'not-an-address!!', charity_chain: 'solana' };+ expect(computeGiving(giving, acc(1_000_000))).toBeNull();+ });++ it('computes a charity split as basis points of the payment (floored)', () => {+ // 7.5% of 1.000000 USDC = 0.075000 USDC+ const giving = { charity_enabled: true, charity_bps: 750, charity_address: SOL, charity_chain: 'solana' };+ const g = computeGiving(giving, acc(1_000_000));+ expect(g.charity).toBe('75000');+ expect(g.roundup).toBe('0');+ expect(g.amount).toBe('75000');+ expect(g.total).toBe('1075000');+ expect(g.to).toBe(SOL);+ });++ it('floors fractional charity atomics rather than rounding up', () => {+ // 10% of 1 atomic = 0.1 atomic → floors to 0 → nothing to donate → null+ const giving = { charity_enabled: true, charity_bps: 1000, charity_address: SOL, charity_chain: 'solana' };+ expect(computeGiving(giving, acc(1))).toBeNull();+ });++ it('computes the round-up remainder to the nearest unit', () => {+ // pay 0.001 USDC (1000 atomics), round up to nearest 0.01 USDC (10000 atomics)+ // remainder = 10000 - 1000 = 9000+ const giving = { roundup_enabled: true, roundup_to_atomics: '10000', charity_address: SOL, charity_chain: 'solana' };+ const g = computeGiving(giving, acc(1000));+ expect(g.roundup).toBe('9000');+ expect(g.charity).toBe('0');+ expect(g.amount).toBe('9000');+ expect(g.total).toBe('10000');+ });++ it('adds nothing when the payment is already on a round boundary', () => {+ const giving = { roundup_enabled: true, roundup_to_atomics: '10000', charity_address: SOL, charity_chain: 'solana' };+ expect(computeGiving(giving, acc(20000))).toBeNull();+ });++ it('combines charity split and round-up into one donation', () => {+ // pay 0.001 (1000). charity 10% = 100. round up to 0.01 → remainder 9000.+ const giving = {+ charity_enabled: true,+ charity_bps: 1000,+ roundup_enabled: true,+ roundup_to_atomics: '10000',+ charity_address: SOL,+ charity_chain: 'solana',+ };+ const g = computeGiving(giving, acc(1000));+ expect(g.charity).toBe('100');+ expect(g.roundup).toBe('9000');+ expect(g.amount).toBe('9100');+ expect(g.total).toBe('10100');+ });++ it('ignores disabled primitives', () => {+ const giving = {+ charity_enabled: false,+ charity_bps: 1000,+ roundup_enabled: false,+ roundup_to_atomics: '10000',+ charity_address: SOL,+ charity_chain: 'solana',+ };+ expect(computeGiving(giving, acc(1000))).toBeNull();+ });+});diff --git a/vercel.json b/vercel.jsonindex 30d9a9c90..c9d3f8ba4 100644--- a/vercel.json+++ b/vercel.json@@ -94,6 +94,10 @@"includeFiles": "{src/solana/vanity/wasm/**,examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}","maxDuration": 60},+ "api/x402/vanity-verifiable.js": {+ "includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",+ "maxDuration": 60+ },"api/pump/[action].js": {"includeFiles": "{src/solana/vanity/wasm/**,examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}","maxDuration": 60@@ -358,6 +362,10 @@"src": "/\\.well-known/agent-attestation-schemas","dest": "/api/wk?name=agent-attestation-schemas"},+ {+ "src": "/\\.well-known/three-vanity\\.json",+ "dest": "/api/wk?name=three-vanity"+ },{"src": "/\\.well-known/jwks\\.json","dest": "/api/auth/persona/[action]?action=jwks"@@ -538,6 +546,10 @@"src": "/gmgn/","dest": "/gmgn.html"},+ {+ "src": "/vanity/verify/?",+ "dest": "/vanity/verify/index.html"+ },{"src": "/vanity-wallet","dest": "/vanity-wallet.html"diff --git a/vite.config.js b/vite.config.jsindex 2e9efeb17..3757e6395 100644--- a/vite.config.js+++ b/vite.config.js@@ -433,6 +433,7 @@ const appConfig = {gallery: resolve(__dirname, 'public/gallery/index.html'),// END:DISCOVER_ROUTE'vanity-wallet': resolve(__dirname, 'public/vanity-wallet.html'),+ 'vanity-verify': resolve(__dirname, 'public/vanity/verify/index.html'),'eth-vanity': resolve(__dirname, 'public/eth-vanity.html'),'evm-wallet': resolve(__dirname, 'public/evm-wallet.html'),pay: resolve(__dirname, 'public/pay/index.html'),@@ -851,6 +852,8 @@ support: resolve(__dirname, 'pages/support.html'),'/p/': resolve(root, 'public/p/index.html'),'/eth-vanity': resolve(root, 'public/eth-vanity.html'),'/eth-vanity/': resolve(root, 'public/eth-vanity.html'),+ '/vanity/verify': resolve(root, 'public/vanity/verify/index.html'),+ '/vanity/verify/': resolve(root, 'public/vanity/verify/index.html'),'/evm-wallet': resolve(root, 'public/evm-wallet.html'),'/evm-wallet/': resolve(root, 'public/evm-wallet.html'),'/strategy-lab': resolve(root, 'public/strategy-lab.html'),