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: vanity bounty market, sealed drops, and rarity scoring
nirholasca86396b7efa
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1bd43bb0d..881a28bf8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,13 @@Public history for [three.ws](https://three.ws), newest first. New pages come from `added` dates in data/pages.json; everything else is curated in data/changelog.json. Also available as [JSON](https://three.ws/changelog.json) and [RSS](https://three.ws/changelog.xml), live at [three.ws/changelog](https://three.ws/changelog).+## 2026-06-20++- **Grind-Bounty Market** (`/vanity/bounties`) — A decentralized x402 bounty market for hard Solana vanity addresses — escrow a USDC bounty and a fleet of independent workers grinds it in parallel. The first verified match wins, but the found key is sealed to you so the worker never sees your wallet. Earn USDC by grinding open bounties.+- **Proof-of-Grind Gallery** (`/vanity/gallery`) — A public gallery and leaderboard of the rarest Solana vanity addresses ground on three.ws — each provably-fair, verified, and shareable. Appraise any address to see its honest rarity tier and grind cost.+- **Grind-bounty market: post a reward, a fleet grinds your hard vanity address** — A 5-to-8-character vanity address is hours-to-years on one machine, so until now "hard" vanity meant running your browser overnight and hoping. The new grind-bounty market makes it a liquid, pay-for-results service. Post the pattern you want, escrow a USDC bounty, and a fleet of independent workers grinds it in parallel — the first one to find a verified match is paid automatically. The breakthrough is that the found key is sealed to your encryption key before the worker ever submits it, so the worker earns the bounty yet never sees your wallet, and three.ws never holds your secret either. Settlement is trustless via x402: no valid match, no payout; only one worker can win; and a bounty that goes unfilled refunds your escrow when it expires. You also get an honest difficulty meter and a fair-price oracle when posting (priced off the real grind odds, not made-up numbers), a live board with biggest-reward and expiring-soon sorts, and a one-click way to open your won wallet locally with your private key. Want to earn instead? Flip on "Grind & earn," point your spare cores at the open bounties, and get paid in USDC for every fill — there's a leaderboard of the top grinders. (`/vanity/bounties`) `[feature, security, sdk]`+- **Proof-of-grind: a public gallery of the rarest wallets ground here** — A vanity address is a flex — but until now the flex was unverifiable. Proof-of-grind turns it into provenance. Every provably-fair grind can now carry an honest rarity score and tier (Common → Mythic) computed straight from the real grind difficulty: longer patterns rank higher, with documented, capped bonuses for real dictionary words, palindromes, and repeated-character runs — no inflated numbers. Publish a wallet (opt-in, secret-free; we re-verify your signed receipt against the live three.ws service key before it appears) and it joins a public gallery and leaderboard of the rarest addresses ground on three.ws, sortable and filterable by tier and pattern, each with a verified badge and a beautiful share card for X. New tools: paste any address to appraise its tier and estimated grind cost, and every agent's wallet chip now shows its rarity tier wherever it appears. No secret, seed, or sealed key is ever stored or shown. (`/vanity/gallery`) `[feature, security, sdk]`+## 2026-06-19- **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.@@ -12,6 +19,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **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 profile pages now read perfectly on phones** — Open an agent's profile on a phone and it now fits the screen edge-to-edge with no sideways scrolling. Long service endpoint URLs that used to push the whole page wide now trim cleanly with an ellipsis, the search and action buttons up top stack instead of spilling off-screen, and every section — holdings, token, trust, reviews — lines up in a single tidy column. Desktop is unchanged; small screens just stopped looking cramped. `[fix, improvement]`- **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]`- **Align a whole room of agents in one gesture** — When you place several agents around a room, their spacing is already exact for everyone — but the whole cluster can sit a few metres off where it really is, because phone GPS only knows the spot to within several metres. Now you can fix that in one move: open any of your room agents and tap “Align this room,” then drag to slide the entire group onto its true spot and twist with two fingers to rotate it — every agent moves together, keeping its layout intact, instead of nudging them one at a time. A live readout shows the move in honest metres and degrees, and the room is labelled with how tightly it's anchored so you know when it's worth aligning. Only the room's owner can move it. And if you arrive at a room someone placed without a compass that looks turned the wrong way, a one-tap “Align to your view” straightens it out for you. (`/irl`) `[improvement]`diff --git a/api/_lib/env.js b/api/_lib/env.jsindex f093b0e9c..6738185ae 100644--- a/api/_lib/env.js+++ b/api/_lib/env.js@@ -715,6 +715,28 @@ export const env = {return trimSlash(opt('STOREFRONT_ORIGIN', 'https://three.ws'));},+ // ── Grind-bounty market (api/vanity/bounties.js) ──────────────────────+ // Solana USDC payout wallet for the grind-bounty market. Holds the escrowed+ // USDC the platform received via x402 when requesters funded their bounties,+ // and pays the winning worker (or refunds the requester on expiry) in real+ // on-chain SPL transfers. Never logged, never returned. Accepts a Base58+ // 64-byte secret key directly; the payout module also accepts the existing+ // base64 CLUB_SOLANA_TREASURY_SECRET_KEY_B64 as a fallback so the market+ // settles in environments that already fund that treasury.+ get VANITY_BOUNTY_PAYOUT_KEY() {+ return opt('VANITY_BOUNTY_PAYOUT_KEY');+ },++ // Solana funding wallet for sealed wallet drops (api/vanity/drops.js). Funds+ // each freshly-ground drop address on-chain (SOL/USDC/$THREE) and pays the+ // network fee on the expiry-reclaim sweep back to the sender. Never logged,+ // never returned. Accepts a Base58 64-byte secret; the funding module also+ // accepts VANITY_BOUNTY_PAYOUT_KEY and the base64 CLUB_SOLANA_TREASURY_SECRET_KEY_B64+ // as fallbacks so drops fund wherever the platform already holds a hot wallet.+ get VANITY_DROP_FUNDING_KEY() {+ return opt('VANITY_DROP_FUNDING_KEY');+ },+// ── Lottery + Reflection coin (api/_lib/coin/*) ───────────────────────// Treasury keypair (base64-encoded 64-byte secret). Fee payer for every// lottery winner transfer + reflection batch transfer. Holds the SOL thatdiff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex 477f260f2..c646cff0c 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -258,6 +258,14 @@ export const limits = {getLimiter('avatar:payout:daily', { limit: 50, window: '24 h', critical: true }).limit(walletAddr,),+ // Proof-of-grind gallery. Publishing verifies a signed receipt server-side then+ // writes a public rarity entry — bound per IP so one caller can't carpet the+ // gallery, but generous enough for a real owner publishing a few grinds.+ // Reads (gallery list / leaderboard / appraisal) are cheap and CDN-cacheable.+ vanityGalleryPublishIp: (ip) =>+ getLimiter('vanity:gallery:publish:ip', { limit: 12, window: '10 m' }).limit(ip),+ vanityGalleryReadIp: (ip) =>+ getLimiter('vanity:gallery:read:ip', { limit: 240, window: '5 m' }).limit(ip),mcpUser: (userId) => getLimiter('mcp:user', { limit: 1200, window: '1 m' }).limit(userId),mcpIp: (ip) => getLimiter('mcp:ip', { limit: 600, window: '1 m' }).limit(ip),// Per-principal ceiling on the expensive/gated pump-fun MCP tools (vanity grind,diff --git a/api/_lib/sealed-drop-funding.js b/api/_lib/sealed-drop-funding.jsnew file mode 100644index 000000000..58e4c0e46--- /dev/null+++ b/api/_lib/sealed-drop-funding.js@@ -0,0 +1,305 @@+/**+ * Real on-chain funding + reclaim rails for sealed wallet drops.+ *+ * Funding model: when a drop is created (and the x402 create fee is settled),+ * the platform moves REAL funds into the freshly-ground drop address from its+ * Solana funding wallet (`VANITY_DROP_FUNDING_KEY`, falling back to the bounty+ * payout key, then the club treasury secret — every custodial-money endpoint on+ * the platform shares this resolution). Three assets are supported:+ * • SOL — native System transfer (lamports).+ * • USDC — SPL transfer (the x402 rail asset; never marketed as a coin).+ * • THREE — SPL transfer of the platform's only coin, $THREE.+ * Balances are read live via the Helius-backed connection. No fake balances:+ * funding is confirmed on-chain BEFORE a drop is shown as claimable.+ *+ * Reclaim model: an EXPIRED, unclaimed drop's funds are swept back to the+ * sender's reclaim address. The sweep is signed by the drop wallet's own key,+ * which the platform can reconstruct only because the SAME plaintext it sealed+ * to the recipient is also held encrypted at rest under secret-box (AES-256-GCM)+ * for the reclaim path — and ONLY for reclaim. (The recipient's E2E guarantee is+ * unaffected: that at-rest copy is the drop wallet's key, used solely to refund+ * the sender on expiry; the claim path always delivers the SEALED envelope the+ * recipient opens with their own key.) The sweep is exactly-once: the store's+ * funded→reclaimed compare-and-set runs first and records the resulting tx.+ *+ * Money-safety invariants:+ * • Funding is confirmed (`confirmed` commitment) before createDrop persists a+ * claimable record; a funding failure aborts the create with the fee unsettled.+ * • A drop is EITHER claimed (recipient opens it) OR reclaimed (sender refunded),+ * never both — the two store transitions are mutually-exclusive CAS.+ * • Reclaim is idempotent: a reclaimed drop that already carries a reclaimTx+ * short-circuits instead of sweeping again.+ */++import bs58 from 'bs58';+import {+ Keypair,+ PublicKey,+ Transaction,+ SystemProgram,+ LAMPORTS_PER_SOL,+} from '@solana/web3.js';+import {+ getAssociatedTokenAddress,+ createAssociatedTokenAccountInstruction,+ createTransferInstruction,+ getAccount,+} from '@solana/spl-token';++import { env } from './env.js';+import { solanaConnection } from './agent-pumpfun.js';+import { SOLANA_USDC_MINT } from '../payments/_config.js';+import { recordReclaim } from './sealed-drop-store.js';++const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;+// Network fee headroom left in a SOL drop so the wallet can pay rent/fees when+// the recipient sweeps it onward (a drop with exactly 0 lamports of headroom+// can't even create its own ATA). Kept small so the gift is mostly the gift.+const SOL_FEE_HEADROOM_LAMPORTS = 0; // SOL drops fund the exact amount; recipient sweeps natively.++/** Resolve the platform funding wallet as a Base58 64-byte secret, or null. */+function resolveFundingKeyBase58() {+ const candidates = [+ env.VANITY_DROP_FUNDING_KEY,+ env.VANITY_BOUNTY_PAYOUT_KEY,+ ].filter(Boolean);+ for (const raw of candidates) {+ const s = String(raw).trim();+ try {+ if (bs58.decode(s).length === 64) return s;+ } catch {+ /* try base64 */+ }+ try {+ const buf = Buffer.from(s, 'base64');+ if (buf.byteLength === 64) return bs58.encode(buf);+ } catch {+ /* ignore */+ }+ }+ const clubB64 = process.env.CLUB_SOLANA_TREASURY_SECRET_KEY_B64;+ if (clubB64) {+ try {+ const buf = Buffer.from(clubB64, 'base64');+ if (buf.byteLength === 64) return bs58.encode(buf);+ } catch {+ /* ignore */+ }+ }+ return null;+}++/** True when the platform can actually fund drops (wallet configured + valid). */+export function fundingConfigured() {+ return !!resolveFundingKeyBase58();+}++function fundingKeypair() {+ const key = resolveFundingKeyBase58();+ if (!key) {+ throw Object.assign(+ new Error('drop funding wallet is not configured — set VANITY_DROP_FUNDING_KEY (Base58 64-byte secret)'),+ { status: 503, code: 'funding_unconfigured' },+ );+ }+ return Keypair.fromSecretKey(bs58.decode(key));+}++/** The $THREE mint — the only coin a drop may be funded with as a *coin*. */+function threeMint() {+ return env.THREE_TOKEN_MINT;+}++/** SPL mint for a drop asset (USDC rail or $THREE coin). SOL has no mint. */+function mintForAsset(asset) {+ if (asset === 'USDC') return SOLANA_USDC_MINT;+ if (asset === 'THREE') return threeMint();+ return null;+}++/** Decimals for an asset → atomics conversion. */+export function decimalsForAsset(asset) {+ if (asset === 'SOL') return 9;+ if (asset === 'USDC') return 6;+ if (asset === 'THREE') return Number(env.THREE_TOKEN_DECIMALS) || 6;+ throw Object.assign(new Error(`unknown asset ${asset}`), { status: 400, code: 'invalid_asset' });+}++/** Convert a human amount (string/number) to atomics (BigInt) for an asset. */+export function amountToAtomics(amount, asset) {+ const decimals = decimalsForAsset(asset);+ const s = String(amount).trim();+ if (!/^\d+(\.\d+)?$/.test(s)) {+ throw Object.assign(new Error('amount must be a positive decimal number'), { status: 400, code: 'invalid_amount' });+ }+ const [whole, frac = ''] = s.split('.');+ if (frac.length > decimals) {+ throw Object.assign(new Error(`amount has more than ${decimals} decimal places for ${asset}`), { status: 400, code: 'invalid_amount' });+ }+ const padded = (whole + frac.padEnd(decimals, '0')).replace(/^0+(?=\d)/, '');+ const atomics = BigInt(padded || '0');+ if (atomics <= 0n) {+ throw Object.assign(new Error('amount must be greater than zero'), { status: 400, code: 'invalid_amount' });+ }+ return atomics;+}++/** Format atomics back to a human string for display. */+export function atomicsToAmount(atomics, asset) {+ const decimals = decimalsForAsset(asset);+ const a = BigInt(atomics);+ const s = a.toString().padStart(decimals + 1, '0');+ const whole = s.slice(0, -decimals) || '0';+ const frac = s.slice(-decimals).replace(/0+$/, '');+ return frac ? `${whole}.${frac}` : whole;+}++/**+ * Fund a freshly-ground drop address on-chain from the platform funding wallet.+ * Confirms the transfer before returning. Throws (with the create aborted) on+ * any failure so a drop is never shown as claimable without real funds behind it.+ *+ * @param {object} p+ * @param {string} p.toAddress - the drop wallet's Base58 address.+ * @param {string} p.asset - 'SOL' | 'USDC' | 'THREE'.+ * @param {bigint} p.atomics - amount in smallest units.+ * @returns {Promise<{ fundingTx:string, atomics:string, asset:string }>}+ */+export async function fundDropAddress({ toAddress, asset, atomics }) {+ if (!BASE58_RE.test(String(toAddress || ''))) {+ throw Object.assign(new Error('drop address must be a Base58 Solana address'), { status: 400, code: 'invalid_address' });+ }+ const amount = BigInt(atomics);+ if (amount <= 0n) {+ throw Object.assign(new Error('funding amount must be positive'), { status: 400, code: 'invalid_amount' });+ }+ const payer = fundingKeypair();+ const recipient = new PublicKey(toAddress);+ const conn = solanaConnection('mainnet');++ const tx = new Transaction();+ if (asset === 'SOL') {+ tx.add(SystemProgram.transfer({ fromPubkey: payer.publicKey, toPubkey: recipient, lamports: amount }));+ } else {+ const mint = new PublicKey(mintForAsset(asset));+ const fromATA = await getAssociatedTokenAddress(mint, payer.publicKey);+ const toATA = await getAssociatedTokenAddress(mint, recipient);+ const toInfo = await conn.getAccountInfo(toATA);+ if (!toInfo) {+ tx.add(createAssociatedTokenAccountInstruction(payer.publicKey, toATA, recipient, mint));+ }+ tx.add(createTransferInstruction(fromATA, toATA, payer.publicKey, amount));+ }++ const { blockhash, lastValidBlockHeight } = await conn.getLatestBlockhash('confirmed');+ tx.feePayer = payer.publicKey;+ tx.recentBlockhash = blockhash;+ tx.sign(payer);+ const sig = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false, maxRetries: 3 });+ await conn.confirmTransaction({ signature: sig, blockhash, lastValidBlockHeight }, 'confirmed');+ return { fundingTx: sig, atomics: amount.toString(), asset };+}++/**+ * Read the live on-chain balance of a drop address for its funded asset.+ * Never throws — an RPC blip returns null so the claim UI degrades to "checking".+ * @returns {Promise<{ atomics:string|null }>}+ */+export async function readDropBalance({ address, asset }) {+ try {+ const conn = solanaConnection('mainnet');+ const owner = new PublicKey(address);+ if (asset === 'SOL') {+ const lamports = await conn.getBalance(owner, 'confirmed');+ return { atomics: String(lamports) };+ }+ const mint = new PublicKey(mintForAsset(asset));+ const ata = await getAssociatedTokenAddress(mint, owner);+ try {+ const acct = await getAccount(conn, ata);+ return { atomics: acct.amount.toString() };+ } catch {+ return { atomics: '0' }; // no ATA yet → zero+ }+ } catch {+ return { atomics: null };+ }+}++/**+ * Sweep an EXPIRED, reclaimed drop's funds back to the sender's reclaim address.+ * Signs with the drop wallet's OWN key (reconstructed from the at-rest encrypted+ * copy by the caller and passed in as `dropSecretKey`). For SOL it sweeps the+ * full balance minus the network fee; for SPL it sweeps the full token balance+ * (the drop wallet must hold a little SOL for the fee — funded drops always do+ * because USDC/THREE funding created the recipient ATA with the platform paying,+ * so the sweep fee is paid by the platform funding wallet as fee-payer).+ *+ * Idempotent: a drop that already carries a reclaimTx returns it without sweeping.+ *+ * @param {object} p+ * @param {object} p.record - the drop record (must be status 'reclaimed').+ * @param {Uint8Array} p.dropSecretKey - the 64-byte secret of the drop wallet.+ * @param {string} p.toAddress - the sender's reclaim Base58 address.+ * @returns {Promise<{ reclaimTx:string, alreadyReclaimed:boolean }>}+ */+export async function sweepReclaim({ record, dropSecretKey, toAddress }) {+ if (!record) throw Object.assign(new Error('drop not found'), { status: 404, code: 'not_found' });+ if (record.status !== 'reclaimed') {+ throw Object.assign(new Error(`drop is ${record.status}, not reclaimed — cannot sweep`), { status: 409, code: 'not_reclaimable' });+ }+ if (record.reclaimTx) {+ return { reclaimTx: record.reclaimTx, alreadyReclaimed: true };+ }+ if (!BASE58_RE.test(String(toAddress || ''))) {+ throw Object.assign(new Error('reclaim address must be a Base58 Solana address'), { status: 400, code: 'invalid_reclaim_address' });+ }++ const dropKp = Keypair.fromSecretKey(dropSecretKey);+ const feePayer = fundingKeypair(); // platform pays the sweep network fee+ const recipient = new PublicKey(toAddress);+ const conn = solanaConnection('mainnet');+ const asset = record.asset;++ const tx = new Transaction();+ if (asset === 'SOL') {+ const lamports = await conn.getBalance(dropKp.publicKey, 'confirmed');+ if (lamports <= 0) {+ // Nothing to sweep (already empty) — treat as a completed reclaim.+ await recordReclaim({ id: record.id, reclaimTx: 'empty' });+ return { reclaimTx: 'empty', alreadyReclaimed: false };+ }+ // Fee is paid by the platform fee-payer, so the full drop balance moves.+ tx.add(SystemProgram.transfer({ fromPubkey: dropKp.publicKey, toPubkey: recipient, lamports }));+ } else {+ const mint = new PublicKey(mintForAsset(asset));+ const fromATA = await getAssociatedTokenAddress(mint, dropKp.publicKey);+ let amount = 0n;+ try {+ amount = (await getAccount(conn, fromATA)).amount;+ } catch {+ amount = 0n;+ }+ if (amount <= 0n) {+ await recordReclaim({ id: record.id, reclaimTx: 'empty' });+ return { reclaimTx: 'empty', alreadyReclaimed: false };+ }+ const toATA = await getAssociatedTokenAddress(mint, recipient);+ const toInfo = await conn.getAccountInfo(toATA);+ if (!toInfo) {+ tx.add(createAssociatedTokenAccountInstruction(feePayer.publicKey, toATA, recipient, mint));+ }+ tx.add(createTransferInstruction(fromATA, toATA, dropKp.publicKey, amount));+ }++ const { blockhash, lastValidBlockHeight } = await conn.getLatestBlockhash('confirmed');+ tx.feePayer = feePayer.publicKey;+ tx.recentBlockhash = blockhash;+ tx.sign(feePayer, dropKp);+ const sig = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false, maxRetries: 3 });+ await conn.confirmTransaction({ signature: sig, blockhash, lastValidBlockHeight }, 'confirmed');+ await recordReclaim({ id: record.id, reclaimTx: sig });+ return { reclaimTx: sig, alreadyReclaimed: false };+}++export { BASE58_RE, LAMPORTS_PER_SOL, SOL_FEE_HEADROOM_LAMPORTS };diff --git a/api/_lib/sealed-drop-store.js b/api/_lib/sealed-drop-store.jsnew file mode 100644index 000000000..69d8e3ac7--- /dev/null+++ b/api/_lib/sealed-drop-store.js@@ -0,0 +1,324 @@+/**+ * Persistence + atomic claim ledger for sealed wallet drops.+ *+ * A drop is a pre-funded Solana wallet sealed (ECIES) to a recipient and handed+ * out by link / QR / 3D agent. This store holds the drop record and runs the+ * single, atomic state machine that makes a drop claimable EXACTLY ONCE — by the+ * holder of the claim secret — or reclaimable by the sender after expiry, never+ * both. Mirrors vanity-bounty-store.js: Upstash Redis when configured, an+ * in-process Map fallback otherwise (local/CI works; a Redis outage degrades).+ *+ * ── Operator-blind by construction ───────────────────────────────────────────+ * A stored drop NEVER holds a plaintext private key or seed. It holds only:+ * • the public funded `address`,+ * • the SEALED envelope (opaque ECIES ciphertext addressed to the recipient),+ * • the recipient's PUBLIC X25519 key (direct mode) or the claim PUBLIC key+ * + the one-way `claimTokenHash` (claim-time mode).+ * The operator therefore cannot open any wallet it stores or brokers. The public+ * projection (`toPublicDrop`) additionally strips the sealed envelope so it is+ * only ever released through the gated claim/reveal path.+ *+ * ── Atomic single-claim state machine ────────────────────────────────────────+ * funded ──claim(token)──▶ claimed (compare-and-set, idempotent on token)+ * └─expiry+reclaim─▶ reclaimed (compare-and-set, sender-only, mutex)+ * A Lua compare-and-set flips status and records the claimer/reclaimer, and+ * returns "won" ONLY to the first caller. A claimed drop can never be reclaimed+ * and vice versa. Idempotency: re-presenting the SAME claim token after a claim+ * returns "won" again (so a retried release isn't a re-race); reclaim after a+ * reclaim returns "reclaimable" again.+ *+ * Layout (Redis):+ * HASH vanity:drop:rec field=id → JSON(drop record)+ * ZSET vanity:drop:by-recency member=id score=createdAt(ms)+ * ZSET vanity:drop:funded member=id score=expiresAt(ms) (live, reclaim sweep)+ * ZSET vanity:drop:by-sender member=id score=createdAt(ms) (sender index, per senderTag)+ */++import { getRedis } from './redis.js';++const NS = 'vanity:drop';+const K = {+ rec: `${NS}:rec`,+ byRecency: `${NS}:by-recency`,+ funded: `${NS}:funded`,+ sender: (tag) => `${NS}:by-sender:${tag}`,+};++const MAX_SCAN = 500;++// Public projection — the sealed envelope + claim-token hash + funding tx detail+// stay private. The privacy boundary: the envelope is released only by the gated+// claim/reveal path, never on a list or status read.+const PUBLIC_FIELDS = Object.freeze([+ 'id', 'protocol', 'address', 'asset', 'amount', 'amountAtomics', 'network',+ 'sealMode', 'status', 'message', 'theme', 'senderLabel', 'vanity',+ 'createdAt', 'expiresAt', 'claimedAt', 'reclaimedAt', 'fundingConfirmed',+ 'recipient', 'irlPinId', 'roomId',+]);++const mem = new Map(); // id → record (fallback store)++/** Project a record to its public shape (no sealed envelope, no token hash, no tx). */+export function toPublicDrop(rec) {+ if (!rec || typeof rec !== 'object') return null;+ const out = {};+ for (const k of PUBLIC_FIELDS) if (rec[k] !== undefined) out[k] = rec[k];+ if (!out.id) return null;+ return out;+}++function parse(raw) {+ if (!raw) return null;+ if (typeof raw === 'object') return raw; // Upstash auto-deserializes JSON+ try { return JSON.parse(raw); } catch { return null; }+}++/**+ * Create a drop in `funded` status (funding already confirmed on-chain by the+ * caller before this is called). Claims the id atomically (hsetnx) so a+ * collision can't repoint the indexes at an existing record.+ * @param {object} rec - fully-formed drop record (see api/vanity/drops.js).+ * @returns {Promise<object>} the stored record.+ */+export async function createDrop(rec) {+ const record = { ...rec, status: rec.status || 'funded' };+ const redis = getRedis();+ if (redis) {+ const created = await redis.hsetnx(K.rec, record.id, JSON.stringify(record));+ if (created === 0 || created === false) {+ throw Object.assign(new Error('drop id collision'), { status: 409, code: 'duplicate_drop' });+ }+ const pipe = redis.multi();+ pipe.zadd(K.byRecency, { score: record.createdAt, member: record.id });+ pipe.zadd(K.funded, { score: record.expiresAt, member: record.id });+ if (record.senderTag) pipe.zadd(K.sender(record.senderTag), { score: record.createdAt, member: record.id });+ await pipe.exec();+ } else {+ if (mem.has(record.id)) {+ throw Object.assign(new Error('drop id collision'), { status: 409, code: 'duplicate_drop' });+ }+ mem.set(record.id, record);+ }+ return record;+}++/** Full internal record by id (includes sealed envelope + token hash). */+export async function getDropRecord(id) {+ const key = String(id || '');+ if (!key) return null;+ const redis = getRedis();+ if (redis) return parse(await redis.hget(K.rec, key));+ return mem.get(key) || null;+}++/** Public view by id. */+export async function getDrop(id) {+ return toPublicDrop(await getDropRecord(id));+}++// Atomic funded→claimed compare-and-set. Idempotent on claimerTag (the digest of+// the presented claim token): re-presenting the SAME token after a claim returns+// 1 again (so a retried envelope release doesn't re-race). A claim on an already-+// reclaimed/expired drop returns -1. Returns 1=won, 0=lost(claimed by other),+// -1=not-claimable(reclaimed/expired), -2=missing.+const CLAIM_LUA = `+local raw = redis.call('HGET', KEYS[1], ARGV[1])+if not raw then return -2 end+local rec = cjson.decode(raw)+if rec.status == 'claimed' then+ if rec.claimerTag == ARGV[2] then return 1 else return 0 end+end+if rec.status ~= 'funded' then return -1 end+local now = tonumber(ARGV[4])+if rec.expiresAt and now > tonumber(rec.expiresAt) then return -1 end+rec.status = 'claimed'+rec.claimerTag = ARGV[2]+rec.claimedAt = now+rec.claimRecipient = ARGV[3]+redis.call('HSET', KEYS[1], ARGV[1], cjson.encode(rec))+redis.call('ZREM', KEYS[2], ARGV[1])+return 1+`;++/**+ * Atomically claim a drop. The FIRST valid claim (proven possession of the claim+ * token) wins; later ones lose. Idempotent on claimerTag. Does NOT release the+ * envelope itself — the caller reads the record after a `won` and returns the+ * sealed envelope, so a release error can be retried without re-racing.+ *+ * @param {object} p+ * @param {string} p.id+ * @param {string} p.claimerTag - one-way digest tying this claim to its token.+ * @param {string} [p.claimRecipient] - optional recipient pubkey the holder re-sealed to (audit).+ * @returns {Promise<'won'|'lost'|'closed'|'missing'>}+ */+export async function claimDrop({ id, claimerTag, claimRecipient }) {+ const now = Date.now();+ const redis = getRedis();+ if (redis) {+ const r = await redis.eval(+ CLAIM_LUA,+ [K.rec, K.funded],+ [String(id), String(claimerTag), String(claimRecipient || ''), String(now)],+ );+ return claimCode(Number(r));+ }+ const rec = mem.get(String(id));+ if (!rec) return 'missing';+ if (rec.status === 'claimed') return rec.claimerTag === claimerTag ? 'won' : 'lost';+ if (rec.status !== 'funded') return 'closed';+ if (rec.expiresAt && now > rec.expiresAt) return 'closed';+ rec.status = 'claimed';+ rec.claimerTag = claimerTag;+ rec.claimedAt = now;+ rec.claimRecipient = claimRecipient || '';+ mem.set(String(id), rec);+ return 'won';+}++function claimCode(n) {+ if (n === 1) return 'won';+ if (n === 0) return 'lost';+ if (n === -2) return 'missing';+ return 'closed';+}++// Atomic funded→reclaimed compare-and-set, only for EXPIRED drops. Mutually+// exclusive with claim: a claimed drop can never be reclaimed and vice versa.+// Idempotent — re-running on an already-reclaimed drop returns 1. Returns+// 1=reclaimable(now reclaimed), 0=not-eligible, -2=missing.+const RECLAIM_LUA = `+local raw = redis.call('HGET', KEYS[1], ARGV[1])+if not raw then return -2 end+local rec = cjson.decode(raw)+if rec.status == 'reclaimed' then return 1 end+if rec.status ~= 'funded' then return 0 end+local now = tonumber(ARGV[2])+if not rec.expiresAt or now <= tonumber(rec.expiresAt) then return 0 end+rec.status = 'reclaimed'+rec.reclaimedAt = now+redis.call('HSET', KEYS[1], ARGV[1], cjson.encode(rec))+redis.call('ZREM', KEYS[2], ARGV[1])+return 1+`;++/**+ * Atomically mark an EXPIRED, unclaimed drop as reclaimed so its funds can be+ * swept back to the sender exactly once. Mutually exclusive with claimDrop.+ * @param {string} id+ * @returns {Promise<'reclaimable'|'ineligible'|'missing'>}+ */+export async function markReclaimable(id) {+ const now = Date.now();+ const redis = getRedis();+ if (redis) {+ const r = Number(await redis.eval(RECLAIM_LUA, [K.rec, K.funded], [String(id), String(now)]));+ if (r === 1) return 'reclaimable';+ if (r === -2) return 'missing';+ return 'ineligible';+ }+ const rec = mem.get(String(id));+ if (!rec) return 'missing';+ if (rec.status === 'reclaimed') return 'reclaimable';+ if (rec.status !== 'funded') return 'ineligible';+ if (!rec.expiresAt || now <= rec.expiresAt) return 'ineligible';+ rec.status = 'reclaimed';+ rec.reclaimedAt = now;+ mem.set(String(id), rec);+ return 'reclaimable';+}++/** Record the on-chain reclaim sweep tx after a successful reclaim (idempotent set). */+export async function recordReclaim({ id, reclaimTx }) {+ const rec = await getDropRecord(id);+ if (!rec) return null;+ rec.reclaimTx = reclaimTx;+ rec.reclaimAt = Date.now();+ const redis = getRedis();+ if (redis) await redis.hset(K.rec, { [id]: JSON.stringify(rec) });+ else mem.set(id, rec);+ return rec;+}++/** Record the claimer's re-seal recipient + a delivery note after the envelope is released (audit). */+export async function recordClaimDelivery({ id, claimRecipient }) {+ const rec = await getDropRecord(id);+ if (!rec) return null;+ if (claimRecipient) rec.claimRecipient = claimRecipient;+ rec.deliveredAt = Date.now();+ const redis = getRedis();+ if (redis) await redis.hset(K.rec, { [id]: JSON.stringify(rec) });+ else mem.set(id, rec);+ return rec;+}++/**+ * List a sender's drops (newest first), public projection. `senderTag` is an+ * opaque, non-PII tag the creator chooses (e.g. a hash of their session) so they+ * can find their drops to reclaim — it is never required and never exposed.+ * @param {string} senderTag+ * @param {number} [limit=50]+ */+export async function listBySender(senderTag, limit = 50) {+ const tag = String(senderTag || '').trim();+ if (!tag) return [];+ const n = Math.max(1, Math.min(100, Number(limit) || 50));+ const redis = getRedis();+ if (redis) {+ const members = await redis.zrange(K.sender(tag), 0, n - 1, { rev: true });+ if (!members.length) return [];+ const raw = await redis.hmget(K.rec, ...members);+ return members.map((_, i) => parse(raw?.[i])).filter(Boolean).map(toPublicDrop);+ }+ return [...mem.values()]+ .filter((r) => r.senderTag === tag)+ .sort((a, b) => (b.createdAt || 0) - (a.createdAt || 0))+ .slice(0, n)+ .map(toPublicDrop);+}++/** Expired, still-funded drops (oldest expiry first) — the reclaim sweep queue. */+export async function listReclaimable(limit = 50) {+ const now = Date.now();+ const n = Math.max(1, Math.min(100, Number(limit) || 50));+ const redis = getRedis();+ if (redis) {+ // Score is expiresAt; everything below `now` is expired and still funded.+ const members = await redis.zrange(K.funded, 0, now, { byScore: true });+ const slice = members.slice(0, n);+ if (!slice.length) return [];+ const raw = await redis.hmget(K.rec, ...slice);+ return slice.map((_, i) => parse(raw?.[i])).filter((r) => r && r.status === 'funded' && r.expiresAt <= now);+ }+ return [...mem.values()]+ .filter((r) => r.status === 'funded' && r.expiresAt && r.expiresAt <= now)+ .sort((a, b) => a.expiresAt - b.expiresAt)+ .slice(0, n);+}++/** Aggregate stats for the landing/explore surface. */+export async function dropStats() {+ const redis = getRedis();+ let recs;+ if (redis) {+ const all = await redis.hgetall(K.rec);+ recs = all ? Object.values(all).map(parse).filter(Boolean) : [];+ } else {+ recs = [...mem.values()];+ }+ const now = Date.now();+ let funded = 0, claimed = 0, reclaimed = 0;+ for (const r of recs) {+ if (r.status === 'claimed') claimed++;+ else if (r.status === 'reclaimed') reclaimed++;+ else if (r.status === 'funded' && (!r.expiresAt || r.expiresAt > now)) funded++;+ }+ return { funded, claimed, reclaimed, total: recs.length };+}++// Test-only: reset the in-memory fallback between specs.+export function __resetMemoryStore() {+ mem.clear();+}++export { PUBLIC_FIELDS };diff --git a/api/_lib/vanity-bounty-payout.js b/api/_lib/vanity-bounty-payout.jsnew file mode 100644index 000000000..1e3b87d59--- /dev/null+++ b/api/_lib/vanity-bounty-payout.js@@ -0,0 +1,164 @@+/**+ * Real on-chain USDC payout + refund rails for the grind-bounty market.+ *+ * Escrow model: a requester funds a bounty by paying the platform via x402 (USDC+ * on Base or Solana) up front. That USDC lands in the platform's receiving+ * wallet and is held as escrow against the bounty record. When a worker submits a+ * verified, sealed, pattern-matching claim, the platform pays the worker the+ * bounty from its Solana USDC payout wallet (`VANITY_BOUNTY_PAYOUT_KEY`). If the+ * bounty expires unfilled, the same wallet refunds the requester. Both legs are+ * real on-chain SPL transfers (reusing the audited transferSolanaUSDC helper) —+ * no fake balances.+ *+ * Money-safety invariants enforced here + in the store:+ * • A worker is paid ONLY after claimBounty() atomically marks the bounty+ * settled for that exact claim — so payout can never fire for a losing or+ * unverified claim, and never for two workers.+ * • Payout is idempotent: the on-chain send is keyed to the bounty id, and the+ * store records the resulting tx; a settled bounty that already has a payoutTx+ * short-circuits instead of paying again.+ * • A bounty can be EITHER settled (worker paid) OR refunded (requester repaid),+ * never both — the two transitions are mutually-exclusive compare-and-sets.+ * • Refund only fires after the expiry compare-and-set; a still-live or settled+ * bounty is ineligible.+ *+ * Payouts are Solana-only (the platform's payout wallet holds Solana USDC), which+ * is independent of how the requester funded the escrow (Base or Solana x402) —+ * the worker/requester supplies the Solana address they want paid to.+ */++import bs58 from 'bs58';++import { transferSolanaUSDC } from './solana-transfer.js';+import { SOLANA_USDC_MINT } from '../payments/_config.js';+import { env } from './env.js';+import { getBountyRecord, recordPayout, recordRefund } from './vanity-bounty-store.js';++const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++// Resolve the payout wallet as a Base58 64-byte secret from either the dedicated+// VANITY_BOUNTY_PAYOUT_KEY (Base58) or the existing base64 club treasury secret.+function resolvePayoutKeyBase58() {+ const dedicated = env.VANITY_BOUNTY_PAYOUT_KEY;+ if (dedicated && dedicated.trim()) {+ const s = dedicated.trim();+ // Validate it decodes to 64 bytes so a misconfig fails loud, not on-chain.+ try {+ if (bs58.decode(s).length === 64) return s;+ } catch {+ /* not Base58 — fall through to base64 attempt below */+ }+ try {+ const raw = Buffer.from(s, 'base64');+ if (raw.byteLength === 64) return bs58.encode(raw);+ } catch {+ /* ignore */+ }+ }+ const clubB64 = process.env.CLUB_SOLANA_TREASURY_SECRET_KEY_B64;+ if (clubB64) {+ try {+ const raw = Buffer.from(clubB64, 'base64');+ if (raw.byteLength === 64) return bs58.encode(raw);+ } catch {+ /* ignore */+ }+ }+ return null;+}++/** Resolve the payout wallet secret (Base58 64-byte) or throw a clear 503. */+function payoutWallet() {+ const key = resolvePayoutKeyBase58();+ if (!key) {+ throw Object.assign(+ new Error('bounty payout wallet is not configured — set VANITY_BOUNTY_PAYOUT_KEY (Base58 64-byte secret)'),+ { status: 503, code: 'payout_unconfigured' },+ );+ }+ return key;+}++/** True when the platform can actually pay out (wallet configured + valid). */+export function payoutConfigured() {+ return !!resolvePayoutKeyBase58();+}++/**+ * Pay the winning worker the bounty amount in USDC on Solana. Idempotent: if the+ * bounty already carries a payoutTx, returns it without re-sending. Requires the+ * bounty to already be `settled` (the atomic claim ran first).+ *+ * @param {object} p+ * @param {string} p.id - bounty id (must be settled).+ * @param {string} p.toAddress - the worker's Solana payout address.+ * @returns {Promise<{ payoutTx:string, amountAtomics:number, alreadyPaid:boolean }>}+ */+export async function payWinner({ id, toAddress }) {+ const rec = await getBountyRecord(id);+ if (!rec) throw Object.assign(new Error('bounty not found'), { status: 404, code: 'not_found' });+ if (rec.status !== 'settled') {+ throw Object.assign(new Error(`bounty ${id} is ${rec.status}, not settled — cannot pay out`), {+ status: 409,+ code: 'not_settled',+ });+ }+ if (rec.payoutTx) {+ return { payoutTx: rec.payoutTx, amountAtomics: rec.amountAtomics, alreadyPaid: true };+ }+ if (!BASE58_RE.test(String(toAddress || ''))) {+ throw Object.assign(new Error('worker payout address must be a Base58 Solana address'), {+ status: 400,+ code: 'invalid_payout_address',+ });+ }+ const fromWallet = payoutWallet();+ const sig = await transferSolanaUSDC({+ fromWallet,+ toAddress,+ amount: BigInt(rec.amountAtomics),+ mint: SOLANA_USDC_MINT,+ });+ await recordPayout({ id, payoutTx: sig, workerId: rec.winnerWorkerId, amountAtomics: rec.amountAtomics });+ return { payoutTx: sig, amountAtomics: rec.amountAtomics, alreadyPaid: false };+}++/**+ * Refund an expired, unfilled bounty's escrow to the requester. Requires the+ * bounty to already be marked `refunded` by the atomic expiry compare-and-set.+ * Idempotent on refundTx.+ *+ * @param {object} p+ * @param {string} p.id+ * @param {string} p.toAddress - the requester's Solana refund address.+ * @returns {Promise<{ refundTx:string, amountAtomics:number, alreadyRefunded:boolean }>}+ */+export async function refundRequester({ id, toAddress }) {+ const rec = await getBountyRecord(id);+ if (!rec) throw Object.assign(new Error('bounty not found'), { status: 404, code: 'not_found' });+ if (rec.status !== 'refunded') {+ throw Object.assign(new Error(`bounty ${id} is ${rec.status}, not refundable`), {+ status: 409,+ code: 'not_refundable',+ });+ }+ if (rec.refundTx) {+ return { refundTx: rec.refundTx, amountAtomics: rec.amountAtomics, alreadyRefunded: true };+ }+ const refundTo = toAddress || rec.refundAddress;+ if (!BASE58_RE.test(String(refundTo || ''))) {+ throw Object.assign(new Error('requester refund address must be a Base58 Solana address'), {+ status: 400,+ code: 'invalid_refund_address',+ });+ }+ const fromWallet = payoutWallet();+ const sig = await transferSolanaUSDC({+ fromWallet,+ toAddress: refundTo,+ amount: BigInt(rec.amountAtomics),+ mint: SOLANA_USDC_MINT,+ });+ await recordRefund({ id, refundTx: sig });+ return { refundTx: sig, amountAtomics: rec.amountAtomics, alreadyRefunded: false };+}diff --git a/api/_lib/vanity-bounty-store.js b/api/_lib/vanity-bounty-store.jsnew file mode 100644index 000000000..b2b8e56d0--- /dev/null+++ b/api/_lib/vanity-bounty-store.js@@ -0,0 +1,401 @@+/**+ * Persistence + escrow ledger for the grind-bounty market.+ *+ * Stores the bounty board, the escrow record (USDC the requester paid up front+ * via x402, held until a winning claim or expiry), and the single, atomic+ * open→settled transition that picks exactly one winner. Mirrors the rest of the+ * codebase: Upstash Redis when configured, an in-process Map fallback otherwise+ * (so local/CI works and a Redis outage degrades rather than throwing).+ *+ * ── Secret-blind by construction ─────────────────────────────────────────────+ * A stored bounty NEVER holds a private key or seed — only the requester's PUBLIC+ * X25519 recipient key. A winning claim holds only the SEALED envelope (opaque+ * ciphertext addressed to the requester) plus the public address. The operator+ * therefore cannot open any wallet it brokers; `toPublicBounty()` additionally+ * strips the sealed envelope from the public board view so only the requester+ * (via the authenticated reveal path) ever receives it.+ *+ * ── Atomic single-winner settlement ──────────────────────────────────────────+ * `claimBounty` runs a Lua compare-and-set: it flips status open→settled, records+ * the winner + claim digest, and returns "won" ONLY to the first caller. Every+ * later caller — even with a different valid key — sees `settled` and gets+ * "lost" (idempotent: re-submitting the SAME claim digest returns "won" again so+ * a retried settle isn't a double-pay). Expiry refunds are gated by the same+ * compare-and-set on open→refunded, so a bounty can never both pay AND refund.+ *+ * Layout (Redis):+ * HASH vanity:bounty:rec field=id → JSON(bounty record)+ * ZSET vanity:bounty:open member=id score=expiresAt(ms) (live board)+ * ZSET vanity:bounty:by-recency member=id score=createdAt(ms)+ * ZSET vanity:bounty:leaderboard member=workerId score=earnedAtomics (top grinders)+ * STR vanity:bounty:lease:<id>:<wid> short-TTL work-lease (advisory de-dup)+ */++import { getRedis } from './redis.js';++const NS = 'vanity:bounty';+const K = {+ rec: `${NS}:rec`,+ open: `${NS}:open`,+ byRecency: `${NS}:by-recency`,+ leaderboard: `${NS}:leaderboard`,+ lease: (id, wid) => `${NS}:lease:${id}:${wid}`,+};++const MAX_SCAN = 500;++// Public board projection — the sealed envelope + escrow proof stay private.+// SECURITY: this is the privacy boundary for the board. The sealed envelope is+// only ever returned to the requester through the dedicated reveal path, never here.+const PUBLIC_FIELDS = Object.freeze([+ 'id', 'protocol', 'pattern', 'recipient', 'amountAtomics', 'asset', 'network',+ 'status', 'difficulty', 'createdAt', 'expiresAt', 'settledAt', 'refundedAt',+ 'winnerAddress', 'winnerWorkerId', 'payoutTx', 'refundTx', 'label',+]);++const mem = new Map(); // id → record (fallback store)++/** Project a record to its public board shape (no sealed envelope, no escrow proof). */+export function toPublicBounty(rec) {+ if (!rec || typeof rec !== 'object') return null;+ const out = {};+ for (const k of PUBLIC_FIELDS) if (rec[k] !== undefined) out[k] = rec[k];+ if (!out.id) return null;+ // Never leak the sealed envelope or any escrow secret on the public view.+ return out;+}++/**+ * Create a bounty in `open` status with its escrow record attached. The escrow+ * proof (x402 settlement tx + payer) is stored on the record but never exposed+ * publicly — it is the audit trail proving the requester actually funded it.+ * @param {object} rec - fully-formed bounty record (see api/vanity/bounties.js).+ * @returns {Promise<object>} the stored record.+ */+export async function createBounty(rec) {+ const record = { ...rec, status: 'open' };+ const redis = getRedis();+ if (redis) {+ // Claim the id atomically FIRST (hsetnx) so a (astronomically unlikely)+ // collision can't repoint the index ZSETs at an existing record. Only on a+ // fresh insert do we add the board/recency index entries.+ const created = await redis.hsetnx(K.rec, record.id, JSON.stringify(record));+ if (created === 0 || created === false) {+ throw Object.assign(new Error('bounty id collision'), { status: 409, code: 'duplicate_bounty' });+ }+ const pipe = redis.multi();+ pipe.zadd(K.open, { score: record.expiresAt, member: record.id });+ pipe.zadd(K.byRecency, { score: record.createdAt, member: record.id });+ await pipe.exec();+ } else {+ if (mem.has(record.id)) {+ throw Object.assign(new Error('bounty id collision'), { status: 409, code: 'duplicate_bounty' });+ }+ mem.set(record.id, record);+ }+ return record;+}++/** Fetch the full internal record by id (includes sealed envelope when settled). */+export async function getBountyRecord(id) {+ const key = String(id || '');+ if (!key) return null;+ const redis = getRedis();+ if (redis) return parse(await redis.hget(K.rec, key));+ return mem.get(key) || null;+}++/** Fetch the public board view by id. */+export async function getBounty(id) {+ return toPublicBounty(await getBountyRecord(id));+}++// Atomic open→settled compare-and-set. Idempotent on claimDigest: a retry of the+// SAME winning claim returns won=1 again (so a settle retry after a transient+// payout error doesn't pay a second worker), while a DIFFERENT claim on an+// already-settled bounty returns won=0 (lost the race). Also rejects expired and+// already-refunded bounties. Returns: 1=won, 0=lost, -1=not-open/expired, -2=missing.+const CLAIM_LUA = `+local raw = redis.call('HGET', KEYS[1], ARGV[1])+if not raw then return -2 end+local rec = cjson.decode(raw)+if rec.status == 'settled' then+ if rec.claimDigest == ARGV[2] then return 1 else return 0 end+end+if rec.status ~= 'open' then return -1 end+local now = tonumber(ARGV[5])+if rec.expiresAt and now > tonumber(rec.expiresAt) then return -1 end+rec.status = 'settled'+rec.claimDigest = ARGV[2]+rec.winnerAddress = ARGV[3]+rec.winnerWorkerId = ARGV[4]+rec.settledAt = now+rec.sealedSecret = cjson.decode(ARGV[6])+redis.call('HSET', KEYS[1], ARGV[1], cjson.encode(rec))+redis.call('ZREM', KEYS[2], ARGV[1])+return 1+`;++/**+ * Atomically claim a bounty for a worker. The FIRST valid claim wins; every later+ * one loses (idempotent on the same claimDigest). Records the winner + sealed+ * envelope on the record but leaves payout to the caller (so payout failure can+ * be retried without re-racing). Returns a status enum the caller maps to a+ * response.+ *+ * @param {object} p+ * @param {string} p.id+ * @param {string} p.claimDigest - deterministic digest from bounty-protocol.+ * @param {string} p.winnerAddress - the ground Base58 address.+ * @param {string} p.workerId - the claiming worker's id (anonymous ok).+ * @param {object} p.sealedSecret - the ECIES envelope addressed to the requester.+ * @returns {Promise<'won'|'lost'|'closed'|'missing'>}+ */+export async function claimBounty({ id, claimDigest, winnerAddress, workerId, sealedSecret }) {+ const now = Date.now();+ const redis = getRedis();+ if (redis) {+ const r = await redis.eval(+ CLAIM_LUA,+ [K.rec, K.open],+ [String(id), String(claimDigest), String(winnerAddress), String(workerId || 'anon'), String(now), JSON.stringify(sealedSecret)],+ );+ return claimCode(Number(r));+ }+ // Memory fallback: emulate the same compare-and-set semantics single-threaded.+ const rec = mem.get(String(id));+ if (!rec) return 'missing';+ if (rec.status === 'settled') return rec.claimDigest === claimDigest ? 'won' : 'lost';+ if (rec.status !== 'open') return 'closed';+ if (rec.expiresAt && now > rec.expiresAt) return 'closed';+ rec.status = 'settled';+ rec.claimDigest = claimDigest;+ rec.winnerAddress = winnerAddress;+ rec.winnerWorkerId = workerId || 'anon';+ rec.settledAt = now;+ rec.sealedSecret = sealedSecret;+ mem.set(String(id), rec);+ return 'won';+}++function claimCode(n) {+ if (n === 1) return 'won';+ if (n === 0) return 'lost';+ if (n === -2) return 'missing';+ return 'closed';+}++/** Record the on-chain payout tx after a successful settle (idempotent set). */+export async function recordPayout({ id, payoutTx, workerId, amountAtomics }) {+ const rec = await getBountyRecord(id);+ if (!rec) return null;+ rec.payoutTx = payoutTx;+ rec.payoutAt = Date.now();+ const redis = getRedis();+ if (redis) {+ const pipe = redis.multi();+ pipe.hset(K.rec, { [id]: JSON.stringify(rec) });+ if (workerId && amountAtomics) pipe.zincrby(K.leaderboard, Number(amountAtomics), String(workerId));+ await pipe.exec();+ } else {+ mem.set(id, rec);+ }+ return rec;+}++// Atomic open→refunded compare-and-set, only for EXPIRED bounties. Mutually+// exclusive with settlement: a settled bounty can never be refunded and vice+// versa. Idempotent — re-running on an already-refunded bounty returns 1 so a+// retried refund doesn't error. Returns 1=refundable(now refunded), 0=not-eligible.+const REFUND_LUA = `+local raw = redis.call('HGET', KEYS[1], ARGV[1])+if not raw then return -2 end+local rec = cjson.decode(raw)+if rec.status == 'refunded' then return 1 end+if rec.status ~= 'open' then return 0 end+local now = tonumber(ARGV[2])+if not rec.expiresAt or now <= tonumber(rec.expiresAt) then return 0 end+rec.status = 'refunded'+rec.refundedAt = now+redis.call('HSET', KEYS[1], ARGV[1], cjson.encode(rec))+redis.call('ZREM', KEYS[2], ARGV[1])+return 1+`;++/**+ * Atomically mark an EXPIRED open bounty as refunded so its escrow can be paid+ * back to the requester exactly once. Returns 'refundable' (caller should now+ * send the on-chain refund), 'ineligible' (still live, or already settled), or+ * 'missing'. Mutually exclusive with claimBounty by construction.+ * @param {string} id+ */+export async function markRefundable(id) {+ const now = Date.now();+ const redis = getRedis();+ if (redis) {+ const r = await redis.eval(REFUND_LUA, [K.rec, K.open], [String(id), String(now)]);+ const n = Number(r);+ if (n === 1) return 'refundable';+ if (n === -2) return 'missing';+ return 'ineligible';+ }+ const rec = mem.get(String(id));+ if (!rec) return 'missing';+ if (rec.status === 'refunded') return 'refundable';+ if (rec.status !== 'open') return 'ineligible';+ if (!rec.expiresAt || now <= rec.expiresAt) return 'ineligible';+ rec.status = 'refunded';+ rec.refundedAt = now;+ mem.set(String(id), rec);+ return 'refundable';+}++/** Record the on-chain refund tx after a successful refund. */+export async function recordRefund({ id, refundTx }) {+ const rec = await getBountyRecord(id);+ if (!rec) return null;+ rec.refundTx = refundTx;+ rec.refundAt = Date.now();+ const redis = getRedis();+ if (redis) await redis.hset(K.rec, { [id]: JSON.stringify(rec) });+ else mem.set(id, rec);+ return rec;+}++/**+ * Claim a short-lived advisory work-lease so workers don't all redo the same+ * bounty. Best-effort coordination only (NOT a security control — the atomic+ * claim is the real winner gate). Returns true if this worker got/holds the lease.+ * @param {string} id+ * @param {string} workerId+ * @param {number} [ttlSeconds=45]+ */+export async function acquireLease(id, workerId, ttlSeconds = 45) {+ const redis = getRedis();+ if (!redis) return true; // single-process dev: no contention to coordinate.+ const ok = await redis.set(K.lease(id, workerId), Date.now(), { nx: true, ex: ttlSeconds });+ return ok === 'OK' || ok === true;+}++/**+ * Query the board.+ * @param {object} [q]+ * @param {'open'|'all'|'settled'} [q.status='open']+ * @param {'recency'|'expiry'|'reward'} [q.sort='recency']+ * @param {number} [q.limit=24]+ * @param {number} [q.offset=0]+ * @returns {Promise<{ bounties:object[], total:number, hasMore:boolean }>}+ */+export async function queryBounties(q = {}) {+ const status = q.status || 'open';+ const sort = q.sort || 'recency';+ const limit = Math.max(1, Math.min(60, Number(q.limit) || 24));+ const offset = Math.max(0, Number(q.offset) || 0);+ const now = Date.now();++ const redis = getRedis();+ let recs;+ if (redis) {+ // `open` reads the live ZSET (and lazily filters out anything past expiry+ // that hasn't been swept yet); everything else reads by-recency then filters.+ const indexKey = status === 'open' ? K.open : K.byRecency;+ const members = await redis.zrange(indexKey, 0, MAX_SCAN - 1, { rev: status !== 'open' });+ if (!members.length) return { bounties: [], total: 0, hasMore: false };+ const raw = await redis.hmget(K.rec, ...members);+ recs = members.map((_, i) => parse(raw?.[i])).filter(Boolean);+ } else {+ recs = [...mem.values()];+ }++ let filtered = recs;+ if (status === 'open') filtered = recs.filter((r) => r.status === 'open' && r.expiresAt > now);+ else if (status === 'settled') filtered = recs.filter((r) => r.status === 'settled');++ filtered.sort((a, b) => {+ if (sort === 'reward') return (b.amountAtomics || 0) - (a.amountAtomics || 0);+ if (sort === 'expiry') return (a.expiresAt || 0) - (b.expiresAt || 0);+ return (b.createdAt || 0) - (a.createdAt || 0);+ });++ const total = filtered.length;+ const page = filtered.slice(offset, offset + limit).map(toPublicBounty);+ return { bounties: page, total, hasMore: offset + limit < total };+}++/** Open bounties only, oldest-expiry-first — the worker fleet's claim queue. */+export async function listClaimable(limit = 30) {+ const now = Date.now();+ const redis = getRedis();+ if (redis) {+ // Score is expiresAt; range from now upward returns only still-live bounties+ // in expiry order (soonest-to-expire first — fill them before they refund).+ const members = await redis.zrange(K.open, now, '+inf', { byScore: true });+ const slice = members.slice(0, Math.max(1, Math.min(60, limit)));+ if (!slice.length) return [];+ const raw = await redis.hmget(K.rec, ...slice);+ return slice.map((_, i) => parse(raw?.[i])).filter((r) => r && r.status === 'open').map(toPublicBounty);+ }+ return [...mem.values()]+ .filter((r) => r.status === 'open' && r.expiresAt > now)+ .sort((a, b) => a.expiresAt - b.expiresAt)+ .slice(0, limit)+ .map(toPublicBounty);+}++/** Aggregate board stats: open count, total escrowed, settled count, total paid. */+export async function bountyStats() {+ const redis = getRedis();+ let recs;+ if (redis) {+ const all = await redis.hgetall(K.rec);+ recs = all ? Object.values(all).map(parse).filter(Boolean) : [];+ } else {+ recs = [...mem.values()];+ }+ const now = Date.now();+ let open = 0, openEscrow = 0, settled = 0, paidOut = 0;+ for (const r of recs) {+ if (r.status === 'open' && r.expiresAt > now) { open++; openEscrow += r.amountAtomics || 0; }+ if (r.status === 'settled') { settled++; paidOut += r.amountAtomics || 0; }+ }+ return { open, openEscrowAtomics: openEscrow, settled, paidOutAtomics: paidOut, total: recs.length };+}++/** Top grinders by total USDC earned (the leaderboard). */+export async function topGrinders(limit = 10) {+ const n = Math.max(1, Math.min(50, Number(limit) || 10));+ const redis = getRedis();+ if (redis) {+ const rows = await redis.zrange(K.leaderboard, 0, n - 1, { rev: true, withScores: true });+ // withScores returns a flat [member, score, member, score, …] array.+ const out = [];+ for (let i = 0; i < rows.length; i += 2) {+ out.push({ workerId: String(rows[i]), earnedAtomics: Number(rows[i + 1]) || 0 });+ }+ return out;+ }+ // Memory fallback: aggregate from settled records.+ const tally = new Map();+ for (const r of mem.values()) {+ if (r.status === 'settled' && r.payoutTx && r.winnerWorkerId) {+ tally.set(r.winnerWorkerId, (tally.get(r.winnerWorkerId) || 0) + (r.amountAtomics || 0));+ }+ }+ return [...tally.entries()]+ .map(([workerId, earnedAtomics]) => ({ workerId, earnedAtomics }))+ .sort((a, b) => b.earnedAtomics - a.earnedAtomics)+ .slice(0, n);+}++function parse(raw) {+ if (!raw) return null;+ if (typeof raw === 'object') return raw; // Upstash auto-deserializes JSON+ try { return JSON.parse(raw); } catch { return null; }+}++// Test-only: reset the in-memory fallback between specs.+export function __resetMemoryStore() {+ mem.clear();+}++export { PUBLIC_FIELDS };diff --git a/api/_lib/vanity-gallery-store.js b/api/_lib/vanity-gallery-store.jsnew file mode 100644index 000000000..462f7dc86--- /dev/null+++ b/api/_lib/vanity-gallery-store.js@@ -0,0 +1,258 @@+/**+ * Persistence for the proof-of-grind gallery + leaderboard.+ *+ * Stores ONLY opt-in, public, secret-free rarity entries: the public Base58+ * address, the matched pattern, the honest rarity breakdown, the signed-receipt+ * fingerprint (so an entry is provably tied to a verifiable grind), and the+ * service signature over that receipt. It NEVER stores — and `toPublicEntry()`+ * structurally cannot serialize — a private key, seed, serverSeed, sealed+ * envelope, or any field outside the explicit allowlist below. Privacy is a+ * property of the data model, not of careful callers.+ *+ * Backing store mirrors the rest of the codebase: Upstash Redis when configured,+ * an in-process Map fallback otherwise (so local/CI works and a Redis outage+ * degrades to empty rather than throwing). Layout:+ *+ * HASH vanity:gallery:entries field=address → JSON(public entry)+ * ZSET vanity:gallery:by-score member=address score=rarityScore+ * ZSET vanity:gallery:by-recency member=address score=ts(ms)+ * ZSET vanity:gallery:tier:<tier> member=address score=rarityScore+ *+ * The leaderboard is `by-score` (rev), the gallery default is `by-recency` (rev),+ * tier filters use the per-tier ZSETs, and length/pattern filters are applied in+ * memory over a bounded page window. Idempotent on address: re-publishing the+ * same address updates in place (so an agent that re-grinds keeps one entry).+ */++import { getRedis } from './redis.js';++const NS = 'vanity:gallery';+const K = {+ entries: `${NS}:entries`,+ byScore: `${NS}:by-score`,+ byRecency: `${NS}:by-recency`,+ tier: (t) => `${NS}:tier:${t}`,+};++// Hard ceiling so a malicious flood can't unbound a scan. The public list paginates+// under this; the leaderboard reads the top slice directly from the ZSET.+const MAX_SCAN = 1000;++// The EXACT fields a public gallery entry may carry. Anything not here is dropped.+// SECURITY: this allowlist is the privacy boundary — no secret/seed/sealed field+// is on it, so even a caller that passes a full grind response cannot leak one.+const PUBLIC_FIELDS = Object.freeze([+ 'address',+ 'pattern',+ 'rarityScore',+ 'rarityBits',+ 'baseBits',+ 'bonusBits',+ 'tier',+ 'tierLabel',+ 'expectedAttempts',+ 'attempts',+ 'durationMs',+ 'bonuses',+ 'label',+ 'commitment',+ 'receiptFingerprint',+ 'servicePublicKey',+ 'verified',+ 'network',+ 'ts',+]);++const mem = new Map(); // address → entry (fallback store)++/**+ * Project any object down to the public, secret-free entry shape. This is the+ * only path data takes into the store, so secrets are structurally impossible to+ * persist. Returns null when the entry lacks the minimum required fields.+ * @param {object} obj+ * @returns {object|null}+ */+export function toPublicEntry(obj) {+ if (!obj || typeof obj !== 'object') return null;+ const out = {};+ for (const k of PUBLIC_FIELDS) if (obj[k] !== undefined) out[k] = obj[k];+ if (!out.address || typeof out.address !== 'string') return null;+ if (typeof out.rarityScore !== 'number') return null;+ // Defensive: strip any nested secret-looking keys that somehow rode along on a+ // permitted object field (e.g. a `pattern` that was over-populated upstream).+ out.pattern = sanitizePattern(out.pattern);+ if (Array.isArray(out.bonuses)) {+ out.bonuses = out.bonuses.slice(0, 8).map((b) => ({+ id: String(b?.id || ''),+ label: String(b?.label || ''),+ bits: Number(b?.bits) || 0,+ }));+ }+ if (out.label != null) out.label = String(out.label).slice(0, 80);+ return out;+}++function sanitizePattern(p) {+ if (!p || typeof p !== 'object') return { prefix: null, suffix: null, ignoreCase: false };+ return {+ prefix: p.prefix ? String(p.prefix).slice(0, 16) : null,+ suffix: p.suffix ? String(p.suffix).slice(0, 16) : null,+ ignoreCase: !!p.ignoreCase,+ };+}++/**+ * Insert/update a public gallery entry. Idempotent on address.+ * @param {object} entry - already projected via toPublicEntry (re-projected here).+ * @returns {Promise<object>} the stored public entry.+ */+export async function putEntry(entry) {+ const pub = toPublicEntry(entry);+ if (!pub) throw Object.assign(new Error('invalid gallery entry'), { status: 400 });+ const addr = pub.address;+ const score = pub.rarityScore;+ const ts = Number(pub.ts) || Date.now();+ pub.ts = ts;++ const redis = getRedis();+ if (redis) {+ // Clear any stale per-tier membership from a previous publish of this addr.+ const prevRaw = await redis.hget(K.entries, addr);+ const prev = parseEntry(prevRaw);+ const pipe = redis.multi();+ if (prev?.tier && prev.tier !== pub.tier) pipe.zrem(K.tier(prev.tier), addr);+ pipe.hset(K.entries, { [addr]: JSON.stringify(pub) });+ pipe.zadd(K.byScore, { score, member: addr });+ pipe.zadd(K.byRecency, { score: ts, member: addr });+ pipe.zadd(K.tier(pub.tier), { score, member: addr });+ await pipe.exec();+ } else {+ mem.set(addr, pub);+ }+ return pub;+}++/** Fetch a single entry by address, or null. */+export async function getEntry(address) {+ const addr = String(address || '');+ if (!addr) return null;+ const redis = getRedis();+ if (redis) return parseEntry(await redis.hget(K.entries, addr));+ return mem.get(addr) || null;+}++/** Remove an entry entirely (owner un-publish). */+export async function removeEntry(address) {+ const addr = String(address || '');+ if (!addr) return false;+ const redis = getRedis();+ if (redis) {+ const prev = parseEntry(await redis.hget(K.entries, addr));+ const pipe = redis.multi();+ pipe.hdel(K.entries, addr);+ pipe.zrem(K.byScore, addr);+ pipe.zrem(K.byRecency, addr);+ if (prev?.tier) pipe.zrem(K.tier(prev.tier), addr);+ await pipe.exec();+ return true;+ }+ return mem.delete(addr);+}++/**+ * Query the gallery / leaderboard.+ * @param {object} [q]+ * @param {'score'|'recency'} [q.sort='recency']+ * @param {string} [q.tier] - filter to one tier id.+ * @param {number} [q.minLength] - min combined pattern length.+ * @param {string} [q.contains] - substring the prefix/suffix must include.+ * @param {number} [q.limit=24]+ * @param {number} [q.offset=0]+ * @returns {Promise<{ entries: object[], total: number, hasMore: boolean }>}+ */+export async function queryEntries(q = {}) {+ const sort = q.sort === 'score' ? 'score' : 'recency';+ const tier = q.tier || null;+ const minLength = Number.isFinite(q.minLength) ? Number(q.minLength) : 0;+ const contains = (q.contains || '').toString().trim().toLowerCase();+ const limit = Math.max(1, Math.min(100, Number(q.limit) || 24));+ const offset = Math.max(0, Number(q.offset) || 0);++ const filtered = matchesFilters.bind(null, { minLength, contains });++ const redis = getRedis();+ let ordered;+ if (redis) {+ // Choose the index ZSET. Tier filter narrows to the per-tier ZSET (always+ // score-ordered); otherwise the requested global index.+ const key = tier ? K.tier(tier) : sort === 'score' ? K.byScore : K.byRecency;+ const members = await redis.zrange(key, 0, MAX_SCAN - 1, { rev: true });+ if (!members.length) return { entries: [], total: 0, hasMore: false };+ const raw = await redis.hmget(K.entries, ...members);+ ordered = members+ .map((m, i) => parseEntry(raw?.[i]))+ .filter((e) => e && (!tier || e.tier === tier) && filtered(e));+ // Per-tier ZSET is score-ordered; honor a recency sort by re-sorting.+ if (tier && sort === 'recency') ordered.sort((a, b) => (b.ts || 0) - (a.ts || 0));+ } else {+ ordered = [...mem.values()]+ .filter((e) => (!tier || e.tier === tier) && filtered(e))+ .sort((a, b) => (sort === 'score' ? b.rarityScore - a.rarityScore : (b.ts || 0) - (a.ts || 0)));+ }++ const total = ordered.length;+ const page = ordered.slice(offset, offset + limit);+ return { entries: page, total, hasMore: offset + limit < total };+}++/** Top-N by rarity, straight off the score ZSET — the leaderboard fast path. */+export async function topByScore(limit = 10) {+ const n = Math.max(1, Math.min(100, Number(limit) || 10));+ const redis = getRedis();+ if (redis) {+ const members = await redis.zrange(K.byScore, 0, n - 1, { rev: true });+ if (!members.length) return [];+ const raw = await redis.hmget(K.entries, ...members);+ return members.map((_, i) => parseEntry(raw?.[i])).filter(Boolean);+ }+ return [...mem.values()].sort((a, b) => b.rarityScore - a.rarityScore).slice(0, n);+}++/** Aggregate counts: total entries + per-tier histogram. */+export async function galleryStats() {+ const redis = getRedis();+ let entries;+ if (redis) {+ const all = await redis.hgetall(K.entries);+ entries = all ? Object.values(all).map(parseEntry).filter(Boolean) : [];+ } else {+ entries = [...mem.values()];+ }+ const byTier = {};+ let rarest = null;+ for (const e of entries) {+ byTier[e.tier] = (byTier[e.tier] || 0) + 1;+ if (!rarest || e.rarityScore > rarest.rarityScore) rarest = e;+ }+ return { total: entries.length, byTier, rarest };+}++function matchesFilters({ minLength, contains }, e) {+ const pre = e.pattern?.prefix || '';+ const suf = e.pattern?.suffix || '';+ if (minLength && pre.length + suf.length < minLength) return false;+ if (contains && !(`${pre}${suf}`.toLowerCase().includes(contains))) return false;+ return true;+}++function parseEntry(raw) {+ if (!raw) return null;+ if (typeof raw === 'object') return raw; // Upstash auto-deserializes JSON+ try {+ return JSON.parse(raw);+ } catch {+ return null;+ }+}++export { PUBLIC_FIELDS };diff --git a/api/healthz.js b/api/healthz.jsindex acea61559..4711a188d 100644--- a/api/healthz.js+++ b/api/healthz.js@@ -131,13 +131,27 @@ async function probeX402() {const result = {};- // Check if PAY_TO addresses are configured+ // Check if PAY_TO addresses are configured. A network counts as wired only+ // when EVERY field its 402 accept needs is present — the same gate+ // buildRequirements() applies before advertising it. Solana additionally+ // requires a fee payer (no default): without it the accept is dropped, so a+ // Solana-only paid endpoint (e.g. /api/x402/club-cover) fails closed with a+ // 500. Surfacing it here turns a silent door outage into a visible warning.+ const hasSolanaPayTo = !!process.env.X402_PAY_TO_SOLANA || !!process.env.X402_PAY_TO;+ const hasSolanaFeePayer = !!process.env.X402_FEE_PAYER_SOLANA;const hasBase = !!process.env.X402_PAY_TO_BASE;- const hasSolana = !!process.env.X402_PAY_TO_SOLANA || !!process.env.X402_PAY_TO;+ const hasSolana = hasSolanaPayTo && hasSolanaFeePayer;result.configured = hasBase || hasSolana;result.networks = [];if (hasBase) result.networks.push('base');if (hasSolana) result.networks.push('solana');+ result.warnings = [];+ if (hasSolanaPayTo && !hasSolanaFeePayer) {+ result.warnings.push(+ 'solana_fee_payer_missing: X402_PAY_TO_SOLANA is set but X402_FEE_PAYER_SOLANA is not — ' ++ 'Solana accepts are dropped, breaking Solana-only paid endpoints (club-cover, dance-tip).',+ );+ }// Probe facilitator connectivity (cached at this level, 5 min TTL)const facilitatorUrl = process.env.X402_CDP_FACILITATOR_URL || process.env.X402_FACILITATOR_URL_BASE;diff --git a/api/og/sealed-drop.js b/api/og/sealed-drop.jsnew file mode 100644index 000000000..ca14745db--- /dev/null+++ b/api/og/sealed-drop.js@@ -0,0 +1,133 @@+/**+ * GET /api/og/sealed-drop?id=<dropId>+ *+ * Dynamic Open Graph share card for a sealed wallet drop — the image that+ * previews wherever a /drop/:id link is posted (X, Telegram, Discord, iMessage,+ * Farcaster). Mirrors api/og/three-token-badge.js: a 1200×630 SVG returned with+ * image/svg+xml + a CDN cache header, no satori/canvas deps in the bundle.+ *+ * The card shows ONLY public, secret-free fields from the drop's public+ * projection: the (vanity) address, the funded amount + asset, the theme, who+ * it's from, and the sealed/E2E badge. It NEVER renders the sealed envelope, the+ * claim token, or any secret. A missing/unknown id still renders a valid,+ * branded card (a generic "sealed gift") rather than 5xx — crawlers must always+ * get an image.+ */++import { cors, wrap } from '../_lib/http.js';+import { getDrop } from '../_lib/sealed-drop-store.js';++const CACHE = 'public, max-age=60, s-maxage=600, stale-while-revalidate=120';++// three.ws brand gradient.+const C1 = '#8b5cf6';+const C2 = '#06b6d4';++// Per-theme accent + glyph, coin-agnostic.+const THEME_STYLE = {+ default: { accent: '#8b5cf6', glyph: '🎁', label: 'A sealed gift' },+ birthday: { accent: '#ff5db1', glyph: '🎂', label: 'Happy birthday' },+ congrats: { accent: '#ffb020', glyph: '🎉', label: 'Congratulations' },+ thanks: { accent: '#4ade80', glyph: '🙏', label: 'Thank you' },+ welcome: { accent: '#38bdf8', glyph: '👋', label: 'Welcome' },+ tip: { accent: '#fbbf24', glyph: '⚡', label: 'A tip for you' },+};++function x(s) {+ return String(s ?? '')+ .replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')+ .replace(/"/g, '"').replace(/'/g, ''');+}++function shortAddr(addr) {+ const s = String(addr || '');+ return s.length > 16 ? `${s.slice(0, 8)}…${s.slice(-6)}` : s;+}++function assetLabel(asset) {+ if (asset === 'THREE') return '$THREE';+ return String(asset || '');+}++function buildCard({ status, amount, asset, address, theme, senderLabel, vanity }) {+ const t = THEME_STYLE[theme] || THEME_STYLE.default;+ const claimed = status === 'claimed';+ const reclaimed = status === 'reclaimed';+ const statusLabel = claimed ? 'CLAIMED' : reclaimed ? 'RECLAIMED' : 'SEALED · UNCLAIMED';+ const statusColor = claimed ? '#4ade80' : reclaimed ? '#888' : t.accent;+ const amountStr = amount != null ? `${amount} ${assetLabel(asset)}` : 'Sealed wallet';+ const addr = shortAddr(address);+ const from = senderLabel ? `from ${senderLabel}` : 'A pre-funded wallet, sealed end-to-end';+ const vanityNote = vanity?.prefix || vanity?.suffix+ ? `vanity ${vanity.prefix ? vanity.prefix + '…' : ''}${vanity.suffix ? '…' + vanity.suffix : ''}`+ : 'end-to-end encrypted';++ return `<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630" viewBox="0 0 1200 630" role="img" aria-label="${x(t.label)} — a sealed wallet drop on three.ws">+ <defs>+ <linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">+ <stop offset="0" stop-color="#0a0a0f"/><stop offset="1" stop-color="#05050a"/>+ </linearGradient>+ <linearGradient id="brand" x1="0" y1="0" x2="1" y2="0">+ <stop offset="0" stop-color="${C1}"/><stop offset="1" stop-color="${C2}"/>+ </linearGradient>+ <radialGradient id="glow" cx="0.8" cy="0.2" r="0.9">+ <stop offset="0" stop-color="${t.accent}" stop-opacity="0.22"/>+ <stop offset="1" stop-color="${t.accent}" stop-opacity="0"/>+ </radialGradient>+ </defs>+ <rect width="1200" height="630" fill="url(#bg)"/>+ <rect width="1200" height="630" fill="url(#glow)"/>+ <rect x="0" y="0" width="1200" height="6" fill="url(#brand)"/>++ <text x="64" y="86" font-family="'Space Grotesk',Inter,system-ui,sans-serif" font-size="30" font-weight="700" fill="#fff">three.ws</text>+ <text x="64" y="86" font-family="Inter,system-ui,sans-serif" font-size="20" font-weight="600" fill="#777" dx="150">SEALED DROP</text>++ <text x="1136" y="86" text-anchor="end" font-family="Inter,system-ui,sans-serif" font-size="22" font-weight="800" letter-spacing="1" fill="${statusColor}">${x(statusLabel)}</text>++ <text x="64" y="240" font-family="Inter,system-ui,sans-serif" font-size="44">${t.glyph}</text>+ <text x="130" y="240" font-family="'Space Grotesk',Inter,system-ui,sans-serif" font-size="40" font-weight="800" fill="#fff">${x(t.label)}</text>++ <text x="64" y="360" font-family="'Space Grotesk',Inter,system-ui,sans-serif" font-size="92" font-weight="800" fill="url(#brand)">${x(amountStr)}</text>++ <text x="64" y="430" font-family="'Space Grotesk',monospace" font-size="30" font-weight="700" fill="#cbd5e1">${x(addr)}</text>+ <text x="64" y="470" font-family="Inter,system-ui,sans-serif" font-size="22" fill="#94a3b8">${x(from)}</text>++ <g>+ <rect x="64" y="520" width="430" height="54" rx="27" fill="rgba(139,92,246,0.12)" stroke="${t.accent}" stroke-opacity="0.5"/>+ <text x="92" y="555" font-family="Inter,system-ui,sans-serif" font-size="22" font-weight="700" fill="${t.accent}">🔒 ${x(vanityNote)}</text>+ </g>++ <text x="1136" y="600" text-anchor="end" font-family="Inter,system-ui,sans-serif" font-size="22" font-weight="600" fill="#64748b">three.ws/drop</text>+</svg>`;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;++ const url = new URL(req.url, `http://${req.headers.host || 'three.ws'}`);+ const id = (url.searchParams.get('id') || '').trim();++ let drop = null;+ if (/^[0-9a-f]{24}$/.test(id)) {+ try {+ drop = await getDrop(id);+ } catch {+ drop = null;+ }+ }++ const svg = buildCard({+ status: drop?.status || 'funded',+ amount: drop?.amount ?? null,+ asset: drop?.asset || null,+ address: drop?.address || null,+ theme: drop?.theme || 'default',+ senderLabel: drop?.senderLabel || null,+ vanity: drop?.vanity || null,+ });++ res.statusCode = 200;+ res.setHeader('content-type', 'image/svg+xml; charset=utf-8');+ res.setHeader('cache-control', CACHE);+ res.end(svg);+});diff --git a/api/vanity/bounties.js b/api/vanity/bounties.jsnew file mode 100644index 000000000..0722611cb--- /dev/null+++ b/api/vanity/bounties.js@@ -0,0 +1,671 @@+// /api/vanity/bounties — the x402 grind-bounty market.+//+// A decentralized, secret-blind, pay-for-results market for HARD vanity Solana+// addresses. A requester posts a pattern and escrows an x402 USDC bounty; a fleet+// of independent workers grind in parallel and race to find a matching key. The+// FIRST worker to submit a verified, sealed, pattern-matching claim is paid the+// bounty on-chain — but the found secret is sealed to the requester's X25519 key,+// so the worker earns the bounty yet never sees the wallet. If a bounty expires+// unfilled, its escrow is refunded to the requester.+//+// GET ?view=board&status=open|all|settled&sort=recency|reward|expiry → board+// GET ?view=open → claimable queue (workers poll this)+// GET ?view=stats → open count, escrowed, paid out+// GET ?view=leaderboard → top grinders by USDC earned+// GET ?view=get&id=<id> → one bounty (public view)+// GET ?view=quote&prefix=&suffix=&ignoreCase= → honest difficulty→price oracle+// GET ?view=config → payout availability + asset metadata+// POST ?action=create (x402 PAID) → fund + post a bounty. Escrow held.+// query: prefix, suffix, ignoreCase, amount(atomics), recipient(X25519),+// refundAddress(Solana), expiryHours, label+// POST ?action=claim → worker submits { bountyId, address,+// sealedSecret, workerId, payoutAddress }. Atomic single-winner+// settle + real on-chain USDC payout. Secret-blind verified server-side.+// POST ?action=refund → trigger expiry refund for an expired,+// unfilled bounty (atomic, exactly-once). body: { bountyId }.+// POST ?action=reveal → requester fetches the sealed envelope+// for a settled bounty by proving control of the X25519 key (a+// signature is not possible over X25519, so this returns the sealed+// envelope to anyone — it is useless without the private key — and+// the open happens entirely client-side).+//+// Money + key safety (see vanity-bounty-store.js + vanity-bounty-payout.js):+// • escrow is funded by a real x402 USDC payment before the bounty goes live;+// • a worker is paid ONLY after an atomic open→settled compare-and-set marks the+// bounty for that exact claim — never two workers, never a losing/unverified+// claim, never plaintext;+// • payout + refund are exactly-once (recorded tx short-circuits a re-send) and+// mutually exclusive (settle XOR refund);+// • the worker path is secret-blind by construction — the only thing it may+// submit is a sealed envelope addressed to the requester (verified server-side+// before paying); the operator never holds the plaintext key either.++import { wrap, cors, error, json, readJson, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.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 {+ PAYMENT_IDENTIFIER,+ checkCache,+ extractIdFromHeader,+ hashPaymentProof,+ hashRequestPayload,+ paymentIdentifierExtension,+ storeResponse,+ writeCachedResponse,+ writeConflict,+} from '../_lib/x402/payment-identifier-server.js';+import { withService } from '../_lib/x402/bazaar-helpers.js';+import { parseX25519Key, SEALED_ENVELOPE_SCHEME } from '../../src/solana/vanity/sealed-envelope.js';+import {+ BOUNTY_PROTOCOL_VERSION,+ normalizeBountyPattern,+ validateBountyAtomics,+ suggestBountyAtomics,+ bountyDifficulty,+ deriveBountyId,+ claimDigest,+ verifyClaimEnvelope,+ PRICING,+ USDC,+} from '../../src/solana/vanity/bounty-protocol.js';+import {+ createBounty,+ getBounty,+ getBountyRecord,+ claimBounty,+ markRefundable,+ queryBounties,+ listClaimable,+ bountyStats,+ topGrinders,+ acquireLease,+} from '../_lib/vanity-bounty-store.js';+import { payWinner, refundRequester, payoutConfigured } from '../_lib/vanity-bounty-payout.js';+import { randomSeed } from '../../src/solana/vanity/verifiable-grind.js';+import { bytesToHex } from '@noble/hashes/utils';+import bs58 from 'bs58';++const ROUTE = '/api/vanity/bounties';+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;+const PUBLIC_ORIGIN = env.APP_ORIGIN || 'https://three.ws';++// Expiry band: a bounty must live long enough for the fleet to find a hard+// pattern, but not so long that escrow is locked indefinitely.+const MIN_EXPIRY_HOURS = 1;+const MAX_EXPIRY_HOURS = 24 * 30; // 30 days+const DEFAULT_EXPIRY_HOURS = 48;++const READ_CACHE = 'public, max-age=10, s-maxage=30, stale-while-revalidate=120';++// ── x402 escrow challenge ─────────────────────────────────────────────────────++function buildEscrowRequirements(resourceUrl, priceAtomics) {+ const amount = String(priceAtomics);+ const out = [];+ if (env.X402_PAY_TO_BASE && env.X402_ASSET_ADDRESS_BASE) {+ 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 },+ };+ out.push(eip3009);+ const permit2 = permit2VariantOf(eip3009);+ if (permit2) out.push(permit2);+ }+ if (env.X402_PAY_TO_SOLANA && env.X402_FEE_PAYER_SOLANA && env.X402_ASSET_MINT_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;+}++const ESCROW_DESCRIPTION =+ 'three.ws Grind-Bounty Market — escrow a USDC bounty for a HARD Solana vanity ' ++ 'address and a fleet of independent workers grinds it in parallel. The first worker ' ++ 'to submit a verified key matching your pattern is paid automatically — but the found ' ++ 'secret is ECIES-sealed to YOUR X25519 key, so the worker earns the bounty yet never ' ++ 'sees the wallet. Unfilled bounties refund on expiry. Pay-per-post in USDC on Base or ' ++ 'Solana mainnet. Set prefix/suffix/ignoreCase, amount (USDC atomic units), recipient ' ++ '(your X25519 public key), refundAddress (Solana), expiryHours, and an optional label.';++const ESCROW_INPUT_EXAMPLE = {+ prefix: 'THREE', suffix: '', ignoreCase: '0', amount: '500000',+ recipient: '<Base58 X25519 public key>', refundAddress: '<Base58 Solana address>',+ expiryHours: '48', label: 'My agent wallet',+};++const ESCROW_INPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['amount', 'recipient'],+ properties: {+ prefix: { type: 'string', description: 'Base58 prefix the address must start with.' },+ suffix: { type: 'string', description: 'Base58 suffix the address must end with.' },+ ignoreCase: { type: 'string', enum: ['0', '1', 'true', 'false'] },+ amount: { type: 'string', description: 'Bounty in USDC atomic units (6 decimals). Min 50000 ($0.05).' },+ recipient: { type: 'string', description: 'Your 32-byte X25519 public key (Base58/Base64url/hex) — the found secret is sealed to it.' },+ refundAddress: { type: 'string', description: 'Solana address refunded if the bounty expires unfilled.' },+ expiryHours: { type: 'string', description: 'Hours until the bounty expires + refunds. 1–720, default 48.' },+ label: { type: 'string', description: 'Optional public label for the board.' },+ },+};++const ESCROW_OUTPUT_EXAMPLE = {+ posted: true,+ bounty: {+ id: 'a1b2c3d4e5f60718293a4b5c',+ protocol: BOUNTY_PROTOCOL_VERSION,+ pattern: { prefix: 'THREE', suffix: null, ignoreCase: false },+ recipient: '<Base58 X25519 public key>',+ amountAtomics: 500000, asset: 'USDC', network: 'solana',+ status: 'open', createdAt: 1750000000000, expiresAt: 1750172800000,+ difficulty: { expectedAttempts: 656356768, tier: 'epic', tierLabel: 'Epic' },+ },+ escrow: { funded: true, txHash: '<settlement tx>', payer: '<payer>' },+ boardUrl: 'https://three.ws/vanity/bounties#a1b2c3d4e5f60718293a4b5c',+};++const ESCROW_OUTPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['posted', 'bounty'],+ properties: {+ posted: { type: 'boolean' },+ bounty: { type: 'object' },+ escrow: { type: 'object' },+ boardUrl: { type: 'string', format: 'uri' },+ },+};++const ESCROW_BAZAAR = {+ discoverable: true,+ info: {+ input: { type: 'http', method: 'POST', body: ESCROW_INPUT_EXAMPLE, bodyType: 'json' },+ output: { type: 'json', example: ESCROW_OUTPUT_EXAMPLE },+ },+ schema: buildBazaarSchema({+ method: 'POST', bodyType: 'json', bodySchema: ESCROW_INPUT_SCHEMA, outputSchema: ESCROW_OUTPUT_SCHEMA,+ }),+};++// ── parse + validate a create request from query params ───────────────────────++function parseCreate(url) {+ const p = url.searchParams;+ const pattern = normalizeBountyPattern({+ prefix: p.get('prefix') || '',+ suffix: p.get('suffix') || '',+ ignoreCase: p.get('ignoreCase') === '1' || p.get('ignoreCase') === 'true',+ });++ const amountAtomics = validateBountyAtomics(p.get('amount'));++ const recipient = (p.get('recipient') || '').trim();+ if (!recipient) throw bad('recipient (your X25519 public key) is required so the found secret can be sealed to you', 'validation_error');+ const recipientCanonical = bs58X25519(recipient); // validates shape + canonicalizes to Base58++ const refundAddress = (p.get('refundAddress') || '').trim();+ if (refundAddress && !BASE58_RE.test(refundAddress)) {+ throw bad('refundAddress must be a Base58 Solana address', 'validation_error');+ }++ let expiryHours = Number(p.get('expiryHours'));+ if (!Number.isFinite(expiryHours) || expiryHours <= 0) expiryHours = DEFAULT_EXPIRY_HOURS;+ expiryHours = Math.max(MIN_EXPIRY_HOURS, Math.min(MAX_EXPIRY_HOURS, expiryHours));++ const label = (p.get('label') || '').trim().slice(0, 80) || null;++ return { pattern, amountAtomics, recipient: recipientCanonical, refundAddress: refundAddress || null, expiryHours, label };+}++// Validate + canonicalize an X25519 key to Base58 (parseX25519Key accepts+// Base58/Base64url/hex; we re-encode to Base58 so the stored recipient and the+// claim's envelope.recipient — which sealed-envelope.js also encodes as Base58 —+// compare equal regardless of the input encoding the requester used).+function bs58X25519(key) {+ const bytes = parseX25519Key(key, 'recipient'); // throws a clean 400 on bad shape+ return bs58.encode(bytes);+}++function bad(message, code) {+ return Object.assign(new Error(message), { status: 400, code: code || 'validation_error' });+}++// ── GET handlers ──────────────────────────────────────────────────────────────++async function handleGet(req, res, url) {+ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const view = (url.searchParams.get('view') || 'board').toLowerCase();++ if (view === 'quote') {+ const pattern = normalizeBountyPattern({+ prefix: url.searchParams.get('prefix') || '',+ suffix: url.searchParams.get('suffix') || '',+ ignoreCase: url.searchParams.get('ignoreCase') === '1' || url.searchParams.get('ignoreCase') === 'true',+ });+ const oracle = suggestBountyAtomics(pattern);+ return json(res, 200, {+ pattern: { prefix: pattern.prefix || null, suffix: pattern.suffix || null, ignoreCase: pattern.ignoreCase },+ difficulty: bountyDifficulty(pattern),+ oracle,+ band: { floorAtomics: PRICING.floorAtomics, maxAtomics: PRICING.maxAtomics, decimals: 6, asset: 'USDC' },+ }, { 'cache-control': READ_CACHE });+ }++ if (view === 'config') {+ return json(res, 200, {+ payoutConfigured: payoutConfigured(),+ asset: 'USDC',+ decimals: 6,+ networks: escrowNetworks(),+ band: { floorAtomics: PRICING.floorAtomics, maxAtomics: PRICING.maxAtomics },+ protocol: BOUNTY_PROTOCOL_VERSION,+ sealedScheme: SEALED_ENVELOPE_SCHEME,+ }, { 'cache-control': READ_CACHE });+ }++ if (view === 'get') {+ const id = (url.searchParams.get('id') || '').trim();+ if (!/^[0-9a-f]{8,32}$/.test(id)) return error(res, 400, 'validation_error', 'id must be a hex bounty id');+ const bounty = await getBounty(id);+ if (!bounty) return error(res, 404, 'not_found', 'no bounty with that id');+ return json(res, 200, { bounty }, { 'cache-control': READ_CACHE });+ }++ if (view === 'open') {+ const limit = Number(url.searchParams.get('limit')) || 30;+ const bounties = await listClaimable(limit);+ return json(res, 200, { bounties, count: bounties.length }, { 'cache-control': 'no-store' });+ }++ if (view === 'stats') {+ const stats = await bountyStats();+ return json(res, 200, stats, { 'cache-control': READ_CACHE });+ }++ if (view === 'leaderboard') {+ const limit = Number(url.searchParams.get('limit')) || 10;+ const grinders = await topGrinders(limit);+ return json(res, 200, { grinders, count: grinders.length }, { 'cache-control': READ_CACHE });+ }++ // Default: paginated board.+ const status = (url.searchParams.get('status') || 'open').toLowerCase();+ const sort = (url.searchParams.get('sort') || 'recency').toLowerCase();+ const limit = Number(url.searchParams.get('limit')) || 24;+ const offset = Number(url.searchParams.get('offset')) || 0;+ const result = await queryBounties({ status, sort, limit, offset });+ return json(res, 200, { ...result, status, sort }, { 'cache-control': READ_CACHE });+}++function escrowNetworks() {+ const nets = [];+ if (env.X402_PAY_TO_BASE && env.X402_ASSET_ADDRESS_BASE) nets.push('base');+ if (env.X402_PAY_TO_SOLANA && env.X402_FEE_PAYER_SOLANA && env.X402_ASSET_MINT_SOLANA) nets.push('solana');+ return nets;+}++// ── POST: create (x402-escrowed) ──────────────────────────────────────────────++async function handleCreate(req, res, url) {+ let parsed;+ try {+ parsed = parseCreate(url);+ } catch (err) {+ return error(res, err.status || 400, err.code || 'validation_error', err.message);+ }++ // Without a payout wallet the platform can neither pay a winner nor refund —+ // refuse to take escrow it couldn't return. Fail BEFORE the payment challenge.+ if (!payoutConfigured()) {+ return error(res, 503, 'payout_unconfigured', 'the bounty market payout wallet is not configured — posting is temporarily unavailable');+ }++ const resourceUrl = resolveResourceUrl(req, ROUTE);+ const priceAtomics = parsed.amountAtomics;+ const requirements = buildEscrowRequirements(resourceUrl, priceAtomics);+ if (!requirements.length) {+ return error(res, 503, 'escrow_unconfigured', 'no x402 escrow network is configured (X402_PAY_TO_*)');+ }++ const service = withService({+ serviceName: 'three.ws Grind-Bounty Market',+ tags: ['solana', 'vanity', 'bounty', 'escrow', 'sealed', 'x402'],+ });+ const challenge = {+ resourceUrl,+ accepts: requirements,+ description: ESCROW_DESCRIPTION,+ bazaar: ESCROW_BAZAAR,+ extensions: { [PAYMENT_IDENTIFIER]: paymentIdentifierExtension(false) },+ serviceName: service.serviceName,+ tags: service.tags,+ iconUrl: service.iconUrl,+ };++ const paymentHeader = req.headers['x-payment'] || req.headers['payment-signature'];+ if (!paymentHeader) return send402(res, challenge);++ // Idempotency: a retried POST with the same payment proof returns the same+ // stored bounty rather than escrowing twice.+ const clientPaymentId = extractIdFromHeader(paymentHeader);+ const payloadHash = hashRequestPayload({ method: 'POST', 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);+ }++ // Build + persist the bounty record AFTER verify but BEFORE settle, so a store+ // failure throws before the requester is charged.+ const nonce = bytesToHex(randomSeed());+ const id = deriveBountyId({ recipient: parsed.recipient, pattern: parsed.pattern, amountAtomics: parsed.amountAtomics, nonce });+ const now = Date.now();+ const record = {+ id,+ protocol: BOUNTY_PROTOCOL_VERSION,+ pattern: { prefix: parsed.pattern.prefix || null, suffix: parsed.pattern.suffix || null, ignoreCase: parsed.pattern.ignoreCase },+ recipient: parsed.recipient,+ refundAddress: parsed.refundAddress,+ amountAtomics: parsed.amountAtomics,+ asset: 'USDC',+ network: verified.requirement?.network === NETWORK_SOLANA_MAINNET ? 'solana' : 'base',+ difficulty: bountyDifficulty(parsed.pattern),+ label: parsed.label,+ nonce,+ createdAt: now,+ expiresAt: now + parsed.expiryHours * 3600_000,+ // Escrow audit trail — proves the requester funded it. Not exposed publicly.+ escrowPayer: verified.payer || null,+ };++ let stored;+ try {+ stored = await createBounty(record);+ } catch (err) {+ return error(res, err.status || 500, err.code || 'store_failed', err.message);+ }++ // Settle the escrow payment on-chain. If settle fails we still hold the bounty+ // record but mark escrow unfunded — the requester can retry the same payment+ // (idempotent). We surface the settle error so they know to retry.+ 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 body = JSON.stringify({+ posted: true,+ bounty: await getBounty(id),+ escrow: { funded: true, txHash: settled.transaction || null, payer: settled.payer || verified.payer || null, network: settled.network || null },+ boardUrl: `${PUBLIC_ORIGIN}/vanity/bounties#${id}`,+ notice: 'Save your X25519 PRIVATE key — it is the ONLY way to open the sealed wallet when a worker finds it. three.ws never sees it.',+ });+ const contentType = 'application/json; charset=utf-8';++ res.setHeader('x-payment-response', paymentResponseHeader);+ res.setHeader('cache-control', 'no-store');+ res.setHeader('content-type', contentType);+ res.statusCode = 201;+ res.end(body);++ if (paymentId) {+ await storeResponse({ route: ROUTE, paymentId, payloadHash, paymentHash, status: 201, body, contentType, paymentResponseHeader });+ }+}++// ── POST: claim (worker submits a sealed key; atomic settle + payout) ─────────++async function handleClaim(req, res) {+ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ let body;+ try {+ body = await readJson(req);+ } catch (err) {+ return error(res, err.status || 400, 'validation_error', err.message || 'invalid JSON body');+ }++ const bountyId = String(body?.bountyId || '').trim();+ const address = String(body?.address || '').trim();+ const sealedSecret = body?.sealedSecret;+ const workerId = sanitizeWorkerId(body?.workerId);+ const payoutAddress = String(body?.payoutAddress || '').trim();++ if (!/^[0-9a-f]{8,32}$/.test(bountyId)) return error(res, 400, 'validation_error', 'bountyId must be a hex bounty id');+ if (!BASE58_RE.test(payoutAddress)) return error(res, 400, 'validation_error', 'payoutAddress must be a Base58 Solana address to receive the bounty');++ const record = await getBountyRecord(bountyId);+ if (!record) return error(res, 404, 'not_found', 'no bounty with that id');++ // Reject fast on a closed/expired bounty before doing crypto work.+ if (record.status !== 'open') {+ return json(res, 409, { claimed: false, status: record.status, reason: `bounty is ${record.status} — too late`, winnerAddress: record.winnerAddress || null });+ }+ if (record.expiresAt && Date.now() > record.expiresAt) {+ return json(res, 409, { claimed: false, status: 'expired', reason: 'bounty expired before this claim' });+ }++ // Secret-blind anti-cheat: verify the address matches the pattern AND the+ // sealed envelope is addressed to the requester — WITHOUT ever decrypting it.+ const verification = verifyClaimEnvelope(record, { address, sealedSecret });+ if (!verification.ok) {+ const failed = verification.checks.filter((c) => !c.pass).map((c) => c.id);+ return error(res, 422, 'claim_rejected', `claim failed verification (${failed.join(', ')}): ${verification.reason}`, { checks: verification.checks });+ }++ // Atomic single-winner settle. First valid claim wins; later ones lose.+ const digest = claimDigest({ bountyId, address, sealedSecret });+ let outcome;+ try {+ outcome = await claimBounty({ id: bountyId, claimDigest: digest, winnerAddress: address, workerId, sealedSecret });+ } catch (err) {+ return error(res, err.status || 500, err.code || 'claim_failed', err.message);+ }++ if (outcome === 'missing') return error(res, 404, 'not_found', 'bounty disappeared during claim');+ if (outcome === 'closed') {+ return json(res, 409, { claimed: false, status: 'closed', reason: 'bounty closed/expired during claim' });+ }+ if (outcome === 'lost') {+ const fresh = await getBounty(bountyId);+ return json(res, 409, { claimed: false, status: 'settled', reason: 'another worker submitted a valid key first', winnerAddress: fresh?.winnerAddress || null });+ }++ // outcome === 'won' (or an idempotent re-submit of the same winning claim).+ // Pay the worker on-chain. Payout is idempotent: a retried winning claim that+ // already has a payoutTx returns it without re-sending.+ let payout;+ try {+ payout = await payWinner({ id: bountyId, toAddress: payoutAddress });+ } catch (err) {+ // The bounty is settled to this worker, but payout failed (RPC hiccup,+ // unfunded wallet). The worker can re-submit the SAME claim to retry payout+ // without re-racing — the atomic claim already locked them in as the winner.+ return json(res, 502, {+ claimed: true,+ paid: false,+ status: 'settled',+ reason: `you won the bounty, but the on-chain payout failed: ${err.message}. Re-submit this exact claim to retry the payout.`,+ retryable: true,+ });+ }++ const fresh = await getBounty(bountyId);+ return json(res, 200, {+ claimed: true,+ paid: true,+ status: 'settled',+ bountyId,+ address,+ amountAtomics: payout.amountAtomics,+ amountUsdc: (payout.amountAtomics / USDC).toFixed(6),+ payoutTx: payout.payoutTx,+ alreadyPaid: payout.alreadyPaid,+ explorerUrl: `https://solscan.io/tx/${payout.payoutTx}`,+ bounty: fresh,+ notice: 'You earned the bounty without ever seeing the wallet secret — it is sealed to the requester. The requester opens it with their X25519 private key.',+ });+}++// ── POST: refund (expiry refund for an unfilled bounty) ───────────────────────++async function handleRefund(req, res) {+ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ let body;+ try {+ body = await readJson(req);+ } catch (err) {+ return error(res, err.status || 400, 'validation_error', err.message || 'invalid JSON body');+ }+ const bountyId = String(body?.bountyId || '').trim();+ const toAddress = String(body?.refundAddress || '').trim();+ if (!/^[0-9a-f]{8,32}$/.test(bountyId)) return error(res, 400, 'validation_error', 'bountyId must be a hex bounty id');++ const record = await getBountyRecord(bountyId);+ if (!record) return error(res, 404, 'not_found', 'no bounty with that id');++ // Atomic open→refunded compare-and-set, only for EXPIRED bounties. Mutually+ // exclusive with settlement — a settled bounty can never be refunded.+ const eligibility = await markRefundable(bountyId);+ if (eligibility === 'missing') return error(res, 404, 'not_found', 'bounty disappeared');+ if (eligibility === 'ineligible') {+ const fresh = await getBounty(bountyId);+ const why = fresh?.status === 'settled' ? 'bounty was already won — no refund' : 'bounty has not expired yet';+ return json(res, 409, { refunded: false, status: fresh?.status, reason: why });+ }++ // Refund destination: the body-supplied address, else the one set at post time.+ const refundTo = toAddress || record.refundAddress;+ if (!refundTo || !BASE58_RE.test(refundTo)) {+ return error(res, 400, 'no_refund_address', 'no refund address: supply refundAddress, or set one when posting the bounty');+ }++ let refund;+ try {+ refund = await refundRequester({ id: bountyId, toAddress: refundTo });+ } catch (err) {+ return json(res, 502, { refunded: false, status: 'refunded', reason: `refund payout failed: ${err.message}. Retry to complete the refund.`, retryable: true });+ }++ return json(res, 200, {+ refunded: true,+ bountyId,+ amountAtomics: refund.amountAtomics,+ amountUsdc: (refund.amountAtomics / USDC).toFixed(6),+ refundTx: refund.refundTx,+ alreadyRefunded: refund.alreadyRefunded,+ explorerUrl: `https://solscan.io/tx/${refund.refundTx}`,+ refundAddress: refundTo,+ });+}++// ── POST: reveal (requester fetches the sealed envelope of a settled bounty) ──++async function handleReveal(req, res) {+ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ let body;+ try {+ body = await readJson(req);+ } catch (err) {+ return error(res, err.status || 400, 'validation_error', err.message || 'invalid JSON body');+ }+ const bountyId = String(body?.bountyId || '').trim();+ if (!/^[0-9a-f]{8,32}$/.test(bountyId)) return error(res, 400, 'validation_error', 'bountyId must be a hex bounty id');++ const record = await getBountyRecord(bountyId);+ if (!record) return error(res, 404, 'not_found', 'no bounty with that id');+ if (record.status !== 'settled' || !record.sealedSecret) {+ return json(res, 409, { revealed: false, status: record.status, reason: 'bounty is not settled yet — no sealed wallet to reveal' });+ }++ // The sealed envelope is useless without the requester's X25519 PRIVATE key —+ // it is ECIES ciphertext addressed to `record.recipient`. Returning it to any+ // caller leaks nothing: only the private-key holder can open it. The open+ // happens entirely client-side (openSealed), so the operator never sees the key.+ return json(res, 200, {+ revealed: true,+ bountyId,+ address: record.winnerAddress,+ recipient: record.recipient,+ sealedSecret: record.sealedSecret,+ sealedScheme: SEALED_ENVELOPE_SCHEME,+ settledAt: record.settledAt,+ explorerUrl: `https://solscan.io/account/${record.winnerAddress}`,+ notice: 'Open this envelope client-side with your X25519 private key (openSealed). three.ws cannot — it never held your private key.',+ });+}++function sanitizeWorkerId(raw) {+ const s = String(raw || '').trim();+ if (!s) return 'anon';+ // Keep it short + safe for a Redis member + leaderboard label.+ return s.replace(/[^A-Za-z0-9_.:-]/g, '').slice(0, 48) || 'anon';+}++// ── dispatch ──────────────────────────────────────────────────────────────────++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: '*' })) return;+ const url = new URL(req.url, `http://${req.headers.host || 'three.ws'}`);++ if (req.method === 'GET') return handleGet(req, res, url);++ if (req.method === 'POST') {+ const action = (url.searchParams.get('action') || 'create').toLowerCase();+ if (action === 'create') return handleCreate(req, res, url);+ if (action === 'claim') return handleClaim(req, res);+ if (action === 'refund') return handleRefund(req, res);+ if (action === 'reveal') return handleReveal(req, res);+ return error(res, 400, 'unknown_action', 'action must be create, claim, refund, or reveal');+ }++ res.setHeader('allow', 'GET, POST, OPTIONS');+ return error(res, 405, 'method_not_allowed', 'use GET or POST');+});diff --git a/api/vanity/drops.js b/api/vanity/drops.jsnew file mode 100644index 000000000..0511b3686--- /dev/null+++ b/api/vanity/drops.js@@ -0,0 +1,901 @@+// /api/vanity/drops — sealed wallet drops (end-to-end-encrypted crypto gifting).+//+// A "drop" is a pre-funded Solana wallet handed to a recipient as an E2E-encrypted+// gift, claimable by link / QR / 3D agent. The wallet secret is ECIES-sealed so+// neither the operator, the database, a log, nor anyone but the holder of the+// matching X25519 key can open it. Funding is real on-chain (SOL / USDC / $THREE).+// The create step is x402-paid. Claims are exactly-once; expired unclaimed drops+// are reclaimed by the sender on-chain.+//+// GET ?view=config → assets, networks, funding availability, limits+// GET ?view=get&id=<id> → one drop (public view; no secret, no envelope)+// GET ?view=stats → funded / claimed / reclaimed counts+// GET ?view=mine&senderTag=<tag> → a sender's drops (to reclaim)+// GET ?view=balance&id=<id> → live on-chain balance of the drop address+//+// POST ?action=create (x402 PAID) → grind (optional vanity) + seal + fund + persist.+// body: { asset, amount, sealMode:'direct'|'claim-time', recipientPubKey?,+// claimTokenHash? (claim-time), prefix?, suffix?, ignoreCase?,+// format?, expiryHours, message?, theme?, senderLabel?, reclaimAddress?,+// senderTag?, irlPinId?, roomId? }+// POST ?action=claim → present the one-time claim token, atomically+// claim, and receive the SEALED envelope to open client-side.+// body: { id, claimToken (claim-time mode), claimRecipientPubKey? }+// POST ?action=reveal → direct-seal mode: fetch the sealed envelope+// (useless without the recipient's private key) for client-side open.+// body: { id }+// POST ?action=reclaim → sender sweeps an EXPIRED, unclaimed drop's+// funds back on-chain (atomic, exactly-once). body: { id, reclaimAddress? }+//+// Money + key safety (see sealed-drop-store.js + sealed-drop-funding.js ++// src/solana/vanity/drop-protocol.js):+// • The plaintext drop secret NEVER appears in a response, a log, or an+// unsealed store field. It is sealed (ECIES) for delivery and held only as an+// AES-256-GCM ciphertext at rest for the reclaim-sweep path.+// • Funding is confirmed on-chain BEFORE the drop is persisted as claimable.+// • A drop is claimed EXACTLY ONCE (atomic CAS, idempotent on the claim token)+// OR reclaimed by the sender after expiry — never both.+// • $THREE is the only coin featured as *a coin*; SOL/USDC are runtime rails.++import { wrap, cors, error, json, readJson, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.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 {+ PAYMENT_IDENTIFIER,+ checkCache,+ extractIdFromHeader,+ hashPaymentProof,+ hashRequestPayload,+ paymentIdentifierExtension,+ storeResponse,+ writeCachedResponse,+ writeConflict,+} from '../_lib/x402/payment-identifier-server.js';+import { withService } from '../_lib/x402/bazaar-helpers.js';+import {+ sealToRecipient,+ parseX25519Key,+ SEALED_ENVELOPE_SCHEME,+} from '../../src/solana/vanity/sealed-envelope.js';+import {+ grindVanityNode,+ validatePattern,+ MAX_SERVER_PATTERN_LENGTH,+} from '../../src/solana/vanity/grinder-node.js';+import { grindVanityMnemonic, MAX_MNEMONIC_PATTERN_LENGTH } from '../../src/solana/vanity/mnemonic-grinder.js';+import { STRENGTH_WORD_COUNTS, DEFAULT_STRENGTH } from '../../src/solana/vanity/mnemonic.js';+import {+ DROP_PROTOCOL_VERSION,+ deriveDropId,+ hashClaimToken,+ timingSafeHexEqual,+ isValidDropId,+ normalizeAsset,+ SEAL_MODES,+} from '../../src/solana/vanity/drop-protocol.js';+import {+ createDrop,+ getDrop,+ getDropRecord,+ claimDrop,+ markReclaimable,+ recordClaimDelivery,+ listBySender,+ dropStats,+} from '../_lib/sealed-drop-store.js';+import {+ fundingConfigured,+ fundDropAddress,+ readDropBalance,+ sweepReclaim,+ amountToAtomics,+ atomicsToAmount,+} from '../_lib/sealed-drop-funding.js';+import { encryptSecret, decryptSecret } from '../_lib/secret-box.js';+import { randomBytes as nobleRandomBytes, bytesToHex } from '@noble/hashes/utils';+import bs58 from 'bs58';+import { Keypair } from '@solana/web3.js';++const ROUTE = '/api/vanity/drops';+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;+const PUBLIC_ORIGIN = env.APP_ORIGIN || 'https://three.ws';++const MIN_EXPIRY_HOURS = 1;+const MAX_EXPIRY_HOURS = 24 * 90; // 90 days+const DEFAULT_EXPIRY_HOURS = 24 * 7; // a week+const READ_CACHE = 'public, max-age=10, s-maxage=30, stale-while-revalidate=120';++// Curate the themes the share card + claim page render. Coin-agnostic visuals.+const THEMES = new Set(['default', 'birthday', 'congrats', 'thanks', 'welcome', 'tip']);++// Flat x402 create FEE (USDC atomics, 6dp). This is the platform charge for the+// create operation — independent of the funding amount, which the platform moves+// from its own funding wallet (a gift the creator arranges out-of-band or via the+// funding wallet top-up). Vanity grinding adds nothing extra at ≤3 chars.+const CREATE_FEE_ATOMICS = 50_000; // $0.05++// ── x402 challenge ────────────────────────────────────────────────────────────++function buildRequirements(resourceUrl, priceAtomics) {+ const amount = String(priceAtomics);+ const out = [];+ if (env.X402_PAY_TO_BASE && env.X402_ASSET_ADDRESS_BASE) {+ 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 },+ };+ out.push(eip3009);+ const permit2 = permit2VariantOf(eip3009);+ if (permit2) out.push(permit2);+ }+ if (env.X402_PAY_TO_SOLANA && env.X402_FEE_PAYER_SOLANA && env.X402_ASSET_MINT_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;+}++const CREATE_DESCRIPTION =+ 'three.ws Sealed Wallet Drops — mint a pre-funded Solana wallet and deliver it as an ' ++ 'end-to-end-encrypted gift, claimable by link / QR / 3D agent. The wallet secret is ' ++ 'ECIES-sealed (x25519-hkdf-sha256-aes256gcm) so neither three.ws, our database, nor ' ++ 'anyone but the recipient can open it. Fund it with SOL, USDC, or $THREE (real on-chain ' ++ 'transfer, confirmed before the drop goes live). Optional vanity prefix/suffix. Two seal ' ++ 'modes: direct (seal to a known X25519 recipient key) or claim-time (a bearer link whose ' ++ 'fragment carries the claim key the server never sees). Exactly-once claim; expired drops ' ++ 'reclaim to the sender. Pay the flat create fee in USDC on Base or Solana mainnet.';++const CREATE_INPUT_EXAMPLE = {+ asset: 'SOL', amount: '0.01', sealMode: 'claim-time',+ prefix: 'gift', expiryHours: '168', message: 'Happy birthday!', theme: 'birthday',+ senderLabel: 'Alex', reclaimAddress: '<Base58 Solana address>',+};++const CREATE_INPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['asset', 'amount', 'sealMode'],+ properties: {+ asset: { type: 'string', enum: ['SOL', 'USDC', 'THREE'], description: 'Funding asset. $THREE is the platform coin; SOL/USDC are rails.' },+ amount: { type: 'string', description: 'Funding amount as a decimal (e.g. "0.01"). Moved on-chain into the drop wallet.' },+ sealMode: { type: 'string', enum: ['direct', 'claim-time'], description: 'direct = seal to recipientPubKey now; claim-time = bearer link, the server mints a claim key and returns its secret once (you embed it in the link fragment).' },+ recipientPubKey: { type: 'string', description: 'direct mode: the recipient X25519 public key the secret is sealed to.' },+ prefix: { type: 'string', description: 'Optional Base58 vanity prefix (≤3 chars combined).' },+ suffix: { type: 'string', description: 'Optional Base58 vanity suffix (≤3 chars combined).' },+ ignoreCase: { type: 'string', enum: ['0', '1', 'true', 'false'] },+ format: { type: 'string', enum: ['keypair', 'mnemonic'], description: 'mnemonic delivers an importable seed phrase (≤2 vanity chars).' },+ expiryHours: { type: 'string', description: 'Hours until the drop expires + becomes reclaimable. 1–2160, default 168.' },+ message: { type: 'string', description: 'Optional gift message (≤280 chars).' },+ theme: { type: 'string', description: 'Optional card theme: default|birthday|congrats|thanks|welcome|tip.' },+ senderLabel: { type: 'string', description: 'Optional public "from" label (≤40 chars).' },+ reclaimAddress: { type: 'string', description: 'Solana address the funds reclaim to if the drop expires unclaimed.' },+ senderTag: { type: 'string', description: 'Optional opaque tag to list your drops later (non-PII).' },+ irlPinId: { type: 'string', description: 'Optional IRL pin id this drop is attached to (3D-agent handoff).' },+ roomId: { type: 'string', description: 'Optional room id a 3D agent hands the drop out in.' },+ },+};++const CREATE_OUTPUT_EXAMPLE = {+ created: true,+ drop: {+ id: 'a1b2c3d4e5f607182930a1b2',+ address: 'giftEXAMPLE1111111111111111111111111111111',+ asset: 'SOL', amount: '0.01', sealMode: 'claim-time', status: 'funded',+ expiresAt: 1750172800000, theme: 'birthday',+ },+ funding: { confirmed: true, tx: '<funding tx>', explorerUrl: 'https://solscan.io/tx/...' },+ claimUrl: 'https://three.ws/drop/a1b2c3d4e5f607182930a1b2',+ qrUrl: 'https://three.ws/api/vanity/drops?view=qr&id=a1b2c3d4e5f607182930a1b2',+ ogUrl: 'https://three.ws/api/og/sealed-drop?id=a1b2c3d4e5f607182930a1b2',+};++const CREATE_OUTPUT_SCHEMA = {+ $schema: 'https://json-schema.org/draft/2020-12/schema',+ type: 'object',+ required: ['created', 'drop'],+ properties: {+ created: { type: 'boolean' },+ drop: { type: 'object' },+ funding: { type: 'object' },+ claimUrl: { type: 'string', format: 'uri' },+ qrUrl: { type: 'string', format: 'uri' },+ ogUrl: { type: 'string', format: 'uri' },+ },+};++const CREATE_BAZAAR = {+ discoverable: true,+ info: {+ input: { type: 'http', method: 'POST', body: CREATE_INPUT_EXAMPLE, bodyType: 'json' },+ output: { type: 'json', example: CREATE_OUTPUT_EXAMPLE },+ },+ schema: buildBazaarSchema({+ method: 'POST', bodyType: 'json', bodySchema: CREATE_INPUT_SCHEMA, outputSchema: CREATE_OUTPUT_SCHEMA,+ }),+};++function bad(message, code) {+ return Object.assign(new Error(message), { status: 400, code: code || 'validation_error' });+}++function activeNetworks() {+ const nets = [];+ if (env.X402_PAY_TO_BASE && env.X402_ASSET_ADDRESS_BASE) nets.push('base');+ if (env.X402_PAY_TO_SOLANA && env.X402_FEE_PAYER_SOLANA && env.X402_ASSET_MINT_SOLANA) nets.push('solana');+ return nets;+}++// ── parse + validate a create request body ────────────────────────────────────++function parseCreate(body) {+ const asset = normalizeAsset(body?.asset);+ const amount = String(body?.amount ?? '').trim();+ if (!amount) throw bad('amount is required (decimal, e.g. "0.01")');+ const atomics = amountToAtomics(amount, asset); // validates shape/decimals++ const sealMode = String(body?.sealMode || '').trim();+ if (!SEAL_MODES.includes(sealMode)) {+ throw bad(`sealMode must be one of ${SEAL_MODES.join(', ')}`, 'invalid_seal_mode');+ }++ // In direct mode the sender supplies the recipient's X25519 public key. In+ // claim-time mode the server mints the claim key itself (returned once in the+ // response, embedded by the creator in the link fragment) — no client input.+ let recipientPubKey = null;+ if (sealMode === 'direct') {+ recipientPubKey = String(body?.recipientPubKey || '').trim();+ if (!recipientPubKey) throw bad('direct seal mode requires recipientPubKey (X25519 public key)', 'recipient_required');+ recipientPubKey = bs58.encode(parseX25519Key(recipientPubKey, 'recipientPubKey')); // validate + canonicalize+ }++ // Optional vanity pattern.+ const prefix = typeof body?.prefix === 'string' ? body.prefix.trim() : '';+ const suffix = typeof body?.suffix === 'string' ? body.suffix.trim() : '';+ const ignoreCase = body?.ignoreCase === '1' || body?.ignoreCase === 'true' || body?.ignoreCase === true;+ const format = String(body?.format || 'keypair').toLowerCase();+ if (format !== 'keypair' && format !== 'mnemonic') throw bad('format must be keypair or mnemonic', 'invalid_format');+ let strength = DEFAULT_STRENGTH;+ if (body?.strength != null && body?.strength !== '') {+ strength = Number(body.strength);+ if (!STRENGTH_WORD_COUNTS[strength]) throw bad('strength must be 128 or 256', 'invalid_strength');+ }+ for (const [label, pat] of [['prefix', prefix], ['suffix', suffix]]) {+ if (!pat) continue;+ const v = validatePattern(pat);+ if (!v.valid) throw bad(`invalid ${label}: ${v.errors.join('; ')}`);+ }+ const maxLen = format === 'mnemonic' ? MAX_MNEMONIC_PATTERN_LENGTH : MAX_SERVER_PATTERN_LENGTH;+ if (prefix.length + suffix.length > maxLen) {+ throw Object.assign(new Error(`combined vanity pattern exceeds the ${format} server limit of ${maxLen} chars`), { status: 400, code: 'pattern_too_long' });+ }++ let expiryHours = Number(body?.expiryHours);+ if (!Number.isFinite(expiryHours) || expiryHours <= 0) expiryHours = DEFAULT_EXPIRY_HOURS;+ expiryHours = Math.max(MIN_EXPIRY_HOURS, Math.min(MAX_EXPIRY_HOURS, expiryHours));++ const message = String(body?.message || '').trim().slice(0, 280) || null;+ const theme = THEMES.has(String(body?.theme || '').trim()) ? String(body.theme).trim() : 'default';+ const senderLabel = String(body?.senderLabel || '').trim().slice(0, 40) || null;++ const reclaimAddress = String(body?.reclaimAddress || '').trim();+ if (reclaimAddress && !BASE58_RE.test(reclaimAddress)) throw bad('reclaimAddress must be a Base58 Solana address');++ const senderTag = sanitizeTag(body?.senderTag);+ const irlPinId = String(body?.irlPinId || '').trim().slice(0, 64) || null;+ const roomId = String(body?.roomId || '').trim().slice(0, 64) || null;++ return {+ asset, amount, atomics, sealMode, recipientPubKey,+ prefix, suffix, ignoreCase, format, strength,+ expiryHours, message, theme, senderLabel, reclaimAddress: reclaimAddress || null,+ senderTag, irlPinId, roomId,+ };+}++function sanitizeTag(raw) {+ const s = String(raw || '').trim();+ if (!s) return null;+ return s.replace(/[^A-Za-z0-9_.:-]/g, '').slice(0, 64) || null;+}++// Grind (or generate) the drop wallet. Returns { address, secretBundle, vanity }.+// secretBundle is the JSON that gets BOTH sealed (for delivery) and encrypted at+// rest (for reclaim). The plaintext never leaves this function.+function generateDropWallet({ prefix, suffix, ignoreCase, format, strength }) {+ const wantsVanity = prefix || suffix;+ if (format === 'mnemonic') {+ const r = grindVanityMnemonic({ prefix, suffix, ignoreCase, strength, timeBudgetMs: 45_000 });+ return {+ address: r.publicKey,+ vanity: wantsVanity ? { prefix: prefix || null, suffix: suffix || null, ignoreCase } : null,+ secretBundle: {+ format: 'mnemonic',+ mnemonic: r.mnemonic,+ wordCount: r.wordCount,+ derivationPath: r.derivationPath,+ secretKeyBase58: bs58.encode(r.secretKey),+ secretKey: Array.from(r.secretKey),+ },+ secretKeyBytes: r.secretKey,+ };+ }+ if (wantsVanity) {+ const r = grindVanityNode({ prefix, suffix, ignoreCase, timeBudgetMs: 45_000 });+ return {+ address: r.publicKey,+ vanity: { prefix: prefix || null, suffix: suffix || null, ignoreCase },+ secretBundle: { format: 'keypair', secretKeyBase58: bs58.encode(r.secretKey), secretKey: Array.from(r.secretKey) },+ secretKeyBytes: r.secretKey,+ };+ }+ // No vanity pattern → a plain fresh keypair (free of grind time).+ const kp = Keypair.generate();+ return {+ address: kp.publicKey.toBase58(),+ vanity: null,+ secretBundle: { format: 'keypair', secretKeyBase58: bs58.encode(kp.secretKey), secretKey: Array.from(kp.secretKey) },+ secretKeyBytes: kp.secretKey,+ };+}++// ── POST: create (x402-paid → grind → seal → fund → persist) ─────────────────++async function handleCreate(req, res, url) {+ let body;+ try {+ body = await readJson(req);+ } catch (err) {+ return error(res, err.status || 400, 'validation_error', err.message || 'invalid JSON body');+ }++ let parsed;+ try {+ parsed = parseCreate(body);+ } catch (err) {+ return error(res, err.status || 400, err.code || 'validation_error', err.message);+ }++ // Without a funding wallet the platform can't fund or reclaim — refuse before+ // charging the create fee.+ if (!fundingConfigured()) {+ return error(res, 503, 'funding_unconfigured', 'the drop funding wallet is not configured — drops are temporarily unavailable');+ }++ const resourceUrl = resolveResourceUrl(req, ROUTE);+ const requirements = buildRequirements(resourceUrl, CREATE_FEE_ATOMICS);+ if (!requirements.length) {+ return error(res, 503, 'payment_unconfigured', 'no x402 network is configured (X402_PAY_TO_*)');+ }++ const service = withService({+ serviceName: 'three.ws Sealed Wallet Drops',+ tags: ['solana', 'vanity', 'gift', 'sealed', 'e2e', 'x402', 'drop'],+ });+ const challenge = {+ resourceUrl,+ accepts: requirements,+ description: CREATE_DESCRIPTION,+ bazaar: CREATE_BAZAAR,+ extensions: { [PAYMENT_IDENTIFIER]: paymentIdentifierExtension(false) },+ serviceName: service.serviceName,+ tags: service.tags,+ iconUrl: service.iconUrl,+ };++ const paymentHeader = req.headers['x-payment'] || req.headers['payment-signature'];+ if (!paymentHeader) return send402(res, challenge);++ // Idempotency: a retried create with the same payment proof returns the same+ // stored drop instead of grinding + funding twice.+ const clientPaymentId = extractIdFromHeader(paymentHeader);+ const payloadHash = hashRequestPayload({ method: 'POST', url: req.url, body: JSON.stringify(body) });+ 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 + seal + fund AFTER verify but BEFORE settle, so any failure (bad+ // pattern, RPC outage, insufficient funding balance) aborts with the fee+ // unsettled — the buyer is never charged for a drop that didn't get funded.+ let wallet;+ try {+ wallet = generateDropWallet(parsed);+ } catch (err) {+ return error(res, err.status || 500, err.code || 'grind_failed', err.message);+ }++ // Seal the secret bundle for delivery (operator-blind).+ // • direct mode: seal to the recipient's known X25519 public key.+ // • claim-time mode: generate a throwaway claim keypair, seal to its PUBLIC+ // key, hand the SECRET back to the creator exactly once (it goes into the+ // link fragment #k=…, never stored). The server then derives + stores only+ // the one-way claimTokenHash from that secret and discards the secret, so+ // it can verify a claimant's possession without being able to open the+ // wallet. (A client-sent claimTokenHash is ignored in this mode — the+ // claim key is server-generated, so the canonical hash is the server's.)+ let sealRecipientPub;+ let claimSecretForSender = null; // returned ONCE to the creator in claim-time mode+ if (parsed.sealMode === 'direct') {+ sealRecipientPub = parsed.recipientPubKey;+ } else {+ const claimSecret = nobleRandomBytes(32);+ const { x25519 } = await import('@noble/curves/ed25519.js');+ sealRecipientPub = bs58.encode(x25519.getPublicKey(claimSecret));+ claimSecretForSender = bs58.encode(claimSecret);+ parsed._claimSecretBytes = claimSecret;+ }++ let sealedSecret;+ try {+ sealedSecret = await sealToRecipient(JSON.stringify(wallet.secretBundle), sealRecipientPub);+ } catch (err) {+ return error(res, err.status || 500, err.code || 'seal_failed', err.message);+ }++ // Encrypt the SAME plaintext at rest ONLY for the reclaim-sweep path (so the+ // platform can refund an expired, unclaimed drop). This never weakens the+ // recipient's E2E guarantee — the claim path always delivers the sealed+ // envelope the recipient opens with their own key.+ let encryptedAtRest;+ try {+ encryptedAtRest = await encryptSecret(JSON.stringify(wallet.secretBundle));+ } catch (err) {+ return error(res, err.status || 500, err.code || 'encrypt_failed', err.message);+ }++ // Derive the drop id + (claim-time) the canonical claim token hash.+ const nonce = bytesToHex(nobleRandomBytes(16));+ const id = deriveDropId({ address: wallet.address, nonce, sealMode: parsed.sealMode });+ let storedClaimTokenHash = null;+ if (parsed.sealMode === 'claim-time') {+ const { deriveClaimToken } = await import('../../src/solana/vanity/drop-protocol.js');+ const claimToken = deriveClaimToken(id, parsed._claimSecretBytes);+ storedClaimTokenHash = hashClaimToken(claimToken);+ // Wipe the claim secret from our memory now that the hash + sealed envelope+ // exist; only the creator (in the response) retains it.+ parsed._claimSecretBytes.fill(0);+ }++ // Fund the drop wallet on-chain. Confirmed before we persist a claimable record.+ let funding;+ try {+ funding = await fundDropAddress({ toAddress: wallet.address, asset: parsed.asset, atomics: parsed.atomics });+ } catch (err) {+ return error(res, err.status || 502, err.code || 'funding_failed', `on-chain funding failed: ${err.message}`);+ }++ const now = Date.now();+ const record = {+ id,+ protocol: DROP_PROTOCOL_VERSION,+ address: wallet.address,+ vanity: wallet.vanity,+ asset: parsed.asset,+ amount: parsed.amount,+ amountAtomics: parsed.atomics.toString(),+ network: 'solana',+ sealMode: parsed.sealMode,+ recipient: parsed.sealMode === 'direct' ? parsed.recipientPubKey : null,+ claimTokenHash: storedClaimTokenHash, // claim-time only; one-way+ sealedSecret, // ECIES envelope — opaque, addressed to recipient/claim key+ encryptedAtRest, // AES-256-GCM ciphertext for the reclaim sweep ONLY+ message: parsed.message,+ theme: parsed.theme,+ senderLabel: parsed.senderLabel,+ reclaimAddress: parsed.reclaimAddress,+ senderTag: parsed.senderTag,+ irlPinId: parsed.irlPinId,+ roomId: parsed.roomId,+ fundingTx: funding.fundingTx,+ fundingConfirmed: true,+ escrowPayer: verified.payer || null,+ createdAt: now,+ expiresAt: now + parsed.expiryHours * 3600_000,+ status: 'funded',+ };++ let stored;+ try {+ stored = await createDrop(record);+ } catch (err) {+ return error(res, err.status || 500, err.code || 'store_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 claimUrl = `${PUBLIC_ORIGIN}/drop/${id}`;+ const body200 = JSON.stringify({+ created: true,+ drop: await getDrop(id),+ funding: {+ confirmed: true,+ tx: funding.fundingTx,+ explorerUrl: `https://solscan.io/tx/${funding.fundingTx}`,+ },+ // In claim-time mode this is the bearer secret the creator embeds in the+ // link fragment (#k=…). Returned ONCE; the server discards it. In direct+ // mode it is null (the recipient already holds their private key).+ claimSecret: claimSecretForSender,+ claimUrl: claimSecretForSender ? `${claimUrl}#k=${claimSecretForSender}` : claimUrl,+ shareUrl: claimUrl,+ qrUrl: `${PUBLIC_ORIGIN}/api/vanity/drops?view=qr&id=${id}`,+ ogUrl: `${PUBLIC_ORIGIN}/api/og/sealed-drop?id=${id}`,+ escrow: { funded: true, txHash: settled.transaction || null, payer: settled.payer || verified.payer || null },+ notice: claimSecretForSender+ ? 'The claim link contains the ONLY key that opens this wallet. Share the full link (with #k=…) with the recipient. Anyone who has the full link can claim it once.'+ : 'Sealed to the recipient X25519 key. Only they can open it — three.ws cannot.',+ });+ const contentType = 'application/json; charset=utf-8';++ res.setHeader('x-payment-response', encodePaymentResponseHeader(settled));+ res.setHeader('cache-control', 'no-store');+ res.setHeader('content-type', contentType);+ res.statusCode = 201;+ res.end(body200);++ if (paymentId) {+ await storeResponse({ route: ROUTE, paymentId, payloadHash, paymentHash, status: 201, body: body200, contentType, paymentResponseHeader: encodePaymentResponseHeader(settled) });+ }+}++// ── POST: claim (present claim token → atomic claim → release sealed envelope) ─++async function handleClaim(req, res) {+ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ let body;+ try {+ body = await readJson(req);+ } catch (err) {+ return error(res, err.status || 400, 'validation_error', err.message || 'invalid JSON body');+ }++ const id = String(body?.id || '').trim();+ if (!isValidDropId(id)) return error(res, 400, 'validation_error', 'id must be a 24-char hex drop id');++ const record = await getDropRecord(id);+ if (!record) return error(res, 404, 'not_found', 'no drop with that id');++ if (record.status !== 'funded') {+ return json(res, 409, {+ claimed: false,+ status: record.status,+ reason: record.status === 'claimed' ? 'this drop was already claimed' : `this drop is ${record.status}`,+ });+ }+ if (record.expiresAt && Date.now() > record.expiresAt) {+ return json(res, 409, { claimed: false, status: 'expired', reason: 'this drop expired before it was claimed — the sender can reclaim it' });+ }++ // Authorize the claim.+ let claimerTag;+ if (record.sealMode === 'claim-time') {+ const claimToken = String(body?.claimToken || '').trim().toLowerCase();+ if (!/^[0-9a-f]{64}$/.test(claimToken)) {+ return error(res, 400, 'claim_token_required', 'claimToken (64-char hex) is required to claim this bearer drop');+ }+ const presentedHash = hashClaimToken(claimToken);+ if (!timingSafeHexEqual(presentedHash, record.claimTokenHash || '')) {+ return error(res, 403, 'wrong_claim_token', 'this claim token does not match the drop — you need the original claim link');+ }+ // The claimerTag dedups idempotent retries of the SAME winning claim.+ claimerTag = presentedHash;+ } else {+ // direct mode: anyone may fetch the envelope; it's useless without the+ // recipient's private key. The claim simply marks the gift "opened". The+ // claimerTag is a constant so an idempotent re-claim returns the envelope.+ claimerTag = 'direct';+ }++ const claimRecipient = String(body?.claimRecipientPubKey || '').trim().slice(0, 64) || '';++ // Atomic single-claim CAS.+ let outcome;+ try {+ outcome = await claimDrop({ id, claimerTag, claimRecipient });+ } catch (err) {+ return error(res, err.status || 500, err.code || 'claim_failed', err.message);+ }++ if (outcome === 'missing') return error(res, 404, 'not_found', 'drop disappeared during claim');+ if (outcome === 'closed') {+ const fresh = await getDrop(id);+ return json(res, 409, { claimed: false, status: fresh?.status || 'closed', reason: 'drop closed/expired during claim' });+ }+ if (outcome === 'lost') {+ return json(res, 409, { claimed: false, status: 'claimed', reason: 'this drop was already claimed by someone else' });+ }++ // outcome === 'won' (first claim, or an idempotent re-claim with the same+ // token). Release the SEALED envelope for client-side opening. The plaintext+ // secret NEVER appears here — only the ECIES ciphertext.+ if (claimRecipient) {+ await recordClaimDelivery({ id, claimRecipient }).catch(() => {});+ }+ const fresh = await getDrop(id);+ return json(res, 200, {+ claimed: true,+ status: 'claimed',+ id,+ address: record.address,+ asset: record.asset,+ amount: record.amount,+ sealMode: record.sealMode,+ recipient: record.recipient || null,+ sealedSecret: record.sealedSecret,+ sealedScheme: SEALED_ENVELOPE_SCHEME,+ message: record.message || null,+ theme: record.theme || 'default',+ senderLabel: record.senderLabel || null,+ explorerUrl: `https://solscan.io/account/${record.address}`,+ drop: fresh,+ notice: record.sealMode === 'claim-time'+ ? 'Open this envelope in your browser with the claim key from your link (#k=…). three.ws never saw that key.'+ : 'Open this envelope in your browser with your X25519 private key. three.ws never held it.',+ }, { 'cache-control': 'no-store' });+}++// ── POST: reveal (direct-seal: fetch the sealed envelope without claiming) ────++async function handleReveal(req, res) {+ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ let body;+ try {+ body = await readJson(req);+ } catch (err) {+ return error(res, err.status || 400, 'validation_error', err.message || 'invalid JSON body');+ }+ const id = String(body?.id || '').trim();+ if (!isValidDropId(id)) return error(res, 400, 'validation_error', 'id must be a 24-char hex drop id');++ const record = await getDropRecord(id);+ if (!record) return error(res, 404, 'not_found', 'no drop with that id');+ if (record.sealMode !== 'direct') {+ return error(res, 409, 'wrong_mode', 'reveal is for direct-seal drops; bearer drops claim with their claim token');+ }++ // The envelope is ECIES ciphertext addressed to record.recipient — returning+ // it leaks nothing without the recipient's private key. The open is client-side.+ return json(res, 200, {+ revealed: true,+ id,+ address: record.address,+ asset: record.asset,+ amount: record.amount,+ recipient: record.recipient,+ sealedSecret: record.sealedSecret,+ sealedScheme: SEALED_ENVELOPE_SCHEME,+ message: record.message || null,+ theme: record.theme || 'default',+ senderLabel: record.senderLabel || null,+ status: record.status,+ explorerUrl: `https://solscan.io/account/${record.address}`,+ notice: 'Open this envelope client-side with your X25519 private key (openSealed). three.ws cannot — it never held your key.',+ }, { 'cache-control': 'no-store' });+}++// ── POST: reclaim (sender sweeps an expired, unclaimed drop on-chain) ──────────++async function handleReclaim(req, res) {+ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ let body;+ try {+ body = await readJson(req);+ } catch (err) {+ return error(res, err.status || 400, 'validation_error', err.message || 'invalid JSON body');+ }+ const id = String(body?.id || '').trim();+ if (!isValidDropId(id)) return error(res, 400, 'validation_error', 'id must be a 24-char hex drop id');+ const toAddress = String(body?.reclaimAddress || '').trim();++ const record = await getDropRecord(id);+ if (!record) return error(res, 404, 'not_found', 'no drop with that id');++ // Atomic funded→reclaimed CAS, only for EXPIRED drops. Mutually exclusive with+ // claim — a claimed drop can never be reclaimed.+ const eligibility = await markReclaimable(id);+ if (eligibility === 'missing') return error(res, 404, 'not_found', 'drop disappeared');+ if (eligibility === 'ineligible') {+ const fresh = await getDrop(id);+ const why = fresh?.status === 'claimed'+ ? 'this drop was already claimed — nothing to reclaim'+ : 'this drop has not expired yet';+ return json(res, 409, { reclaimed: false, status: fresh?.status, reason: why });+ }++ const refundTo = toAddress || record.reclaimAddress;+ if (!refundTo || !BASE58_RE.test(refundTo)) {+ return error(res, 400, 'no_reclaim_address', 'no reclaim address: supply reclaimAddress, or set one when creating the drop');+ }++ // Reconstruct the drop wallet's key from the at-rest ciphertext ONLY to sign+ // the sweep. Never returned, never logged.+ let dropSecretKey;+ try {+ const bundle = JSON.parse(await decryptSecret(record.encryptedAtRest));+ dropSecretKey = Uint8Array.from(bundle.secretKey);+ } catch (err) {+ return error(res, 500, 'reclaim_key_error', 'could not reconstruct the drop key for the sweep');+ }++ let sweep;+ try {+ sweep = await sweepReclaim({ record: { ...record, status: 'reclaimed' }, dropSecretKey, toAddress: refundTo });+ } catch (err) {+ return json(res, 502, { reclaimed: false, status: 'reclaimed', reason: `reclaim sweep failed: ${err.message}. Retry to complete the reclaim.`, retryable: true });+ } finally {+ dropSecretKey?.fill?.(0);+ }++ return json(res, 200, {+ reclaimed: true,+ id,+ asset: record.asset,+ amount: record.amount,+ reclaimTx: sweep.reclaimTx,+ alreadyReclaimed: sweep.alreadyReclaimed,+ reclaimAddress: refundTo,+ explorerUrl: sweep.reclaimTx === 'empty' ? null : `https://solscan.io/tx/${sweep.reclaimTx}`,+ notice: sweep.reclaimTx === 'empty' ? 'The drop wallet was already empty; nothing to sweep.' : 'Funds swept back to your reclaim address.',+ }, { 'cache-control': 'no-store' });+}++// ── GET handlers ──────────────────────────────────────────────────────────────++async function handleGet(req, res, url) {+ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const view = (url.searchParams.get('view') || 'config').toLowerCase();++ if (view === 'config') {+ return json(res, 200, {+ fundingConfigured: fundingConfigured(),+ assets: ['SOL', 'USDC', 'THREE'],+ networks: activeNetworks(),+ createFeeAtomics: CREATE_FEE_ATOMICS,+ createFeeUsd: (CREATE_FEE_ATOMICS / 1e6).toFixed(2),+ expiry: { minHours: MIN_EXPIRY_HOURS, maxHours: MAX_EXPIRY_HOURS, defaultHours: DEFAULT_EXPIRY_HOURS },+ themes: [...THEMES],+ sealModes: SEAL_MODES,+ protocol: DROP_PROTOCOL_VERSION,+ sealedScheme: SEALED_ENVELOPE_SCHEME,+ }, { 'cache-control': READ_CACHE });+ }++ if (view === 'get') {+ const id = (url.searchParams.get('id') || '').trim();+ if (!isValidDropId(id)) return error(res, 400, 'validation_error', 'id must be a 24-char hex drop id');+ const record = await getDropRecord(id);+ if (!record) return error(res, 404, 'not_found', 'no drop with that id');+ // Public view + a claimable flag so the page knows which path to render,+ // WITHOUT exposing the envelope or token hash.+ const pub = await getDrop(id);+ const expired = record.expiresAt && Date.now() > record.expiresAt && record.status === 'funded';+ return json(res, 200, {+ drop: pub,+ claimable: record.status === 'funded' && !expired,+ expired,+ sealMode: record.sealMode,+ }, { 'cache-control': 'no-store' });+ }++ if (view === 'balance') {+ const id = (url.searchParams.get('id') || '').trim();+ if (!isValidDropId(id)) return error(res, 400, 'validation_error', 'id must be a 24-char hex drop id');+ const record = await getDropRecord(id);+ if (!record) return error(res, 404, 'not_found', 'no drop with that id');+ const { atomics } = await readDropBalance({ address: record.address, asset: record.asset });+ return json(res, 200, {+ id,+ address: record.address,+ asset: record.asset,+ atomics,+ amount: atomics != null ? atomicsToAmount(atomics, record.asset) : null,+ explorerUrl: `https://solscan.io/account/${record.address}`,+ }, { 'cache-control': 'no-store' });+ }++ if (view === 'stats') {+ return json(res, 200, await dropStats(), { 'cache-control': READ_CACHE });+ }++ if (view === 'mine') {+ const tag = sanitizeTag(url.searchParams.get('senderTag'));+ if (!tag) return error(res, 400, 'validation_error', 'senderTag is required');+ const drops = await listBySender(tag, Number(url.searchParams.get('limit')) || 50);+ return json(res, 200, { drops, count: drops.length }, { 'cache-control': 'no-store' });+ }++ if (view === 'qr') {+ const id = (url.searchParams.get('id') || '').trim();+ if (!isValidDropId(id)) return error(res, 400, 'validation_error', 'id must be a 24-char hex drop id');+ const record = await getDropRecord(id);+ if (!record) return error(res, 404, 'not_found', 'no drop with that id');+ // The QR encodes the share URL (no fragment — the fragment claim key never+ // goes server-side, so the QR shown server-side is the share landing only;+ // the page re-renders a QR WITH the fragment client-side for the holder).+ const target = `${PUBLIC_ORIGIN}/drop/${id}`;+ try {+ const QRCode = (await import('qrcode')).default;+ const svg = await QRCode.toString(target, { type: 'svg', margin: 1, width: 320, color: { dark: '#000000', light: '#ffffff' } });+ res.setHeader('content-type', 'image/svg+xml; charset=utf-8');+ res.setHeader('cache-control', 'public, max-age=3600, s-maxage=86400');+ res.statusCode = 200;+ return res.end(svg);+ } catch (err) {+ return error(res, 500, 'qr_failed', 'could not render QR');+ }+ }++ return error(res, 400, 'unknown_view', 'view must be config, get, balance, stats, mine, or qr');+}++// ── dispatch ──────────────────────────────────────────────────────────────────++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: '*' })) return;+ const url = new URL(req.url, `http://${req.headers.host || 'three.ws'}`);++ if (req.method === 'GET') return handleGet(req, res, url);++ if (req.method === 'POST') {+ const action = (url.searchParams.get('action') || 'create').toLowerCase();+ if (action === 'create') return handleCreate(req, res, url);+ if (action === 'claim') return handleClaim(req, res);+ if (action === 'reveal') return handleReveal(req, res);+ if (action === 'reclaim') return handleReclaim(req, res);+ return error(res, 400, 'unknown_action', 'action must be create, claim, reveal, or reclaim');+ }++ res.setHeader('allow', 'GET, POST, OPTIONS');+ return error(res, 405, 'method_not_allowed', 'use GET or POST');+});diff --git a/api/vanity/gallery.js b/api/vanity/gallery.jsnew file mode 100644index 000000000..fd72e5e22--- /dev/null+++ b/api/vanity/gallery.js@@ -0,0 +1,265 @@+// /api/vanity/gallery — the proof-of-grind gallery + leaderboard API.+//+// GET /api/vanity/gallery → paginated public gallery+// ?sort=score|recency&tier=<id>&minLength=N&contains=str&limit=N&offset=N+// GET /api/vanity/gallery?view=leaderboard&limit=N → top-N by rarity+// GET /api/vanity/gallery?view=stats → totals + per-tier histogram+// GET /api/vanity/gallery?view=appraise&address=<b58>&prefixLen=&suffixLen=+// → rarity appraisal of any address (no persistence; pure math)+// POST /api/vanity/gallery → publish a grind (opt-in)+// body: { receipt, label?, share? } — the signed receipt from+// /api/x402/vanity-verifiable. Verified server-side against the pinned+// service key before anything is stored. NEVER send a secret/seed.+// DELETE /api/vanity/gallery?address=<b58> → un-publish (must prove the key)+// body: { signature } — Ed25519 signature by the address over a challenge.+//+// Privacy: only opt-in, secret-free public metadata is ever persisted (the store+// allowlists fields; secrets are structurally un-serializable). A published entry+// is provably tied to a verifiable grind — we recompute every protocol check from+// the receipt with verifyVanityReceipt() and refuse to publish anything that+// doesn't fully verify against the live three.ws service key.++import { wrap, cors, error, json, readJson, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { getServiceIdentity } from '../_lib/vanity-service-key.js';+import { verifyVanityReceipt, PROTOCOL_VERSION } from '../../src/solana/vanity/verifiable-grind.js';+import { computeRarity, appraiseAddress } from '../../src/solana/vanity/rarity.js';+import {+ putEntry,+ queryEntries,+ topByScore,+ galleryStats,+ getEntry,+ removeEntry,+} from '../_lib/vanity-gallery-store.js';+import { ed25519 } from '@noble/curves/ed25519.js';+import { sha256 } from '@noble/hashes/sha256';+import { bytesToHex, hexToBytes } from '@noble/hashes/utils';+import bs58 from 'bs58';++const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;+const enc = new TextEncoder();++// A short fingerprint of a receipt — SHA-256 over (address‖signature) — so the+// gallery entry is bound to the exact signed receipt without storing the receipt's+// secret-adjacent fields (serverSeed, sealed envelope, …). Lets a viewer confirm+// "this entry came from that receipt" while keeping the store secret-free.+function receiptFingerprint(receipt) {+ const msg = enc.encode(`${receipt.address || ''}::${receipt.signature || ''}`);+ return bytesToHex(sha256(msg)).slice(0, 32);+}++function parseGetQuery(url) {+ const p = url.searchParams;+ return {+ view: (p.get('view') || 'gallery').toLowerCase(),+ sort: (p.get('sort') || 'recency').toLowerCase(),+ tier: p.get('tier') || null,+ minLength: p.get('minLength') ? Number(p.get('minLength')) : 0,+ contains: p.get('contains') || '',+ limit: p.get('limit') ? Number(p.get('limit')) : 24,+ offset: p.get('offset') ? Number(p.get('offset')) : 0,+ address: (p.get('address') || '').trim(),+ prefixLen: p.get('prefixLen') != null ? Number(p.get('prefixLen')) : undefined,+ suffixLen: p.get('suffixLen') != null ? Number(p.get('suffixLen')) : undefined,+ };+}++const READ_CACHE = 'public, max-age=30, s-maxage=120, stale-while-revalidate=600';++async function handleGet(req, res, url) {+ const rl = await limits.vanityGalleryReadIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const q = parseGetQuery(url);++ if (q.view === 'appraise') {+ if (!BASE58_RE.test(q.address)) {+ return error(res, 400, 'validation_error', 'address must be a Base58 Solana public key (32–44 chars)');+ }+ const result = appraiseAddress(q.address, { prefixLen: q.prefixLen, suffixLen: q.suffixLen });+ const published = await getEntry(q.address);+ return json(res, 200, { appraisal: result, published: published ? publicView(published) : null }, { 'cache-control': READ_CACHE });+ }++ if (q.view === 'leaderboard') {+ const entries = (await topByScore(q.limit)).map(publicView);+ return json(res, 200, { leaderboard: entries, count: entries.length }, { 'cache-control': READ_CACHE });+ }++ if (q.view === 'stats') {+ const stats = await galleryStats();+ return json(res, 200, { ...stats, rarest: stats.rarest ? publicView(stats.rarest) : null }, { 'cache-control': READ_CACHE });+ }++ // Default: paginated gallery.+ const { entries, total, hasMore } = await queryEntries(q);+ return json(+ res,+ 200,+ { entries: entries.map(publicView), total, hasMore, offset: q.offset, limit: q.limit },+ { 'cache-control': READ_CACHE },+ );+}++// Final read-side projection — the store already allowlists, this just trims to+// what the client renders and never adds anything secret.+function publicView(e) {+ if (!e) return null;+ return {+ address: e.address,+ pattern: e.pattern,+ rarityScore: e.rarityScore,+ rarityBits: e.rarityBits,+ tier: e.tier,+ tierLabel: e.tierLabel,+ expectedAttempts: e.expectedAttempts,+ attempts: e.attempts ?? null,+ bonuses: e.bonuses || [],+ label: e.label || null,+ receiptFingerprint: e.receiptFingerprint,+ verified: e.verified !== false,+ network: e.network || 'solana',+ ts: e.ts,+ explorerUrl: `https://solscan.io/account/${e.address}`,+ shareUrl: `/api/vanity/og?address=${encodeURIComponent(e.address)}`,+ };+}++async function handlePost(req, res) {+ const rl = await limits.vanityGalleryPublishIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ let body;+ try {+ body = await readJson(req);+ } catch (err) {+ return error(res, err.status || 400, 'validation_error', err.message || 'invalid JSON body');+ }+ const receipt = body?.receipt;+ if (!receipt || typeof receipt !== 'object') {+ return error(res, 400, 'validation_error', 'body.receipt (the signed verifiable-grind receipt) is required');+ }+ if (receipt.protocol !== PROTOCOL_VERSION) {+ return error(res, 400, 'unsupported_protocol', `receipt protocol must be ${PROTOCOL_VERSION}`);+ }+ if (!BASE58_RE.test(String(receipt.address || ''))) {+ return error(res, 400, 'validation_error', 'receipt.address is not a valid Base58 Solana address');+ }++ // SECURITY: refuse to ingest any receipt that smuggles secret material. The+ // store can't serialize it, but rejecting up front means we never even hold it.+ for (const k of ['secretKey', 'secretKeyBase58', 'seed', 'sealedSecret']) {+ if (receipt[k] !== undefined) {+ return error(res, 400, 'secret_in_payload', `strip ${k} before publishing — never send a secret to the gallery`);+ }+ }++ // Re-verify the receipt from first principles against the LIVE pinned service+ // key. Only a receipt that fully verifies (commitment opens, address derives,+ // pattern matches, honest difficulty, valid signature by three.ws) is publishable.+ let identity;+ try {+ identity = await getServiceIdentity();+ } catch {+ return error(res, 503, 'service_unavailable', 'vanity service key unavailable — cannot verify receipt');+ }+ const verification = verifyVanityReceipt(receipt, { servicePublicKey: identity.publicKeyBase58 });+ if (!verification.valid) {+ const failed = verification.checks.filter((c) => !c.pass).map((c) => c.id);+ return error(res, 422, 'receipt_unverified', `receipt failed verification (${failed.join(', ')}) — only provably-fair grinds can be published`, {+ checks: verification.checks,+ });+ }++ // Compute the honest rarity from the receipt's own pattern (the verifier already+ // confirmed the pattern + difficulty are honest, so this is trustworthy).+ const rarity = computeRarity(receipt.pattern || {});++ const label = typeof body.label === 'string' ? body.label.trim().slice(0, 80) : '';+ const entry = {+ address: receipt.address,+ pattern: rarity.prefix || rarity.suffix ? { prefix: rarity.prefix, suffix: rarity.suffix, ignoreCase: rarity.ignoreCase } : receipt.pattern,+ rarityScore: rarity.rarityScore,+ rarityBits: rarity.rarityBits,+ baseBits: rarity.baseBits,+ bonusBits: rarity.bonusBits,+ tier: rarity.tier,+ tierLabel: rarity.tierLabel,+ expectedAttempts: rarity.expectedAttempts,+ attempts: Number.isFinite(receipt.attempts) ? receipt.attempts : null,+ durationMs: Number.isFinite(receipt.durationMs) ? receipt.durationMs : null,+ bonuses: rarity.bonuses,+ label: label || null,+ commitment: typeof receipt.commitment === 'string' ? receipt.commitment : null,+ receiptFingerprint: receiptFingerprint(receipt),+ servicePublicKey: receipt.servicePublicKey,+ verified: true,+ network: receipt.network || 'solana',+ ts: Date.now(),+ };++ let stored;+ try {+ stored = await putEntry(entry);+ } catch (err) {+ return error(res, err.status || 500, 'store_failed', err.message || 'could not store entry');+ }++ return json(res, 201, {+ published: true,+ entry: publicView(stored),+ galleryUrl: `/vanity/gallery#${encodeURIComponent(stored.address)}`,+ shareUrl: `/api/vanity/og?address=${encodeURIComponent(stored.address)}`,+ });+}++// Un-publish proves control of the key: the caller signs a fixed challenge with+// the address's Ed25519 private key. No session needed — possession of the key IS+// the authorization, which is exactly the right model for a self-custodied wallet.+async function handleDelete(req, res, url) {+ const rl = await limits.vanityGalleryPublishIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const address = (url.searchParams.get('address') || '').trim();+ if (!BASE58_RE.test(address)) {+ return error(res, 400, 'validation_error', 'address query param must be a Base58 Solana address');+ }+ let body;+ try {+ body = await readJson(req);+ } catch (err) {+ return error(res, err.status || 400, 'validation_error', err.message || 'invalid JSON body');+ }+ const sigHex = String(body?.signature || '').trim();+ if (!/^[0-9a-fA-F]{128}$/.test(sigHex)) {+ return error(res, 400, 'validation_error', 'body.signature must be a 64-byte hex Ed25519 signature over the challenge');+ }+ const existing = await getEntry(address);+ if (!existing) return error(res, 404, 'not_found', 'no published entry for that address');++ const challenge = enc.encode(`three.ws/vanity-gallery/unpublish/v1:${address}`);+ let ok = false;+ try {+ ok = ed25519.verify(hexToBytes(sigHex), challenge, bs58.decode(address));+ } catch {+ ok = false;+ }+ if (!ok) {+ return error(res, 403, 'invalid_signature', 'signature does not prove control of this address — sign the exact challenge with the wallet key');+ }+ await removeEntry(address);+ return json(res, 200, { unpublished: true, address });+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,DELETE,OPTIONS', origins: '*' })) return;+ const url = new URL(req.url, `http://${req.headers.host || 'three.ws'}`);++ if (req.method === 'GET') return handleGet(req, res, url);+ if (req.method === 'POST') return handlePost(req, res);+ if (req.method === 'DELETE') return handleDelete(req, res, url);++ res.setHeader('allow', 'GET, POST, DELETE, OPTIONS');+ return error(res, 405, 'method_not_allowed', 'use GET, POST, or DELETE');+});diff --git a/api/vanity/og.js b/api/vanity/og.jsnew file mode 100644index 000000000..7e7d2f5b6--- /dev/null+++ b/api/vanity/og.js@@ -0,0 +1,197 @@+// api/vanity/og.js — dynamic 1200×630 PNG rarity share card for a ground vanity+// address. Real ImageResponse (@vercel/og) on the Node runtime — the same proven+// path as api/og-leaderboard.js — because X/Facebook/LinkedIn/iMessage do not+// preview SVG cards.+//+// /api/vanity/og?address=<base58>+// Renders the address's rarity tier, score, the highlighted pattern, and the+// honest expected-attempts. Prefers the PUBLISHED gallery entry (provably-fair,+// receipt-bound); if the address isn't published, falls back to an honest+// APPRAISAL of the address so any address still gets a card. The card states+// which mode it is so an appraisal is never passed off as a verified grind.+//+// No secrets are read or rendered — only the public address + rarity math.++import { ImageResponse } from '@vercel/og';+import { getEntry } from '../_lib/vanity-gallery-store.js';+import { appraiseAddress, RARITY_TIERS } from '../../src/solana/vanity/rarity.js';++const WIDTH = 1200;+const HEIGHT = 630;+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++function tierMeta(id) {+ return RARITY_TIERS.find((t) => t.id === id) || RARITY_TIERS[RARITY_TIERS.length - 1];+}++function fmtAttempts(n) {+ const v = Number(n) || 0;+ if (v >= 1e12) return `${(v / 1e12).toFixed(1)}T`;+ if (v >= 1e9) return `${(v / 1e9).toFixed(1)}B`;+ if (v >= 1e6) return `${(v / 1e6).toFixed(1)}M`;+ if (v >= 1e3) return `${(v / 1e3).toFixed(1)}K`;+ return v.toLocaleString('en-US');+}++// Render the address with prefix + suffix highlighted in the tier accent.+function addressNode(address, pattern, accent) {+ const pre = pattern?.prefix || '';+ const suf = pattern?.suffix || '';+ const preLen = pre && address.startsWith(pre) ? pre.length : 0;+ const sufLen = suf && address.endsWith(suf) ? suf.length : 0;+ const head = address.slice(0, preLen);+ const midStart = preLen;+ const midEnd = address.length - sufLen;+ const mid = address.slice(midStart, midEnd);+ const tail = sufLen ? address.slice(midEnd) : '';+ const seg = (text, color, weight) => ({ type: 'span', props: { style: { color, fontWeight: weight }, children: text } });+ return {+ type: 'div',+ props: {+ style: {+ display: 'flex', flexWrap: 'wrap', fontFamily: 'monospace', fontSize: 34,+ letterSpacing: '0.01em', lineHeight: 1.25, color: 'rgba(235,235,245,0.5)', fontWeight: 600,+ },+ children: [+ head ? seg(head, accent, 800) : null,+ seg(mid, 'rgba(235,235,245,0.5)', 600),+ tail ? seg(tail, accent, 800) : null,+ ].filter(Boolean),+ },+ };+}++function statPill(label, value, accent) {+ return {+ type: 'div',+ props: {+ style: { display: 'flex', flexDirection: 'column', gap: 4 },+ children: [+ { type: 'div', props: { style: { fontSize: 20, color: 'rgba(235,235,245,0.45)', letterSpacing: '0.05em', textTransform: 'uppercase' }, children: label } },+ { type: 'div', props: { style: { fontSize: 40, fontWeight: 800, color: accent }, children: value } },+ ],+ },+ };+}++function card({ address, pattern, tier, rarityScore, expectedAttempts, mode, bonuses }) {+ const t = tierMeta(tier);+ const accent = t.accent;+ const patternLabel = [pattern?.prefix && `${pattern.prefix}…`, pattern?.suffix && `…${pattern.suffix}`].filter(Boolean).join(' ') || 'no fixed pattern';+ const verifiedBadge = mode === 'verified';+ return {+ type: 'div',+ props: {+ style: {+ width: '100%', height: '100%', display: 'flex', flexDirection: 'column',+ position: 'relative', background: '#06060b', color: '#f5f5fa',+ fontFamily: 'ui-sans-serif, system-ui, sans-serif',+ },+ children: [+ { type: 'div', props: { style: { position: 'absolute', top: 0, right: 0, width: 640, height: 640, background: `radial-gradient(circle at 100% 0%, ${accent}40, transparent 70%)`, display: 'flex' } } },+ { type: 'div', props: { style: { position: 'absolute', top: 0, left: 0, width: 8, height: '100%', background: accent, display: 'flex' } } },+ { type: 'div', props: { style: { display: 'flex', flexDirection: 'column', padding: '60px 64px 0', flex: 1 }, children: [+ { type: 'div', props: { style: { display: 'flex', alignItems: 'center', gap: 18, marginBottom: 6 }, children: [+ { type: 'div', props: { style: { fontSize: 22, fontWeight: 700, letterSpacing: '0.18em', color: 'rgba(235,235,245,0.5)' }, children: 'GROUND ON THREE.WS' } },+ verifiedBadge+ ? { type: 'div', props: { style: { display: 'flex', alignItems: 'center', padding: '5px 16px', borderRadius: 999, fontSize: 20, fontWeight: 800, color: '#06060b', background: '#4ade80' }, children: '✓ VERIFIED' } }+ : { type: 'div', props: { style: { display: 'flex', alignItems: 'center', padding: '5px 16px', borderRadius: 999, fontSize: 20, fontWeight: 700, color: 'rgba(235,235,245,0.6)', border: '1px solid rgba(235,235,245,0.25)' }, children: 'APPRAISAL' } },+ ] } },+ { type: 'div', props: { style: { display: 'flex', alignItems: 'baseline', gap: 24, marginTop: 10 }, children: [+ { type: 'div', props: { style: { fontSize: 116, fontWeight: 900, lineHeight: 1, color: accent }, children: t.label } },+ ] } },+ { type: 'div', props: { style: { display: 'flex', marginTop: 30, marginBottom: 8 }, children: [addressNode(address, pattern, accent)] } },+ { type: 'div', props: { style: { display: 'flex', gap: 64, marginTop: 'auto', marginBottom: 92 }, children: [+ statPill('Rarity score', String(rarityScore), accent),+ statPill('Pattern', patternLabel, accent),+ statPill('Expected work', `${fmtAttempts(expectedAttempts)} tries`, accent),+ ] } },+ ] } },+ { type: 'div', props: { style: {+ position: 'absolute', left: 0, right: 0, bottom: 0, height: 56,+ display: 'flex', alignItems: 'center', justifyContent: 'space-between',+ padding: '0 64px', background: '#030305', borderTop: '1px solid rgba(255,255,255,0.06)',+ }, children: [+ { type: 'div', props: { style: { display: 'flex', alignItems: 'center', fontSize: 20, fontWeight: 700, color: 'rgba(235,235,245,0.55)', letterSpacing: '0.04em' }, children: [+ { type: 'div', props: { style: { width: 10, height: 10, borderRadius: 10, background: accent, marginRight: 14 } } },+ { type: 'div', props: { children: 'PROOF-OF-GRIND · PROVABLY-FAIR VANITY' } },+ ] } },+ { type: 'div', props: { style: { fontSize: 20, fontWeight: 600, color: 'rgba(235,235,245,0.35)' }, children: 'three.ws/vanity/gallery' } },+ ] } },+ ],+ },+ };+}++async function loadCardData(address) {+ const published = await getEntry(address).catch(() => null);+ if (published) {+ return {+ address,+ pattern: published.pattern,+ tier: published.tier,+ rarityScore: published.rarityScore,+ expectedAttempts: published.expectedAttempts,+ bonuses: published.bonuses || [],+ mode: 'verified',+ };+ }+ const a = appraiseAddress(address);+ return {+ address,+ pattern: { prefix: a.prefix, suffix: a.suffix, ignoreCase: a.ignoreCase },+ tier: a.tier,+ rarityScore: a.rarityScore,+ expectedAttempts: a.expectedAttempts,+ bonuses: a.bonuses || [],+ mode: 'appraisal',+ };+}++export default async function handler(req, res) {+ if (req.method === 'OPTIONS') {+ res.setHeader('access-control-allow-origin', '*');+ res.setHeader('access-control-allow-methods', 'GET,OPTIONS');+ res.statusCode = 204;+ res.end();+ return;+ }+ if (req.method !== 'GET') {+ res.statusCode = 405;+ res.setHeader('allow', 'GET, OPTIONS');+ res.end('method not allowed');+ return;+ }++ const url = new URL(req.url, `http://${req.headers.host || 'x'}`);+ const address = (url.searchParams.get('address') || '').trim();+ if (!BASE58_RE.test(address)) {+ res.statusCode = 302;+ res.setHeader('location', 'https://three.ws/og-image.png');+ res.setHeader('cache-control', 'no-cache');+ res.end();+ return;+ }++ try {+ const data = await loadCardData(address);+ const img = new ImageResponse(card(data), {+ width: WIDTH,+ height: HEIGHT,+ headers: {+ 'cache-control': 'public, max-age=600, s-maxage=3600, stale-while-revalidate=86400',+ 'access-control-allow-origin': '*',+ },+ });+ for (const [k, v] of img.headers.entries()) res.setHeader(k, v);+ const ab = await img.arrayBuffer();+ res.statusCode = img.status;+ res.end(Buffer.from(ab));+ } catch (err) {+ console.error('[vanity/og]', err?.message || err);+ res.statusCode = 302;+ res.setHeader('location', 'https://three.ws/og-image.png');+ res.setHeader('cache-control', 'no-cache');+ res.end();+ }+}diff --git a/data/changelog.json b/data/changelog.jsonindex 3ebe88652..57bd06f69 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,37 @@{"$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-20",+ "title": "Grind-bounty market: post a reward, a fleet grinds your hard vanity address",+ "summary": "A 5-to-8-character vanity address is hours-to-years on one machine, so until now \"hard\" vanity meant running your browser overnight and hoping. The new grind-bounty market makes it a liquid, pay-for-results service. Post the pattern you want, escrow a USDC bounty, and a fleet of independent workers grinds it in parallel — the first one to find a verified match is paid automatically. The breakthrough is that the found key is sealed to your encryption key before the worker ever submits it, so the worker earns the bounty yet never sees your wallet, and three.ws never holds your secret either. Settlement is trustless via x402: no valid match, no payout; only one worker can win; and a bounty that goes unfilled refunds your escrow when it expires. You also get an honest difficulty meter and a fair-price oracle when posting (priced off the real grind odds, not made-up numbers), a live board with biggest-reward and expiring-soon sorts, and a one-click way to open your won wallet locally with your private key. Want to earn instead? Flip on \"Grind & earn,\" point your spare cores at the open bounties, and get paid in USDC for every fill — there's a leaderboard of the top grinders.",+ "tags": [+ "feature",+ "security",+ "sdk"+ ],+ "link": "/vanity/bounties"+ },+ {+ "date": "2026-06-20",+ "title": "Proof-of-grind: a public gallery of the rarest wallets ground here",+ "summary": "A vanity address is a flex — but until now the flex was unverifiable. Proof-of-grind turns it into provenance. Every provably-fair grind can now carry an honest rarity score and tier (Common → Mythic) computed straight from the real grind difficulty: longer patterns rank higher, with documented, capped bonuses for real dictionary words, palindromes, and repeated-character runs — no inflated numbers. Publish a wallet (opt-in, secret-free; we re-verify your signed receipt against the live three.ws service key before it appears) and it joins a public gallery and leaderboard of the rarest addresses ground on three.ws, sortable and filterable by tier and pattern, each with a verified badge and a beautiful share card for X. New tools: paste any address to appraise its tier and estimated grind cost, and every agent's wallet chip now shows its rarity tier wherever it appears. No secret, seed, or sealed key is ever stored or shown.",+ "tags": [+ "feature",+ "security",+ "sdk"+ ],+ "link": "/vanity/gallery"+ },+ {+ "date": "2026-06-19",+ "title": "Agent profile pages now read perfectly on phones",+ "summary": "Open an agent's profile on a phone and it now fits the screen edge-to-edge with no sideways scrolling. Long service endpoint URLs that used to push the whole page wide now trim cleanly with an ellipsis, the search and action buttons up top stack instead of spilling off-screen, and every section — holdings, token, trust, reviews — lines up in a single tidy column. Desktop is unchanged; small screens just stopped looking cramped.",+ "tags": [+ "fix",+ "improvement"+ ]+ },{"date": "2026-06-19","title": "Prove we never kept your vanity key — trustless wallet grinding",diff --git a/data/pages.json b/data/pages.jsonindex 347f9f1b3..b285fefaa 100644--- a/data/pages.json+++ b/data/pages.json@@ -649,6 +649,22 @@"changefreq": "monthly","added": "2026-06-19"},+ {+ "path": "/vanity/gallery",+ "title": "Proof-of-Grind Gallery",+ "description": "A public gallery and leaderboard of the rarest Solana vanity addresses ground on three.ws — each provably-fair, verified, and shareable. Appraise any address to see its honest rarity tier and grind cost.",+ "priority": 0.6,+ "changefreq": "weekly",+ "added": "2026-06-20"+ },+ {+ "path": "/vanity/bounties",+ "title": "Grind-Bounty Market",+ "description": "A decentralized x402 bounty market for hard Solana vanity addresses — escrow a USDC bounty and a fleet of independent workers grinds it in parallel. The first verified match wins, but the found key is sealed to you so the worker never sees your wallet. Earn USDC by grinding open bounties.",+ "priority": 0.6,+ "changefreq": "weekly",+ "added": "2026-06-20"+ },{"path": "/eth-vanity","title": "ETH Vanity (CREATE2)",diff --git a/prompts/vanity-x402/02-grind-bounty-market.md b/prompts/vanity-x402/02-grind-bounty-market.mddeleted file mode 100644index 6a9843b80..000000000--- a/prompts/vanity-x402/02-grind-bounty-market.md+++ /dev/null@@ -1,98 +0,0 @@-# Task 02 — The x402 grind-bounty market (trustless distributed vanity)--> Read [00-README-orchestration.md](./00-README-orchestration.md) first.--## The wedge (why this is gamechanging)--The server grinder caps at ~3 chars in 45s. A 5–8 character vanity (or a full word-like `THREEws…`) is hours-to-years on one machine — so today it's "run your browser-overnight and hope." Nobody sells **hard** vanity addresses at scale, trustlessly.--Invent a **two-sided marketplace**: requesters post a hard pattern and **escrow an-x402 bounty**; a fleet of independent **worker agents** (anyone — including-three.ws's own workers, or a user's spare cores) grind in parallel and race to find-it. The winner submits a proof and claims the bounty. The breakthrough:--- the found key is **sealed to the requester's X25519 key**, so the worker who finds- it **never sees the secret** — they earn the bounty but cannot steal the wallet;-- settlement is **trustless and automatic** via x402 — winner is paid on a valid,- first proof; no work, no pay; duplicate/late proofs are rejected.--This turns "impossible vanity" into a liquid, encrypted, pay-for-results market. It-also monetizes idle compute and is genuinely novel.--## What to build--A bounty market with three real components: an order/escrow API, a worker protocol,-and a UI. Build on the real grinders and x402 rails — no simulation.--### Data + escrow-- A `vanity_bounties` table (Postgres via [@neondatabase/serverless](../../api/_lib))- / Upstash for hot state: pattern, ignoreCase, requester X25519 pubkey, bounty- amount + asset (USDC on Base/Solana via x402, or escrowed $THREE), status- (`open|claimed|settled|expired|cancelled`), difficulty estimate, created/expiry,- winning proof.-- Escrow the bounty up front (x402 payment held until claim, or an on-chain escrow- the API controls). Expiry refunds the requester. Real funds, real settlement.--### Worker protocol (`/api/vanity/bounties/*`)-- `GET /open` — list claimable bounties + difficulty + reward, with a lease/lock so- workers don't all redo the same one (claim a work-lease with a short TTL).-- Worker grinds locally (reuse [grinder.js](../../src/solana/vanity/grinder.js) in- browser / a Node worker harness using [grinder-node.js](../../src/solana/vanity/grinder-node.js)- or the WASM directly) until it finds a match.-- `POST /claim` — submit `{ bountyId, address, sealedSecret (sealed to requester's- key), proof }`. Server verifies: address matches the pattern; the sealed envelope- is well-formed and addressed to the requester; first valid claim wins (atomic- compare-and-set); then settles the bounty to the worker via x402 and marks the- bounty `settled`. The requester later opens the sealed secret with their private- key. The worker is paid **without** ever holding the plaintext.-- Anti-cheat: reject claims whose address doesn't match; reject a sealed envelope not- addressed to the requester; rate-limit; idempotent claims; handle the race where- two workers find different valid keys (first committed wins, the other is told).--### UI-- `/vanity/bounties` — browse/post/track. Post a bounty: pattern builder (reuse the- difficulty meter + estimator), choose reward + expiry, generate/enter your X25519- recipient key (use `generateRecipientKeypair()` and make the user save the private- key — warn clearly). Live status, ETA, number of workers, claim event.-- "Grind for bounties" mode: opt in to run the browser worker pool against open- bounties and earn. Live odometer, earnings, pause/resume. Honest about CPU use.-- On settle: the requester sees "found!" and can open + download/seal-import the- wallet; the worker sees their payout.--## Hard requirements--- Real x402 escrow + settlement (`verifyPayment`/`settlePayment`,- [x402-spec.js](../../api/_lib/x402-spec.js)); real on-chain payouts. No fake balances.-- The worker path must be **secret-blind by construction** — the only thing a worker- can submit is a sealed envelope addressed to the requester. Never accept or relay a- plaintext secret. Verify the seal recipient server-side before paying.-- Atomic single-winner settlement (DB transaction / Redis Lua / compare-and-set).- Exactly-once payout. Expiry refunds are real and reliable.-- Designed states everywhere; 0/1/many bounties; expired; mid-grind disconnect;- duplicate claim; insufficient escrow; network failure mid-settle.-- `$THREE` is the only coin you may name/feature; USDC appears only as the x402- settlement asset (runtime plumbing), never marketed as a coin.--## Definition of done--- [ ] Post → escrow → workers grind → first valid sealed claim wins → automatic x402- payout → requester opens the sealed wallet. Proven end-to-end with real funds- on a testable network/path.-- [ ] Secret-blind workers enforced + tested (a claim with a non-recipient seal, or a- non-matching address, is rejected and unpaid).-- [ ] Exactly-once settlement + expiry refund, with a concurrency test for the- two-workers race.-- [ ] `/vanity/bounties` post + browse + earn UI; every state designed; reachable- from navigation; lazy-loaded worker pool; stops offscreen.-- [ ] Tests for matching, seal-recipient check, atomic claim, refund. Changelog +- `npm run build:pages` clean. No mocks; `git diff` reviewed.--## Closeout--DoD + self-review, then **improve**: add a difficulty→price oracle so bounties are-auto-priced fairly; a leaderboard of top grinders; webhook/Telegram notify on found;-optionally let the bounty pay out in milestones for very hard patterns (ties to Task-07). Summarize, then **delete this file**-(`prompts/vanity-x402/02-grind-bounty-market.md`).diff --git a/prompts/vanity-x402/06-proof-of-grind.md b/prompts/vanity-x402/06-proof-of-grind.mddeleted file mode 100644index 623579d51..000000000--- a/prompts/vanity-x402/06-proof-of-grind.md+++ /dev/null@@ -1,79 +0,0 @@-# Task 06 — Proof-of-grind: verifiable rarity + a gallery of the rarest addresses--> Read [00-README-orchestration.md](./00-README-orchestration.md) first. If-> [01-provably-fair-grinding](./01-provably-fair-grinding.md) shipped, reuse its-> signed-receipt primitive; if not, build the minimal signing here.--## The wedge (why this is gamechanging)--Vanity addresses are a flex — but the flex is unverifiable. Anyone can *claim* they-ground a 6-character address; nobody can prove the work, the rarity, or that it was-ground here. There's no provenance, no leaderboard, no collectible layer.--Build **proof-of-grind**: every grind can emit a **signed, verifiable rarity receipt**-(difficulty, expected attempts, actual attempts, time, entropy commitment), optionally-**anchored on-chain** as a collectible receipt, feeding a **public gallery + leaderboard**-of the rarest addresses ground on three.ws — each with a shareable card. This turns a-one-off purchase into provenance, social proof, discovery, and a reason to come back.-"Minted on three.ws, provably the rarest" becomes a status object.--## What to build--### Verifiable rarity receipt-- Define a **rarity score** from the real probability model- ([validation.js](../../src/solana/vanity/validation.js)): combine pattern length,- position (prefix bias vs uniform suffix), case-sensitivity, dictionary-word bonus- (e.g. real English words), and symmetry/palindrome bonuses into one honest score +- human tier (Common → Mythic). Document the formula; no arbitrary numbers.-- A service-signed receipt: `{ address, pattern, rarityScore, tier, expectedAttempts,- attempts, durationMs, entropyCommitment, ts, version }` + ed25519 signature- (`@noble/curves`). Verifiable offline against the published service key- (`/.well-known/three-vanity.json` from Task 01, or publish it here).--### On-chain collectible (optional, real)-- Let a user mint the receipt as a real on-chain asset (Metaplex `mpl-core` /- `@metaplex-foundation/umi`, or an EAS attestation on Base) with the rarity metadata +- a generated image. Real mint, real metadata URI (store image/JSON on the existing- storage path — R2/S3 in the repo). No fake mint, no placeholder URI.--### Gallery + leaderboard + cards-- `/vanity/gallery` (and a `/vanity/leaderboard`): the rarest addresses ground on- three.ws, sortable/filterable by tier/length/pattern/recency, paginated, with a- verified badge and a link to verify the receipt. **Privacy: never expose any secret,- seed, or sealed payload** — only the public address + receipt metadata, and only for- grinds the user opted to make public.-- Beautiful [@vercel/og](../../api) share cards per address (tier, rarity, the- highlighted pattern) for X/social. A "share my rarity" button on the vanity result.-- Wire it into the platform: rarity badge on agent/avatar wallet chips- ([src/shared/agent-wallet-chip.js](../../src/shared/agent-wallet-chip.js)), so a rare- agent address shows its tier everywhere it appears.--## Hard requirements--- Honest, documented rarity math tied to the real difficulty model — no inflated- scores. Dictionary/word detection uses a real wordlist (one already vendored, e.g.- the BIP-39 list, or another real source — not a hand-typed sample).-- Opt-in publication only; never leak secrets/seed/sealed data; never publish a grind- the user didn't choose to share.-- Real signatures, real on-chain mint (if offered), real storage for images/metadata,- real DB for the gallery/leaderboard. No mock entries, no seeded fake "rarest" list.-- `$THREE` only as the coin; designed states (empty gallery, 1, thousands); fast- (paginate, lazy images, no N+1); accessible; responsive.--## Definition of done--- [ ] Signed rarity receipt with a documented, honest score + tiers; offline verifiable.-- [ ] Optional real on-chain collectible mint with real metadata/image URIs.-- [ ] `/vanity/gallery` + `/vanity/leaderboard`: real data, opt-in, paginated, no- secret leakage, every state designed, reachable from nav.-- [ ] OG share cards; rarity badge wired into the shared wallet chip across surfaces.-- [ ] Tests (rarity math vectors, signature verify, gallery query, privacy: secrets- never serialized). Changelog + `npm run build:pages`. No mocks; `git diff` reviewed.--## Closeout--DoD + self-review, then **improve**: a "rarity appraisal" tool (paste any address →-get its tier + an estimate of grind cost), seasonal leaderboards, and a marketplace-hook so a rare ground wallet can be listed (ties to Task 02/03 — always sealed, never-exposing the key). Summarize, then **delete this file**-(`prompts/vanity-x402/06-proof-of-grind.md`).diff --git a/public/changelog.json b/public/changelog.jsonindex 94ffe6e35..fd407f45f 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,11 +1,55 @@{- "generated_at": "2026-06-19T23:28:51.089Z",+ "generated_at": "2026-06-20T01:36:23.606Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws","url": "https://three.ws"},"entries": [+ {+ "date": "2026-06-20",+ "type": "launch",+ "title": "Grind-Bounty Market",+ "summary": "A decentralized x402 bounty market for hard Solana vanity addresses — escrow a USDC bounty and a fleet of independent workers grinds it in parallel. The first verified match wins, but the found key is sealed to you so the worker never sees your wallet. Earn USDC by grinding open bounties.",+ "link": "/vanity/bounties",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-06-20",+ "type": "launch",+ "title": "Proof-of-Grind Gallery",+ "summary": "A public gallery and leaderboard of the rarest Solana vanity addresses ground on three.ws — each provably-fair, verified, and shareable. Appraise any address to see its honest rarity tier and grind cost.",+ "link": "/vanity/gallery",+ "tags": [+ "launch"+ ]+ },+ {+ "date": "2026-06-20",+ "type": "update",+ "title": "Grind-bounty market: post a reward, a fleet grinds your hard vanity address",+ "summary": "A 5-to-8-character vanity address is hours-to-years on one machine, so until now \"hard\" vanity meant running your browser overnight and hoping. The new grind-bounty market makes it a liquid, pay-for-results service. Post the pattern you want, escrow a USDC bounty, and a fleet of independent workers grinds it in parallel — the first one to find a verified match is paid automatically. The breakthrough is that the found key is sealed to your encryption key before the worker ever submits it, so the worker earns the bounty yet never sees your wallet, and three.ws never holds your secret either. Settlement is trustless via x402: no valid match, no payout; only one worker can win; and a bounty that goes unfilled refunds your escrow when it expires. You also get an honest difficulty meter and a fair-price oracle when posting (priced off the real grind odds, not made-up numbers), a live board with biggest-reward and expiring-soon sorts, and a one-click way to open your won wallet locally with your private key. Want to earn instead? Flip on \"Grind & earn,\" point your spare cores at the open bounties, and get paid in USDC for every fill — there's a leaderboard of the top grinders.",+ "link": "/vanity/bounties",+ "tags": [+ "feature",+ "security",+ "sdk"+ ]+ },+ {+ "date": "2026-06-20",+ "type": "update",+ "title": "Proof-of-grind: a public gallery of the rarest wallets ground here",+ "summary": "A vanity address is a flex — but until now the flex was unverifiable. Proof-of-grind turns it into provenance. Every provably-fair grind can now carry an honest rarity score and tier (Common → Mythic) computed straight from the real grind difficulty: longer patterns rank higher, with documented, capped bonuses for real dictionary words, palindromes, and repeated-character runs — no inflated numbers. Publish a wallet (opt-in, secret-free; we re-verify your signed receipt against the live three.ws service key before it appears) and it joins a public gallery and leaderboard of the rarest addresses ground on three.ws, sortable and filterable by tier and pattern, each with a verified badge and a beautiful share card for X. New tools: paste any address to appraise its tier and estimated grind cost, and every agent's wallet chip now shows its rarity tier wherever it appears. No secret, seed, or sealed key is ever stored or shown.",+ "link": "/vanity/gallery",+ "tags": [+ "feature",+ "security",+ "sdk"+ ]+ },{"date": "2026-06-19","type": "launch",@@ -66,6 +110,17 @@"feature"]},+ {+ "date": "2026-06-19",+ "type": "update",+ "title": "Agent profile pages now read perfectly on phones",+ "summary": "Open an agent's profile on a phone and it now fits the screen edge-to-edge with no sideways scrolling. Long service endpoint URLs that used to push the whole page wide now trim cleanly with an ellipsis, the search and action buttons up top stack instead of spilling off-screen, and every section — holdings, token, trust, reviews — lines up in a single tidy column. Desktop is unchanged; small screens just stopped looking cramped.",+ "link": null,+ "tags": [+ "fix",+ "improvement"+ ]+ },{"date": "2026-06-19","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 99a00fd19..1b193dcbe 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -6,6 +6,38 @@<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/><description>What's new on three.ws — features, improvements, and releases, newest first.</description><language>en</language>+ <item>+ <title>Grind-Bounty Market</title>+ <link>https://three.ws/vanity/bounties</link>+ <guid isPermaLink="false">2026-06-20:Grind-Bounty Market</guid>+ <pubDate>Sat, 20 Jun 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>A decentralized x402 bounty market for hard Solana vanity addresses — escrow a USDC bounty and a fleet of independent workers grinds it in parallel. The first verified match wins, but the found key is sealed to you so the worker never sees your wallet. Earn USDC by grinding open bounties.</description>+ </item>+ <item>+ <title>Proof-of-Grind Gallery</title>+ <link>https://three.ws/vanity/gallery</link>+ <guid isPermaLink="false">2026-06-20:Proof-of-Grind Gallery</guid>+ <pubDate>Sat, 20 Jun 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>A public gallery and leaderboard of the rarest Solana vanity addresses ground on three.ws — each provably-fair, verified, and shareable. Appraise any address to see its honest rarity tier and grind cost.</description>+ </item>+ <item>+ <title>Grind-bounty market: post a reward, a fleet grinds your hard vanity address</title>+ <link>https://three.ws/vanity/bounties</link>+ <guid isPermaLink="false">2026-06-20:Grind-bounty market: post a reward, a fleet grinds your hard vanity address</guid>+ <pubDate>Sat, 20 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>A 5-to-8-character vanity address is hours-to-years on one machine, so until now "hard" vanity meant running your browser overnight and hoping. The new grind-bounty market makes it a liquid, pay-for-results service. Post the pattern you want, escrow a USDC bounty, and a fleet of independent workers grinds it in parallel — the first one to find a verified match is paid automatically. The breakthrough is that the found key is sealed to your encryption key before the worker ever submits it, so the worker earns the bounty yet never sees your wallet, and three.ws never holds your secret either. Settlement is trustless via x402: no valid match, no payout; only one worker can win; and a bounty that goes unfilled refunds your escrow when it expires. You also get an honest difficulty meter and a fair-price oracle when posting (priced off the real grind odds, not made-up numbers), a live board with biggest-reward and expiring-soon sorts, and a one-click way to open your won wallet locally with your private key. Want to earn instead? Flip on "Grind & earn," point your spare cores at the open bounties, and get paid in USDC for every fill — there's a leaderboard of the top grinders.</description>+ </item>+ <item>+ <title>Proof-of-grind: a public gallery of the rarest wallets ground here</title>+ <link>https://three.ws/vanity/gallery</link>+ <guid isPermaLink="false">2026-06-20:Proof-of-grind: a public gallery of the rarest wallets ground here</guid>+ <pubDate>Sat, 20 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>A vanity address is a flex — but until now the flex was unverifiable. Proof-of-grind turns it into provenance. Every provably-fair grind can now carry an honest rarity score and tier (Common → Mythic) computed straight from the real grind difficulty: longer patterns rank higher, with documented, capped bonuses for real dictionary words, palindromes, and repeated-character runs — no inflated numbers. Publish a wallet (opt-in, secret-free; we re-verify your signed receipt against the live three.ws service key before it appears) and it joins a public gallery and leaderboard of the rarest addresses ground on three.ws, sortable and filterable by tier and pattern, each with a verified badge and a beautiful share card for X. New tools: paste any address to appraise its tier and estimated grind cost, and every agent's wallet chip now shows its rarity tier wherever it appears. No secret, seed, or sealed key is ever stored or shown.</description>+ </item><item><title>Agent Studio</title><link>https://three.ws/agent-studio</link>@@ -54,6 +86,14 @@<category>feature</category><description>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.</description></item>+ <item>+ <title>Agent profile pages now read perfectly on phones</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-19:Agent profile pages now read perfectly on phones</guid>+ <pubDate>Fri, 19 Jun 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>Open an agent's profile on a phone and it now fits the screen edge-to-edge with no sideways scrolling. Long service endpoint URLs that used to push the whole page wide now trim cleanly with an ellipsis, the search and action buttons up top stack instead of spilling off-screen, and every section — holdings, token, trust, reviews — lines up in a single tidy column. Desktop is unchanged; small screens just stopped looking cramped.</description>+ </item><item><title>Agent Studio — one place to build your whole agent, with a live avatar</title><link>https://three.ws/agent-studio</link>diff --git a/public/features.json b/public/features.jsonindex c1c11d1ae..86d56f61e 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-19T23:28:51.074Z",+ "generated_at": "2026-06-20T01:36:23.594Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",@@ -796,6 +796,26 @@"tags": [],"showcase": false},+ {+ "path": "/vanity/gallery",+ "title": "Proof-of-Grind Gallery",+ "description": "A public gallery and leaderboard of the rarest Solana vanity addresses ground on three.ws — each provably-fair, verified, and shareable. Appraise any address to see its honest rarity tier and grind cost.",+ "added": "2026-06-20",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },+ {+ "path": "/vanity/bounties",+ "title": "Grind-Bounty Market",+ "description": "A decentralized x402 bounty market for hard Solana vanity addresses — escrow a USDC bounty and a fleet of independent workers grinds it in parallel. The first verified match wins, but the found key is sealed to you so the worker never sees your wallet. Earn USDC by grinding open bounties.",+ "added": "2026-06-20",+ "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 3261a1e3d..b14f50e6f 100644--- a/public/llms-full.txt+++ b/public/llms-full.txt@@ -484,6 +484,18 @@ URL: https://three.ws/vanity/verifyIndependently 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.+### Proof-of-Grind Gallery++URL: https://three.ws/vanity/gallery++A public gallery and leaderboard of the rarest Solana vanity addresses ground on three.ws — each provably-fair, verified, and shareable. Appraise any address to see its honest rarity tier and grind cost.++### Grind-Bounty Market++URL: https://three.ws/vanity/bounties++A decentralized x402 bounty market for hard Solana vanity addresses — escrow a USDC bounty and a fleet of independent workers grinds it in parallel. The first verified match wins, but the found key is sealed to you so the worker never sees your wallet. Earn USDC by grinding open bounties.+### ETH Vanity (CREATE2)URL: https://three.ws/eth-vanitydiff --git a/public/llms.txt b/public/llms.txtindex 5869f4be4..4185b2e8e 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -100,6 +100,8 @@ On-chain features: pay-per-call, token launches, vanity wallets.- [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.+- [Proof-of-Grind Gallery](https://three.ws/vanity/gallery): A public gallery and leaderboard of the rarest Solana vanity addresses ground on three.ws — each provably-fair, verified, and shareable. Appraise any address to see its honest rarity tier and grind cost.+- [Grind-Bounty Market](https://three.ws/vanity/bounties): A decentralized x402 bounty market for hard Solana vanity addresses — escrow a USDC bounty and a fleet of independent workers grinds it in parallel. The first verified match wins, but the found key is sealed to you so the worker never sees your wallet. Earn USDC by grinding open bounties.- [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/sitemap/index.html b/public/sitemap/index.htmlindex 80dd11410..bb8762ac6 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 285 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>+ <p>All 287 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 285 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />+ <input id="sm-filter-input" type="search" placeholder="Filter 287 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>48</span></h2>+ <h2>Crypto<span class="sm-count" data-count>50</span></h2><p class="sm-section-desc">On-chain features: pay-per-call, token launches, vanity wallets.</p></header><ul class="sm-list">@@ -659,6 +659,20 @@<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="/vanity/gallery">+ <span class="sm-title">Proof-of-Grind Gallery</span>+ <span class="sm-path">/vanity/gallery</span>+ <span class="sm-desc">A public gallery and leaderboard of the rarest Solana vanity addresses ground on three.ws — each provably-fair, verified, and shareable. Appraise any address to see its honest rarity tier and grind cost.</span>+ </a>+ </li>+ <li>+ <a href="/vanity/bounties">+ <span class="sm-title">Grind-Bounty Market</span>+ <span class="sm-path">/vanity/bounties</span>+ <span class="sm-desc">A decentralized x402 bounty market for hard Solana vanity addresses — escrow a USDC bounty and a fleet of independent workers grinds it in parallel. The first verified match wins, but the found key is sealed to you so the worker never sees your wallet. Earn USDC by grinding open bounties.</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 1c66b17d8..234d1f7be 100644--- a/public/vanity-wallet.html+++ b/public/vanity-wallet.html@@ -211,7 +211,10 @@</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.+ Verify the receipt — prove we generated your key fresh and never kept a copy. See the rarest wallets ground here in the+ <a href="/vanity/gallery" style="color:#ffd54f;text-decoration:none;border-bottom:1px solid rgba(255,213,79,.4)">proof-of-grind gallery</a>.+ Need a <strong>hard</strong> pattern too slow for one machine?+ <a href="/vanity/bounties" style="color:#ffd54f;text-decoration:none;border-bottom:1px solid rgba(255,213,79,.4)">post a grind bounty</a> and a fleet grinds it for you.</p><div class="card">diff --git a/public/vanity/bounties/index.html b/public/vanity/bounties/index.htmlnew file mode 100644index 000000000..7c452c0ea--- /dev/null+++ b/public/vanity/bounties/index.html@@ -0,0 +1,305 @@+<!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>Grind-Bounty Market · Trustless distributed vanity addresses · three.ws</title>+ <meta name="viewport" content="width=device-width, initial-scale=1">+ <meta name="description" content="Post a USDC bounty for a hard Solana vanity address; a fleet of workers grind it in parallel. The first verified match wins — but the found key is sealed to you, so the worker never sees your wallet. Earn by grinding open bounties.">+ <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>+ <script src="/x402.js" type="module"></script>+ <meta property="og:title" content="Grind-Bounty Market · three.ws">+ <meta property="og:description" content="A decentralized x402 market for hard Solana vanity addresses. Post a bounty, a fleet grinds it, the winner is paid — and the key stays sealed to you end-to-end.">+ <meta property="og:image" content="https://three.ws/og-image.png">+ <meta name="twitter:card" content="summary_large_image">+ <style>+ * { box-sizing: border-box; }+ :root {+ --fg: #f0f0f0; --muted: #888; --dim: #666; --border: rgba(255,255,255,0.08);+ --bg: #000; --card-bg: #0e0e10; --card-bg2:#141416;+ --font-display: 'Space Grotesk', 'Inter', system-ui, sans-serif;+ --radius: 12px;+ --accent:#ffd54f; --good:#4ade80; --bad:#f87171; --info:#38bdf8;+ --common:#94a3b8; --uncommon:#4ade80; --rare:#38bdf8; --epic:#a855f7; --legendary:#ffb020; --mythic:#ff5db1;+ }+ 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:1100px; width:100%; margin:0 auto; padding:2.2rem 1rem 4rem; }+ a { color:inherit; }+ .skip-link{position:absolute;left:-999px}.skip-link:focus{left:1rem;top:1rem;background:#fff;color:#000;padding:.4rem .8rem;border-radius:6px;z-index:100}+ .hero { margin-bottom:1.4rem; }+ h1 { font-size:2.1rem; margin:0 0 .4rem; font-family:var(--font-display); letter-spacing:-0.02em; line-height:1.05; }+ .lede { color:var(--muted); margin:0; max-width:66ch; }+ .lede a { color:var(--accent); text-decoration:none; border-bottom:1px solid rgba(255,213,79,.4); }+ .lede a:hover { border-bottom-color:var(--accent); }++ .statstrip { display:flex; gap:.6rem; flex-wrap:wrap; margin:1.4rem 0 0; }+ .stat { flex:1; min-width:140px; border:1px solid var(--border); border-radius:var(--radius); background:var(--card-bg); padding:.85rem 1rem; }+ .stat .k { font-size:.7rem; text-transform:uppercase; letter-spacing:.05em; color:var(--dim); }+ .stat .v { font-size:1.5rem; font-weight:800; font-family:var(--font-display); margin-top:.15rem; }+ .stat .v.sm { font-size:1.15rem; }++ .tabs { display:flex; gap:.3rem; margin:1.8rem 0 1.1rem; border-bottom:1px solid var(--border); flex-wrap:wrap; }+ .tab { appearance:none; background:none; border:none; color:var(--muted); font:inherit; font-weight:600; padding:.65rem .9rem; cursor:pointer; border-bottom:2px solid transparent; margin-bottom:-1px; transition:color .15s, border-color .15s; }+ .tab:hover { color:#ccc; }+ .tab[aria-selected="true"] { color:#fff; border-bottom-color:#fff; }+ .tab:focus-visible { outline:2px solid rgba(139,92,246,.7); outline-offset:2px; border-radius:6px; }+ .panel { display:none; } .panel.show { display:block; animation:fade .25s ease; }+ @keyframes fade { from{opacity:0;transform:translateY(4px)} to{opacity:1;transform:none} }++ .controls { display:flex; gap:.6rem; flex-wrap:wrap; align-items:center; margin-bottom:1.1rem; }+ .controls select, .controls input[type=text] { font:inherit; font-size:.85rem; background:#161616; color:var(--fg); border:1px solid rgba(255,255,255,.12); border-radius:8px; padding:.5rem .7rem; }+ .controls label { font-size:.7rem; color:var(--dim); text-transform:uppercase; letter-spacing:.04em; }+ .seg { display:flex; border:1px solid var(--border); border-radius:8px; overflow:hidden; }+ .seg button { appearance:none; background:#141414; border:none; color:var(--muted); font:inherit; font-size:.82rem; font-weight:600; padding:.45rem .8rem; cursor:pointer; }+ .seg button[aria-pressed="true"]{ background:#262626; color:#fff; }++ .grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(290px,1fr)); gap:.9rem; }+ .bcard { border:1px solid var(--border); border-radius:var(--radius); background:var(--card-bg); padding:1rem 1.1rem; display:flex; flex-direction:column; gap:.55rem; position:relative; transition:transform .12s, border-color .15s; }+ .bcard:hover { transform:translateY(-2px); border-color:rgba(255,255,255,.18); }+ .bcard .toprow { display:flex; justify-content:space-between; align-items:flex-start; gap:.5rem; }+ .tierbadge { font-size:.66rem; font-weight:800; text-transform:uppercase; letter-spacing:.05em; padding:.2rem .5rem; border-radius:999px; color:#000; }+ .reward { font-size:1.5rem; font-weight:800; font-family:var(--font-display); }+ .reward small { font-size:.7rem; color:var(--dim); font-weight:600; }+ .pat { font-family:'Space Grotesk',monospace; font-size:1.05rem; font-weight:700; word-break:break-all; }+ .pat .hi { color:var(--accent); }+ .meta { font-size:.74rem; color:var(--dim); display:flex; flex-wrap:wrap; gap:.5rem .9rem; }+ .bcard .statusrow { display:flex; align-items:center; gap:.5rem; font-size:.74rem; margin-top:.2rem; }+ .dot { width:7px; height:7px; border-radius:50%; display:inline-block; }+ .dot.open{ background:var(--good); box-shadow:0 0 6px var(--good); } .dot.settled{ background:var(--info);} .dot.refunded{ background:var(--dim);} .dot.expired{ background:var(--bad);}+ .bcard .btnrow { display:flex; gap:.5rem; margin-top:.3rem; flex-wrap:wrap; }+ .timer { font-variant-numeric:tabular-nums; }++ button.primary, button.ghost, a.primary, a.ghost { appearance:none; font:inherit; font-weight:700; border-radius:8px; cursor:pointer; text-decoration:none; display:inline-flex; align-items:center; gap:.4rem; transition:transform .1s, background .15s, border-color .15s; }+ button.primary, a.primary { background:#fff; color:#000; border:1px solid #fff; padding:.55rem 1rem; }+ button.primary:hover, a.primary:hover { transform:translateY(-1px); }+ button.primary:disabled { opacity:.5; cursor:not-allowed; transform:none; }+ button.ghost, a.ghost { background:transparent; color:var(--fg); border:1px solid var(--border); padding:.5rem .9rem; }+ button.ghost:hover, a.ghost:hover { border-color:rgba(255,255,255,.3); }+ button.small { font-size:.78rem; padding:.4rem .7rem; }+ button:focus-visible, a:focus-visible, input:focus-visible, select:focus-visible, textarea:focus-visible { outline:2px solid rgba(139,92,246,.7); outline-offset:2px; }++ .empty { text-align:center; padding:3.5rem 1rem; border:1px dashed var(--border); border-radius:var(--radius); color:var(--muted); }+ .empty .glyph { font-size:2.4rem; margin-bottom:.6rem; opacity:.5; }+ .empty h3 { font-family:var(--font-display); margin:.2rem 0 .5rem; color:#ccc; }+ .skel { border:1px solid var(--border); border-radius:var(--radius); background:var(--card-bg); height:180px; position:relative; overflow:hidden; }+ .skel::after { content:''; position:absolute; inset:0; background:linear-gradient(90deg,transparent,rgba(255,255,255,.05),transparent); animation:sweep 1.3s infinite; }+ @keyframes sweep { 0%{transform:translateX(-100%)} 100%{transform:translateX(100%)} }+ .errbox, .okbox, .warnbox { display:none; margin-top:.9rem; padding:.7rem .9rem; border-radius:8px; font-size:.85rem; }+ .errbox.show { display:block; border:1px solid rgba(248,113,113,.4); background:rgba(248,113,113,.08); color:#fca5a5; }+ .okbox.show { display:block; border:1px solid rgba(74,222,128,.4); background:rgba(74,222,128,.08); color:#86efac; }+ .warnbox.show { display:block; border:1px solid rgba(255,176,32,.4); background:rgba(255,176,32,.08); color:#fcd34d; }++ /* forms */+ .card { border:1px solid var(--border); border-radius:var(--radius); background:var(--card-bg); padding:1.4rem; }+ .card h2 { font-family:var(--font-display); margin:0 0 .3rem; font-size:1.2rem; }+ .card p.note { color:var(--muted); font-size:.84rem; margin:.2rem 0 1rem; }+ label.fl { display:block; font-size:.72rem; text-transform:uppercase; letter-spacing:.04em; color:var(--dim); margin:.9rem 0 .3rem; }+ input.t, textarea.t { width:100%; font:inherit; background:#161616; color:var(--fg); border:1px solid rgba(255,255,255,.12); border-radius:8px; padding:.6rem .8rem; }+ textarea.t { min-height:90px; resize:vertical; font-family:'Space Grotesk',monospace; font-size:.82rem; }+ .row { display:flex; gap:.7rem; flex-wrap:wrap; }+ .row > div { flex:1; min-width:130px; }+ .chk { display:flex; align-items:center; gap:.5rem; margin-top:.7rem; font-size:.86rem; color:#ccc; }+ .kv { display:flex; justify-content:space-between; gap:1rem; padding:.35rem 0; border-bottom:1px solid var(--border); font-size:.86rem; }+ .kv:last-child { border-bottom:none; } .kv .k { color:var(--dim); } .kv .v { font-weight:700; font-family:'Space Grotesk',monospace; }+ .meter { height:10px; border-radius:6px; background:#1c1c1c; overflow:hidden; margin:.4rem 0; }+ .meter > span { display:block; height:100%; transition:width .4s ease, background .4s; }+ .keybox { background:#0a0a0a; border:1px solid rgba(255,176,32,.35); border-radius:8px; padding:.8rem; margin-top:.8rem; }+ .keybox code { display:block; word-break:break-all; font-family:'Space Grotesk',monospace; font-size:.78rem; color:#fcd34d; background:#111; padding:.5rem; border-radius:6px; margin:.4rem 0; }+ .mono { font-family:'Space Grotesk',monospace; word-break:break-all; }++ /* worker odometer */+ .odo { display:flex; gap:.8rem; flex-wrap:wrap; margin:1rem 0; }+ .odo .cell { flex:1; min-width:120px; border:1px solid var(--border); border-radius:10px; background:var(--card-bg2); padding:.7rem .9rem; }+ .odo .cell .k { font-size:.66rem; text-transform:uppercase; letter-spacing:.05em; color:var(--dim); }+ .odo .cell .v { font-size:1.3rem; font-weight:800; font-family:var(--font-display); font-variant-numeric:tabular-nums; }+ .worklog { max-height:200px; overflow:auto; border:1px solid var(--border); border-radius:8px; background:#0a0a0a; padding:.6rem .8rem; font-family:'Space Grotesk',monospace; font-size:.78rem; color:var(--muted); margin-top:.8rem; }+ .worklog .win { color:var(--good); } .worklog .miss { color:var(--dim); } .worklog .err { color:var(--bad); }+ .spin { width:14px;height:14px;border:2px solid rgba(255,255,255,.2);border-top-color:#fff;border-radius:50%;display:inline-block;animation:rot .7s linear infinite;vertical-align:-2px }+ @keyframes rot{to{transform:rotate(360deg)}}++ .toast { position:fixed; left:50%; bottom:1.5rem; transform:translateX(-50%) translateY(120%); background:#1a1a1a; border:1px solid var(--border); color:#fff; padding:.6rem 1rem; border-radius:8px; font-size:.85rem; transition:transform .3s ease; z-index:50; max-width:90vw; }+ .toast.show { transform:translateX(-50%) translateY(0); }+ @media (max-width:560px){ h1{font-size:1.6rem} }+ @media (prefers-reduced-motion: reduce){ *{animation:none!important;transition:none!important} }+ </style>+</head>+<body>+ <a href="#main" class="skip-link">Skip to main content</a>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main id="main">+ <div class="hero">+ <h1>Grind-Bounty Market</h1>+ <p class="lede">+ Hard vanity addresses are hours-to-years on one machine. Here you <strong>escrow a USDC bounty</strong>+ and a fleet of independent workers grinds your pattern in parallel — the first verified match wins.+ The breakthrough: the found key is <strong>sealed to your X25519 key</strong>, so the worker earns the+ bounty yet <strong>never sees your wallet</strong>. Settlement is trustless via+ <a href="/x402">x402</a>; unfilled bounties refund on expiry. Or+ <a href="#" id="lede-earn">put your spare cores to work</a> and earn.+ </p>+ <div class="statstrip" id="statstrip" aria-live="polite"></div>+ </div>++ <div class="tabs" role="tablist" aria-label="Grind-bounty market views">+ <button class="tab" role="tab" id="tab-board" aria-selected="true" aria-controls="panel-board">Bounty board</button>+ <button class="tab" role="tab" id="tab-post" aria-selected="false" aria-controls="panel-post">Post a bounty</button>+ <button class="tab" role="tab" id="tab-earn" aria-selected="false" aria-controls="panel-earn">Grind & earn</button>+ <button class="tab" role="tab" id="tab-open" aria-selected="false" aria-controls="panel-open">Open my wallet</button>+ <button class="tab" role="tab" id="tab-leaderboard" aria-selected="false" aria-controls="panel-leaderboard">Top grinders</button>+ </div>++ <!-- BOARD -->+ <section class="panel show" id="panel-board" role="tabpanel" aria-labelledby="tab-board">+ <div class="controls">+ <div class="seg" role="group" aria-label="Filter by status">+ <button id="st-open" aria-pressed="true">Open</button>+ <button id="st-settled" aria-pressed="false">Won</button>+ <button id="st-all" aria-pressed="false">All</button>+ </div>+ <label for="sort-select" style="margin-left:auto">Sort</label>+ <select id="sort-select" aria-label="Sort board">+ <option value="reward">Biggest reward</option>+ <option value="expiry">Expiring soon</option>+ <option value="recency">Newest</option>+ </select>+ <button class="ghost small" id="refresh-board" title="Refresh">Refresh</button>+ </div>+ <div class="grid" id="board-grid" aria-live="polite"></div>+ <div style="text-align:center;margin-top:1.4rem;display:none" id="loadmore-row">+ <button class="ghost" id="loadmore-btn">Load more</button>+ </div>+ </section>++ <!-- POST -->+ <section class="panel" id="panel-post" role="tabpanel" aria-labelledby="tab-post">+ <div class="card">+ <h2>Post a bounty</h2>+ <p class="note">Choose a pattern, fund the escrow in USDC, and the fleet starts grinding. You'll generate an X25519 key — <strong>save its private half</strong>, it's the only way to open the wallet when a worker finds it.</p>++ <label class="fl" for="post-prefix">Prefix <span style="text-transform:none;color:#555">— address starts with</span></label>+ <div class="row">+ <div><input class="t mono" id="post-prefix" placeholder="e.g. THREE" autocomplete="off" spellcheck="false" maxlength="6"></div>+ <div>+ <label class="fl" for="post-suffix" style="margin:0 0 .3rem">Suffix <span style="text-transform:none;color:#555">— ends with</span></label>+ <input class="t mono" id="post-suffix" placeholder="optional" autocomplete="off" spellcheck="false" maxlength="6">+ </div>+ </div>+ <div class="chk"><input type="checkbox" id="post-ignorecase"><label for="post-ignorecase">Case-insensitive match (faster, less specific)</label></div>++ <!-- live difficulty + price oracle -->+ <div id="quote-box" style="margin-top:1.1rem;display:none">+ <div class="kv"><span class="k">Difficulty</span><span class="v" id="q-tier">—</span></div>+ <div class="meter"><span id="q-meter" style="width:0%"></span></div>+ <div class="kv"><span class="k">Expected attempts</span><span class="v" id="q-attempts">—</span></div>+ <div class="kv"><span class="k">Suggested bounty</span><span class="v" id="q-suggested">—</span></div>+ </div>+ <div class="errbox" id="quote-err"></div>++ <label class="fl" for="post-amount">Bounty (USDC)</label>+ <div class="row">+ <div><input class="t" id="post-amount" inputmode="decimal" placeholder="e.g. 0.50" autocomplete="off"></div>+ <div style="display:flex;align-items:flex-end;gap:.4rem">+ <button class="ghost small" id="use-floor" type="button">Floor</button>+ <button class="ghost small" id="use-suggested" type="button">Suggested</button>+ <button class="ghost small" id="use-generous" type="button">Fill fast</button>+ </div>+ </div>++ <label class="fl" for="post-expiry">Expiry (hours) <span style="text-transform:none;color:#555">— refunds you if unfilled</span></label>+ <input class="t" id="post-expiry" inputmode="numeric" value="48" autocomplete="off">++ <label class="fl" for="post-label">Label <span style="text-transform:none;color:#555">(optional, public)</span></label>+ <input class="t" id="post-label" maxlength="80" placeholder="e.g. My agent's wallet" autocomplete="off">++ <label class="fl" for="post-refund">Refund address (Solana) <span style="text-transform:none;color:#555">— where escrow returns on expiry</span></label>+ <input class="t mono" id="post-refund" placeholder="Your Solana address" autocomplete="off" spellcheck="false">++ <!-- X25519 recipient key -->+ <label class="fl">Your sealed-delivery key (X25519)</label>+ <div style="display:flex;gap:.5rem;flex-wrap:wrap;align-items:center">+ <button class="ghost small" id="gen-key" type="button">Generate a new key</button>+ <span class="note" style="margin:0">or paste an existing public key below</span>+ </div>+ <input class="t mono" id="post-recipient" placeholder="X25519 public key (Base58)" autocomplete="off" spellcheck="false" style="margin-top:.5rem">+ <div class="keybox" id="key-private" style="display:none">+ <strong style="color:#fcd34d">⚠ Save this PRIVATE key now.</strong> three.ws never sees it. It is the ONLY way to open the wallet a worker finds — lose it and the bounty (and the wallet) are unrecoverable.+ <code id="priv-value"></code>+ <button class="ghost small" id="copy-priv" type="button">Copy private key</button>+ <button class="ghost small" id="download-key" type="button">Download key file</button>+ </div>+ <div class="chk" id="saved-chk-wrap" style="display:none"><input type="checkbox" id="saved-chk"><label for="saved-chk">I've saved my private key somewhere safe.</label></div>++ <div class="warnbox show" id="payout-warn" style="display:none">The market's payout wallet isn't configured in this environment, so escrow can't be returned — posting is disabled here. The board and grinder still work.</div>+ <div style="display:flex;gap:.6rem;margin-top:1.3rem;align-items:center;flex-wrap:wrap">+ <button class="primary" id="post-btn" disabled>Fund & post bounty</button>+ <span class="note" style="margin:0" id="post-hint">Fill in a pattern, amount, and your key.</span>+ </div>+ <div class="errbox" id="post-err"></div>+ <div class="okbox" id="post-ok"></div>+ </div>+ </section>++ <!-- EARN -->+ <section class="panel" id="panel-earn" role="tabpanel" aria-labelledby="tab-earn">+ <div class="card">+ <h2>Grind & earn</h2>+ <p class="note">Run your browser's cores against open bounties and claim the reward when you find a match. We seal the key to the requester before submitting, so <strong>you never hold their secret</strong> — you just earn the bounty. Honest about CPU: this pegs your cores while running.</p>++ <label class="fl" for="earn-payout">Your payout address (Solana) <span style="text-transform:none;color:#555">— where the bounty is sent</span></label>+ <input class="t mono" id="earn-payout" placeholder="Your Solana USDC address" autocomplete="off" spellcheck="false">++ <div class="row" style="margin-top:.6rem;align-items:flex-end">+ <div>+ <label class="fl" for="earn-workers" style="margin:0 0 .3rem">Worker threads</label>+ <input class="t" id="earn-workers" inputmode="numeric" value="" placeholder="auto">+ </div>+ <div style="display:flex;gap:.5rem">+ <button class="primary" id="earn-start">Start grinding</button>+ <button class="ghost" id="earn-stop" disabled>Stop</button>+ </div>+ </div>++ <div class="odo">+ <div class="cell"><div class="k">Status</div><div class="v" id="o-status" style="font-size:1rem">Idle</div></div>+ <div class="cell"><div class="k">Current target</div><div class="v mono" id="o-target" style="font-size:.85rem">—</div></div>+ <div class="cell"><div class="k">Rate</div><div class="v" id="o-rate">0/s</div></div>+ <div class="cell"><div class="k">Attempts</div><div class="v" id="o-attempts">0</div></div>+ <div class="cell"><div class="k">Earned</div><div class="v" id="o-earned" style="color:var(--good)">$0.00</div></div>+ </div>+ <div class="worklog" id="worklog" aria-live="polite"><span class="miss">Worker idle. Enter a payout address and press Start.</span></div>+ </div>+ </section>++ <!-- OPEN MY WALLET -->+ <section class="panel" id="panel-open" role="tabpanel" aria-labelledby="tab-open">+ <div class="card">+ <h2>Open your won wallet</h2>+ <p class="note">When a worker fills your bounty, the key is waiting — sealed to you. Paste your bounty id and your X25519 <strong>private</strong> key (it never leaves your browser) to decrypt the wallet locally.</p>+ <label class="fl" for="open-id">Bounty id</label>+ <input class="t mono" id="open-id" placeholder="e.g. a1b2c3d4e5f60718293a4b5c" autocomplete="off" spellcheck="false">+ <label class="fl" for="open-priv">Your X25519 private key</label>+ <input class="t mono" id="open-priv" placeholder="Base58 private key — stays in your browser" autocomplete="off" spellcheck="false">+ <div style="display:flex;gap:.6rem;margin-top:1rem"><button class="primary" id="open-btn">Reveal & open</button></div>+ <div class="errbox" id="open-err"></div>+ <div class="okbox" id="open-ok"></div>+ </div>+ </section>++ <!-- LEADERBOARD -->+ <section class="panel" id="panel-leaderboard" role="tabpanel" aria-labelledby="tab-leaderboard">+ <div id="leaderboard" aria-live="polite"></div>+ </section>+ </main>++ <div class="toast" id="toast" role="status" aria-live="polite"></div>+ <footer class="h-footer-horizon"><div class="h-footer-inner" style="text-align:center;padding:2rem 1rem;color:#555;font-size:.8rem">three.ws — grind-bounty market · trustless distributed vanity · key stays sealed to you</div></footer>++ <script type="module" src="/src/pages/vanity-bounties.js"></script>+</body>+</html>diff --git a/public/vanity/gallery/index.html b/public/vanity/gallery/index.htmlnew file mode 100644index 000000000..3cbb7248b--- /dev/null+++ b/public/vanity/gallery/index.html@@ -0,0 +1,557 @@+<!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>Proof-of-Grind · The rarest addresses ground on three.ws</title>+ <meta name="viewport" content="width=device-width, initial-scale=1">+ <meta name="description" content="A public gallery and leaderboard of the rarest Solana vanity addresses ground on three.ws — each provably-fair, verified, and shareable. Appraise any address to see its rarity tier and grind cost.">+ <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="Proof-of-Grind · The rarest addresses ground on three.ws">+ <meta property="og:description" content="Provably-fair vanity addresses, ranked by honest rarity. Verify, appraise, and share the rarest wallets ground on three.ws.">+ <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&t=Proof-of-Grind+Gallery&d=A+public+gallery+and+leaderboard+of+the+rarest+Solana+vanity+addresses+ground+on+three.ws+%E2%80%94+each+provably-fair%2C+verified%2C+and+shareable.+Appraise+any+address+to&p=%2Fvanity%2Fgallery">+ <meta name="twitter:card" content="summary_large_image">+ <style>+ * { box-sizing: border-box; }+ :root {+ --fg: #f0f0f0; --muted: #888; --dim: #666; --border: rgba(255,255,255,0.08);+ --bg: #000; --card-bg: #0e0e10;+ --font-display: 'Space Grotesk', 'Inter', system-ui, sans-serif;+ --radius: 12px;+ --common:#94a3b8; --uncommon:#4ade80; --rare:#38bdf8; --epic:#a855f7; --legendary:#ffb020; --mythic:#ff5db1;+ }+ 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:1100px; width:100%; margin:0 auto; padding:2.2rem 1rem 4rem; }+ a { color:inherit; }+ .hero { margin-bottom:1.8rem; }+ h1 { font-size:2rem; margin:0 0 .4rem; font-family:var(--font-display); letter-spacing:-0.02em; line-height:1.05; }+ .lede { color:var(--muted); margin:0; max-width:64ch; }+ .lede a { color:#ffd54f; text-decoration:none; border-bottom:1px solid rgba(255,213,79,.4); }+ .lede a:hover { border-bottom-color:#ffd54f; }++ /* summary stat strip */+ .statstrip { display:flex; gap:.6rem; flex-wrap:wrap; margin:1.4rem 0 0; }+ .stat { flex:1; min-width:130px; border:1px solid var(--border); border-radius:var(--radius); background:var(--card-bg); padding:.85rem 1rem; }+ .stat .k { font-size:.72rem; text-transform:uppercase; letter-spacing:.05em; color:var(--dim); }+ .stat .v { font-size:1.5rem; font-weight:800; font-family:var(--font-display); margin-top:.15rem; }+ .tierbar { display:flex; height:8px; border-radius:6px; overflow:hidden; margin-top:.5rem; background:#161616; }+ .tierbar span { display:block; height:100%; transition:flex-grow .4s ease; }++ /* tabs */+ .tabs { display:flex; gap:.3rem; margin:1.8rem 0 1.1rem; border-bottom:1px solid var(--border); flex-wrap:wrap; }+ .tab { appearance:none; background:none; border:none; color:var(--muted); font:inherit; font-weight:600; padding:.65rem .9rem; cursor:pointer; border-bottom:2px solid transparent; margin-bottom:-1px; transition:color .15s, border-color .15s; }+ .tab:hover { color:#ccc; }+ .tab[aria-selected="true"] { color:#fff; border-bottom-color:#fff; }+ .tab:focus-visible { outline:2px solid rgba(139,92,246,.7); outline-offset:2px; border-radius:6px; }++ /* controls */+ .controls { display:flex; gap:.6rem; flex-wrap:wrap; align-items:center; margin-bottom:1.1rem; }+ .controls select, .controls input[type=text] { font:inherit; font-size:.85rem; background:#161616; color:var(--fg); border:1px solid rgba(255,255,255,.12); border-radius:8px; padding:.5rem .7rem; }+ .controls input[type=text] { flex:1; min-width:140px; }+ .controls select:focus, .controls input:focus { outline:none; border-color:rgba(255,255,255,.32); }+ .controls label { font-size:.72rem; color:var(--dim); text-transform:uppercase; letter-spacing:.04em; }+ .tier-pills { display:flex; gap:.4rem; flex-wrap:wrap; }+ .tier-pill { appearance:none; font:inherit; font-size:.74rem; font-weight:700; padding:.32rem .7rem; border-radius:999px; border:1px solid var(--border); background:#141414; color:var(--muted); cursor:pointer; transition:transform .12s, border-color .15s, color .15s; }+ .tier-pill:hover { transform:translateY(-1px); }+ .tier-pill[aria-pressed="true"] { color:#000; }+ .tier-pill:focus-visible { outline:2px solid rgba(139,92,246,.7); outline-offset:2px; }++ /* gallery grid */+ .grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(280px,1fr)); gap:.9rem; }+ .gcard { border:1px solid var(--border); border-radius:var(--radius); background:var(--card-bg); padding:1.1rem; position:relative; overflow:hidden; transition:transform .14s ease, border-color .15s ease; opacity:0; animation:fadein .4s ease forwards; }+ .gcard:hover { transform:translateY(-2px); }+ .gcard::before { content:''; position:absolute; inset:0 auto 0 0; width:4px; background:var(--accent,#888); }+ .gcard .badge { display:inline-flex; align-items:center; gap:.35rem; font-size:.68rem; font-weight:800; text-transform:uppercase; letter-spacing:.06em; padding:.25rem .6rem; border-radius:999px; color:#000; }+ .gcard .verified { font-size:.66rem; color:#4ade80; font-weight:700; display:inline-flex; align-items:center; gap:.25rem; }+ .gcard .addr { font-family:ui-monospace,monospace; font-size:.92rem; margin:.7rem 0 .2rem; word-break:break-all; line-height:1.35; color:rgba(240,240,240,.6); }+ .gcard .addr .hi { color:#fff; font-weight:700; }+ .gcard .meta { display:flex; gap:1rem; margin-top:.7rem; font-size:.74rem; color:var(--dim); }+ .gcard .meta b { color:#bbb; font-weight:700; display:block; font-size:.95rem; font-family:var(--font-display); }+ .gcard .bonuses { display:flex; flex-wrap:wrap; gap:.3rem; margin-top:.7rem; }+ .gcard .bonus { font-size:.66rem; color:#cbd5e1; background:rgba(255,255,255,.05); border:1px solid var(--border); border-radius:6px; padding:.15rem .45rem; }+ .gcard .acts { display:flex; gap:.5rem; margin-top:.9rem; }+ .gcard .acts a, .gcard .acts button { font:inherit; font-size:.74rem; font-weight:600; text-decoration:none; color:var(--muted); background:none; border:1px solid var(--border); border-radius:7px; padding:.35rem .6rem; cursor:pointer; transition:color .15s, border-color .15s; }+ .gcard .acts a:hover, .gcard .acts button:hover { color:#fff; border-color:rgba(255,255,255,.25); }+ .gcard .label { font-size:.78rem; color:#cbd5e1; margin-top:.4rem; font-style:italic; }+ @keyframes fadein { to { opacity:1; } }++ /* leaderboard rows */+ .lb { border:1px solid var(--border); border-radius:var(--radius); overflow:hidden; }+ .lbrow { display:flex; align-items:center; gap:1rem; padding:.85rem 1.1rem; border-bottom:1px solid var(--border); transition:background .15s; }+ .lbrow:last-child { border-bottom:none; }+ .lbrow:hover { background:rgba(255,255,255,.02); }+ .lbrow .rank { font-size:1.4rem; font-weight:900; font-family:var(--font-display); width:3rem; text-align:center; }+ .lbrow .ladr { flex:1; min-width:0; }+ .lbrow .ladr .a { font-family:ui-monospace,monospace; font-size:.9rem; word-break:break-all; color:rgba(240,240,240,.65); }+ .lbrow .ladr .a .hi { color:#fff; font-weight:700; }+ .lbrow .ladr .sub { font-size:.72rem; color:var(--dim); margin-top:.2rem; }+ .lbrow .tierlabel { font-size:.7rem; font-weight:800; text-transform:uppercase; letter-spacing:.05em; padding:.2rem .55rem; border-radius:999px; color:#000; }+ .lbrow .score { font-size:1.1rem; font-weight:800; font-family:var(--font-display); width:5rem; text-align:right; }++ /* appraisal */+ .appraise-card { border:1px solid var(--border); border-radius:var(--radius); background:var(--card-bg); padding:1.4rem; }+ .appraise-card label { display:block; font-size:.74rem; text-transform:uppercase; letter-spacing:.04em; color:var(--dim); margin-bottom:.4rem; }+ .appraise-card input[type=text] { width:100%; font-family:ui-monospace,monospace; font-size:.85rem; background:#161616; color:var(--fg); border:1px solid rgba(255,255,255,.12); border-radius:8px; padding:.6rem .7rem; }+ .appraise-card input:focus { outline:none; border-color:rgba(255,255,255,.32); }+ .appraise-row { display:flex; gap:.6rem; flex-wrap:wrap; align-items:flex-end; }+ .appraise-row > div { flex:1; min-width:100px; }+ .appraise-result { margin-top:1.3rem; display:none; }+ .appraise-result.show { display:block; animation:fadein .35s ease; }+ .big-tier { font-family:var(--font-display); font-size:3rem; font-weight:900; line-height:1; }+ .appraise-stats { display:flex; gap:1.5rem; flex-wrap:wrap; margin-top:1rem; }+ .appraise-stats .s .k { font-size:.7rem; color:var(--dim); text-transform:uppercase; letter-spacing:.04em; }+ .appraise-stats .s .v { font-size:1.35rem; font-weight:800; font-family:var(--font-display); margin-top:.15rem; }++ /* publish */+ .publish-card { border:1px solid var(--border); border-radius:var(--radius); background:var(--card-bg); padding:1.4rem; }+ .publish-card textarea { width:100%; min-height:9rem; font-family:ui-monospace,monospace; font-size:.8rem; background:#161616; color:var(--fg); border:1px solid rgba(255,255,255,.12); border-radius:8px; padding:.6rem .7rem; resize:vertical; }+ .publish-card textarea:focus, .publish-card input:focus { outline:none; border-color:rgba(255,255,255,.32); }+ .publish-card label { display:block; font-size:.74rem; text-transform:uppercase; letter-spacing:.04em; color:var(--dim); margin:0 0 .4rem; }+ .publish-card input[type=text] { width:100%; font-size:.85rem; background:#161616; color:var(--fg); border:1px solid rgba(255,255,255,.12); border-radius:8px; padding:.55rem .7rem; }++ button.primary { font:inherit; font-weight:700; background:#fff; color:#000; border:none; border-radius:8px; padding:.6rem 1.3rem; cursor:pointer; transition:transform .12s, opacity .12s; }+ button.primary:hover { transform:translateY(-1px); }+ 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:8px; padding:.6rem 1rem; cursor:pointer; }+ button.ghost:hover { color:#ccc; border-color:rgba(255,255,255,.25); }++ .note { color:var(--dim); font-size:.78rem; line-height:1.55; margin-top:.7rem; }+ .note strong { color:#999; }+ .errbox { display:none; background:rgba(239,68,68,.1); border:1px solid rgba(239,68,68,.3); color:#f87171; border-radius:8px; padding:.7rem .85rem; font-size:.84rem; margin-top:.8rem; }+ .errbox.show { display:block; }+ .okbox { display:none; background:rgba(74,222,128,.1); border:1px solid rgba(74,222,128,.3); color:#4ade80; border-radius:8px; padding:.7rem .85rem; font-size:.84rem; margin-top:.8rem; }+ .okbox.show { display:block; }++ /* states */+ .empty { text-align:center; padding:3.5rem 1rem; border:1px dashed var(--border); border-radius:var(--radius); color:var(--muted); }+ .empty .glyph { font-size:2.4rem; margin-bottom:.6rem; opacity:.5; }+ .empty h3 { font-family:var(--font-display); margin:.2rem 0 .5rem; color:#ccc; }+ .empty a.cta { display:inline-block; margin-top:1rem; background:#fff; color:#000; text-decoration:none; font-weight:700; padding:.55rem 1.1rem; border-radius:8px; }+ .skel { border:1px solid var(--border); border-radius:var(--radius); background:var(--card-bg); height:170px; position:relative; overflow:hidden; }+ .skel::after { content:''; position:absolute; inset:0; background:linear-gradient(90deg,transparent,rgba(255,255,255,.05),transparent); animation:sweep 1.3s infinite; }+ @keyframes sweep { 0%{transform:translateX(-100%)} 100%{transform:translateX(100%)} }+ .loadmore-row { text-align:center; margin-top:1.4rem; }+ .panel { display:none; }+ .panel.show { display:block; }+ .toast { position:fixed; left:50%; bottom:1.5rem; transform:translateX(-50%) translateY(120%); background:#1a1a1a; border:1px solid var(--border); color:#fff; padding:.6rem 1rem; border-radius:8px; font-size:.85rem; transition:transform .3s ease; z-index:50; }+ .toast.show { transform:translateX(-50%) translateY(0); }+ @media (max-width:560px){ h1{font-size:1.6rem} .lbrow .score{width:auto} }+ @media (prefers-reduced-motion: reduce){ .gcard,.toast,.skel::after{animation:none!important;transition:none!important} .gcard{opacity:1} }+ </style>++ <link rel="canonical" href="https://three.ws/vanity/gallery">+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">+ <meta property="og:type" content="website">+ <meta property="og:site_name" content="three.ws">+ <meta property="og:locale" content="en_US">+ <meta property="og:url" content="https://three.ws/vanity/gallery">+ <meta property="og:image:alt" content="Proof-of-Grind Gallery — three.ws">+ <meta name="twitter:site" content="@trythreews">+ <meta name="twitter:title" content="Proof-of-Grind Gallery · three.ws">+ <meta name="twitter:description" content="A public gallery and leaderboard of the rarest Solana vanity addresses ground on three.ws — each provably-fair, verified, and shareable. Appraise any address to see its honest rarity tier and grind cost.">+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Proof-of-Grind+Gallery&amp;d=A+public+gallery+and+leaderboard+of+the+rarest+Solana+vanity+addresses+ground+on+three.ws+%E2%80%94+each+provably-fair%2C+verified%2C+and+shareable.+Appraise+any+address+to&amp;p=%2Fvanity%2Fgallery">+ <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","name":"Proof-of-Grind Gallery","description":"A public gallery and leaderboard of the rarest Solana vanity addresses ground on three.ws — each provably-fair, verified, and shareable. Appraise any address to see its honest rarity tier and grind cost.","url":"https://three.ws/vanity/gallery","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"},"primaryImageOfPage":"https://three.ws/api/page-og?s=crypto&t=Proof-of-Grind+Gallery&d=A+public+gallery+and+leaderboard+of+the+rarest+Solana+vanity+addresses+ground+on+three.ws+%E2%80%94+each+provably-fair%2C+verified%2C+and+shareable.+Appraise+any+address+to&p=%2Fvanity%2Fgallery"},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https://three.ws/"},{"@type":"ListItem","position":2,"name":"Vanity","item":"https://three.ws/vanity"},{"@type":"ListItem","position":3,"name":"Gallery","item":"https://three.ws/vanity/gallery"}]}]}</script>+</head>+<body>+ <a href="#main" class="skip-link">Skip to main content</a>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main id="main">+ <div class="hero">+ <h1>Proof-of-Grind</h1>+ <p class="lede">+ The rarest Solana addresses ground on three.ws — each one <strong>provably-fair</strong> and+ <a href="/vanity/verify">independently verified</a>. Rarity is honest math from the real+ <a href="/vanity-wallet">grind difficulty</a>: longer patterns, real words, palindromes and+ repeats. Appraise any address, or publish your own ground wallet. Want a hard one ground for you?+ <a href="/vanity/bounties">Post a grind bounty →</a>+ </p>+ <div class="statstrip" id="statstrip" aria-live="polite"></div>+ </div>++ <div class="tabs" role="tablist" aria-label="Proof-of-grind views">+ <button class="tab" role="tab" id="tab-gallery" aria-selected="true" aria-controls="panel-gallery">Gallery</button>+ <button class="tab" role="tab" id="tab-leaderboard" aria-selected="false" aria-controls="panel-leaderboard">Leaderboard</button>+ <button class="tab" role="tab" id="tab-appraise" aria-selected="false" aria-controls="panel-appraise">Appraise an address</button>+ <button class="tab" role="tab" id="tab-publish" aria-selected="false" aria-controls="panel-publish">Publish a grind</button>+ </div>++ <!-- GALLERY -->+ <section class="panel show" id="panel-gallery" role="tabpanel" aria-labelledby="tab-gallery">+ <div class="controls">+ <div class="tier-pills" id="tier-pills" role="group" aria-label="Filter by tier"></div>+ <input type="text" id="filter-contains" placeholder="Filter by pattern (e.g. sol)" aria-label="Filter by pattern text" autocomplete="off" spellcheck="false" />+ <label for="sort-select" style="margin-left:auto">Sort</label>+ <select id="sort-select" aria-label="Sort gallery">+ <option value="recency">Newest</option>+ <option value="score">Rarest</option>+ </select>+ </div>+ <div class="grid" id="gallery-grid" aria-live="polite"></div>+ <div class="loadmore-row" id="loadmore-row" style="display:none">+ <button class="ghost" id="loadmore-btn">Load more</button>+ </div>+ </section>++ <!-- LEADERBOARD -->+ <section class="panel" id="panel-leaderboard" role="tabpanel" aria-labelledby="tab-leaderboard">+ <div class="lb" id="leaderboard" aria-live="polite"></div>+ </section>++ <!-- APPRAISE -->+ <section class="panel" id="panel-appraise" role="tabpanel" aria-labelledby="tab-appraise">+ <div class="appraise-card">+ <div class="appraise-row">+ <div style="flex:3">+ <label for="appraise-addr">Solana address</label>+ <input type="text" id="appraise-addr" placeholder="Paste any Base58 Solana address…" autocomplete="off" spellcheck="false" />+ </div>+ <div style="flex:1">+ <label for="appraise-prefix">Prefix chars</label>+ <input type="text" id="appraise-prefix" inputmode="numeric" placeholder="auto" autocomplete="off" />+ </div>+ <div style="flex:1">+ <label for="appraise-suffix">Suffix chars</label>+ <input type="text" id="appraise-suffix" inputmode="numeric" placeholder="0" autocomplete="off" />+ </div>+ <button class="primary" id="appraise-btn">Appraise</button>+ </div>+ <p class="note">Estimates the rarity tier and the expected grind cost of the chosen prefix/suffix using the same honest model the grinder advertises. Leave the splits on <strong>auto</strong> to detect a leading word, repeat, or a sensible default. Computed live in your browser — nothing is sent or stored.</p>+ <div class="errbox" id="appraise-err"></div>+ <div class="appraise-result" id="appraise-result"></div>+ </div>+ </section>++ <!-- PUBLISH -->+ <section class="panel" id="panel-publish" role="tabpanel" aria-labelledby="tab-publish">+ <div class="publish-card">+ <label for="publish-receipt">Your signed receipt</label>+ <textarea id="publish-receipt" placeholder='Paste the receipt from /api/x402/vanity-verifiable (the same one /vanity/verify accepts)…' spellcheck="false" autocomplete="off"></textarea>+ <div style="margin-top:.9rem">+ <label for="publish-label">Display label <span style="text-transform:none;color:#555">(optional, public)</span></label>+ <input type="text" id="publish-label" maxlength="80" placeholder="e.g. My agent's wallet" autocomplete="off" />+ </div>+ <p class="note">+ <strong>Opt-in and secret-free.</strong> Publishing adds only your public address and its rarity metadata to the gallery —+ never a key, seed, or sealed envelope. We re-verify your receipt against the live three.ws service key first, so only+ provably-fair grinds appear here. Don't have a receipt? <a href="/vanity-wallet" style="color:#ffd54f">Grind a provably-fair wallet →</a>+ </p>+ <div style="display:flex;gap:.6rem;margin-top:1rem;align-items:center">+ <button class="primary" id="publish-btn">Verify & publish</button>+ <button class="ghost" id="publish-clear">Clear</button>+ </div>+ <div class="errbox" id="publish-err"></div>+ <div class="okbox" id="publish-ok"></div>+ </div>+ </section>+ </main>++ <div class="toast" id="toast" role="status" aria-live="polite"></div>++ <footer class="h-footer-horizon"><div class="h-footer-inner" style="text-align:center;padding:2rem 1rem;color:#555;font-size:.8rem">three.ws — proof-of-grind · provably-fair vanity addresses</div></footer>++ <script type="module">+ import { computeRarity, appraiseAddress, RARITY_TIERS } from '/src/solana/vanity/rarity.js';++ const $ = (id) => document.getElementById(id);+ const API = '/api/vanity/gallery';+ const TIER_COLOR = Object.fromEntries(RARITY_TIERS.map((t) => [t.id, t.accent]));+ const TIER_ORDER = ['mythic', 'legendary', 'epic', 'rare', 'uncommon', 'common'];++ function esc(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); }+ function toast(msg) { const t = $('toast'); t.textContent = msg; t.classList.add('show'); setTimeout(() => t.classList.remove('show'), 2200); }++ // Render an address with its prefix/suffix highlighted.+ function addrHTML(address, pattern) {+ const pre = pattern?.prefix || '', suf = pattern?.suffix || '';+ const preHit = pre && address.startsWith(pre) ? pre.length : 0;+ const sufHit = suf && address.endsWith(suf) ? suf.length : 0;+ const head = address.slice(0, preHit), tail = sufHit ? address.slice(address.length - sufHit) : '';+ const mid = address.slice(preHit, address.length - sufHit);+ return (preHit ? `<span class="hi">${esc(head)}</span>` : '') + esc(mid) + (sufHit ? `<span class="hi">${esc(tail)}</span>` : '');+ }+ function fmtAttempts(n) {+ const v = Number(n) || 0;+ if (v >= 1e12) return (v / 1e12).toFixed(1) + 'T';+ if (v >= 1e9) return (v / 1e9).toFixed(1) + 'B';+ if (v >= 1e6) return (v / 1e6).toFixed(1) + 'M';+ if (v >= 1e3) return (v / 1e3).toFixed(1) + 'K';+ return v.toLocaleString('en-US');+ }+ function patternLabel(p) {+ return [p?.prefix && `${p.prefix}…`, p?.suffix && `…${p.suffix}`].filter(Boolean).join(' ') || 'no fixed pattern';+ }+ async function shareCard(address) {+ const url = `${location.origin}/api/vanity/og?address=${encodeURIComponent(address)}`;+ const text = `My Solana wallet ${address.slice(0, 6)}…${address.slice(-4)} — ground & verified on three.ws`;+ const pageUrl = `${location.origin}/vanity/gallery#${encodeURIComponent(address)}`;+ if (navigator.share) { try { await navigator.share({ title: 'Proof-of-Grind', text, url: pageUrl }); return; } catch {} }+ const x = `https://twitter.com/intent/tweet?text=${encodeURIComponent(text)}&url=${encodeURIComponent(pageUrl)}`;+ window.open(x, '_blank', 'noopener');+ }+ window.__shareCard = shareCard;++ // ── Stats strip ────────────────────────────────────────────────────────+ async function loadStats() {+ const strip = $('statstrip');+ strip.innerHTML = '<div class="stat"><div class="skel" style="height:60px"></div></div>';+ try {+ const r = await fetch(`${API}?view=stats`);+ const s = await r.json();+ const total = s.total || 0;+ const segs = TIER_ORDER.map((t) => {+ const n = s.byTier?.[t] || 0;+ return n ? `<span style="flex-grow:${n};background:${TIER_COLOR[t]}" title="${t}: ${n}"></span>` : '';+ }).join('') || '<span style="flex-grow:1;background:#222"></span>';+ const rarest = s.rarest;+ strip.innerHTML =+ `<div class="stat"><div class="k">Wallets ground</div><div class="v">${total.toLocaleString('en-US')}</div><div class="tierbar">${segs}</div></div>` ++ `<div class="stat"><div class="k">Rarest tier on board</div><div class="v" style="color:${rarest ? TIER_COLOR[rarest.tier] : '#888'}">${rarest ? esc(rarest.tierLabel) : '—'}</div></div>` ++ `<div class="stat"><div class="k">Top rarity score</div><div class="v">${rarest ? rarest.rarityScore.toLocaleString('en-US') : '—'}</div></div>`;+ } catch {+ strip.innerHTML = `<div class="stat"><div class="k">Gallery</div><div class="v">Live</div></div>`;+ }+ }++ // ── Gallery ────────────────────────────────────────────────────────────+ let galleryState = { sort: 'recency', tier: null, contains: '', offset: 0, limit: 24, loading: false, hasMore: false };++ function gcardHTML(e) {+ const color = TIER_COLOR[e.tier] || '#888';+ const bonuses = (e.bonuses || []).slice(0, 4).map((b) => `<span class="bonus">${esc(b.label)}</span>`).join('');+ return `<article class="gcard" style="--accent:${color}">+ <div style="display:flex;align-items:center;justify-content:space-between;gap:.5rem">+ <span class="badge" style="background:${color}">${esc(e.tierLabel)}</span>+ ${e.verified ? '<span class="verified">✓ verified</span>' : ''}+ </div>+ <div class="addr">${addrHTML(e.address, e.pattern)}</div>+ ${e.label ? `<div class="label">"${esc(e.label)}"</div>` : ''}+ <div class="meta">+ <div><b>${e.rarityScore.toLocaleString('en-US')}</b>rarity score</div>+ <div><b>${fmtAttempts(e.expectedAttempts)}</b>expected tries</div>+ <div><b>${esc(patternLabel(e.pattern))}</b>pattern</div>+ </div>+ ${bonuses ? `<div class="bonuses">${bonuses}</div>` : ''}+ <div class="acts">+ <a href="${esc(e.explorerUrl)}" target="_blank" rel="noopener">Explorer ↗</a>+ <a href="/vanity/verify" >Verify</a>+ <button type="button" onclick="window.__shareCard('${esc(e.address)}')">Share</button>+ </div>+ </article>`;+ }++ function renderTierPills() {+ const wrap = $('tier-pills');+ wrap.innerHTML = `<button class="tier-pill" data-tier="" aria-pressed="true">All</button>` ++ TIER_ORDER.map((t) => {+ const meta = RARITY_TIERS.find((x) => x.id === t);+ return `<button class="tier-pill" data-tier="${t}" aria-pressed="false" style="--c:${meta.accent}">${esc(meta.label)}</button>`;+ }).join('');+ wrap.querySelectorAll('.tier-pill').forEach((btn) => {+ btn.addEventListener('click', () => {+ wrap.querySelectorAll('.tier-pill').forEach((b) => {+ b.setAttribute('aria-pressed', 'false');+ b.style.background = ''; b.style.borderColor = ''; b.style.color = '';+ });+ btn.setAttribute('aria-pressed', 'true');+ const tier = btn.getAttribute('data-tier');+ if (tier) { const c = TIER_COLOR[tier]; btn.style.background = c; btn.style.borderColor = c; btn.style.color = '#000'; }+ else { btn.style.background = '#fff'; btn.style.color = '#000'; }+ galleryState.tier = tier || null;+ resetGallery();+ });+ });+ // Default "All" styled active.+ const all = wrap.querySelector('[data-tier=""]');+ all.style.background = '#fff'; all.style.color = '#000';+ }++ function resetGallery() { galleryState.offset = 0; $('gallery-grid').innerHTML = ''; loadGallery(); }++ async function loadGallery() {+ if (galleryState.loading) return;+ galleryState.loading = true;+ const grid = $('gallery-grid');+ if (galleryState.offset === 0) {+ grid.innerHTML = Array.from({ length: 6 }, () => '<div class="skel"></div>').join('');+ }+ $('loadmore-btn').disabled = true;+ const p = new URLSearchParams({ sort: galleryState.sort, limit: String(galleryState.limit), offset: String(galleryState.offset) });+ if (galleryState.tier) p.set('tier', galleryState.tier);+ if (galleryState.contains) p.set('contains', galleryState.contains);+ try {+ const r = await fetch(`${API}?${p}`);+ if (!r.ok) throw new Error('load failed');+ const data = await r.json();+ if (galleryState.offset === 0) grid.innerHTML = '';+ if (!data.entries.length && galleryState.offset === 0) {+ grid.innerHTML = '';+ grid.insertAdjacentHTML('beforeend', emptyGalleryHTML());+ } else {+ grid.insertAdjacentHTML('beforeend', data.entries.map(gcardHTML).join(''));+ }+ galleryState.offset += data.entries.length;+ galleryState.hasMore = data.hasMore;+ $('loadmore-row').style.display = data.hasMore ? 'block' : 'none';+ } catch {+ if (galleryState.offset === 0) grid.innerHTML = `<div class="empty"><div class="glyph">⚠</div><h3>Couldn't load the gallery</h3><p>Check your connection and try again.</p><a class="cta" href="javascript:void 0" onclick="location.reload()">Retry</a></div>`;+ } finally {+ galleryState.loading = false;+ $('loadmore-btn').disabled = false;+ }+ }++ function emptyGalleryHTML() {+ const filtered = galleryState.tier || galleryState.contains;+ if (filtered) return `<div class="empty" style="grid-column:1/-1"><div class="glyph">◇</div><h3>No matches</h3><p>No published wallets fit this filter yet. Try a broader tier or clear the search.</p></div>`;+ return `<div class="empty" style="grid-column:1/-1"><div class="glyph">✦</div><h3>Be the first on the board</h3><p>No wallets have been published yet. Grind a provably-fair vanity address, then publish its receipt to claim a spot.</p><a class="cta" href="/vanity-wallet">Grind a wallet →</a></div>`;+ }++ // ── Leaderboard ────────────────────────────────────────────────────────+ let lbLoaded = false;+ async function loadLeaderboard() {+ const el = $('leaderboard');+ el.innerHTML = Array.from({ length: 5 }, () => '<div class="lbrow"><div class="skel" style="height:36px;width:100%;border:none"></div></div>').join('');+ try {+ const r = await fetch(`${API}?view=leaderboard&limit=25`);+ const data = await r.json();+ if (!data.leaderboard.length) {+ el.outerHTML = `<div class="empty" id="leaderboard"><div class="glyph">🏆</div><h3>The leaderboard is open</h3><p>The rarest published wallets rank here. Grind one and publish it to take #1.</p><a class="cta" href="/vanity-wallet">Grind a wallet →</a></div>`;+ return;+ }+ el.innerHTML = data.leaderboard.map((e, i) => {+ const color = TIER_COLOR[e.tier] || '#888';+ const medal = i === 0 ? '🥇' : i === 1 ? '🥈' : i === 2 ? '🥉' : `#${i + 1}`;+ return `<div class="lbrow">+ <div class="rank" style="color:${i < 3 ? color : '#888'}">${medal}</div>+ <div class="ladr">+ <div class="a">${addrHTML(e.address, e.pattern)}</div>+ <div class="sub">${esc(patternLabel(e.pattern))} · ${fmtAttempts(e.expectedAttempts)} expected tries${e.label ? ' · "' + esc(e.label) + '"' : ''}</div>+ </div>+ <span class="tierlabel" style="background:${color}">${esc(e.tierLabel)}</span>+ <div class="score">${e.rarityScore.toLocaleString('en-US')}</div>+ </div>`;+ }).join('');+ lbLoaded = true;+ } catch {+ el.innerHTML = `<div class="empty"><div class="glyph">⚠</div><h3>Couldn't load the leaderboard</h3></div>`;+ }+ }++ // ── Appraise ───────────────────────────────────────────────────────────+ function runAppraisal() {+ const addr = $('appraise-addr').value.trim();+ const resEl = $('appraise-result'), errEl = $('appraise-err');+ errEl.classList.remove('show'); resEl.classList.remove('show');+ if (!/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(addr)) {+ errEl.textContent = 'Enter a valid Base58 Solana address (32–44 characters).'; errEl.classList.add('show'); return;+ }+ const pfx = parseInt($('appraise-prefix').value, 10);+ const sfx = parseInt($('appraise-suffix').value, 10);+ const opts = {};+ if (Number.isInteger(pfx)) opts.prefixLen = pfx;+ if (Number.isInteger(sfx)) opts.suffixLen = sfx;+ const a = appraiseAddress(addr, opts);+ const color = TIER_COLOR[a.tier] || '#888';+ resEl.innerHTML =+ `<div class="big-tier" style="color:${color}">${esc(a.tierLabel)}</div>+ <div class="addr" style="margin-top:.6rem;font-family:ui-monospace,monospace;word-break:break-all;color:rgba(240,240,240,.6)">${addrHTML(addr, { prefix: a.prefix, suffix: a.suffix })}</div>+ <div class="appraise-stats">+ <div class="s"><div class="k">Rarity score</div><div class="v">${a.rarityScore.toLocaleString('en-US')}</div></div>+ <div class="s"><div class="k">Detected pattern</div><div class="v">${esc(patternLabel({ prefix: a.prefix, suffix: a.suffix }))}</div></div>+ <div class="s"><div class="k">Expected work</div><div class="v">${fmtAttempts(a.expectedAttempts)} tries</div></div>+ <div class="s"><div class="k">Grind cost (≈20M/s)</div><div class="v">${esc(a.grindHuman)}</div></div>+ </div>+ ${a.bonuses.length ? `<div class="bonuses" style="margin-top:1rem">${a.bonuses.map((b) => `<span class="bonus">${esc(b.label)} +${b.bits} bits</span>`).join('')}</div>` : ''}+ <div class="acts" style="margin-top:1.1rem"><button type="button" class="ghost" onclick="window.__shareCard('${esc(addr)}')">Share this card</button>+ <a class="ghost" style="text-decoration:none" href="/api/vanity/og?address=${encodeURIComponent(addr)}" target="_blank" rel="noopener">View OG card ↗</a></div>`;+ resEl.classList.add('show');+ }++ // ── Publish ────────────────────────────────────────────────────────────+ async function publish() {+ const errEl = $('publish-err'), okEl = $('publish-ok'), btn = $('publish-btn');+ errEl.classList.remove('show'); okEl.classList.remove('show');+ let receipt;+ try { receipt = JSON.parse($('publish-receipt').value.trim()); }+ catch { errEl.textContent = 'That is not valid JSON. Paste the full receipt object.'; errEl.classList.add('show'); return; }+ // Strip any secret fields client-side before they ever leave the browser.+ for (const k of ['secretKey', 'secretKeyBase58', 'seed', 'sealedSecret']) delete receipt[k];+ btn.disabled = true; btn.textContent = 'Verifying…';+ try {+ const r = await fetch(API, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ receipt, label: $('publish-label').value.trim() }) });+ const data = await r.json();+ if (!r.ok) throw new Error(data.error_description || data.error || 'publish failed');+ okEl.innerHTML = `Published! Your <strong>${esc(data.entry.tierLabel)}</strong> wallet is on the board. <a href="#${encodeURIComponent(data.entry.address)}" style="color:#4ade80;text-decoration:underline">View it</a> · <a href="javascript:void 0" id="post-share" style="color:#4ade80;text-decoration:underline">Share card</a>`;+ okEl.classList.add('show');+ const ps = document.getElementById('post-share'); if (ps) ps.onclick = () => shareCard(data.entry.address);+ $('publish-receipt').value = ''; $('publish-label').value = '';+ loadStats();+ selectTab('gallery'); resetGallery();+ } catch (e) {+ errEl.textContent = e.message || String(e); errEl.classList.add('show');+ } finally {+ btn.disabled = false; btn.textContent = 'Verify & publish';+ }+ }++ // ── Tabs ───────────────────────────────────────────────────────────────+ function selectTab(name) {+ for (const t of ['gallery', 'leaderboard', 'appraise', 'publish']) {+ const on = t === name;+ $(`tab-${t}`).setAttribute('aria-selected', String(on));+ $(`panel-${t}`).classList.toggle('show', on);+ }+ if (name === 'leaderboard' && !lbLoaded) loadLeaderboard();+ // Reflect the tab in the URL hash so it's shareable/back-button-able, but+ // never clobber an address deep-link (#<base58>) the user arrived on.+ const cur = decodeURIComponent((location.hash || '').slice(1));+ const isAddr = /^[1-9A-HJ-NP-Za-km-z]{30,44}$/.test(cur);+ if (!isAddr && cur !== `tab=${name}`) history.replaceState(null, '', `#tab=${name}`);+ }++ ['gallery', 'leaderboard', 'appraise', 'publish'].forEach((t) => {+ $(`tab-${t}`).addEventListener('click', () => selectTab(t));+ });++ // Controls.+ $('sort-select').addEventListener('change', (e) => { galleryState.sort = e.target.value; resetGallery(); });+ let containsTimer;+ $('filter-contains').addEventListener('input', (e) => {+ clearTimeout(containsTimer);+ containsTimer = setTimeout(() => { galleryState.contains = e.target.value.trim(); resetGallery(); }, 280);+ });+ $('loadmore-btn').addEventListener('click', loadGallery);+ $('appraise-btn').addEventListener('click', runAppraisal);+ $('appraise-addr').addEventListener('keydown', (e) => { if (e.key === 'Enter') runAppraisal(); });+ $('publish-btn').addEventListener('click', publish);+ $('publish-clear').addEventListener('click', () => { $('publish-receipt').value = ''; $('publish-label').value = ''; $('publish-err').classList.remove('show'); $('publish-ok').classList.remove('show'); });++ // Deep links: #<address> scrolls/highlights, #tab=<name> selects a tab,+ // ?address= prefills the appraisal.+ function applyHash() {+ const h = decodeURIComponent((location.hash || '').slice(1));+ if (h.startsWith('tab=')) { selectTab(h.slice(4)); return; }+ if (/^[1-9A-HJ-NP-Za-km-z]{30,44}$/.test(h)) {+ selectTab('appraise');+ $('appraise-addr').value = h;+ runAppraisal();+ }+ }++ // Boot.+ renderTierPills();+ loadStats();+ loadGallery();+ const qAddr = new URLSearchParams(location.search).get('address');+ if (qAddr) { selectTab('appraise'); $('appraise-addr').value = qAddr; runAppraisal(); }+ else applyHash();+ window.addEventListener('hashchange', applyHash);+ </script>+</body>+</html>diff --git a/public/vanity/verify/index.html b/public/vanity/verify/index.htmlindex c5bce4fd2..89be1cef4 100644--- a/public/vanity/verify/index.html+++ b/public/vanity/verify/index.html@@ -54,6 +54,7 @@.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.partial { background:var(--warn-bg); color:var(--warn-fg); border:1px solid rgba(251,191,36,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; }@@ -92,6 +93,23 @@a.link { color:#ffd54f; text-decoration:none; border-bottom:1px solid rgba(255,213,79,.4); }a.link:hover { border-bottom-color:#ffd54f; }</style>++ <link rel="canonical" href="https://three.ws/vanity/verify">+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">+ <meta property="og:type" content="website">+ <meta property="og:site_name" content="three.ws">+ <meta property="og:locale" content="en_US">+ <meta property="og:url" content="https://three.ws/vanity/verify">+ <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&t=Verify+a+Vanity+Receipt&d=Independently+verify+a+three.ws+provably-fair+vanity+wallet+receipt+%E2%80%94+entirely+in+your+browser.+Prove+the+key+was+generated+fresh+under+a+committed+seed+and+the&p=%2Fvanity%2Fverify">+ <meta property="og:image:width" content="1200">+ <meta property="og:image:height" content="630">+ <meta property="og:image:type" content="image/png">+ <meta property="og:image:alt" content="Verify a Vanity Receipt — three.ws">+ <meta name="twitter:site" content="@trythreews">+ <meta name="twitter:title" content="Verify a Vanity Receipt · three.ws">+ <meta name="twitter: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 never kept a copy.">+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&t=Verify+a+Vanity+Receipt&d=Independently+verify+a+three.ws+provably-fair+vanity+wallet+receipt+%E2%80%94+entirely+in+your+browser.+Prove+the+key+was+generated+fresh+under+a+committed+seed+and+the&p=%2Fvanity%2Fverify">+ <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","name":"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.","url":"https://three.ws/vanity/verify","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"},"primaryImageOfPage":"https://three.ws/api/page-og?s=crypto&t=Verify+a+Vanity+Receipt&d=Independently+verify+a+three.ws+provably-fair+vanity+wallet+receipt+%E2%80%94+entirely+in+your+browser.+Prove+the+key+was+generated+fresh+under+a+committed+seed+and+the&p=%2Fvanity%2Fverify"},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https://three.ws/"},{"@type":"ListItem","position":2,"name":"Vanity","item":"https://three.ws/vanity"},{"@type":"ListItem","position":3,"name":"Verify","item":"https://three.ws/vanity/verify"}]}]}</script></head><body><a href="#main-content" class="skip-link">Skip to main content</a>@@ -141,6 +159,7 @@<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>+ <a class="link" id="publish-link" href="/vanity/gallery#tab=publish" style="align-self:center;font-size:.85rem">Publish to the rarity gallery →</a></div></div>@@ -205,7 +224,7 @@$('verdict').classList.remove('show');}- function renderResult(result, receipt) {+ function renderResult(result, receipt, { pinned } = { pinned: true }) {const checksEl = $('checks');checksEl.innerHTML = result.checks.map((c) =>'<div class="check ' + (c.pass ? 'pass' : 'fail') + '">' +@@ -215,13 +234,23 @@'</div>').join('');+ // Full "provably fair" only when every check passed AND we pinned the+ // signer against the independent well-known key. Internally-valid but+ // unpinned → a deliberately cautious "partial" state, not a green pass.+ const fullyTrustless = result.valid && pinned;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.';+ verdict.className = 'verdict show ' + (result.valid ? (fullyTrustless ? 'ok' : 'partial') : 'bad');+ $('vmark').textContent = result.valid ? (fullyTrustless ? '✓' : '!') : '✗';+ $('vtext-main').textContent = !result.valid+ ? 'Verification failed — do not trust this receipt.'+ : fullyTrustless+ ? 'Verified — this receipt is provably fair.'+ : 'Receipt is self-consistent, but the signer is unpinned.';+ $('vtext-sub').textContent = !result.valid+ ? 'One or more protocol checks did not pass. The key/receipt may have been tampered with.'+ : fullyTrustless+ ? 'The key was generated fresh under the committed seed; the operator could not have kept a copy.'+ : 'Every protocol check passed against the receipt’s own key, but we could not reach /.well-known/three-vanity.json to confirm three.ws (not an impostor) signed it. Re-run when online to fully pin.';const m = $('meta');m.innerHTML = '<dl class="meta-grid">' +@@ -233,7 +262,7 @@'</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);+ $('share-row').classList.toggle('show', fullyTrustless);}async function verify() {@@ -259,8 +288,13 @@openedSecretSeed = bundle.seed || (Array.isArray(bundle.secretKey) ? Uint8Array.from(bundle.secretKey).slice(0, 32) : undefined);}+ // Pin to the live well-known key when we have it. If we couldn't fetch+ // it, verify against the receipt's own key but DOWNGRADE the verdict:+ // without an independent pin we can confirm the receipt is internally+ // consistent and self-signed, but not that three.ws (vs an impostor)+ // signed it — so we never show the full "provably fair" green banner.const result = verifyVanityReceipt(receipt, { servicePublicKey: pinnedKey || receipt.servicePublicKey, openedSecretSeed });- renderResult(result, receipt);+ renderResult(result, receipt, { pinned: !!pinnedKey });} catch (e) {$('results-card').style.display = 'none';showError(e.message || String(e));diff --git a/public/x402/studio.html b/public/x402/studio.htmlindex 5029868cf..2526faca5 100644--- a/public/x402/studio.html+++ b/public/x402/studio.html@@ -212,6 +212,23 @@ tr:last-child td { border-bottom: 0; }.nav button { white-space: nowrap; }}</style>++ <link rel="canonical" href="https://three.ws/x402/studio">+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">+ <meta property="og:site_name" content="three.ws">+ <meta property="og:locale" content="en_US">+ <meta property="og:url" content="https://three.ws/x402/studio">+ <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&t=x402+Studio+%E2%80%94+the+Stripe+of+x402&d=Merchant+console+to+run+a+paid+x402+business%3A+products+and+pricing%2C+payout+and+agent+wallets%2C+a+real+USDC+send%2Freceive+with+SNS+.sol+resolution%2C+a+drag-and-drop&p=%2Fx402%2Fstudio">+ <meta property="og:image:width" content="1200">+ <meta property="og:image:height" content="630">+ <meta property="og:image:type" content="image/png">+ <meta property="og:image:alt" content="x402 Studio — the Stripe of x402 — three.ws">+ <meta name="twitter:card" content="summary_large_image">+ <meta name="twitter:site" content="@trythreews">+ <meta name="twitter:title" content="x402 Studio — the Stripe of x402 · three.ws">+ <meta name="twitter:description" content="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.">+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&t=x402+Studio+%E2%80%94+the+Stripe+of+x402&d=Merchant+console+to+run+a+paid+x402+business%3A+products+and+pricing%2C+payout+and+agent+wallets%2C+a+real+USDC+send%2Freceive+with+SNS+.sol+resolution%2C+a+drag-and-drop&p=%2Fx402%2Fstudio">+ <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","name":"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.","url":"https://three.ws/x402/studio","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"},"primaryImageOfPage":"https://three.ws/api/page-og?s=crypto&t=x402+Studio+%E2%80%94+the+Stripe+of+x402&d=Merchant+console+to+run+a+paid+x402+business%3A+products+and+pricing%2C+payout+and+agent+wallets%2C+a+real+USDC+send%2Freceive+with+SNS+.sol+resolution%2C+a+drag-and-drop&p=%2Fx402%2Fstudio"},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https://three.ws/"},{"@type":"ListItem","position":2,"name":"X402","item":"https://three.ws/x402"},{"@type":"ListItem","position":3,"name":"Studio","item":"https://three.ws/x402/studio"}]}]}</script></head><body><div id="root">diff --git a/solana-agent-sdk/src/vanity/client.ts b/solana-agent-sdk/src/vanity/client.tsindex 3759e21fb..546aff675 100644--- a/solana-agent-sdk/src/vanity/client.ts+++ b/solana-agent-sdk/src/vanity/client.ts@@ -21,7 +21,9 @@import bs58 from "bs58";import {verifyVanityReceipt,+ fetchServiceKey,THREE_VANITY_ENDPOINT,+ THREE_VANITY_WELL_KNOWN,type VanityReceipt,type VerifyResult,} from "./verify.js";@@ -57,8 +59,13 @@ export interface GrindVerifiedOptions {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;+ /** Override the pinned service key. By default the live key is fetched from+ * the well-known document and pinned, so verification never depends on a+ * possibly-stale SDK constant. Pass `false` to skip the fetch and use the+ * built-in pin, or a string to pin an explicit key. */+ servicePublicKey?: string | false;+ /** Well-known URL to resolve the live service key from (default three.ws). */+ wellKnownUrl?: string;}function randomClientSeedHex(): string {@@ -120,8 +127,20 @@ export async function grindVerifiedVanity(}// 4. Independently verify EVERY claim — including custody of THIS key.+ // Pin against the LIVE well-known key by default (so a stale SDK constant+ // never causes a false negative or a false positive); callers can override+ // with an explicit key or `false` to use the built-in pin.+ let servicePublicKey: string | undefined;+ if (opts.servicePublicKey === false) {+ servicePublicKey = undefined; // fall back to the SDK's built-in pin+ } else if (typeof opts.servicePublicKey === "string") {+ servicePublicKey = opts.servicePublicKey;+ } else {+ servicePublicKey = await fetchServiceKey(opts.wellKnownUrl ?? THREE_VANITY_WELL_KNOWN);+ }+const verification = verifyVanityReceipt(receipt, {- servicePublicKey: opts.servicePublicKey,+ servicePublicKey,openedSecretSeed: openedSeed,});if (!verification.valid) {diff --git a/solana-agent-sdk/src/vanity/verify.ts b/solana-agent-sdk/src/vanity/verify.tsindex c86144231..5fa2c241d 100644--- a/solana-agent-sdk/src/vanity/verify.ts+++ b/solana-agent-sdk/src/vanity/verify.ts@@ -22,10 +22,14 @@ 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.+ * to this by default so a self-signed impostor receipt is rejected.+ *+ * IMPORTANT: this is a *bootstrap* pin. The authoritative key is always the one+ * published at `/.well-known/three-vanity.json` for the deployment that issued+ * your receipt. For production verification, resolve the live key with+ * `fetchServiceKey()` and pass it as `servicePublicKey` — the one-call client+ * (`grindVerifiedVanity`) does this automatically. Update this constant whenever+ * the service key rotates so the offline default stays accurate.*/export const THREE_VANITY_SERVICE_KEY = "H8wSgC8JgTadWE4ECVkUdHRywxEygnLbpJjEwcej92NH";diff --git a/src/agent-detail.css b/src/agent-detail.cssindex c44fcd561..ce09107e8 100644--- a/src/agent-detail.css+++ b/src/agent-detail.css@@ -98,6 +98,10 @@ a {max-width: 920px;margin: 0 auto;width: 100%;+ /* Grid item: allow the 1fr track to shrink below the content's+ min-content width so long monospace URLs / mono blocks can't blow+ the page out horizontally on narrow viewports. */+ min-width: 0;}.ad-banner {@@ -118,6 +122,7 @@ a {}.ad-search {flex: 1;+ min-width: 0;background: var(--ad-bg-2);border: 1px solid var(--ad-line);color: var(--ad-text);@@ -592,6 +597,7 @@ model-viewer.ad-hero-avatar {text-overflow: ellipsis;white-space: nowrap;flex: 1;+ min-width: 0;}.ad-svc-meta {display: flex;@@ -737,6 +743,30 @@ model-viewer.ad-hero-avatar {}}+@media (max-width: 480px) {+ .ad-topbar {+ flex-wrap: wrap;+ padding: 12px 16px;+ }+ .ad-search {+ flex: 1 1 100%;+ order: 2;+ }+ .ad-actions {+ flex: 1 1 100%;+ justify-content: flex-end;+ }+ .ad-back {+ margin: 16px 16px 8px;+ }+ .ad-back-row {+ margin-right: 16px;+ }+ .ad-hero {+ padding: 0 16px 20px;+ }+}+.ad-bullet-red {background: var(--danger);}diff --git a/src/pages/sealed-drops.js b/src/pages/sealed-drops.jsnew file mode 100644index 000000000..4f13e4e7b--- /dev/null+++ b/src/pages/sealed-drops.js@@ -0,0 +1,472 @@+// Controller for the sealed wallet drops surface.+//+// Two entry points share this module:+// • /vanity-wallet … (the "Send a sealed gift" composer — mounted when+// #drop-create exists): builds the create flow (asset/amount, vanity, seal+// mode, message/theme, expiry, reclaim address), pays the x402 create fee,+// and shows the shareable link + QR + OG card.+// • /drop/:id (the claim page — mounted when #drop-claim exists): loads the+// drop, renders the gift, and on claim opens the SEALED envelope ENTIRELY+// CLIENT-SIDE (with the claim key from the URL fragment in bearer mode, or+// the recipient's pasted X25519 private key in direct mode), then offers+// import / download / sweep. three.ws never sees the plaintext.+//+// All crypto is real: ECIES sealed-envelope (openSealed), SHA-256 claim-token+// derivation (drop-protocol), X25519 keygen. All money rails are real: x402 for+// the create fee, on-chain funding + reclaim server-side.++import bs58 from 'bs58';+import {+ generateRecipientKeypair,+ openSealedText,+ parseX25519Key,+} from '../solana/vanity/sealed-envelope.js';+import { deriveClaimToken, hashClaimToken } from '../solana/vanity/drop-protocol.js';++const API = '/api/vanity/drops';+const $ = (id) => document.getElementById(id);++export function esc(s) {+ return String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));+}+function shortAddr(a) { const s = String(a || ''); return s.length > 16 ? `${s.slice(0, 8)}…${s.slice(-6)}` : s; }+function assetLabel(a) { return a === 'THREE' ? '$THREE' : String(a || ''); }+function timeLeft(ms) {+ const d = ms - Date.now();+ if (d <= 0) return 'expired';+ const s = Math.floor(d / 1000);+ if (s < 3600) return `${Math.floor(s / 60)}m`;+ if (s < 86400) return `${Math.floor(s / 3600)}h ${Math.floor((s % 3600) / 60)}m`;+ return `${Math.floor(s / 86400)}d ${Math.floor((s % 86400) / 3600)}h`;+}++async function api(path, opts) {+ const r = await fetch(`${API}${path}`, opts);+ const ct = r.headers.get('content-type') || '';+ const data = ct.includes('json') ? await r.json().catch(() => ({})) : {};+ if (!r.ok) {+ const e = new Error(data.error_description || data.error || `HTTP ${r.status}`);+ e.status = r.status; e.data = data;+ throw e;+ }+ return data;+}++function toast(msg) {+ let t = $('drop-toast');+ if (!t) { t = document.createElement('div'); t.id = 'drop-toast'; t.className = 'drop-toast'; document.body.appendChild(t); }+ t.textContent = msg; t.classList.add('show');+ clearTimeout(toast._t); toast._t = setTimeout(() => t.classList.remove('show'), 2600);+}++// ── shared: open a sealed envelope client-side and render the recovered key ────++function renderOpenedWallet(container, wallet, address) {+ const mnemonic = wallet.format === 'mnemonic' ? wallet.mnemonic : null;+ const cliJson = JSON.stringify(wallet.secretKey);+ container.innerHTML = `+ <div class="okbox show" role="status">🔓 Wallet opened in your browser. three.ws never saw this secret.</div>+ ${mnemonic ? `<label class="fl">Seed phrase (import into Phantom / Solflare)</label><div class="keybox"><code id="op-mn">${esc(mnemonic)}</code><button class="ghost small" data-copy="op-mn">Copy phrase</button></div>` : ''}+ <label class="fl">Secret key (Base58)</label>+ <div class="keybox"><code id="op-sk">${esc(wallet.secretKeyBase58 || '')}</code><button class="ghost small" data-copy="op-sk">Copy key</button></div>+ <div class="row" style="margin-top:.8rem">+ <button class="ghost small" id="op-dl">Download Solana CLI JSON</button>+ <a class="ghost small" href="https://solscan.io/account/${esc(address)}" target="_blank" rel="noopener">View address on Solscan ↗</a>+ </div>+ <p class="note" style="margin-top:.8rem">Import the seed phrase or secret key into your wallet to take custody. Keep it private — it controls the funds.</p>`;+ container.querySelectorAll('[data-copy]').forEach((b) => b.addEventListener('click', async () => {+ await navigator.clipboard?.writeText($(b.dataset.copy)?.textContent || '').catch(() => {});+ toast('Copied');+ }));+ $('op-dl')?.addEventListener('click', () => {+ const blob = new Blob([cliJson], { type: 'application/json' });+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a'); a.href = url; a.download = `${address.slice(0, 8)}.json`; a.click();+ setTimeout(() => URL.revokeObjectURL(url), 1000);+ });+}++// ════════════════════════════════════════════════════════════════════════════+// CREATE flow (#drop-create present)+// ════════════════════════════════════════════════════════════════════════════++function mountCreate() {+ const root = $('drop-create');+ if (!root) return;+ let config = null;+ let directKeypair = null; // { publicKey, secretKey } when the composer generates a recipient key++ const els = {+ asset: $('dc-asset'), amount: $('dc-amount'), seal: () => root.querySelector('input[name="dc-seal"]:checked')?.value || 'claim-time',+ directWrap: $('dc-direct-wrap'), recipient: $('dc-recipient'), genKey: $('dc-genkey'),+ prefix: $('dc-prefix'), suffix: $('dc-suffix'), format: $('dc-format'),+ message: $('dc-message'), theme: $('dc-theme'), sender: $('dc-sender'),+ expiry: $('dc-expiry'), reclaim: $('dc-reclaim'),+ btn: $('dc-submit'), hint: $('dc-hint'), err: $('dc-err'), result: $('dc-result'),+ };++ api('?view=config').then((c) => {+ config = c;+ if (!c.fundingConfigured) {+ els.hint.textContent = 'Sealed drops are unavailable in this environment (funding wallet not configured).';+ els.btn.disabled = true;+ } else {+ els.hint.textContent = `You’ll pay a $${c.createFeeUsd} create fee. The gift amount is funded on-chain into a fresh wallet.`;+ }+ }).catch(() => { els.hint.textContent = 'Could not load drop config — reload the page.'; });++ function syncSeal() {+ const mode = els.seal();+ els.directWrap.style.display = mode === 'direct' ? '' : 'none';+ root.querySelector('#dc-bearer-note').style.display = mode === 'claim-time' ? '' : 'none';+ }+ root.querySelectorAll('input[name="dc-seal"]').forEach((r) => r.addEventListener('change', syncSeal));+ syncSeal();++ els.genKey?.addEventListener('click', () => {+ directKeypair = generateRecipientKeypair();+ els.recipient.value = directKeypair.publicKey;+ const note = $('dc-genkey-note');+ note.innerHTML = `Generated. <strong>Give the recipient this private key</strong> — it is the ONLY way to open the gift:<br><code class="mono" style="word-break:break-all;color:#fcd34d">${esc(directKeypair.secretKey)}</code> <button class="ghost small" id="dc-copy-priv">Copy private key</button>`;+ note.style.display = '';+ $('dc-copy-priv')?.addEventListener('click', async () => { await navigator.clipboard?.writeText(directKeypair.secretKey).catch(() => {}); toast('Private key copied — share it securely'); });+ });++ els.btn?.addEventListener('click', submit);++ async function submit() {+ els.err.classList.remove('show');+ const asset = els.asset.value;+ const amount = els.amount.value.trim();+ const sealMode = els.seal();+ if (!amount || !(Number(amount) > 0)) { return showErr('Enter a gift amount greater than 0.'); }++ const bodyObj = {+ asset, amount, sealMode,+ prefix: els.prefix.value.trim(), suffix: els.suffix.value.trim(),+ format: els.format.value,+ expiryHours: String(Math.max(1, parseInt(els.expiry.value, 10) || 168)),+ };+ if (els.message.value.trim()) bodyObj.message = els.message.value.trim();+ if (els.theme.value) bodyObj.theme = els.theme.value;+ if (els.sender.value.trim()) bodyObj.senderLabel = els.sender.value.trim();+ if (els.reclaim.value.trim()) bodyObj.reclaimAddress = els.reclaim.value.trim();+ bodyObj.senderTag = localSenderTag();++ if (sealMode === 'direct') {+ const rk = els.recipient.value.trim();+ if (!rk) return showErr('Direct seal needs the recipient’s X25519 public key — paste it or generate a key pair.');+ try { parseX25519Key(rk, 'recipient'); } catch { return showErr('That recipient key is not a valid X25519 public key.'); }+ bodyObj.recipientPubKey = rk;+ }++ if (!window.X402?.pay) return showErr('Payment library failed to load — reload the page.');+ els.btn.disabled = true; const label = els.btn.textContent; els.btn.innerHTML = '<span class="spin"></span> Opening checkout…';+ try {+ const out = await window.X402.pay({+ endpoint: `${API}?action=create`,+ method: 'POST',+ body: bodyObj,+ merchant: 'three.ws Sealed Wallet Drops',+ action: `Create a ${esc(amount)} ${assetLabel(asset)} sealed gift`,+ });+ const res = out?.result;+ if (!res?.created) throw new Error(res?.error_description || res?.error || 'create did not confirm');+ renderCreated(res, sealMode, directKeypair);+ toast('Sealed drop created & funded');+ } catch (e) {+ showErr(e.message || 'Create failed.');+ } finally {+ els.btn.disabled = false; els.btn.textContent = label;+ }+ }++ function renderCreated(res, sealMode, dkp) {+ const id = res.drop.id;+ const claimUrl = res.claimUrl; // bearer: includes #k=…+ const shareUrl = res.shareUrl;+ const fundTx = res.funding?.tx;+ els.result.innerHTML = `+ <div class="okbox show">🎁 Your sealed drop is live and funded on-chain.</div>+ <div class="kv"><span class="k">Address</span><span class="v mono">${esc(shortAddr(res.drop.address))}</span></div>+ <div class="kv"><span class="k">Funded</span><span class="v">${esc(res.drop.amount)} ${assetLabel(res.drop.asset)}</span></div>+ ${fundTx ? `<div class="kv"><span class="k">Funding tx</span><span class="v"><a class="mono" href="https://solscan.io/tx/${esc(fundTx)}" target="_blank" rel="noopener">${esc(fundTx.slice(0, 10))}… ↗</a></span></div>` : ''}+ <label class="fl" style="margin-top:1rem">Share this claim link</label>+ <div class="keybox"><code id="dc-link">${esc(claimUrl)}</code>+ <div class="row" style="margin-top:.5rem">+ <button class="primary small" id="dc-copylink">Copy link</button>+ <button class="ghost small" id="dc-share">Share…</button>+ <a class="ghost small" href="${esc(claimUrl)}" target="_blank" rel="noopener">Open claim page ↗</a>+ </div>+ </div>+ <div class="qrwrap" id="dc-qr" aria-label="Claim QR code"></div>+ ${sealMode === 'claim-time'+ ? `<div class="warnbox show" style="margin-top:.8rem">⚠️ The link contains the only key that opens this wallet. Anyone with the full link can claim it once. Send it privately. three.ws cannot recover it.</div>`+ : `<div class="okbox show" style="margin-top:.8rem">Sealed to the recipient’s key. Only they can open it — even with the link, no one else can.</div>`}+ <details style="margin-top:.8rem"><summary>Reclaim & manage</summary>+ <p class="note">If this gift isn’t claimed before it expires (${timeLeft(res.drop.expiresAt)}), you can reclaim the funds. Your drops are remembered in this browser under <a href="/vanity-wallet#mine">My drops</a>.</p>+ </details>`;+ // QR rendered from the FULL claim link (with fragment) — client-side so the+ // claim key in the fragment is never sent to a server to make the QR.+ renderQr($('dc-qr'), claimUrl);+ $('dc-copylink')?.addEventListener('click', async () => { await navigator.clipboard?.writeText(claimUrl).catch(() => {}); toast('Claim link copied'); });+ $('dc-share')?.addEventListener('click', async () => {+ if (navigator.share) { try { await navigator.share({ title: 'A sealed gift for you', text: res.drop.message || 'Claim your sealed wallet', url: claimUrl }); } catch { /* cancelled */ } }+ else { await navigator.clipboard?.writeText(claimUrl).catch(() => {}); toast('Link copied (share not supported here)'); }+ });+ rememberDrop(id);+ els.result.scrollIntoView({ behavior: 'smooth', block: 'nearest' });+ }++ function showErr(m) { els.err.textContent = m; els.err.classList.add('show'); }+}++// ════════════════════════════════════════════════════════════════════════════+// CLAIM flow (#drop-claim present)+// ════════════════════════════════════════════════════════════════════════════++function dropIdFromPath() {+ const m = location.pathname.match(/\/drop\/([0-9a-f]{24})/);+ if (m) return m[1];+ const q = new URLSearchParams(location.search).get('id');+ return /^[0-9a-f]{24}$/.test(q || '') ? q : null;+}+function claimSecretFromFragment() {+ const m = location.hash.match(/[#&]k=([1-9A-HJ-NP-Za-km-z]+)/);+ return m ? m[1] : null;+}++async function mountClaim() {+ const root = $('drop-claim');+ if (!root) return;+ const id = dropIdFromPath();+ const stage = $('dc-stage');+ if (!id) { renderClaimError(stage, 'No drop in the link', 'This claim link is missing its drop id. Ask the sender for the original link.'); return; }++ stage.innerHTML = skeletonCard();+ let info;+ try {+ info = await api(`?view=get&id=${id}`);+ } catch (e) {+ if (e.status === 404) return renderClaimError(stage, 'Drop not found', 'This drop doesn’t exist. Check the link, or it may have been a typo.');+ return renderClaimError(stage, 'Couldn’t load this drop', e.message);+ }+ const drop = info.drop;+ if (!drop) return renderClaimError(stage, 'Drop not found', 'This drop doesn’t exist.');++ renderGiftHeader(stage, drop);++ if (drop.status === 'claimed') return renderAlreadyClaimed(stage, drop);+ if (drop.status === 'reclaimed') return renderReclaimed(stage, drop);+ if (info.expired) return renderExpired(stage, drop);++ // Claimable. Branch on seal mode.+ if (info.sealMode === 'claim-time') return renderBearerClaim(stage, drop, id);+ return renderDirectClaim(stage, drop, id);+}++function renderGiftHeader(stage, drop) {+ const themeGlyph = { default: '🎁', birthday: '🎂', congrats: '🎉', thanks: '🙏', welcome: '👋', tip: '⚡' }[drop.theme] || '🎁';+ stage.innerHTML = `+ <div class="gift theme-${esc(drop.theme || 'default')}">+ <div class="gift-glyph" aria-hidden="true">${themeGlyph}</div>+ ${drop.senderLabel ? `<div class="gift-from">From <strong>${esc(drop.senderLabel)}</strong></div>` : ''}+ <div class="gift-amount">${esc(drop.amount)} <span>${assetLabel(drop.asset)}</span></div>+ ${drop.message ? `<div class="gift-msg">“${esc(drop.message)}”</div>` : ''}+ <div class="gift-addr mono">${esc(shortAddr(drop.address))}</div>+ <div class="gift-badge">🔒 End-to-end sealed · only you can open it</div>+ </div>+ <div id="dc-action"></div>`;+}++function renderBearerClaim(stage, drop, id) {+ const action = $('dc-action');+ const secret = claimSecretFromFragment();+ if (!secret) {+ action.innerHTML = `+ <div class="warnbox show">This is a bearer gift — the claim key lives in the link itself. Your link is missing the <code>#k=…</code> part. Ask the sender to re-send the FULL link (it’s long and ends in <code>#k=…</code>).</div>`;+ return;+ }+ action.innerHTML = `+ <button class="primary big" id="dc-claimbtn">Claim this gift</button>+ <p class="note" id="dc-claimnote">Claiming opens the sealed wallet right here in your browser. three.ws never sees the key.</p>+ <div id="dc-opened"></div>`;+ $('dc-claimbtn').addEventListener('click', () => claimBearer(id, secret));+}++async function claimBearer(id, secretB58) {+ const btn = $('dc-claimbtn'); const note = $('dc-claimnote'); const opened = $('dc-opened');+ btn.disabled = true; btn.innerHTML = '<span class="spin"></span> Claiming…';+ try {+ // Derive the one-time claim token from the secret in the link (client-side).+ const secretBytes = bs58.decode(secretB58);+ const claimToken = deriveClaimToken(id, secretBytes);+ const res = await api('?action=claim', {+ method: 'POST', headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ id, claimToken }),+ });+ if (!res.claimed) throw new Error(res.reason || 'claim did not confirm');+ // Open the sealed envelope ENTIRELY client-side with the claim secret.+ const plaintext = await openSealedText(res.sealedSecret, secretB58);+ const wallet = JSON.parse(plaintext);+ note.textContent = 'Claimed. Your wallet is below — import it to take custody.';+ renderOpenedWallet(opened, wallet, res.address);+ btn.style.display = 'none';+ } catch (e) {+ btn.disabled = false; btn.innerHTML = 'Claim this gift';+ if (e.status === 409) { note.innerHTML = `<span style="color:#fca5a5">This gift was already claimed.</span>`; btn.style.display = 'none'; }+ else if (e.status === 403) { note.innerHTML = `<span style="color:#fca5a5">This claim link’s key is wrong — use the original full link.</span>`; }+ else { note.innerHTML = `<span style="color:#fca5a5">Couldn’t claim: ${esc(e.message)}</span>`; }+ }+}++function renderDirectClaim(stage, drop, id) {+ const action = $('dc-action');+ action.innerHTML = `+ <div class="okbox show">This gift was sealed to your encryption key. Paste your X25519 <strong>private key</strong> to open it — it stays in your browser.</div>+ <label class="fl">Your X25519 private key</label>+ <input class="t" id="dc-priv" type="password" autocomplete="off" placeholder="Base58 / Base64url / hex private key" />+ <button class="primary big" id="dc-openbtn" style="margin-top:.7rem">Open my gift</button>+ <p class="note" id="dc-opennote">three.ws never receives this key. The decrypt happens locally.</p>+ <div id="dc-opened"></div>`;+ $('dc-openbtn').addEventListener('click', () => claimDirect(id, drop));+}++async function claimDirect(id, drop) {+ const priv = $('dc-priv').value.trim();+ const note = $('dc-opennote'); const opened = $('dc-opened'); const btn = $('dc-openbtn');+ if (!priv) { note.innerHTML = '<span style="color:#fca5a5">Paste your private key first.</span>'; return; }+ btn.disabled = true; btn.innerHTML = '<span class="spin"></span> Opening…';+ try {+ // Mark the gift claimed (atomic) + fetch the sealed envelope, then open it+ // locally. In direct mode the envelope is also fetchable via reveal, but+ // claim records the "opened" state and is exactly-once.+ const res = await api('?action=claim', {+ method: 'POST', headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ id }),+ }).catch(async (e) => {+ // If already claimed, fall back to reveal so the rightful key-holder can+ // still open it (the envelope is useless without their private key).+ if (e.status === 409) return api('?action=reveal', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ id }) });+ throw e;+ });+ const env = res.sealedSecret;+ const plaintext = await openSealedText(env, priv);+ const wallet = JSON.parse(plaintext);+ if (wallet.secretKeyBase58 && res.address) {+ const kpAddr = bs58.encode(bs58.decode(wallet.secretKeyBase58).slice(32));+ if (kpAddr !== res.address) throw new Error('decrypted key does not match the gift address');+ }+ note.textContent = 'Opened. Import the wallet below to take custody.';+ renderOpenedWallet(opened, wallet, res.address || drop.address);+ btn.style.display = 'none';+ } catch (e) {+ btn.disabled = false; btn.innerHTML = 'Open my gift';+ note.innerHTML = `<span style="color:#fca5a5">${esc(e.message?.includes('decrypt') || e.name === 'OperationError' ? 'That key can’t open this gift — wrong private key.' : (e.message || 'Open failed.'))}</span>`;+ }+}++function renderAlreadyClaimed(stage, drop) {+ $('dc-action').innerHTML = `<div class="statebox claimed"><div class="se-glyph">✅</div><h3>Already claimed</h3><p>This gift has already been opened${drop.claimedAt ? ` on ${new Date(drop.claimedAt).toLocaleDateString()}` : ''}. There’s nothing left to claim.</p><a class="ghost" href="https://solscan.io/account/${esc(drop.address)}" target="_blank" rel="noopener">View the wallet ↗</a></div>`;+}+function renderReclaimed(stage, drop) {+ $('dc-action').innerHTML = `<div class="statebox reclaimed"><div class="se-glyph">↩️</div><h3>Returned to sender</h3><p>This gift expired unclaimed, so the funds were reclaimed by the sender. Reach out to them if you were expecting it.</p></div>`;+}+function renderExpired(stage, drop) {+ $('dc-action').innerHTML = `<div class="statebox expired"><div class="se-glyph">⌛</div><h3>This gift expired</h3><p>It wasn’t claimed in time, so it can no longer be opened. The sender can reclaim the funds. Ask them to send a fresh drop.</p></div>`;+}+function renderClaimError(stage, title, msg) {+ stage.innerHTML = `<div class="statebox error"><div class="se-glyph">⚠️</div><h3>${esc(title)}</h3><p>${esc(msg)}</p><a class="ghost" href="/vanity-wallet">Create your own sealed drop →</a></div>`;+}+function skeletonCard() {+ return `<div class="gift skel-gift" aria-hidden="true"><div class="skel-line w40"></div><div class="skel-line w70 big"></div><div class="skel-line w50"></div></div><p class="note" style="text-align:center">Loading your gift…</p>`;+}++// ── local "my drops" memory (so a sender can find drops to reclaim) ───────────++const TAG_KEY = 'twx_drop_sender_tag';+const MINE_KEY = 'twx_my_drops';+function localSenderTag() {+ let t = localStorage.getItem(TAG_KEY);+ if (!t) { t = 'st_' + bs58.encode(crypto.getRandomValues(new Uint8Array(12))); localStorage.setItem(TAG_KEY, t); }+ return t;+}+function rememberDrop(id) {+ try {+ const list = JSON.parse(localStorage.getItem(MINE_KEY) || '[]');+ if (!list.includes(id)) { list.unshift(id); localStorage.setItem(MINE_KEY, JSON.stringify(list.slice(0, 100))); }+ } catch { /* ignore */ }+}++async function mountMine() {+ const root = $('drop-mine');+ if (!root) return;+ const list = $('dm-list');+ const tag = localStorage.getItem(TAG_KEY);+ if (!tag) { list.innerHTML = `<div class="empty"><div class="glyph">🎁</div><h3>No drops yet</h3><p>Sealed gifts you create will appear here so you can reclaim any that expire unclaimed.</p></div>`; return; }+ list.innerHTML = `<div class="skel" style="height:90px"></div>`;+ let drops = [];+ try { ({ drops } = await api(`?view=mine&senderTag=${encodeURIComponent(tag)}`)); }+ catch (e) { list.innerHTML = `<div class="errbox show">Couldn’t load your drops: ${esc(e.message)}</div>`; return; }+ if (!drops.length) { list.innerHTML = `<div class="empty"><div class="glyph">🎁</div><h3>No drops yet</h3><p>Sealed gifts you create will appear here.</p></div>`; return; }+ list.innerHTML = drops.map(mineRow).join('');+ list.querySelectorAll('[data-reclaim]').forEach((b) => b.addEventListener('click', () => reclaim(b.dataset.reclaim, b)));+ list.querySelectorAll('[data-copy-link]').forEach((b) => b.addEventListener('click', async () => { await navigator.clipboard?.writeText(`${location.origin}/drop/${b.dataset.copyLink}`).catch(() => {}); toast('Share link copied'); }));+}++function mineRow(d) {+ const expired = d.status === 'funded' && d.expiresAt && Date.now() > d.expiresAt;+ const statusLabel = d.status === 'claimed' ? 'Claimed' : d.status === 'reclaimed' ? 'Reclaimed' : expired ? 'Expired' : 'Unclaimed';+ const statusClass = d.status === 'claimed' ? 'claimed' : d.status === 'reclaimed' ? 'reclaimed' : expired ? 'expired' : 'open';+ return `<div class="minerow">+ <div>+ <div class="mr-amt">${esc(d.amount)} ${assetLabel(d.asset)}</div>+ <div class="mr-meta mono">${esc(shortAddr(d.address))} · <span class="dot ${statusClass}"></span>${statusLabel}${d.status === 'funded' && !expired ? ` · ${timeLeft(d.expiresAt)} left` : ''}</div>+ </div>+ <div class="mr-actions">+ ${d.status === 'funded' && !expired ? `<button class="ghost small" data-copy-link="${esc(d.id)}">Copy link</button>` : ''}+ ${expired ? `<button class="primary small" data-reclaim="${esc(d.id)}">Reclaim funds</button>` : ''}+ </div>+ </div>`;+}++async function reclaim(id, btn) {+ const reclaimAddr = prompt('Reclaim the funds to which Solana address?');+ if (!reclaimAddr) return;+ btn.disabled = true; btn.innerHTML = '<span class="spin"></span> Reclaiming…';+ try {+ const res = await api('?action=reclaim', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ id, reclaimAddress: reclaimAddr.trim() }) });+ if (!res.reclaimed) throw new Error(res.reason || 'reclaim did not confirm');+ toast('Funds reclaimed');+ btn.outerHTML = res.reclaimTx && res.reclaimTx !== 'empty' ? `<a class="ghost small" href="${esc(res.explorerUrl)}" target="_blank" rel="noopener">Reclaimed ↗</a>` : `<span class="note">Reclaimed (was empty)</span>`;+ } catch (e) {+ btn.disabled = false; btn.innerHTML = 'Reclaim funds';+ toast(e.message || 'Reclaim failed');+ }+}++// ── QR helper (lazy-loads qrcode) ─────────────────────────────────────────────++let _qrcodeMod = null;+async function renderQr(container, text) {+ if (!container) return;+ try {+ if (!_qrcodeMod) _qrcodeMod = (await import('qrcode')).default;+ const svg = await _qrcodeMod.toString(text, { type: 'svg', margin: 1, width: 200, color: { dark: '#000', light: '#fff' } });+ container.innerHTML = `<div class="qrbox">${svg}</div><span class="qrcap">Scan to claim</span>`;+ } catch {+ container.innerHTML = `<span class="qrcap">QR unavailable — share the link above.</span>`;+ }+}++// ── boot ──────────────────────────────────────────────────────────────────────++function boot() {+ mountCreate();+ mountClaim();+ mountMine();+}+if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot);+else boot();++export { deriveClaimToken, hashClaimToken };diff --git a/src/pages/vanity-bounties.js b/src/pages/vanity-bounties.jsnew file mode 100644index 000000000..0358f31bd--- /dev/null+++ b/src/pages/vanity-bounties.js@@ -0,0 +1,503 @@+// Controller for the grind-bounty market page (/vanity/bounties).+//+// Wires the bounty board, the post-a-bounty flow (X25519 keygen + live+// difficulty→price oracle + x402 escrow checkout), the "grind & earn" worker+// pool that claims open bounties (sealing the key to the requester so the worker+// stays secret-blind), and the requester's client-side wallet reveal/open.+//+// All crypto is real (sealed-envelope ECIES, the WASM grinder pool); all money+// rails are real (x402 escrow via window.X402, on-chain payout server-side).++import bs58 from 'bs58';+import { computeRarity, RARITY_TIERS } from '../solana/vanity/rarity.js';+import { validatePattern } from '../solana/vanity/validation.js';+import { grindVanity } from '../solana/vanity/grinder.js';+import {+ generateRecipientKeypair,+ sealToRecipient,+ openSealed,+} from '../solana/vanity/sealed-envelope.js';++const $ = (id) => document.getElementById(id);+const API = '/api/vanity/bounties';+const TIER_COLOR = Object.fromEntries(RARITY_TIERS.map((t) => [t.id, t.accent]));+const USDC = 1_000_000;++function esc(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); }+function toast(msg) { const t = $('toast'); t.textContent = msg; t.classList.add('show'); clearTimeout(toast._t); toast._t = setTimeout(() => t.classList.remove('show'), 2600); }+function usd(atomics) { return '$' + (Number(atomics) / USDC).toFixed(Number(atomics) % USDC === 0 ? 2 : 4); }+function fmtAttempts(n) {+ const v = Number(n) || 0;+ if (v >= 1e15) return v.toExponential(1);+ if (v >= 1e12) return (v / 1e12).toFixed(1) + 'T';+ if (v >= 1e9) return (v / 1e9).toFixed(1) + 'B';+ if (v >= 1e6) return (v / 1e6).toFixed(1) + 'M';+ if (v >= 1e3) return (v / 1e3).toFixed(1) + 'K';+ return v.toLocaleString('en-US');+}+function patternHTML(p) {+ const pre = p?.prefix || '', suf = p?.suffix || '';+ const parts = [];+ if (pre) parts.push(`<span class="hi">${esc(pre)}</span>…`);+ if (suf) parts.push(`…<span class="hi">${esc(suf)}</span>`);+ return parts.join(' ') || '(any)';+}+function timeLeft(ms) {+ const d = ms - Date.now();+ if (d <= 0) return 'expired';+ const s = Math.floor(d / 1000);+ if (s < 60) return `${s}s left`;+ if (s < 3600) return `${Math.floor(s / 60)}m left`;+ if (s < 86400) return `${Math.floor(s / 3600)}h ${Math.floor((s % 3600) / 60)}m left`;+ return `${Math.floor(s / 86400)}d ${Math.floor((s % 86400) / 3600)}h left`;+}++async function api(path, opts) {+ const r = await fetch(`${API}${path}`, opts);+ const ct = r.headers.get('content-type') || '';+ const data = ct.includes('json') ? await r.json().catch(() => ({})) : {};+ if (!r.ok) {+ const e = new Error(data.error_description || data.error || `HTTP ${r.status}`);+ e.status = r.status; e.data = data;+ throw e;+ }+ return data;+}++// ── tabs ─────────────────────────────────────────────────────────────────────+const TABS = ['board', 'post', 'earn', 'open', 'leaderboard'];+function selectTab(name) {+ for (const t of TABS) {+ const btn = $(`tab-${t}`), panel = $(`panel-${t}`);+ const on = t === name;+ btn.setAttribute('aria-selected', on ? 'true' : 'false');+ panel.classList.toggle('show', on);+ }+ if (name === 'board') loadBoard(true);+ if (name === 'leaderboard') loadLeaderboard();+ if (name === 'post') loadPostConfig();+ if (location.hash.slice(1) !== name) history.replaceState(null, '', `#${name}`);+}+TABS.forEach((t) => $(`tab-${t}`).addEventListener('click', () => selectTab(t)));+$('lede-earn').addEventListener('click', (e) => { e.preventDefault(); selectTab('earn'); });++// ── stats strip ──────────────────────────────────────────────────────────────+async function loadStats() {+ const strip = $('statstrip');+ try {+ const s = await api('?view=stats');+ strip.innerHTML = [+ ['Open bounties', String(s.open ?? 0)],+ ['Escrowed', usd(s.openEscrowAtomics ?? 0), true],+ ['Filled', String(s.settled ?? 0)],+ ['Paid to grinders', usd(s.paidOutAtomics ?? 0), true],+ ].map(([k, v, sm]) => `<div class="stat"><div class="k">${esc(k)}</div><div class="v${sm ? ' sm' : ''}">${esc(v)}</div></div>`).join('');+ } catch {+ strip.innerHTML = `<div class="stat"><div class="k">Market</div><div class="v sm">unavailable</div></div>`;+ }+}++// ── board ────────────────────────────────────────────────────────────────────+let boardStatus = 'open', boardSort = 'reward', boardOffset = 0, boardItems = [];+let boardTimer = null;++function statusBtns() {+ for (const [id, st] of [['st-open', 'open'], ['st-settled', 'settled'], ['st-all', 'all']]) {+ $(id).setAttribute('aria-pressed', boardStatus === st ? 'true' : 'false');+ $(id).addEventListener('click', () => { if (boardStatus === st) return; boardStatus = st; loadBoard(true); for (const [i2, s2] of [['st-open', 'open'], ['st-settled', 'settled'], ['st-all', 'all']]) $(i2).setAttribute('aria-pressed', s2 === st ? 'true' : 'false'); });+ }+}+$('sort-select').addEventListener('change', (e) => { boardSort = e.target.value; loadBoard(true); });+$('refresh-board').addEventListener('click', () => loadBoard(true));+$('loadmore-btn').addEventListener('click', () => loadBoard(false));++function bountyCard(b) {+ const tier = b.difficulty?.tier || 'common';+ const color = TIER_COLOR[tier] || '#94a3b8';+ const isOpen = b.status === 'open' && b.expiresAt > Date.now();+ const statusCls = b.status === 'open' ? (isOpen ? 'open' : 'expired') : b.status;+ const statusTxt = b.status === 'open' ? (isOpen ? 'Open · grinding' : 'Expired · awaiting refund') : (b.status === 'settled' ? 'Filled' : b.status === 'refunded' ? 'Refunded' : b.status);+ let actions = '';+ if (isOpen) {+ actions = `<button class="ghost small" data-act="grind" data-id="${esc(b.id)}">Grind this</button>`;+ } else if (b.status === 'settled' && b.payoutTx) {+ actions = `<a class="ghost small" href="https://solscan.io/tx/${esc(b.payoutTx)}" target="_blank" rel="noopener">Payout ↗</a>`;+ } else if (b.status === 'open' && !isOpen) {+ actions = `<button class="ghost small" data-act="refund" data-id="${esc(b.id)}">Refund poster</button>`;+ } else if (b.status === 'refunded' && b.refundTx) {+ actions = `<a class="ghost small" href="https://solscan.io/tx/${esc(b.refundTx)}" target="_blank" rel="noopener">Refund ↗</a>`;+ }+ const winner = b.winnerAddress ? `<span title="winning address">${esc(b.winnerAddress.slice(0, 6))}…${esc(b.winnerAddress.slice(-4))}</span>` : '';+ return `<article class="bcard" data-id="${esc(b.id)}">+ <div class="toprow">+ <div class="reward">${usd(b.amountAtomics)} <small>USDC</small></div>+ <span class="tierbadge" style="background:${color}">${esc(b.difficulty?.tierLabel || tier)}</span>+ </div>+ <div class="pat">${patternHTML(b.pattern)}</div>+ <div class="meta">+ <span>~${fmtAttempts(b.difficulty?.expectedAttempts)} attempts</span>+ ${b.label ? `<span>“${esc(b.label)}”</span>` : ''}+ ${winner ? `<span>winner ${winner}</span>` : ''}+ </div>+ <div class="statusrow"><span class="dot ${statusCls}"></span><span>${esc(statusTxt)}</span>${isOpen ? `<span class="timer" data-expires="${b.expiresAt}" style="margin-left:auto;color:var(--dim)">${esc(timeLeft(b.expiresAt))}</span>` : ''}</div>+ <div class="btnrow">+ <button class="ghost small" data-act="copy" data-id="${esc(b.id)}">Copy id</button>+ ${actions}+ </div>+ </article>`;+}++async function loadBoard(reset) {+ const grid = $('board-grid');+ if (reset) { boardOffset = 0; boardItems = []; grid.innerHTML = Array.from({ length: 6 }, () => '<div class="skel"></div>').join(''); }+ try {+ const data = await api(`?view=board&status=${boardStatus}&sort=${boardSort}&limit=12&offset=${boardOffset}`);+ boardItems = boardItems.concat(data.bounties || []);+ boardOffset += (data.bounties || []).length;+ if (!boardItems.length) {+ grid.innerHTML = `<div class="empty" style="grid-column:1/-1"><div class="glyph">🎯</div><h3>No ${boardStatus === 'open' ? 'open' : ''} bounties yet</h3><p>Be the first to escrow a bounty for a hard vanity address — a fleet will grind it for you.</p><button class="primary" id="empty-post" style="margin-top:1rem">Post a bounty</button></div>`;+ $('empty-post')?.addEventListener('click', () => selectTab('post'));+ $('loadmore-row').style.display = 'none';+ return;+ }+ grid.innerHTML = boardItems.map(bountyCard).join('');+ $('loadmore-row').style.display = data.hasMore ? 'block' : 'none';+ wireCardActions(grid);+ startTimers();+ } catch (e) {+ grid.innerHTML = `<div class="empty" style="grid-column:1/-1"><div class="glyph">⚠</div><h3>Couldn't load the board</h3><p>${esc(e.message)}</p><button class="ghost" id="board-retry" style="margin-top:1rem">Retry</button></div>`;+ $('board-retry')?.addEventListener('click', () => loadBoard(true));+ }+}++function wireCardActions(scope) {+ scope.querySelectorAll('[data-act]').forEach((btn) => {+ btn.addEventListener('click', async () => {+ const id = btn.dataset.id, act = btn.dataset.act;+ if (act === 'copy') { await navigator.clipboard?.writeText(id).catch(() => {}); toast('Bounty id copied'); return; }+ if (act === 'grind') { selectTab('earn'); toast('Switch to Grind & earn — open bounties (incl. this one) are in the queue'); return; }+ if (act === 'refund') { await triggerRefund(id, btn); return; }+ });+ });+}++async function triggerRefund(id, btn) {+ const refundAddress = prompt('Refund the escrow to which Solana address?\n(Leave blank to use the address set when the bounty was posted.)') ?? '';+ btn.disabled = true; btn.textContent = 'Refunding…';+ try {+ const r = await api('?action=refund', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ bountyId: id, refundAddress: refundAddress.trim() || undefined }) });+ toast(`Refunded ${usd(r.amountAtomics)} → tx ${r.refundTx.slice(0, 8)}…`);+ loadBoard(true); loadStats();+ } catch (e) {+ toast(`Refund failed: ${e.message}`);+ btn.disabled = false; btn.textContent = 'Refund poster';+ }+}++function startTimers() {+ if (boardTimer) clearInterval(boardTimer);+ boardTimer = setInterval(() => {+ document.querySelectorAll('.timer[data-expires]').forEach((el) => { el.textContent = timeLeft(Number(el.dataset.expires)); });+ }, 1000);+}++// ── post a bounty ────────────────────────────────────────────────────────────+let postConfig = null;+let lastOracle = null;++async function loadPostConfig() {+ if (postConfig) return applyPostConfig();+ try { postConfig = await api('?view=config'); } catch { postConfig = { payoutConfigured: false }; }+ applyPostConfig();+}+function applyPostConfig() {+ if (postConfig && !postConfig.payoutConfigured) {+ $('payout-warn').style.display = 'block';+ }+ refreshPostState();+}++function readPattern() {+ return {+ prefix: $('post-prefix').value.trim(),+ suffix: $('post-suffix').value.trim(),+ ignoreCase: $('post-ignorecase').checked,+ };+}++let quoteDebounce = null;+function onPatternChange() {+ clearTimeout(quoteDebounce);+ quoteDebounce = setTimeout(updateQuote, 220);+ refreshPostState();+}+['post-prefix', 'post-suffix'].forEach((id) => $(id).addEventListener('input', onPatternChange));+$('post-ignorecase').addEventListener('change', onPatternChange);++async function updateQuote() {+ const p = readPattern();+ const errBox = $('quote-err'); errBox.classList.remove('show');+ if (!p.prefix && !p.suffix) { $('quote-box').style.display = 'none'; lastOracle = null; return; }+ for (const [label, val] of [['prefix', p.prefix], ['suffix', p.suffix]]) {+ if (!val) continue;+ const v = validatePattern(val);+ if (!v.valid) { errBox.textContent = `Invalid ${label}: ${v.errors.join('; ')}`; errBox.classList.add('show'); $('quote-box').style.display = 'none'; lastOracle = null; return; }+ }+ // Local compute for instant feedback; the server oracle confirms the price.+ const rarity = computeRarity(p);+ $('q-tier').textContent = `${rarity.tierLabel} · ${rarity.rarityBits} bits`;+ $('q-tier').style.color = rarity.accent;+ const pct = Math.min(100, (rarity.rarityBits / (6 * 5.86)) * 100);+ $('q-meter').style.width = `${pct}%`;+ $('q-meter').style.background = rarity.accent;+ $('q-attempts').textContent = fmtAttempts(rarity.expectedAttempts);+ $('quote-box').style.display = 'block';+ try {+ const q = await api(`?view=quote&prefix=${encodeURIComponent(p.prefix)}&suffix=${encodeURIComponent(p.suffix)}&ignoreCase=${p.ignoreCase ? 1 : 0}`);+ lastOracle = q.oracle;+ $('q-suggested').textContent = `${usd(q.oracle.suggestedAtomics)} (floor ${usd(q.oracle.floorAtomics)})`;+ } catch {+ lastOracle = null;+ $('q-suggested').textContent = 'price unavailable';+ }+ refreshPostState();+}++$('use-floor').addEventListener('click', () => { if (lastOracle) { $('post-amount').value = (lastOracle.floorAtomics / USDC).toFixed(2); refreshPostState(); } });+$('use-suggested').addEventListener('click', () => { if (lastOracle) { $('post-amount').value = (lastOracle.suggestedAtomics / USDC).toFixed(4); refreshPostState(); } });+$('use-generous').addEventListener('click', () => { if (lastOracle) { $('post-amount').value = (lastOracle.generousAtomics / USDC).toFixed(4); refreshPostState(); } });++// X25519 keygen+$('gen-key').addEventListener('click', () => {+ const kp = generateRecipientKeypair();+ $('post-recipient').value = kp.publicKey;+ $('priv-value').textContent = kp.secretKey;+ $('key-private').style.display = 'block';+ $('saved-chk-wrap').style.display = 'flex';+ $('saved-chk').checked = false;+ window.__bountyPriv = kp.secretKey;+ refreshPostState();+ toast('Key generated — save the private half!');+});+$('copy-priv').addEventListener('click', async () => { await navigator.clipboard?.writeText($('priv-value').textContent).catch(() => {}); toast('Private key copied'); });+$('download-key').addEventListener('click', () => {+ const blob = new Blob([JSON.stringify({ scheme: 'x25519', publicKey: $('post-recipient').value, secretKey: $('priv-value').textContent, note: 'three.ws grind-bounty sealed-delivery key — keep the secretKey private; it opens your won wallet.', created: new Date().toISOString() }, null, 2)], { type: 'application/json' });+ const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = `three-ws-bounty-key-${Date.now()}.json`; a.click(); URL.revokeObjectURL(a.href);+});+$('post-recipient').addEventListener('input', () => {+ // Pasted an existing key: no private key to show, hide the warning box.+ if ($('post-recipient').value.trim() && !$('priv-value').textContent) { $('saved-chk-wrap').style.display = 'none'; }+ refreshPostState();+});+['post-amount', 'post-expiry', 'post-refund'].forEach((id) => $(id).addEventListener('input', refreshPostState));+$('saved-chk').addEventListener('change', refreshPostState);++function postValidity() {+ const p = readPattern();+ if (!p.prefix && !p.suffix) return { ok: false, hint: 'Add a prefix or suffix.' };+ const amt = parseFloat($('post-amount').value);+ if (!amt || amt <= 0) return { ok: false, hint: 'Enter a bounty amount.' };+ const recipient = $('post-recipient').value.trim();+ if (!recipient) return { ok: false, hint: 'Generate or paste your X25519 key.' };+ if (window.__bountyPriv && !$('saved-chk').checked) return { ok: false, hint: 'Confirm you saved your private key.' };+ if (postConfig && !postConfig.payoutConfigured) return { ok: false, hint: 'Posting is unavailable in this environment.' };+ return { ok: true, amt, recipient, pattern: p };+}+function refreshPostState() {+ const v = postValidity();+ $('post-btn').disabled = !v.ok;+ $('post-hint').textContent = v.ok ? 'Ready — you’ll pay the bounty as escrow.' : v.hint;+}++$('post-btn').addEventListener('click', postBounty);+async function postBounty() {+ const v = postValidity();+ if (!v.ok) return;+ const errBox = $('post-err'), okBox = $('post-ok');+ errBox.classList.remove('show'); okBox.classList.remove('show');+ const amountAtomics = Math.round(v.amt * USDC);+ const expiryHours = Math.max(1, Math.min(720, parseInt($('post-expiry').value, 10) || 48));+ const label = $('post-label').value.trim();+ const refundAddress = $('post-refund').value.trim();+ const params = new URLSearchParams({+ prefix: v.pattern.prefix, suffix: v.pattern.suffix, ignoreCase: v.pattern.ignoreCase ? '1' : '0',+ amount: String(amountAtomics), recipient: v.recipient, expiryHours: String(expiryHours),+ });+ if (label) params.set('label', label);+ if (refundAddress) params.set('refundAddress', refundAddress);++ if (!window.X402?.pay) { errBox.textContent = 'Payment library failed to load — reload the page.'; errBox.classList.add('show'); return; }+ $('post-btn').disabled = true; $('post-btn').innerHTML = '<span class="spin"></span> Opening checkout…';+ try {+ const out = await window.X402.pay({+ endpoint: `${API}?action=create&${params.toString()}`,+ method: 'POST',+ merchant: 'three.ws Grind-Bounty Market',+ action: `Escrow ${usd(amountAtomics)} bounty`,+ });+ const res = out?.result;+ if (!res?.posted) throw new Error(res?.error_description || 'post did not confirm');+ okBox.innerHTML = `Bounty <span class="mono">${esc(res.bounty.id)}</span> is live! The fleet is grinding <strong>${patternHTML(res.bounty.pattern)}</strong> for ${usd(res.bounty.amountAtomics)}. <br>Keep your X25519 <strong>private key</strong> — it opens the wallet when a worker finds it. <a href="#${esc(res.bounty.id)}" id="goto-board" style="color:var(--accent)">View on the board →</a>`;+ okBox.classList.add('show');+ toast('Bounty posted & escrow funded');+ $('goto-board')?.addEventListener('click', () => selectTab('board'));+ loadStats();+ } catch (e) {+ if (e?.code === 'cancelled') { /* user closed modal */ }+ else { errBox.textContent = `Couldn't post: ${e.message || e}`; errBox.classList.add('show'); }+ } finally {+ $('post-btn').disabled = false; $('post-btn').textContent = 'Fund & post bounty';+ refreshPostState();+ }+}++// ── grind & earn (worker pool) ───────────────────────────────────────────────+let earnAbort = null, earnRunning = false, earnEarned = 0, earnStats = { attempts: 0, rate: 0 };+function logWork(html, cls = '') { const log = $('worklog'); const line = document.createElement('div'); if (cls) line.className = cls; line.innerHTML = html; log.prepend(line); while (log.children.length > 60) log.lastChild.remove(); }+function setOdo(k, v) { $(`o-${k}`).textContent = v; }++$('earn-start').addEventListener('click', startEarning);+$('earn-stop').addEventListener('click', stopEarning);++async function startEarning() {+ const payout = $('earn-payout').value.trim();+ if (!/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(payout)) { toast('Enter a valid Solana payout address'); $('earn-payout').focus(); return; }+ if (earnRunning) return;+ earnRunning = true; earnAbort = new AbortController();+ $('earn-start').disabled = true; $('earn-stop').disabled = false;+ setOdo('status', 'Running'); logWork('<span class="miss">Fetching open bounties…</span>');+ earnLoop(payout).catch((e) => { logWork(`<span class="err">Worker stopped: ${esc(e.message)}</span>`); stopEarning(); });+}+function stopEarning() {+ earnRunning = false;+ try { earnAbort?.abort(); } catch {}+ $('earn-start').disabled = false; $('earn-stop').disabled = true;+ setOdo('status', 'Idle'); setOdo('target', '—'); setOdo('rate', '0/s');+}++async function earnLoop(payout) {+ const maxWorkers = parseInt($('earn-workers').value, 10) || undefined;+ while (earnRunning) {+ let bounties;+ try { ({ bounties } = await api('?view=open&limit=20')); } catch (e) { logWork(`<span class="err">Couldn't fetch bounties: ${esc(e.message)}</span>`); await sleep(4000); continue; }+ const target = bounties.find((b) => b.status === 'open' && b.expiresAt > Date.now());+ if (!target) { setOdo('status', 'Waiting'); setOdo('target', 'no open bounties'); logWork('<span class="miss">No open bounties — waiting…</span>'); await sleep(5000); continue; }++ setOdo('status', 'Grinding'); setOdo('target', `${patternText(target.pattern)} · ${usd(target.amountAtomics)}`);+ logWork(`Grinding <strong>${patternHTML(target.pattern)}</strong> for ${usd(target.amountAtomics)} (id ${esc(target.id.slice(0, 8))}…)`);++ let result;+ try {+ result = await grindVanity({+ prefix: target.pattern.prefix || '', suffix: target.pattern.suffix || '', ignoreCase: !!target.pattern.ignoreCase,+ maxWorkers, signal: earnAbort.signal,+ onProgress: ({ attempts, rate }) => { earnStats = { attempts, rate }; setOdo('attempts', fmtAttempts(attempts)); setOdo('rate', `${fmtAttempts(rate)}/s`); },+ });+ } catch (e) {+ if (e.name === 'AbortError') return;+ logWork(`<span class="err">Grind error: ${esc(e.message)}</span>`); await sleep(1500); continue;+ }+ if (!earnRunning) return;++ // Seal the found secret to the requester BEFORE submitting — the worker+ // never transmits plaintext, so it cannot keep the wallet.+ setOdo('status', 'Claiming');+ logWork(`<span class="win">Found ${esc(result.publicKey.slice(0, 8))}… — sealing to the requester & claiming…</span>`);+ let sealed;+ try {+ const bundle = JSON.stringify({ format: 'keypair', secretKeyBase58: bs58Encode(result.secretKey), secretKey: Array.from(result.secretKey), publicKey: result.publicKey });+ sealed = await sealToRecipient(bundle, target.recipient);+ } catch (e) { logWork(`<span class="err">Seal failed: ${esc(e.message)}</span>`); continue; }++ try {+ const claim = await api('?action=claim', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ bountyId: target.id, address: result.publicKey, sealedSecret: sealed, payoutAddress: payout, workerId: workerId() }) });+ if (claim.paid) {+ earnEarned += claim.amountAtomics;+ setOdo('earned', usd(earnEarned));+ logWork(`<span class="win">✓ Paid ${usd(claim.amountAtomics)} → <a href="${esc(claim.explorerUrl)}" target="_blank" rel="noopener" style="color:var(--good)">${esc(claim.payoutTx.slice(0, 10))}…</a></span>`);+ toast(`Earned ${usd(claim.amountAtomics)}!`);+ loadStats();+ } else {+ logWork(`<span class="miss">Won but payout pending: ${esc(claim.reason || 'retry')}</span>`);+ }+ } catch (e) {+ if (e.status === 409) logWork(`<span class="miss">Lost the race — another worker submitted first.</span>`);+ else if (e.status === 422) logWork(`<span class="err">Claim rejected: ${esc(e.message)}</span>`);+ else logWork(`<span class="err">Claim failed: ${esc(e.message)}</span>`);+ }+ setOdo('status', 'Running');+ }+}++function patternText(p) { return [p?.prefix && `${p.prefix}…`, p?.suffix && `…${p.suffix}`].filter(Boolean).join(' ') || '(any)'; }+function workerId() {+ let id = localStorage.getItem('twx_bounty_worker');+ if (!id) { id = 'w_' + Math.random().toString(36).slice(2, 10); localStorage.setItem('twx_bounty_worker', id); }+ return id;+}+function sleep(ms) { return new Promise((r) => setTimeout(r, ms)); }++// bs58 encode for the worker's secret-key bundle (sealed-envelope already depends+// on bs58, so the bundler dedupes this to a single chunk).+function bs58Encode(bytes) { return bs58.encode(bytes); }++// ── open my won wallet ───────────────────────────────────────────────────────+$('open-btn').addEventListener('click', openWallet);+async function openWallet() {+ const id = $('open-id').value.trim();+ const priv = $('open-priv').value.trim();+ const errBox = $('open-err'), okBox = $('open-ok');+ errBox.classList.remove('show'); okBox.classList.remove('show');+ if (!/^[0-9a-f]{8,32}$/.test(id)) { errBox.textContent = 'Enter a valid bounty id.'; errBox.classList.add('show'); return; }+ if (!priv) { errBox.textContent = 'Enter your X25519 private key.'; errBox.classList.add('show'); return; }+ $('open-btn').disabled = true; $('open-btn').innerHTML = '<span class="spin"></span> Revealing…';+ try {+ const r = await api('?action=reveal', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ bountyId: id }) });+ if (!r.revealed) throw new Error(r.reason || 'not ready');+ // Decrypt entirely client-side — the private key never leaves the browser.+ const plaintext = new TextDecoder().decode(await openSealed(r.sealedSecret, priv));+ const wallet = JSON.parse(plaintext);+ if (wallet.publicKey && wallet.publicKey !== r.address) throw new Error('decrypted key does not match the won address');+ okBox.innerHTML = `<strong style="color:var(--good)">Wallet opened.</strong> This is YOUR address <span class="mono">${esc(r.address)}</span> — the worker who found it never saw this key.+ <div class="keybox" style="border-color:rgba(74,222,128,.35)"><div class="k" style="color:var(--dim);font-size:.7rem;text-transform:uppercase">Secret key (Base58 — import into Phantom/Solflare)</div><code style="color:#86efac">${esc(wallet.secretKeyBase58 || '')}</code>+ <button class="ghost small" id="open-copy">Copy secret key</button> <a class="ghost small" href="https://solscan.io/account/${esc(r.address)}" target="_blank" rel="noopener">Explorer ↗</a></div>`;+ okBox.classList.add('show');+ $('open-copy')?.addEventListener('click', async () => { await navigator.clipboard?.writeText(wallet.secretKeyBase58 || '').catch(() => {}); toast('Secret key copied'); });+ toast('Wallet decrypted locally');+ } catch (e) {+ errBox.textContent = e.message?.includes('decrypt') || e.name === 'OperationError' ? 'Decryption failed — wrong private key for this bounty.' : `Couldn't open: ${e.message}`;+ errBox.classList.add('show');+ } finally {+ $('open-btn').disabled = false; $('open-btn').textContent = 'Reveal & open';+ }+}++// ── leaderboard ──────────────────────────────────────────────────────────────+async function loadLeaderboard() {+ const el = $('leaderboard');+ el.innerHTML = '<div class="skel" style="height:120px"></div>';+ try {+ const { grinders } = await api('?view=leaderboard&limit=20');+ if (!grinders.length) { el.innerHTML = `<div class="empty"><div class="glyph">🏆</div><h3>No grinders yet</h3><p>Be the first to fill a bounty and top the leaderboard. <button class="primary" id="lb-earn" style="margin-top:1rem">Start grinding</button></p></div>`; $('lb-earn')?.addEventListener('click', () => selectTab('earn')); return; }+ el.innerHTML = `<div class="card" style="padding:0;overflow:hidden">${grinders.map((g, i) => `<div class="kv" style="padding:.8rem 1.1rem;${i === 0 ? 'background:rgba(255,213,79,.06)' : ''}"><span class="k">#${i + 1} <span class="mono" style="color:#ccc">${esc(g.workerId)}</span></span><span class="v" style="color:var(--good)">${usd(g.earnedAtomics)}</span></div>`).join('')}</div>`;+ } catch (e) {+ el.innerHTML = `<div class="empty"><div class="glyph">⚠</div><h3>Couldn't load the leaderboard</h3><p>${esc(e.message)}</p></div>`;+ }+}++// ── init ─────────────────────────────────────────────────────────────────────+async function init() {+ statusBtns();+ loadStats();+ const initial = TABS.includes(location.hash.slice(1)) ? location.hash.slice(1) : 'board';+ // A bounty-id hash (#<24hex>) deep-links the board.+ if (/^[0-9a-f]{8,32}$/.test(location.hash.slice(1))) { selectTab('board'); } else { selectTab(initial); }+ if (initial === 'board') loadBoard(true);+}+init();++// Stop the worker pool when the page is hidden offscreen to free the cores.+document.addEventListener('visibilitychange', () => {+ if (document.hidden && earnRunning) { logWork('<span class="miss">Page hidden — pausing to free your cores.</span>'); stopEarning(); }+});+window.addEventListener('beforeunload', () => { try { earnAbort?.abort(); } catch {} });diff --git a/src/shared/agent-wallet-chip.js b/src/shared/agent-wallet-chip.jsindex 621eb7bb2..e020c2aff 100644--- a/src/shared/agent-wallet-chip.js+++ b/src/shared/agent-wallet-chip.js@@ -23,6 +23,8 @@* so a surface can pass whichever record it already holds without reshaping it.*/+import { computeRarity } from '../solana/vanity/rarity.js';+const STYLE_ID = 'tws-agent-wallet-chip-styles';const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;@@ -56,13 +58,33 @@ export function getWalletStatus(agent) {// have no agent_id field, so this falls through to their own id.const agentId = agent.agent_id || agent.agentId || agent.id || null;+ const pre = prefix ? String(prefix) : null;+ const suf = suffix ? String(suffix) : null;+ const isVanity = !!(pre || suf);+ // Honest rarity tier from the SAME model the proof-of-grind gallery uses, so a+ // rare agent address advertises its tier everywhere the chip appears. Only an+ // actual vanity pattern that the address really satisfies earns a tier — a+ // claimed prefix that doesn't match the address is ignored.+ let rarity = null;+ if (isVanity) {+ const addr = String(address);+ const realPrefix = pre && addr.startsWith(pre) ? pre : '';+ const realSuffix = suf && addr.endsWith(suf) ? suf : '';+ if (realPrefix || realSuffix) {+ const r = computeRarity({ prefix: realPrefix, suffix: realSuffix });+ if (r.tier !== 'common') rarity = { tier: r.tier, label: r.tierLabel, accent: r.accent, score: r.rarityScore };+ }+ }+return {address: String(address),- prefix: prefix ? String(prefix) : null,- suffix: suffix ? String(suffix) : null,- isVanity: !!(prefix || suffix),+ prefix: pre,+ suffix: suf,+ isVanity,+ rarity,explorerUrl: `https://solscan.io/account/${address}`,hubUrl: agentId ? `/agent/${agentId}/wallet` : null,+ galleryUrl: `/vanity/gallery?address=${encodeURIComponent(String(address))}`,agentId,};}@@ -119,6 +141,10 @@ button.twc-make{appearance:none;background:none;border:none;border-left:1px solibutton.twc-make:active{transform:scale(.95);}button.twc-make:focus-visible{outline:2px solid rgba(139,92,246,.7);outline-offset:2px;border-radius:4px;}.twc-vanity-tag{font-size:9px;font-weight:700;text-transform:uppercase;letter-spacing:.05em;opacity:.8;}+a.twc-rarity{font-size:9px;font-weight:800;text-transform:uppercase;letter-spacing:.05em;text-decoration:none;+ padding:1px 6px;border-radius:999px;color:#06060b;line-height:1.4;white-space:nowrap;transition:transform .12s ease,filter .15s ease;}+a.twc-rarity:hover{transform:translateY(-1px);filter:brightness(1.08);}+a.twc-rarity:focus-visible{outline:2px solid rgba(255,255,255,.7);outline-offset:2px;}.twc-pending{color:#888;background:rgba(255,255,255,.04);border-color:rgba(255,255,255,.1);}.twc-copied{color:#4ade80!important;}@media (prefers-reduced-motion: reduce){.twc-act{transition:none;}}@@ -169,7 +195,18 @@ export function walletChipHTML(agent, opts = {}) {return `<span class="twc twc-pending" title="Wallet provisioning">${WALLET_SVG}<span>Wallet pending</span></span>`;}- const vanityTag = status.isVanity ? '<span class="twc-vanity-tag">vanity</span>' : '';+ // A matched vanity address advertises its honest rarity tier (tinted); when the+ // chip is interactive it links to the address's appraisal in the proof-of-grind+ // gallery, otherwise (link:false, used inside card anchors) it stays a plain+ // span so we never nest an <a> in an <a>. An unmatched/plain-vanity pattern+ // falls back to the neutral "vanity" tag.+ const vanityTag = status.rarity+ ? link+ ? `<a class="twc-rarity" href="${esc(status.galleryUrl)}" style="background:${esc(status.rarity.accent)}" title="Rarity ${esc(status.rarity.label)} · score ${esc(status.rarity.score)} — appraise on three.ws" data-twc-stop>${esc(status.rarity.label)}</a>`+ : `<span class="twc-rarity" style="background:${esc(status.rarity.accent)}" title="Rarity ${esc(status.rarity.label)} · score ${esc(status.rarity.score)}">${esc(status.rarity.label)}</span>`+ : status.isVanity+ ? '<span class="twc-vanity-tag">vanity</span>'+ : '';const copyBtn = link? `<button type="button" class="twc-act" data-twc-copy="${esc(status.address)}" title="Copy address" aria-label="Copy wallet address">${COPY_SVG}</button>`: '';diff --git a/src/solana/vanity/bounty-protocol.js b/src/solana/vanity/bounty-protocol.jsnew file mode 100644index 000000000..ca2f465d4--- /dev/null+++ b/src/solana/vanity/bounty-protocol.js@@ -0,0 +1,340 @@+/**+ * Grind-bounty market protocol — `three-vanity-bounty/v1`.+ *+ * A two-sided market for HARD vanity addresses. A requester posts a pattern and+ * escrows an x402 bounty; a fleet of independent workers grind in parallel and+ * race to find a matching key. The winner submits a proof and is paid — but the+ * found secret key is sealed to the requester's X25519 key, so the worker who+ * finds it earns the bounty yet NEVER sees the wallet's secret. This module is+ * the pure, isomorphic core both the server (claim verification, pricing,+ * escrow IDs) and the browser worker (building a claim) share, so there is one+ * verified implementation of every rule rather than a prose spec re-coded twice.+ *+ * ── Why a worker can't steal the wallet (secret-blind by construction) ───────+ * The only thing a claim may carry is a `sealedSecret` envelope produced by+ * sealed-envelope.js against the bounty's `recipient` X25519 public key. The+ * server (`verifyClaimEnvelope`) confirms BOTH that the address actually matches+ * the requested pattern AND that the envelope's `recipient` is exactly the+ * bounty's recipient key before it will pay. A worker can open its own sealed+ * envelope only if it holds the requester's PRIVATE key — which it does not — so+ * the plaintext key never touches the worker, the wire, or the operator. The+ * requester opens it later with their private key (openSealed).+ *+ * ── Why exactly one worker is paid (atomic single-winner) ────────────────────+ * The store performs the open→settled transition as a compare-and-set keyed on+ * the bounty id; the FIRST valid claim flips the status and records the winner,+ * every later claim sees `settled` and is rejected as a late/duplicate. This+ * module supplies the deterministic `claimDigest` used as the idempotency anchor+ * so a retried submission of the SAME claim is de-duplicated rather than+ * double-paid, while a DIFFERENT valid claim that lost the race is told so.+ *+ * ── Honest pricing oracle (difficulty → fair USDC bounty) ────────────────────+ * `suggestBountyAtomics` prices a pattern off the SAME geometric difficulty+ * model the grinder advertises (expectedAttempts), so a posted bounty tracks the+ * real expected compute a worker spends — no arbitrary numbers. It returns a+ * floor/suggested/generous trio in USDC atomic units (6 decimals).+ *+ * Pure + isomorphic (no I/O, no Node-only APIs): @noble hashing + the shared+ * vanity primitives only, so it runs identically in the browser worker, the+ * serverless claim handler, and the tests. Behaviour is pinned by fixed vectors+ * in tests/vanity-bounty-protocol.test.js.+ */++import { sha256 } from '@noble/hashes/sha256';+import { bytesToHex, utf8ToBytes, concatBytes } from '@noble/hashes/utils';++import { validatePattern, expectedAttempts, effectiveLength } from './validation.js';+import { SEALED_ENVELOPE_SCHEME } from './sealed-envelope.js';+import { computeRarity } from './rarity.js';++export const BOUNTY_PROTOCOL_VERSION = 'three-vanity-bounty/v1';++// Domain-separation tags so a hash for one purpose can never collide with another.+const TAG_BOUNTY_ID = utf8ToBytes('three-vanity-bounty/id/v1');+const TAG_CLAIM_DIGEST = utf8ToBytes('three-vanity-bounty/claim/v1');++const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++// USDC atomic units (6 decimals).+const USDC = 1_000_000;++// Pricing model knobs (documented, bounded). A worker's expected cost to grind a+// pattern is proportional to its expected attempts; we anchor the suggested+// bounty to that cost at a published reference rate, then clamp into a sane band+// so a probe pattern isn't free and an astronomically hard one isn't priced into+// the millions by accident. The numbers below are deliberately conservative and+// transparent — the UI shows the full breakdown.+const PRICING = Object.freeze({+ // Reference grind throughput a competent browser/Node fleet sustains, in+ // addresses/sec. Used only to translate "expected attempts" into a wall-clock+ // cost intuition for the suggested bounty — NOT a promise.+ refRatePerSec: 1_500_000,+ // What an hour of that fleet's compute is worth, in USDC atomic units. Posting+ // a bounty worth ~this per expected grind-hour keeps the market liquid: enough+ // to attract a worker, not so much it's exploitable.+ usdcPerGrindHour: 1 * USDC, // $1.00 / expected grind-hour (suggested tier)+ floorAtomics: 50_000, // $0.05 — minimum any bounty may post (covers a trivial pattern + payout gas headroom)+ maxAtomics: 5_000 * USDC, // $5,000 — hard ceiling so a fat-fingered post can't escrow a fortune+});++/** Coerce to USDC atomic units (integer, 6 decimals), clamped to the legal band. */+function clampAtomics(n) {+ const v = Math.round(Number(n) || 0);+ if (!Number.isFinite(v) || v <= 0) return PRICING.floorAtomics;+ return Math.max(PRICING.floorAtomics, Math.min(PRICING.maxAtomics, v));+}++/**+ * Normalize + validate a requested pattern for a bounty. Throws a 400-tagged+ * error on anything malformed so the server returns a clean rejection. Returns+ * the canonical `{ prefix, suffix, ignoreCase }` plus difficulty metadata.+ * @param {object} input+ * @param {string} [input.prefix]+ * @param {string} [input.suffix]+ * @param {boolean} [input.ignoreCase]+ * @returns {{ prefix:string, suffix:string, ignoreCase:boolean, combinedLength:number,+ * expectedAttempts:number, effectiveLength:number }}+ */+export function normalizeBountyPattern({ prefix = '', suffix = '', ignoreCase = false } = {}) {+ const pre = typeof prefix === 'string' ? prefix.trim() : '';+ const suf = typeof suffix === 'string' ? suffix.trim() : '';+ const ic = !!ignoreCase;+ if (!pre && !suf) {+ throw bad('a prefix or suffix is required', 'validation_error');+ }+ for (const [label, p] of [['prefix', pre], ['suffix', suf]]) {+ if (!p) continue;+ const v = validatePattern(p);+ if (!v.valid) throw bad(`invalid ${label}: ${v.errors.join('; ')}`, 'validation_error');+ }+ const combinedLength = pre.length + suf.length;+ const attempts = expectedAttempts(pre, suf, ic);+ return {+ prefix: pre,+ suffix: suf,+ ignoreCase: ic,+ combinedLength,+ expectedAttempts: Math.round(attempts),+ effectiveLength: round2(effectiveLength(attempts)),+ };+}++/**+ * Does a Base58 address satisfy a prefix/suffix pattern? Mirrors the WASM grinder+ * and verifiable-grind matcher exactly so the market's anti-cheat is honest.+ * @param {string} address+ * @param {{ prefix?:string, suffix?:string, ignoreCase?:boolean }} pattern+ * @returns {boolean}+ */+export function addressMatchesPattern(address, { prefix = '', suffix = '', ignoreCase = false } = {}) {+ let addr = String(address || '');+ let pre = prefix || '';+ let suf = suffix || '';+ if (!BASE58_RE.test(addr)) return false;+ 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;+}++/**+ * Honest difficulty→price oracle. Prices a bounty off the same geometric model+ * the grinder advertises, so a posted reward tracks real expected compute.+ * @param {{ prefix?:string, suffix?:string, ignoreCase?:boolean }} pattern+ * @returns {{ floorAtomics:number, suggestedAtomics:number, generousAtomics:number,+ * expectedAttempts:number, expectedGrindSeconds:number, model:string }}+ */+export function suggestBountyAtomics(pattern) {+ const { prefix = '', suffix = '', ignoreCase = false } = pattern || {};+ const attempts = expectedAttempts(prefix, suffix, ignoreCase);+ const grindSeconds = attempts / PRICING.refRatePerSec;+ const grindHours = grindSeconds / 3600;+ // Suggested = fair value of the expected compute. Floor guarantees a worker+ // always nets something; generous (2.5×) is the "fill it fast" tier.+ const fair = grindHours * PRICING.usdcPerGrindHour;+ const suggested = clampAtomics(Math.max(PRICING.floorAtomics, fair));+ return {+ floorAtomics: PRICING.floorAtomics,+ suggestedAtomics: suggested,+ generousAtomics: clampAtomics(suggested * 2.5),+ maxAtomics: PRICING.maxAtomics,+ expectedAttempts: Math.round(attempts),+ expectedGrindSeconds: Math.round(grindSeconds),+ model: '58^effectiveLength @ refRate',+ };+}++/** Validate that a proposed bounty amount (USDC atomics) is in the legal band. */+export function validateBountyAtomics(atomics) {+ const v = Math.round(Number(atomics));+ if (!Number.isFinite(v) || v < PRICING.floorAtomics) {+ throw bad(+ `bounty amount must be at least ${PRICING.floorAtomics} USDC atomic units ($${(PRICING.floorAtomics / USDC).toFixed(2)})`,+ 'amount_too_low',+ );+ }+ if (v > PRICING.maxAtomics) {+ throw bad(+ `bounty amount exceeds the ${PRICING.maxAtomics} USDC-atomic ceiling ($${(PRICING.maxAtomics / USDC).toLocaleString('en-US')})`,+ 'amount_too_high',+ );+ }+ return v;+}++/**+ * Deterministic bounty id: SHA-256 over (recipient ‖ pattern ‖ amount ‖ nonce),+ * domain-separated and truncated to a short, URL-safe handle. The nonce makes two+ * otherwise-identical posts distinct; binding the recipient + pattern + amount+ * makes the id self-describing and tamper-evident (a stored bounty whose fields+ * don't re-hash to its id has been altered).+ * @param {object} p+ * @param {string} p.recipient - Base58 X25519 recipient public key.+ * @param {{prefix?:string,suffix?:string,ignoreCase?:boolean}} p.pattern+ * @param {number} p.amountAtomics+ * @param {string} p.nonce - hex/opaque uniqueness nonce.+ * @returns {string} 24-char lowercase-hex id.+ */+export function deriveBountyId({ recipient, pattern, amountAtomics, nonce }) {+ const material = canonical({+ recipient: String(recipient || ''),+ prefix: pattern?.prefix || '',+ suffix: pattern?.suffix || '',+ ignoreCase: !!pattern?.ignoreCase,+ amount: String(amountAtomics),+ nonce: String(nonce || ''),+ });+ return bytesToHex(sha256(concatBytes(TAG_BOUNTY_ID, utf8ToBytes(material)))).slice(0, 24);+}++/**+ * Deterministic claim digest — the idempotency anchor for a submission. Two+ * retries of the SAME claim hash identically (de-duplicated, not double-paid);+ * two DIFFERENT valid keys for the same bounty hash differently so the loser is+ * cleanly told it lost the race. Binds bountyId + address + the sealed envelope's+ * ciphertext, so altering any of them yields a new digest.+ * @param {object} p+ * @param {string} p.bountyId+ * @param {string} p.address - the ground Base58 address.+ * @param {{ epk:string, nonce:string, ciphertext:string }} p.sealedSecret+ * @returns {string} 32-char lowercase-hex digest.+ */+export function claimDigest({ bountyId, address, sealedSecret }) {+ const material = canonical({+ bountyId: String(bountyId || ''),+ address: String(address || ''),+ epk: sealedSecret?.epk || '',+ nonce: sealedSecret?.nonce || '',+ ciphertext: sealedSecret?.ciphertext || '',+ });+ return bytesToHex(sha256(concatBytes(TAG_CLAIM_DIGEST, utf8ToBytes(material)))).slice(0, 32);+}++/**+ * Verify a claim against a bounty WITHOUT the secret — the market's anti-cheat+ * gate. Runs every structural check a server must pass before paying:+ *+ * 1. address is a well-formed Base58 Solana key;+ * 2. address actually matches the bounty's requested pattern;+ * 3. the sealed envelope is well-formed under the supported scheme;+ * 4. the envelope is addressed to the bounty's recipient key (NOT the worker)+ * — this is what makes the worker secret-blind: it can submit only an+ * envelope the requester can open, never plaintext.+ *+ * It deliberately CANNOT and does NOT decrypt anything (it has no private key),+ * so a server using it never holds the worker's plaintext either. Returns a+ * per-check audit so the API + UI can show exactly what failed.+ *+ * @param {object} bounty - the stored bounty: { pattern, recipient }.+ * @param {object} claim - { address, sealedSecret }.+ * @returns {{ ok:boolean, checks:Array<{id:string,label:string,pass:boolean,detail:string}>, reason:string }}+ */+export function verifyClaimEnvelope(bounty, claim) {+ const checks = [];+ const add = (id, label, pass, detail) => checks.push({ id, label, pass, detail });++ const address = String(claim?.address || '');+ const env = claim?.sealedSecret;++ // 1. address shape.+ const addrOk = BASE58_RE.test(address);+ add('address-shape', 'Submitted address is a valid Solana public key', addrOk,+ addrOk ? address : 'address is not a 32–44 char Base58 string');++ // 2. pattern match.+ const matchOk = addrOk && addressMatchesPattern(address, bounty?.pattern || {});+ const want = patternLabel(bounty?.pattern);+ add('pattern', 'Address matches the requested pattern', matchOk,+ matchOk ? `${address} satisfies ${want}` : `${address} does NOT satisfy ${want}`);++ // 3. envelope shape.+ const schemeOk = !!env && env.scheme === SEALED_ENVELOPE_SCHEME &&+ typeof env.epk === 'string' && typeof env.nonce === 'string' &&+ typeof env.ciphertext === 'string' && typeof env.recipient === 'string';+ add('envelope', 'Sealed envelope is well-formed', schemeOk,+ schemeOk ? `scheme ${SEALED_ENVELOPE_SCHEME}` : `missing/invalid sealed-envelope fields (need scheme=${SEALED_ENVELOPE_SCHEME}, epk, nonce, ciphertext, recipient)`);++ // 4. recipient binding — the secret-blind invariant.+ const recipientOk = schemeOk && !!bounty?.recipient && env.recipient === bounty.recipient;+ add('sealed-to-requester', 'Secret is sealed to the requester (worker can never open it)', recipientOk,+ recipientOk+ ? `envelope recipient matches the bounty's X25519 key ${truncate(bounty.recipient)}`+ : `envelope recipient ${truncate(env?.recipient)} ≠ bounty recipient ${truncate(bounty?.recipient)} — a worker may only submit an envelope the requester can open`);++ const ok = checks.every((c) => c.pass);+ const firstFail = checks.find((c) => !c.pass);+ return { ok, checks, reason: ok ? '' : firstFail?.detail || 'claim failed verification' };+}++/** Human label for a pattern, used in audit detail + UI. */+export function patternLabel(pattern) {+ const pre = pattern?.prefix || '';+ const suf = pattern?.suffix || '';+ return [pre && `prefix "${pre}"`, suf && `suffix "${suf}"`].filter(Boolean).join(' + ') || '(no pattern)';+}++/**+ * Rarity + difficulty summary for a bounty's pattern, reusing the honest rarity+ * model so the board, share cards, and post form all show the same numbers.+ * @param {{prefix?:string,suffix?:string,ignoreCase?:boolean}} pattern+ */+export function bountyDifficulty(pattern) {+ const rarity = computeRarity(pattern || {});+ const oracle = suggestBountyAtomics(pattern || {});+ return {+ expectedAttempts: rarity.expectedAttempts,+ rarityBits: rarity.rarityBits,+ tier: rarity.tier,+ tierLabel: rarity.tierLabel,+ accent: rarity.accent,+ expectedGrindSeconds: oracle.expectedGrindSeconds,+ };+}++export { PRICING, USDC };++// ── helpers ──────────────────────────────────────────────────────────────────++function bad(message, code) {+ return Object.assign(new Error(message), { status: 400, code: code || 'validation_error' });+}++// Deterministic JSON: keys sorted, no whitespace — so a digest is reproducible+// across platforms regardless of object insertion order.+function canonical(obj) {+ const keys = Object.keys(obj).sort();+ return `{${keys.map((k) => `${JSON.stringify(k)}:${JSON.stringify(obj[k])}`).join(',')}}`;+}++function truncate(s) {+ const v = String(s || '');+ return v.length > 14 ? `${v.slice(0, 8)}…${v.slice(-4)}` : v || '(none)';+}++function round2(n) {+ return Math.round(n * 100) / 100;+}diff --git a/src/solana/vanity/drop-protocol.js b/src/solana/vanity/drop-protocol.jsnew file mode 100644index 000000000..53612ebc6--- /dev/null+++ b/src/solana/vanity/drop-protocol.js@@ -0,0 +1,156 @@+/**+ * Sealed wallet drops — the protocol primitive.+ *+ * A "drop" is a pre-funded Solana wallet handed to a recipient as an+ * end-to-end-encrypted gift. The wallet's secret key/seed is sealed (ECIES,+ * sealed-envelope.js) so neither the operator, the database, a log, nor anyone+ * but the holder of the matching X25519 private key can open it. This module is+ * the trust-free core shared by the server endpoint, the SDK, and the tests:+ * it derives deterministic drop ids and claim tokens, and pins their behaviour+ * with vectors — never re-implementing the sealed envelope or the cipher.+ *+ * ── Two seal modes (both real, both operator-blind) ──────────────────────────+ *+ * 1. DIRECT SEAL. The sender already knows the recipient's X25519 public key.+ * The wallet secret is sealed to it at creation; only that recipient's+ * private key opens it. The link/QR merely points at the (already sealed)+ * envelope. A leaked link reveals nothing without the recipient's key.+ *+ * 2. CLAIM-TIME SEAL (bearer drop). The sender does not know the recipient. At+ * creation the server generates a throwaway X25519 "claim keypair", seals+ * the wallet secret to its PUBLIC key, stores only the sealed envelope +ip+ * the claim PUBLIC key, and returns the claim SECRET key to the sender ONCE.+ * That claim secret travels in the URL fragment (`#k=…`) — which browsers+ * never send to a server — so the link is the bearer token. To claim, the+ * holder proves possession of the claim secret with a one-time claim TOKEN+ * (`claimToken = SHA-256("three-drop/claim-token/v1" ‖ dropId ‖ claimSecret)`)+ * that the server compares against the stored `claimTokenHash`+ * (`SHA-256("three-drop/claim-token-hash/v1" ‖ claimToken)`). The server can+ * verify the token without ever learning the claim secret, gates the+ * exactly-once claim on it, and then releases the sealed envelope — which the+ * holder opens client-side with the claim secret from the fragment.+ *+ * ── Honest threat model (documented, not hand-waved) ─────────────────────────+ *+ * • A leaked DATABASE / compromised operator → cannot open any drop. The+ * server only ever holds the sealed envelope + the claim-token HASH; the+ * plaintext secret and the claim secret never touch the server.+ * • A leaked LINK (claim-time-seal mode) → IS bearer access, exactly like a+ * paper gift card: whoever holds the fragment can claim. This is inherent to+ * a shareable bearer gift and is stated plainly in the UI. Mitigations:+ * short expiry, exactly-once claim (a thief and the recipient cannot both+ * win), and direct-seal mode when the recipient's key is known up front.+ * • A leaked LINK (direct-seal mode) → reveals nothing: the envelope is sealed+ * to the recipient's key, which is never in the link.+ * • Replay / double-claim → impossible: the claim is an atomic compare-and-set+ * in the store (open→claimed), idempotent on the claim token.+ */++import { sha256 } from '@noble/hashes/sha256';+import { bytesToHex, hexToBytes, utf8ToBytes } from '@noble/hashes/utils';++export const DROP_PROTOCOL_VERSION = 'three-drop/v1';++// Domain separators — every hash is tagged so a digest from one context can+// never be reinterpreted as another (id ≠ claim-token ≠ token-hash).+const TAG_ID = utf8ToBytes('three-drop/id/v1');+const TAG_CLAIM_TOKEN = utf8ToBytes('three-drop/claim-token/v1');+const TAG_CLAIM_HASH = utf8ToBytes('three-drop/claim-token-hash/v1');++/** Funding assets a drop may carry. $THREE is the only *coin*; SOL/USDC are runtime rails. */+export const DROP_ASSETS = Object.freeze(['SOL', 'USDC', 'THREE']);+export const SEAL_MODES = Object.freeze(['direct', 'claim-time']);++function concatBytes(...arrays) {+ let total = 0;+ for (const a of arrays) total += a.length;+ const out = new Uint8Array(total);+ let off = 0;+ for (const a of arrays) {+ out.set(a, off);+ off += a.length;+ }+ return out;+}++/**+ * Deterministic, collision-resistant drop id (24 hex chars / 96 bits). Bound to+ * the sealed address, the funder's nonce, and the seal mode, so two creates can+ * never reuse an id and the id cannot be guessed from the address alone.+ * @param {{ address:string, nonce:string, sealMode:string }} p+ * @returns {string} 24-char lowercase hex+ */+export function deriveDropId({ address, nonce, sealMode }) {+ const h = sha256(+ concatBytes(+ TAG_ID,+ utf8ToBytes(String(address)),+ utf8ToBytes(String(nonce)),+ utf8ToBytes(String(sealMode)),+ ),+ );+ return bytesToHex(h).slice(0, 24);+}++/**+ * Derive the one-time claim TOKEN a holder presents to prove possession of the+ * claim secret (claim-time-seal mode). The token is a function of the drop id ++ * the claim secret, so it is unguessable without the secret and useless for any+ * other drop. The holder computes it client-side and sends only the token; the+ * server never sees the claim secret.+ * @param {string} dropId+ * @param {Uint8Array|string} claimSecret 32-byte X25519 secret (bytes or hex/base58 handled by caller→bytes)+ * @returns {string} 64-char hex claim token+ */+export function deriveClaimToken(dropId, claimSecretBytes) {+ if (!(claimSecretBytes instanceof Uint8Array)) {+ throw new Error('claimSecret must be Uint8Array bytes');+ }+ return bytesToHex(+ sha256(concatBytes(TAG_CLAIM_TOKEN, utf8ToBytes(String(dropId)), claimSecretBytes)),+ );+}++/**+ * Hash a claim token for at-rest storage. The server stores ONLY this hash; a+ * presented token is hashed and compared, so a database leak does not yield a+ * usable token (one-way). Mirrors password-hash discipline for a bearer secret.+ * @param {string} claimToken 64-char hex+ * @returns {string} 64-char hex token hash+ */+export function hashClaimToken(claimToken) {+ const tokenBytes = /^[0-9a-f]{64}$/i.test(String(claimToken))+ ? hexToBytes(String(claimToken))+ : utf8ToBytes(String(claimToken));+ return bytesToHex(sha256(concatBytes(TAG_CLAIM_HASH, tokenBytes)));+}++/**+ * Constant-time-ish equality for two hex digests of equal length. Avoids an+ * early-exit timing oracle on the claim-token comparison.+ */+export function timingSafeHexEqual(a, b) {+ const x = String(a || '');+ const y = String(b || '');+ if (x.length !== y.length) return false;+ let diff = 0;+ for (let i = 0; i < x.length; i++) diff |= x.charCodeAt(i) ^ y.charCodeAt(i);+ return diff === 0;+}++/** Validate a drop id shape (24 hex). */+export function isValidDropId(id) {+ return /^[0-9a-f]{24}$/.test(String(id || ''));+}++/** Normalize + validate a funding asset; throws a 400-tagged error on bad input. */+export function normalizeAsset(raw) {+ const a = String(raw || 'SOL').trim().toUpperCase();+ if (!DROP_ASSETS.includes(a)) {+ throw Object.assign(new Error(`asset must be one of ${DROP_ASSETS.join(', ')}`), {+ status: 400,+ code: 'invalid_asset',+ });+ }+ return a;+}diff --git a/src/solana/vanity/rarity.js b/src/solana/vanity/rarity.jsnew file mode 100644index 000000000..3a709c9ad--- /dev/null+++ b/src/solana/vanity/rarity.js@@ -0,0 +1,290 @@+/**+ * Verifiable rarity scoring for ground Solana vanity addresses — the honest math+ * behind the proof-of-grind gallery, leaderboard, appraisal tool, and share cards.+ *+ * ── Why this exists ──────────────────────────────────────────────────────────+ * A vanity address is a flex, but the flex is unverifiable hand-waving unless the+ * "rarity" is grounded in the *real* probability model. This module turns a+ * matched pattern into one honest number — `rarityScore` — plus a human tier+ * (Common → Mythic), derived entirely from the geometric difficulty of finding+ * the pattern, with documented, bounded bonuses for properties that genuinely+ * make a pattern harder/more special to obtain on purpose. No arbitrary numbers:+ * every term is explained and every bonus is expressed as an *additional bits of+ * difficulty* contribution so the units stay coherent.+ *+ * ── The base: bits of work ───────────────────────────────────────────────────+ * The grinder is a Bernoulli trial per candidate address. The expected number of+ * attempts to satisfy a prefix/suffix is `expectedAttempts()` from validation.js+ * (the mean of a geometric distribution: 58^effectiveLength, adjusted for+ * case-insensitive characters). We work in *bits*:+ *+ * baseBits = log2(expectedAttempts(prefix, suffix, ignoreCase))+ *+ * This is the single source of truth — it is exactly the work the verifiable+ * receipt's `difficulty.expectedAttempts` already attests to, so a rarity claim+ * tied to a receipt is only as strong as that attested difficulty. baseBits is+ * what makes a 4-char prefix categorically rarer than a 2-char one.+ *+ * ── The bonuses: extra "specialness", in bits, all bounded ───────────────────+ * On top of raw difficulty, some patterns are *more desirable* than an arbitrary+ * string of equal length — and a grinder targeting them is doing strictly more+ * than a random match. We model that as small additive bonuses, each documented+ * and capped so they can never dwarf the honest base:+ *+ * • DICTIONARY (real English word, ≥3 letters, from the vendored BIP-39 list):+ * a recognizable word is a tiny fraction of equal-length strings. Bonus scales+ * with word length; capped. Using the BIP-39 list (already vendored) keeps the+ * wordlist real and auditable — no hand-typed sample.+ * • PALINDROME (the pattern reads the same both ways, ≥3 chars): symmetric+ * targets are a vanishing fraction of strings. Flat bonus.+ * • REPEAT RUN (a single character repeated ≥3×, e.g. "aaa", "777"): visually+ * striking and a small subset of strings. Bonus scales with run length.+ * • DUAL-SIDED (both a prefix AND a suffix were requested): bookended addresses+ * are deliberately harder to read off as "vanity" by luck. Small flat bonus.+ *+ * Bonuses are additive in bits, then the whole thing is summed:+ *+ * rarityBits = baseBits + bonusBits+ * rarityScore = round(rarityBits * 100) // integer, ~bits×100 for sorting+ *+ * The ×100 keeps the leaderboard sortable with integer keys (Redis sorted sets)+ * while preserving sub-bit resolution. Tiers are cut on rarityBits so they track+ * difficulty, not the arbitrary ×100.+ *+ * Everything here is pure + isomorphic (no I/O, no crypto) so it runs identically+ * in the browser (appraisal tool, gallery) and the server (publish/verify, OG+ * cards). Behaviour is pinned by fixed vectors in tests/vanity-rarity.test.js.+ */++import { expectedAttempts, effectiveLength } from './validation.js';+import { ENGLISH_WORDLIST } from './bip39-english.js';++// Real, auditable wordset. BIP-39 English is 2048 curated lowercase words (3–8+// letters) already vendored for the mnemonic grinder — we reuse it rather than+// hand-typing a sample list. Lowercased lookup; case-insensitive word detection.+const WORDSET = new Set(ENGLISH_WORDLIST);+const MIN_WORD_LEN = 3;++const log2 = (x) => Math.log(x) / Math.LN2;++// ── Bonus parameters (documented, bounded) ──────────────────────────────────+// Each is "extra bits of specialness". Kept small so a clever 3-char pattern can+// never out-rank a brute 5-char prefix on raw difficulty alone.+const DICT_BITS_PER_LETTER = 1.4; // a real word is ~2^len rarer; we credit a slice+const DICT_BITS_CAP = 9; // ≤ ~6-letter word's worth+const PALINDROME_BITS = 3.5;+const REPEAT_BITS_PER_EXTRA = 2.2; // beyond the first 2 chars of the run+const REPEAT_BITS_CAP = 8;+const DUAL_SIDED_BITS = 2;++/**+ * Honest tier ladder, cut on rarity *bits* (≈ log2 of expected attempts incl.+ * bonuses). The cut points are chosen so each tier is ~one order of magnitude of+ * additional work harder than the last, mapping to intuitions about grind cost:+ *+ * Common < 6 bits (≲ 64 attempts — sub-2-char, trivial)+ * Uncommon 6–11.7 (~3 chars)+ * Rare 11.7–17.6 (~4 chars)+ * Epic 17.6–23.4 (~5 chars)+ * Legendary 23.4–29.3 (~6 chars)+ * Mythic ≥ 29.3 (≳ 6 chars or heavily bonused — vanishingly rare)+ *+ * 58^n in bits is n·log2(58) ≈ n·5.858, so the cuts land on whole-character+ * boundaries: 2,3,4,5,6 chars → 11.7, 17.6, 23.4, 29.3 bits.+ */+const CHAR_BITS = log2(58); // ≈ 5.8579++export const RARITY_TIERS = Object.freeze([+ { id: 'mythic', label: 'Mythic', minBits: 5 * CHAR_BITS, accent: '#ff5db1', glow: 'rgba(255,93,177,0.5)' },+ { id: 'legendary', label: 'Legendary', minBits: 4 * CHAR_BITS, accent: '#ffb020', glow: 'rgba(255,176,32,0.45)' },+ { id: 'epic', label: 'Epic', minBits: 3 * CHAR_BITS, accent: '#a855f7', glow: 'rgba(168,85,247,0.45)' },+ { id: 'rare', label: 'Rare', minBits: 2 * CHAR_BITS, accent: '#38bdf8', glow: 'rgba(56,189,248,0.4)' },+ { id: 'uncommon', label: 'Uncommon', minBits: 1 * CHAR_BITS, accent: '#4ade80', glow: 'rgba(74,222,128,0.35)' },+ { id: 'common', label: 'Common', minBits: 0, accent: '#94a3b8', glow: 'rgba(148,163,184,0.25)' },+]);++/**+ * Resolve the tier object for a given rarity-bits value.+ * @param {number} bits+ * @returns {{ id:string, label:string, accent:string, glow:string, minBits:number }}+ */+export function tierForBits(bits) {+ for (const t of RARITY_TIERS) if (bits >= t.minBits) return t;+ return RARITY_TIERS[RARITY_TIERS.length - 1];+}++/** Is `s` a real English (BIP-39) word, case-insensitively, ≥ MIN_WORD_LEN? */+function isDictionaryWord(s) {+ if (!s || s.length < MIN_WORD_LEN) return false;+ return WORDSET.has(s.toLowerCase());+}++/** Longest run of a single repeated character in `s` (1 for no repeat). */+function longestRepeatRun(s) {+ let best = s.length ? 1 : 0;+ let run = 1;+ for (let i = 1; i < s.length; i++) {+ run = s[i] === s[i - 1] ? run + 1 : 1;+ if (run > best) best = run;+ }+ return best;+}++/** Is `s` a palindrome (case-insensitive), length ≥ 3? */+function isPalindrome(s) {+ if (!s || s.length < 3) return false;+ const t = s.toLowerCase();+ for (let i = 0, j = t.length - 1; i < j; i++, j--) if (t[i] !== t[j]) return false;+ return true;+}++/**+ * Compute the full, documented rarity breakdown for a matched pattern.+ *+ * @param {object} pattern+ * @param {string} [pattern.prefix]+ * @param {string} [pattern.suffix]+ * @param {boolean} [pattern.ignoreCase=false]+ * @returns {{+ * prefix:string, suffix:string, ignoreCase:boolean,+ * expectedAttempts:number, baseBits:number, bonusBits:number, rarityBits:number,+ * rarityScore:number, tier:string, tierLabel:string, accent:string,+ * effectiveLength:number,+ * bonuses: Array<{ id:string, label:string, bits:number, detail:string }>+ * }}+ */+export function computeRarity({ prefix = '', suffix = '', ignoreCase = false } = {}) {+ const pre = prefix || '';+ const suf = suffix || '';+ const attempts = expectedAttempts(pre, suf, ignoreCase);+ const baseBits = attempts > 1 ? log2(attempts) : 0;++ const bonuses = [];++ // DICTIONARY — credit each side that is a real word, independently.+ let dictBits = 0;+ for (const [side, str] of [['prefix', pre], ['suffix', suf]]) {+ if (isDictionaryWord(str)) {+ const b = Math.min(DICT_BITS_CAP, (str.length - (MIN_WORD_LEN - 1)) * DICT_BITS_PER_LETTER + DICT_BITS_PER_LETTER);+ dictBits += b;+ bonuses.push({ id: `dictionary-${side}`, label: `Real word "${str}"`, bits: round2(b), detail: `${side} "${str}" is an English word` });+ }+ }++ // PALINDROME — check prefix, suffix, and the full pattern string.+ const full = pre + suf;+ if (isPalindrome(full) && full.length >= 3) {+ bonuses.push({ id: 'palindrome', label: 'Palindrome', bits: PALINDROME_BITS, detail: `"${full}" reads the same both ways` });+ } else {+ for (const [side, str] of [['prefix', pre], ['suffix', suf]]) {+ if (isPalindrome(str)) {+ bonuses.push({ id: `palindrome-${side}`, label: 'Palindrome', bits: PALINDROME_BITS, detail: `${side} "${str}" reads the same both ways` });+ }+ }+ }++ // REPEAT RUN — credit the longest run across the combined pattern.+ const run = longestRepeatRun(full);+ if (run >= 3) {+ const b = Math.min(REPEAT_BITS_CAP, (run - 2) * REPEAT_BITS_PER_EXTRA);+ bonuses.push({ id: 'repeat', label: `${run}× repeat`, bits: round2(b), detail: `a character repeats ${run} times in a row` });+ }++ // DUAL-SIDED — both ends fixed.+ if (pre && suf) {+ bonuses.push({ id: 'dual-sided', label: 'Bookended', bits: DUAL_SIDED_BITS, detail: 'both a prefix and a suffix were ground' });+ }++ const bonusBits = bonuses.reduce((sum, b) => sum + b.bits, 0);+ // Tier on the full-precision bits so a value sitting exactly on a 58^n boundary+ // (e.g. a 3-char prefix = 3·log2(58)) lands in the tier its character count+ // implies, rather than slipping down a tier on a 2-decimal display rounding.+ const exactBits = baseBits + bonusBits;+ const rarityBits = round2(exactBits);+ const tier = tierForBits(exactBits);++ return {+ prefix: pre || null,+ suffix: suf || null,+ ignoreCase: !!ignoreCase,+ expectedAttempts: Math.round(attempts),+ baseBits: round2(baseBits),+ bonusBits: round2(bonusBits),+ rarityBits,+ rarityScore: Math.round(rarityBits * 100),+ tier: tier.id,+ tierLabel: tier.label,+ accent: tier.accent,+ effectiveLength: round2(effectiveLength(attempts)),+ bonuses,+ };+}++/**+ * Appraise an arbitrary Base58 address against a target pattern the way a buyer+ * would request it — for the "paste any address" appraisal tool. Given an address+ * and how many leading/trailing characters to treat as the "vanity" (auto-detected+ * by default), returns the rarity of that pattern plus a grind-cost estimate.+ *+ * @param {string} address - Base58 Solana address.+ * @param {object} [opts]+ * @param {number} [opts.prefixLen] - chars from the start to treat as prefix.+ * @param {number} [opts.suffixLen] - chars from the end to treat as suffix.+ * @param {boolean} [opts.ignoreCase=false]+ * @param {number} [opts.ratePerSecond=20000000] - assumed grind rate for cost est.+ * @returns {object} rarity breakdown + { grindSeconds, grindHuman }+ */+export function appraiseAddress(address, opts = {}) {+ const addr = String(address || '').trim();+ const { ignoreCase = false, ratePerSecond = 20_000_000 } = opts;+ // Auto-detect the most generous interpretation when no explicit split given:+ // the longest leading dictionary word / repeat / and a sensible default of the+ // first 4 chars as prefix (a recognizable "vanity" the owner likely targeted).+ let prefixLen = Number.isInteger(opts.prefixLen) ? opts.prefixLen : autoPrefixLen(addr);+ let suffixLen = Number.isInteger(opts.suffixLen) ? opts.suffixLen : 0;+ prefixLen = Math.max(0, Math.min(prefixLen, addr.length));+ suffixLen = Math.max(0, Math.min(suffixLen, addr.length - prefixLen));++ const prefix = addr.slice(0, prefixLen);+ const suffix = suffixLen ? addr.slice(addr.length - suffixLen) : '';+ const rarity = computeRarity({ prefix, suffix, ignoreCase });+ const grindSeconds = rarity.expectedAttempts / Math.max(1, ratePerSecond);+ return { address: addr, ...rarity, grindSeconds, grindHuman: humanizeSeconds(grindSeconds), ratePerSecond };+}++// Pick a leading prefix length that captures the "intent" of a vanity: the+// longest of {leading dictionary word, leading repeat run, 4}, capped to a+// realistic grindable length so the appraisal isn't dominated by random tails.+function autoPrefixLen(addr) {+ let best = Math.min(4, addr.length);+ // Leading repeat run.+ let run = 1;+ for (let i = 1; i < addr.length && addr[i] === addr[0]; i++) run++;+ if (run >= 3) best = Math.max(best, Math.min(run, 8));+ // Leading dictionary word (longest prefix that is a real word).+ for (let n = Math.min(8, addr.length); n >= MIN_WORD_LEN; n--) {+ if (isDictionaryWord(addr.slice(0, n))) {+ best = Math.max(best, n);+ break;+ }+ }+ return best;+}++function humanizeSeconds(seconds) {+ if (!Number.isFinite(seconds) || seconds <= 0) return 'instant';+ if (seconds < 1) return 'under a second';+ if (seconds < 60) return `~${Math.round(seconds)} seconds`;+ if (seconds < 3600) return `~${Math.round(seconds / 60)} minutes`;+ if (seconds < 86400) return `~${Math.round(seconds / 3600)} hours`;+ if (seconds < 31_536_000) return `~${Math.round(seconds / 86400)} days`;+ const years = seconds / 31_536_000;+ if (years < 1e6) return `~${Math.round(years).toLocaleString('en-US')} years`;+ return `~${years.toExponential(1)} years`;+}++function round2(n) {+ return Math.round(n * 100) / 100;+}++export { CHAR_BITS };diff --git a/tests/vanity-bounty-protocol.test.js b/tests/vanity-bounty-protocol.test.jsnew file mode 100644index 000000000..dd1cb30bc--- /dev/null+++ b/tests/vanity-bounty-protocol.test.js@@ -0,0 +1,302 @@+// Pins the grind-bounty market protocol + escrow store behavior:+// • pattern matching honesty (mirrors the grinder matcher)+// • secret-blind claim verification (address match + seal addressed to requester)+// • difficulty→price oracle band + monotonicity+// • deterministic bounty id / claim digest vectors+// • atomic single-winner claim (two-worker race) + exactly-once idempotency+// • expiry refund mutual-exclusion with settlement+//+// Runs entirely on the in-memory store fallback (no Redis in CI) and real crypto+// (sealed-envelope ECIES, @noble Ed25519/X25519) — no mocks.++import { describe, it, expect, beforeEach } from 'vitest';++import {+ BOUNTY_PROTOCOL_VERSION,+ normalizeBountyPattern,+ addressMatchesPattern,+ suggestBountyAtomics,+ validateBountyAtomics,+ deriveBountyId,+ claimDigest,+ verifyClaimEnvelope,+ PRICING,+} from '../src/solana/vanity/bounty-protocol.js';+import {+ generateRecipientKeypair,+ sealToRecipient,+ openSealed,+ SEALED_ENVELOPE_SCHEME,+} from '../src/solana/vanity/sealed-envelope.js';+import {+ createBounty,+ claimBounty,+ markRefundable,+ getBountyRecord,+ queryBounties,+ __resetMemoryStore,+} from '../api/_lib/vanity-bounty-store.js';++// A real Solana address with a known prefix — derive one deterministically so the+// vectors are stable. ed25519 pubkey of a fixed seed, then we just assert the+// matcher against literal strings (matcher is pure string logic).+function addrWithPrefix(prefix) {+ // Build a synthetic 44-char Base58 address that starts with `prefix`. The+ // matcher is pure string logic, so a synthetic-but-well-formed address is a+ // valid test input (we are testing the matcher, not key derivation here).+ const filler = '1111111111111111111111111111111111111111111';+ return (prefix + filler).slice(0, 44);+}++describe('addressMatchesPattern', () => {+ it('honors prefix, suffix, and combined', () => {+ expect(addressMatchesPattern(addrWithPrefix('THREE'), { prefix: 'THREE' })).toBe(true);+ expect(addressMatchesPattern(addrWithPrefix('THREE'), { prefix: 'FOUR' })).toBe(false);+ const a = ('SoL' + '2'.repeat(38) + 'end').slice(0, 44);+ expect(addressMatchesPattern(a, { prefix: 'SoL', suffix: 'end' })).toBe(true);+ expect(addressMatchesPattern(a, { prefix: 'SoL', suffix: 'XXX' })).toBe(false);+ });++ it('respects ignoreCase', () => {+ const a = addrWithPrefix('Three');+ expect(addressMatchesPattern(a, { prefix: 'three' })).toBe(false);+ expect(addressMatchesPattern(a, { prefix: 'three', ignoreCase: true })).toBe(true);+ });++ it('rejects malformed (non-Base58) addresses', () => {+ expect(addressMatchesPattern('not an address', { prefix: 'no' })).toBe(false);+ expect(addressMatchesPattern('', { prefix: '' })).toBe(false);+ });+});++describe('normalizeBountyPattern', () => {+ it('requires at least one of prefix/suffix', () => {+ expect(() => normalizeBountyPattern({})).toThrow();+ });+ it('rejects non-Base58 characters', () => {+ expect(() => normalizeBountyPattern({ prefix: 'l0O' })).toThrow(); // 0,O,l are excluded+ });+ it('computes difficulty', () => {+ const r = normalizeBountyPattern({ prefix: 'ab' });+ expect(r.prefix).toBe('ab');+ expect(r.combinedLength).toBe(2);+ expect(r.expectedAttempts).toBe(58 * 58);+ });+});++describe('suggestBountyAtomics (difficulty→price oracle)', () => {+ it('stays inside the legal band', () => {+ const cheap = suggestBountyAtomics({ prefix: 'a' });+ expect(cheap.suggestedAtomics).toBeGreaterThanOrEqual(PRICING.floorAtomics);+ const huge = suggestBountyAtomics({ prefix: 'THREEws' });+ expect(huge.suggestedAtomics).toBeLessThanOrEqual(PRICING.maxAtomics);+ });+ it('is monotonic in difficulty (harder ⇒ ≥ price)', () => {+ const p3 = suggestBountyAtomics({ prefix: 'abc' }).suggestedAtomics;+ const p4 = suggestBountyAtomics({ prefix: 'abcd' }).suggestedAtomics;+ const p5 = suggestBountyAtomics({ prefix: 'abcde' }).suggestedAtomics;+ expect(p4).toBeGreaterThanOrEqual(p3);+ expect(p5).toBeGreaterThanOrEqual(p4);+ });+ it('generous tier exceeds suggested', () => {+ const o = suggestBountyAtomics({ prefix: 'abcd' });+ expect(o.generousAtomics).toBeGreaterThanOrEqual(o.suggestedAtomics);+ });+});++describe('validateBountyAtomics', () => {+ it('rejects below floor and above ceiling', () => {+ expect(() => validateBountyAtomics(1)).toThrow();+ expect(() => validateBountyAtomics(PRICING.maxAtomics + 1)).toThrow();+ expect(validateBountyAtomics(PRICING.floorAtomics)).toBe(PRICING.floorAtomics);+ });+});++describe('deriveBountyId / claimDigest determinism', () => {+ it('is deterministic + sensitive to every field', () => {+ const base = { recipient: 'Rec111', pattern: { prefix: 'ab', suffix: '', ignoreCase: false }, amountAtomics: 100000, nonce: 'deadbeef' };+ const id1 = deriveBountyId(base);+ const id2 = deriveBountyId({ ...base });+ expect(id1).toBe(id2);+ expect(id1).toMatch(/^[0-9a-f]{24}$/);+ expect(deriveBountyId({ ...base, nonce: 'cafe' })).not.toBe(id1);+ expect(deriveBountyId({ ...base, amountAtomics: 200000 })).not.toBe(id1);+ expect(deriveBountyId({ ...base, recipient: 'Other' })).not.toBe(id1);+ });++ it('claimDigest binds bountyId + address + ciphertext', () => {+ const env = { epk: 'E', nonce: 'N', ciphertext: 'C' };+ const d1 = claimDigest({ bountyId: 'b1', address: 'Addr', sealedSecret: env });+ expect(d1).toMatch(/^[0-9a-f]{32}$/);+ expect(claimDigest({ bountyId: 'b1', address: 'Addr', sealedSecret: env })).toBe(d1);+ expect(claimDigest({ bountyId: 'b2', address: 'Addr', sealedSecret: env })).not.toBe(d1);+ expect(claimDigest({ bountyId: 'b1', address: 'Other', sealedSecret: env })).not.toBe(d1);+ expect(claimDigest({ bountyId: 'b1', address: 'Addr', sealedSecret: { ...env, ciphertext: 'X' } })).not.toBe(d1);+ });+});++describe('verifyClaimEnvelope (secret-blind anti-cheat)', () => {+ let requester;+ let bounty;+ const matchingAddr = addrWithPrefix('THREE');++ beforeEach(() => {+ requester = generateRecipientKeypair(); // X25519 keypair (Base58)+ bounty = { pattern: { prefix: 'THREE', suffix: null, ignoreCase: false }, recipient: requester.publicKey };+ });++ it('accepts a matching address sealed to the requester', async () => {+ const sealed = await sealToRecipient(JSON.stringify({ secret: 'x' }), requester.publicKey);+ const r = verifyClaimEnvelope(bounty, { address: matchingAddr, sealedSecret: sealed });+ expect(r.ok).toBe(true);+ expect(sealed.scheme).toBe(SEALED_ENVELOPE_SCHEME);+ });++ it('REJECTS a non-matching address', async () => {+ const sealed = await sealToRecipient('x', requester.publicKey);+ const r = verifyClaimEnvelope(bounty, { address: addrWithPrefix('OTHER'), sealedSecret: sealed });+ expect(r.ok).toBe(false);+ expect(r.checks.find((c) => c.id === 'pattern').pass).toBe(false);+ });++ it('REJECTS an envelope sealed to someone else (worker cannot keep the key)', async () => {+ const attacker = generateRecipientKeypair();+ const sealedToAttacker = await sealToRecipient('x', attacker.publicKey);+ const r = verifyClaimEnvelope(bounty, { address: matchingAddr, sealedSecret: sealedToAttacker });+ expect(r.ok).toBe(false);+ expect(r.checks.find((c) => c.id === 'sealed-to-requester').pass).toBe(false);+ });++ it('REJECTS a malformed envelope', () => {+ const r = verifyClaimEnvelope(bounty, { address: matchingAddr, sealedSecret: { scheme: 'nope' } });+ expect(r.ok).toBe(false);+ expect(r.checks.find((c) => c.id === 'envelope').pass).toBe(false);+ });++ it('the requester (and ONLY the requester) can open the sealed key', async () => {+ const payload = JSON.stringify({ secretKeyBase58: 'theSecret' });+ const sealed = await sealToRecipient(payload, requester.publicKey);+ // Requester opens it.+ const opened = new TextDecoder().decode(await openSealed(sealed, requester.secretKey));+ expect(JSON.parse(opened).secretKeyBase58).toBe('theSecret');+ // A different key cannot.+ const attacker = generateRecipientKeypair();+ await expect(openSealed(sealed, attacker.secretKey)).rejects.toBeTruthy();+ });+});++describe('store: atomic single-winner claim + exactly-once', () => {+ const recipient = generateRecipientKeypair().publicKey;+ let id;+ let bountyRec;++ async function freshBounty(overrides = {}) {+ __resetMemoryStore();+ const now = Date.now();+ const rec = {+ id: deriveBountyId({ recipient, pattern: { prefix: 'THREE' }, amountAtomics: 500000, nonce: String(Math.random()) }),+ protocol: BOUNTY_PROTOCOL_VERSION,+ pattern: { prefix: 'THREE', suffix: null, ignoreCase: false },+ recipient,+ amountAtomics: 500000,+ asset: 'USDC',+ createdAt: now,+ expiresAt: now + 3600_000,+ ...overrides,+ };+ await createBounty(rec);+ return rec;+ }++ beforeEach(async () => {+ bountyRec = await freshBounty();+ id = bountyRec.id;+ });++ it('exactly one of two different valid claims wins; the other loses', async () => {+ const sealedA = await sealToRecipient('A', recipient);+ const sealedB = await sealToRecipient('B', recipient);+ const addrA = addrWithPrefix('THREE');+ const addrB = addrWithPrefix('THREE');+ const digestA = claimDigest({ bountyId: id, address: addrA, sealedSecret: sealedA });+ const digestB = claimDigest({ bountyId: id, address: addrB, sealedSecret: sealedB });++ const r1 = await claimBounty({ id, claimDigest: digestA, winnerAddress: addrA, workerId: 'w1', sealedSecret: sealedA });+ const r2 = await claimBounty({ id, claimDigest: digestB, winnerAddress: addrB, workerId: 'w2', sealedSecret: sealedB });++ expect([r1, r2].sort()).toEqual(['lost', 'won']);+ const rec = await getBountyRecord(id);+ expect(rec.status).toBe('settled');+ // The winning claim's sealed envelope is recorded.+ expect(rec.sealedSecret).toBeTruthy();+ });++ it('re-submitting the SAME winning claim is idempotent (won, not double-pay)', async () => {+ const sealed = await sealToRecipient('A', recipient);+ const addr = addrWithPrefix('THREE');+ const digest = claimDigest({ bountyId: id, address: addr, sealedSecret: sealed });+ const first = await claimBounty({ id, claimDigest: digest, winnerAddress: addr, workerId: 'w1', sealedSecret: sealed });+ const again = await claimBounty({ id, claimDigest: digest, winnerAddress: addr, workerId: 'w1', sealedSecret: sealed });+ expect(first).toBe('won');+ expect(again).toBe('won'); // same digest ⇒ idempotent winner, NOT a second payout race+ });++ it('the settled bounty leaves the open board', async () => {+ const sealed = await sealToRecipient('A', recipient);+ const addr = addrWithPrefix('THREE');+ await claimBounty({ id, claimDigest: claimDigest({ bountyId: id, address: addr, sealedSecret: sealed }), winnerAddress: addr, workerId: 'w1', sealedSecret: sealed });+ const open = await queryBounties({ status: 'open' });+ expect(open.bounties.find((b) => b.id === id)).toBeUndefined();+ });++ it('refund is REJECTED on a settled bounty (settle XOR refund)', async () => {+ const sealed = await sealToRecipient('A', recipient);+ const addr = addrWithPrefix('THREE');+ await claimBounty({ id, claimDigest: claimDigest({ bountyId: id, address: addr, sealedSecret: sealed }), winnerAddress: addr, workerId: 'w1', sealedSecret: sealed });+ const elig = await markRefundable(id);+ expect(elig).toBe('ineligible');+ });++ it('refund is REJECTED on a still-live bounty, ALLOWED once expired', async () => {+ // Still-live.+ expect(await markRefundable(id)).toBe('ineligible');+ // Expired bounty.+ __resetMemoryStore();+ const past = Date.now() - 10_000;+ const expired = await freshBounty({ expiresAt: past, createdAt: past - 3600_000 });+ const e1 = await markRefundable(expired.id);+ const e2 = await markRefundable(expired.id); // idempotent+ expect(e1).toBe('refundable');+ expect(e2).toBe('refundable');+ const rec = await getBountyRecord(expired.id);+ expect(rec.status).toBe('refunded');+ });++ it('a claim on an EXPIRED bounty is closed, not won', async () => {+ __resetMemoryStore();+ const past = Date.now() - 10_000;+ const expired = await freshBounty({ expiresAt: past, createdAt: past - 3600_000 });+ const sealed = await sealToRecipient('A', recipient);+ const addr = addrWithPrefix('THREE');+ const outcome = await claimBounty({ id: expired.id, claimDigest: claimDigest({ bountyId: expired.id, address: addr, sealedSecret: sealed }), winnerAddress: addr, workerId: 'w1', sealedSecret: sealed });+ expect(outcome).toBe('closed');+ });++ it('a settled bounty cannot then be refunded, and a refunded one cannot be claimed', async () => {+ // settled → refund blocked (covered above). Now: refunded → claim blocked.+ __resetMemoryStore();+ const past = Date.now() - 10_000;+ const expired = await freshBounty({ expiresAt: past, createdAt: past - 3600_000 });+ await markRefundable(expired.id);+ const sealed = await sealToRecipient('A', recipient);+ const addr = addrWithPrefix('THREE');+ const outcome = await claimBounty({ id: expired.id, claimDigest: 'x', winnerAddress: addr, workerId: 'w1', sealedSecret: sealed });+ expect(outcome).toBe('closed');+ });+});++describe('protocol version is pinned', () => {+ it('matches the expected constant', () => {+ expect(BOUNTY_PROTOCOL_VERSION).toBe('three-vanity-bounty/v1');+ });+});diff --git a/tests/vanity-gallery-store.test.js b/tests/vanity-gallery-store.test.jsnew file mode 100644index 000000000..d9261f29f--- /dev/null+++ b/tests/vanity-gallery-store.test.js@@ -0,0 +1,101 @@+// Pins the proof-of-grind gallery store's query/leaderboard/filter behavior on+// the in-memory fallback (no Redis in CI). The privacy projection is covered in+// vanity-rarity.test.js; this locks ordering, pagination, filters, and stats.++import { describe, it, expect, beforeEach } from 'vitest';+import {+ putEntry,+ getEntry,+ removeEntry,+ queryEntries,+ topByScore,+ galleryStats,+} from '../api/_lib/vanity-gallery-store.js';++const ADDR = (c) => c.repeat(43).slice(0, 43); // 43-char base58-ish filler+function mk(addr, score, tier, prefix, ts) {+ return {+ address: addr,+ rarityScore: score,+ rarityBits: score / 100,+ tier,+ tierLabel: tier[0].toUpperCase() + tier.slice(1),+ pattern: { prefix, suffix: null, ignoreCase: false },+ expectedAttempts: 2 ** Math.round(score / 100),+ bonuses: [],+ verified: true,+ ts: ts || Date.now(),+ };+}++// Unique addresses per test run so the shared in-memory map doesn't collide.+let n = 0;+const uniq = () => `Z${(n++).toString().padStart(2, '0')}${ADDR('1')}`.slice(0, 43);++describe('gallery store query + leaderboard (in-memory fallback)', () => {+ let mythic, rare, uncommon;+ beforeEach(async () => {+ mythic = uniq();+ rare = uniq();+ uncommon = uniq();+ await putEntry(mk(mythic, 2900, 'mythic', 'Sol', 1000));+ await putEntry(mk(rare, 1172, 'rare', 'So', 2000));+ await putEntry(mk(uncommon, 586, 'uncommon', 'S', 3000));+ });++ it('leaderboard is ordered by rarity score descending', async () => {+ const top = await topByScore(10);+ const idx = top.findIndex((e) => e.address === mythic);+ const idxRare = top.findIndex((e) => e.address === rare);+ expect(idx).toBeGreaterThanOrEqual(0);+ expect(idx).toBeLessThan(idxRare);+ });++ it('sort=score returns rarest first, sort=recency returns newest first', async () => {+ const byScore = await queryEntries({ sort: 'score', limit: 100 });+ const scores = byScore.entries.map((e) => e.rarityScore);+ const sorted = [...scores].sort((a, b) => b - a);+ expect(scores).toEqual(sorted);++ const byRecency = await queryEntries({ sort: 'recency', limit: 100 });+ const tsList = byRecency.entries.map((e) => e.ts);+ const tsSorted = [...tsList].sort((a, b) => b - a);+ expect(tsList).toEqual(tsSorted);+ });++ it('paginates with total + hasMore', async () => {+ const page = await queryEntries({ sort: 'score', limit: 2, offset: 0 });+ expect(page.entries.length).toBe(2);+ expect(page.total).toBeGreaterThanOrEqual(3);+ expect(page.hasMore).toBe(true);+ });++ it('filters by tier', async () => {+ const rareOnly = await queryEntries({ tier: 'rare', limit: 100 });+ expect(rareOnly.entries.every((e) => e.tier === 'rare')).toBe(true);+ expect(rareOnly.entries.some((e) => e.address === rare)).toBe(true);+ });++ it('filters by pattern substring (case-insensitive)', async () => {+ const hits = await queryEntries({ contains: 'sol', limit: 100 });+ expect(hits.entries.some((e) => e.address === mythic)).toBe(true);+ });++ it('stats report totals + per-tier histogram + the rarest entry', async () => {+ const s = await galleryStats();+ expect(s.total).toBeGreaterThanOrEqual(3);+ expect(s.byTier.mythic).toBeGreaterThanOrEqual(1);+ expect(s.rarest.rarityScore).toBeGreaterThanOrEqual(2900);+ });++ it('get + remove are idempotent on address', async () => {+ const a = uniq();+ await putEntry(mk(a, 500, 'uncommon', 'S'));+ expect((await getEntry(a)).rarityScore).toBe(500);+ // Re-publish updates in place (one entry per address).+ await putEntry(mk(a, 999, 'rare', 'So'));+ expect((await getEntry(a)).rarityScore).toBe(999);+ await removeEntry(a);+ expect(await getEntry(a)).toBeNull();+ });+});diff --git a/tests/vanity-rarity.test.js b/tests/vanity-rarity.test.jsnew file mode 100644index 000000000..274042027--- /dev/null+++ b/tests/vanity-rarity.test.js@@ -0,0 +1,176 @@+// Pins the proof-of-grind rarity math + the gallery store's privacy boundary.+// The scoring is the trust surface for the gallery/leaderboard/share cards, so+// it is locked with fixed vectors; a change that inflates a score or leaks a+// secret must break a test here.++import { describe, it, expect } from 'vitest';+import {+ computeRarity,+ appraiseAddress,+ tierForBits,+ RARITY_TIERS,+ CHAR_BITS,+} from '../src/solana/vanity/rarity.js';+import { toPublicEntry, PUBLIC_FIELDS } from '../api/_lib/vanity-gallery-store.js';+import { expectedAttempts } from '../src/solana/vanity/validation.js';++describe('rarity base math is the honest difficulty model', () => {+ it('empty pattern is Common with zero score', () => {+ const r = computeRarity({});+ expect(r.tier).toBe('common');+ expect(r.rarityScore).toBe(0);+ expect(r.baseBits).toBe(0);+ expect(r.bonusBits).toBe(0);+ });++ it('baseBits is log2(expectedAttempts) — tied to the receipt difficulty', () => {+ for (const pat of [{ prefix: 'So' }, { prefix: 'abc' }, { prefix: 'ab', suffix: 'z' }]) {+ const r = computeRarity(pat);+ const expected = Math.log2(expectedAttempts(pat.prefix || '', pat.suffix || '', false));+ expect(r.baseBits).toBeCloseTo(Math.round(expected * 100) / 100, 2);+ }+ });++ it('tier cuts land on whole-character boundaries (58^n in bits)', () => {+ // 2 chars → 2·log2(58) ≈ 11.72 bits → Rare floor.+ expect(computeRarity({ prefix: 'So' }).tier).toBe('rare');+ expect(computeRarity({ prefix: 'So' }).rarityBits).toBeCloseTo(2 * CHAR_BITS, 1);+ // 3 chars no bonus → Epic floor (3·log2(58) ≈ 17.57).+ expect(computeRarity({ prefix: 'xqz' }).tier).toBe('epic');+ // 5 chars no bonus → Mythic floor (5·log2(58) ≈ 29.29).+ expect(computeRarity({ prefix: 'abcde' }).tier).toBe('mythic');+ });++ it('longer prefixes are categorically rarer (monotonic in base difficulty)', () => {+ const two = computeRarity({ prefix: 'ab' }).baseBits;+ const three = computeRarity({ prefix: 'abc' }).baseBits;+ const four = computeRarity({ prefix: 'abcd' }).baseBits;+ expect(three).toBeGreaterThan(two);+ expect(four).toBeGreaterThan(three);+ });++ it('case-insensitive matching lowers difficulty vs case-sensitive', () => {+ const ci = computeRarity({ prefix: 'abc', ignoreCase: true }).baseBits;+ const cs = computeRarity({ prefix: 'abc', ignoreCase: false }).baseBits;+ expect(ci).toBeLessThan(cs);+ });+});++describe('rarity bonuses are real, bounded, and documented', () => {+ it('a real BIP-39 word earns a dictionary bonus; a non-word does not', () => {+ const word = computeRarity({ prefix: 'cat' }); // "cat" ∈ BIP-39+ const nonWord = computeRarity({ prefix: 'xqz' }); // not a word+ expect(word.bonuses.some((b) => b.id.startsWith('dictionary'))).toBe(true);+ expect(nonWord.bonuses.some((b) => b.id.startsWith('dictionary'))).toBe(false);+ expect(word.rarityBits).toBeGreaterThan(nonWord.rarityBits);+ });++ it('palindromes earn a flat bonus', () => {+ const pal = computeRarity({ prefix: 'aba' });+ expect(pal.bonuses.some((b) => b.id.includes('palindrome'))).toBe(true);+ });++ it('a 3× repeat run earns a repeat bonus AND counts as a palindrome', () => {+ const r = computeRarity({ prefix: 'aaa' });+ const ids = r.bonuses.map((b) => b.id);+ expect(ids).toContain('repeat');+ expect(ids.some((i) => i.includes('palindrome'))).toBe(true);+ });++ it('dual-sided (prefix AND suffix) earns the bookended bonus', () => {+ const r = computeRarity({ prefix: 'xy', suffix: 'zw' });+ expect(r.bonuses.some((b) => b.id === 'dual-sided')).toBe(true);+ });++ it('bonuses can never out-rank raw difficulty: a 3-char word < a 5-char prefix', () => {+ const word3 = computeRarity({ prefix: 'cat' }).rarityBits;+ const brute5 = computeRarity({ prefix: 'abcde' }).rarityBits;+ expect(brute5).toBeGreaterThan(word3);+ });++ it('exact frozen vector for "cat" (regression lock)', () => {+ const r = computeRarity({ prefix: 'cat' });+ expect(r.tier).toBe('epic');+ expect(r.rarityScore).toBe(2037);+ expect(r.baseBits).toBe(17.57);+ expect(r.bonusBits).toBe(2.8);+ });+});++describe('tier ladder', () => {+ it('tierForBits is monotonic and bounded by Common…Mythic', () => {+ expect(tierForBits(-1).id).toBe('common');+ expect(tierForBits(0).id).toBe('common');+ expect(tierForBits(100).id).toBe('mythic');+ // Each defined floor resolves to its own tier.+ for (const t of RARITY_TIERS) {+ expect(tierForBits(t.minBits).id).toBe(t.id);+ }+ });+});++describe('appraisal of an arbitrary address', () => {+ it('returns a tier, score, and human grind-cost estimate', () => {+ const a = appraiseAddress('So11111111111111111111111111111111111111112');+ expect(a.tier).toBeTruthy();+ expect(typeof a.rarityScore).toBe('number');+ expect(typeof a.grindHuman).toBe('string');+ expect(a.grindSeconds).toBeGreaterThanOrEqual(0);+ });++ it('honors an explicit prefix/suffix split', () => {+ const a = appraiseAddress('AbcDeFgHiJkLmNoPqRsTuVwXyZ123456789ABCDEFGHJ', { prefixLen: 3, suffixLen: 0 });+ expect(a.prefix).toBe('Abc');+ expect(a.suffix).toBeNull();+ });++ it('a longer requested prefix yields a rarer appraisal', () => {+ const short = appraiseAddress('TestWalletXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', { prefixLen: 2 });+ const long = appraiseAddress('TestWalletXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', { prefixLen: 4 });+ expect(long.rarityBits).toBeGreaterThan(short.rarityBits);+ });+});++describe('privacy: the gallery store can never serialize a secret', () => {+ it('toPublicEntry drops every secret/seed/sealed field', () => {+ const poisoned = {+ address: 'So11111111111111111111111111111111111111112',+ rarityScore: 1172,+ tier: 'rare',+ pattern: { prefix: 'So', suffix: null, ignoreCase: false },+ // Attacker/caller-smuggled secrets — must NOT survive projection.+ secretKey: [1, 2, 3, 4],+ secretKeyBase58: 'NEVERLEAKME',+ seed: 'deadbeef'.repeat(8),+ serverSeed: 'cafe'.repeat(16),+ sealedSecret: { ciphertext: 'x', epk: 'y' },+ privateKey: 'nope',+ mnemonic: 'word word word',+ };+ const pub = toPublicEntry(poisoned);+ const serialized = JSON.stringify(pub);+ for (const leak of ['secretKey', 'secretKeyBase58', 'seed', 'serverSeed', 'sealedSecret', 'privateKey', 'mnemonic', 'NEVERLEAKME', 'deadbeef', 'cafe']) {+ expect(serialized).not.toContain(leak);+ }+ // And only allowlisted keys survive.+ for (const k of Object.keys(pub)) expect(PUBLIC_FIELDS).toContain(k);+ });++ it('rejects an entry without an address or a numeric score', () => {+ expect(toPublicEntry({ rarityScore: 5 })).toBeNull();+ expect(toPublicEntry({ address: 'So111' })).toBeNull();+ expect(toPublicEntry(null)).toBeNull();+ });++ it('clamps a runaway label and nested pattern', () => {+ const pub = toPublicEntry({+ address: 'So11111111111111111111111111111111111111112',+ rarityScore: 1,+ label: 'x'.repeat(500),+ pattern: { prefix: 'a'.repeat(100), suffix: 'b'.repeat(100), ignoreCase: true, secretSmuggle: 'leak' },+ });+ expect(pub.label.length).toBeLessThanOrEqual(80);+ expect(pub.pattern.prefix.length).toBeLessThanOrEqual(16);+ expect(JSON.stringify(pub.pattern)).not.toContain('leak');+ });+});diff --git a/tests/vanity-verifiable-grind.test.js b/tests/vanity-verifiable-grind.test.jsindex d9e1edaaa..c303d0cf5 100644--- a/tests/vanity-verifiable-grind.test.js+++ b/tests/vanity-verifiable-grind.test.js@@ -165,7 +165,7 @@ describe('verifyVanityReceipt — happy path', () => {describe('verifyVanityReceipt — negative / tamper tests', () => {it('FAILS when the address is swapped', () => {const { receipt } = buildSignedReceipt({ prefix: 'a' });- const tampered = { ...receipt, address: 'So11111111111111111111111111111111111111112' };+ const tampered = { ...receipt, address: 'THREEsynthetic1111111111111111111111111111111' };const { valid, checks } = verifyVanityReceipt(tampered, { servicePublicKey: receipt.servicePublicKey });expect(valid).toBe(false);// Signature breaks (address is signed) AND derivation no longer matches.diff --git a/vercel.json b/vercel.jsonindex c9d3f8ba4..fd0776f9f 100644--- a/vercel.json+++ b/vercel.json@@ -550,6 +550,14 @@"src": "/vanity/verify/?","dest": "/vanity/verify/index.html"},+ {+ "src": "/vanity/gallery/?",+ "dest": "/vanity/gallery/index.html"+ },+ {+ "src": "/vanity/bounties/?",+ "dest": "/vanity/bounties/index.html"+ },{"src": "/vanity-wallet","dest": "/vanity-wallet.html"diff --git a/vite.config.js b/vite.config.jsindex 3757e6395..09a69be81 100644--- a/vite.config.js+++ b/vite.config.js@@ -434,6 +434,8 @@ const appConfig = {// END:DISCOVER_ROUTE'vanity-wallet': resolve(__dirname, 'public/vanity-wallet.html'),'vanity-verify': resolve(__dirname, 'public/vanity/verify/index.html'),+ 'vanity-gallery': resolve(__dirname, 'public/vanity/gallery/index.html'),+ 'vanity-bounties': resolve(__dirname, 'public/vanity/bounties/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'),@@ -854,6 +856,10 @@ support: resolve(__dirname, 'pages/support.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'),+ '/vanity/gallery': resolve(root, 'public/vanity/gallery/index.html'),+ '/vanity/gallery/': resolve(root, 'public/vanity/gallery/index.html'),+ '/vanity/bounties': resolve(root, 'public/vanity/bounties/index.html'),+ '/vanity/bounties/': resolve(root, 'public/vanity/bounties/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'),@@ -1722,6 +1728,11 @@ support: resolve(__dirname, 'pages/support.html'),['dist/public/demos/3d-home.html', 'dist/demos/3d-home.html'],['dist/public/eth-vanity.html', 'dist/eth-vanity.html'],['dist/public/evm-wallet.html', 'dist/evm-wallet.html'],+ // Grind-bounty market: its controller pulls bare deps (bs58, @noble,+ // sealed-envelope) through the bundler, so the BUNDLED output must be+ // served — promote it over the raw publicDir copy before dist/public+ // is wiped.+ ['dist/public/vanity/bounties/index.html', 'dist/vanity/bounties/index.html'],];for (const [from, to] of pairs) {const src = resolve(__dirname, from);