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 suffix support, aixbt pay HUD, metaplex/agent-wallet scripts, blog posts
nirholas33023f63f473
diff --git a/.gitignore b/.gitignoreindex a479e61ec..20c545568 100644--- a/.gitignore+++ b/.gitignore@@ -199,3 +199,7 @@ __pycache__/# three.ws presence sweep — regenerate with `npm run presence`three-ws-presence.jsonthree-ws-presence.md++# Exported custodial wallet backups — never commit+agent-wallets.*+blog/3d-ai-crypto-convergence.mddiff --git a/api/_lib/provider-health.js b/api/_lib/provider-health.jsindex 69be27cad..e3fa15c1b 100644--- a/api/_lib/provider-health.js+++ b/api/_lib/provider-health.js@@ -19,6 +19,14 @@ const COOLDOWN_PREFIX = 'llm-cooldown:';// that a provider that has recovered is retried promptly.const DEFAULT_COOLDOWN_SECONDS = 45;+// Cooldown for auth/billing failures (401 invalid-or-expired key, 403 forbidden,+// 402 out of credits). Unlike a rate-limit, a bad key or an unfunded account+// won't recover in 45s — it's broken for the whole deploy until ops fixes it. A+// longer window means the misconfigured provider is probed roughly once every+// few minutes instead of burning attempt-0 of every single request, while still+// recovering on its own once the key/billing is fixed (the cooldown just expires).+export const AUTH_COOLDOWN_SECONDS = 300;+/*** Record that `provider` is unhealthy, so it is skipped for `seconds`. The* cache TTL is the cooldown — presence of the key means "in cooldown", and itdiff --git a/api/_lib/three-brand.js b/api/_lib/three-brand.jsindex eaa98e122..8444434ac 100644--- a/api/_lib/three-brand.js+++ b/api/_lib/three-brand.js@@ -258,10 +258,13 @@ export function buildAgentRegistrationMetadata(a) {];return {- type: [- 'https://eips.ethereum.org/EIPS/eip-8004#registration-v1',- 'https://three.ws/specs/3d-agent-card-v1',- ],+ // Metaplex's Agent Registry indexer requires `type` to be a STRING matching+ // the EIP-8004 registration-v1 URL. An array here makes the indexer reject+ // the registration-v1 shape and fall back to a name/description/image-only+ // record — silently dropping active/x402Support/services/supportedTrust from+ // the agent page. Keep `type` a string; carry the three.ws spec separately.+ type: 'https://eips.ethereum.org/EIPS/eip-8004#registration-v1',+ additionalTypes: ['https://three.ws/specs/3d-agent-card-v1'],name: a.name,description,image,diff --git a/api/agents/solana-wallet.js b/api/agents/solana-wallet.jsindex c44c4131c..7990eb775 100644--- a/api/agents/solana-wallet.js+++ b/api/agents/solana-wallet.js@@ -338,6 +338,7 @@ async function handleWallet(req, res, id) {delete meta.solana_address;delete meta.encrypted_solana_secret;delete meta.solana_vanity_prefix;+ delete meta.solana_vanity_suffix;delete meta.solana_wallet_source;await sql`UPDATE agent_identities SET meta = ${JSON.stringify(meta)}::jsonb WHERE id = ${id}`;return json(res, 200, { data: { ok: true } });@@ -345,7 +346,7 @@ async function handleWallet(req, res, id) {if (req.method === 'POST') {const body = await readJson(req).catch(() => ({}));- const importing = body && (body.secret_key || body.vanity_prefix);+ const importing = body && (body.secret_key || body.vanity_prefix || body.vanity_suffix);if (importing) {const sk = body.secret_key;@@ -360,9 +361,20 @@ async function handleWallet(req, res, id) {if (!BASE58_RE.test(body.vanity_prefix) || body.vanity_prefix.length > 6) return error(res, 400, 'validation_error', 'vanity_prefix is not valid base58 (max 6 chars)');if (!address.startsWith(body.vanity_prefix)) return error(res, 400, 'validation_error', 'vanity_prefix does not match the keypair address');}+ if (body.vanity_suffix) {+ if (!BASE58_RE.test(body.vanity_suffix) || body.vanity_suffix.length > 6) return error(res, 400, 'validation_error', 'vanity_suffix is not valid base58 (max 6 chars)');+ if (!address.endsWith(body.vanity_suffix)) return error(res, 400, 'validation_error', 'vanity_suffix does not match the keypair address');+ }if (meta.solana_address) return error(res, 409, 'conflict', 'agent already has a Solana wallet — DELETE /api/agents/:id/solana first to replace');const encrypted_secret = await _encryptSecret(Buffer.from(kp.secretKey).toString('base64'));- meta = { ...meta, solana_address: address, encrypted_solana_secret: encrypted_secret, solana_wallet_source: 'imported_vanity', ...(body.vanity_prefix ? { solana_vanity_prefix: body.vanity_prefix } : {}) };+ meta = {+ ...meta,+ solana_address: address,+ encrypted_solana_secret: encrypted_secret,+ solana_wallet_source: 'imported_vanity',+ ...(body.vanity_prefix ? { solana_vanity_prefix: body.vanity_prefix } : {}),+ ...(body.vanity_suffix ? { solana_vanity_suffix: body.vanity_suffix } : {}),+ };await sql`UPDATE agent_identities SET meta = ${JSON.stringify(meta)}::jsonb WHERE id = ${id}`;} else if (!meta.solana_address) {const sol = await generateSolanaAgentWallet();@@ -410,6 +422,7 @@ async function handleWallet(req, res, id) {sol: lamports == null ? null : lamports / 1e9,...(balanceError ? { balance_error: balanceError } : {}),vanity_prefix: meta.solana_vanity_prefix || null,+ vanity_suffix: meta.solana_vanity_suffix || null,source: meta.solana_wallet_source || (meta.encrypted_solana_secret ? 'generated' : null),sns_domain: attachedSns || favoriteSns,sns_source: attachedSns ? 'attached' : (favoriteSns ? 'favorite' : null),diff --git a/api/chat.js b/api/chat.jsindex 79f839085..280a205a2 100644--- a/api/chat.js+++ b/api/chat.js@@ -31,7 +31,7 @@ import { loadUserProviderKeys } from './_lib/provider-keys.js';import { watsonxConfig, watsonxAuthHeaders } from './_lib/watsonx.js';import { orchestrateConfig } from './_lib/orchestrate.js';import { guardianConfig, governSend, sendCapUsd } from './_lib/granite-guardian.js';-import { markProviderCooldown, providersInCooldown } from './_lib/provider-health.js';+import { markProviderCooldown, providersInCooldown, AUTH_COOLDOWN_SECONDS } from './_lib/provider-health.js';import {DEFAULT_FREE_MODEL,PROVIDER_MODEL_DEFAULTS,@@ -525,6 +525,43 @@ export default wrap(async (req, res) => {continue;}+ // Auth / billing failures (401 invalid-or-expired key, 403 forbidden, 402+ // out of credits) are NOT transient and NOT a per-call caller mistake — the+ // provider is misconfigured or unfunded for the whole deploy, so every+ // request hits the identical wall. The generic branch below only fails over+ // on 429/5xx, so a bad server ANTHROPIC_API_KEY used to hard-fail chat for+ // signed-in users even while Groq/OpenRouter were healthy. Treat these as+ // provider-down: cool the provider for a long window (the key won't fix+ // itself in 45s), skip its remaining sibling routes (same dead key → same+ // 401), and fail over to the next provider.+ if (upstream.status === 401 || upstream.status === 403 || upstream.status === 402) {+ const text = await upstream.text().catch(() => '');+ void markProviderCooldown(route.name, AUTH_COOLDOWN_SECONDS);+ let next = routeIdx + 1;+ while (next < fallbackRoutes.length && fallbackRoutes[next].name === route.name) next++;+ if (next < fallbackRoutes.length && Date.now() < deadline) {+ console.warn(`[chat:${route.name}] ${upstream.status} (auth/billing) — cooling ${AUTH_COOLDOWN_SECONDS}s, failing over to ${fallbackRoutes[next].name}/${fallbackRoutes[next].model}: ${text.slice(0, 120)}`);+ routeIdx = next;+ route = fallbackRoutes[routeIdx];+ includeTools = true;+ retriedTransient = false;+ continue;+ }+ // Every remaining route is the same misconfigured provider (or the time+ // budget is spent) — surface a terminal error here. The body is already+ // consumed, so we can't fall through to the generic `!upstream.ok` block+ // (it would re-read an empty stream); build the response inline instead.+ captureException(new Error(`${route.name} upstream ${upstream.status}`), {+ route: 'chat', provider: route.name, status: upstream.status, body: text.slice(0, 400),+ });+ console.error(`[chat:${route.name}] ${upstream.status} (auth/billing, final — no healthy provider left)`, text.slice(0, 200));+ res.setHeader('Retry-After', '20');+ return error(res, 503, 'rate_limited', 'The AI chat is at capacity right now. Please try again in a few seconds.', {+ providers_tried: providersTried(attempted),+ retry_after: 20,+ });+ }+// Fall over on rate-limit (429) and transient gateway errors (502/503/504).// Don't re-fetch on 4xx other than 429 — those are caller mistakes that// the next provider would also reject.diff --git a/api/marketplace/[action].js b/api/marketplace/[action].jsindex e4d757fd9..eb0b01ab2 100644--- a/api/marketplace/[action].js+++ b/api/marketplace/[action].js@@ -22,7 +22,7 @@ import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';import { publicUrl } from '../_lib/r2.js';import { clientIp, limits } from '../_lib/rate-limit.js';-import { markProviderCooldown } from '../_lib/provider-health.js';+import { markProviderCooldown, AUTH_COOLDOWN_SECONDS } from '../_lib/provider-health.js';import { z } from 'zod';const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;@@ -808,15 +808,25 @@ async function handlePreview(req, res, id) {const text = await upstream.text().catch(() => '');console.warn(`[preview:${route.name}] ${upstream.status} — ${text.slice(0, 200)}`);- // 429 / 5xx are capacity or transient upstream failures — record a cooldown- // for the shared provider-health breaker before failing over.+ // Fail over on rate-limit (429), transient upstream errors (5xx), AND+ // auth/billing failures (401 bad/expired key, 403 forbidden, 402 out of+ // credits). The auth/billing group is what used to hard-fail this endpoint:+ // a bad server ANTHROPIC_API_KEY returned 502 to every preview without ever+ // trying the healthy free tiers. These are provider-down conditions for the+ // whole deploy, so cool the provider down — a long window for auth/billing+ // (the key won't recover in 45s), the default window for a transient blip —+ // and move to the next provider.+ const authBilling = upstream.status === 401 || upstream.status === 403 || upstream.status === 402;const transient = upstream.status === 429 || upstream.status >= 500;- if (transient) void markProviderCooldown(route.name);- const canFailOver = i + 1 < routes.length && transient;+ const failable = transient || authBilling;+ if (authBilling) void markProviderCooldown(route.name, AUTH_COOLDOWN_SECONDS);+ else if (transient) void markProviderCooldown(route.name);+ const canFailOver = i + 1 < routes.length && failable;if (canFailOver) continue;- // Chain exhausted. A capacity/transient terminal failure degrades to- // 503 + Retry-After (client backs off); a genuine bad status stays a 502.- if (transient) {+ // Chain exhausted. A capacity/transient/auth terminal failure degrades to+ // 503 + Retry-After (client backs off); only a genuine non-failable bad+ // status stays a 502.+ if (failable) {res.setHeader('Retry-After', '20');return error(res, 503, 'rate_limited', 'Agent preview is briefly at capacity. Please try again in a few seconds.');}diff --git a/blog/3d-ai-crypto-convergence.html b/blog/3d-ai-crypto-convergence.htmlnew file mode 100644index 000000000..fa335ae0e--- /dev/null+++ b/blog/3d-ai-crypto-convergence.html@@ -0,0 +1,192 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>3D + AI + Web3 Just Converged: three.ws Shipped the Whole Stack</title>+ <meta name="description" content="A web2 unicorn just raised ~$200M to build 3D AI agents. three.ws is the only crypto-native team that already shipped the full stack: browser 3D, a multi-provider MCP runtime, and on-chain agent wallets that pay each other in USDC. Open source on GitHub, published to npm, and live on Anthropic's MCP Registry.">+ <meta name="keywords" content="three.ws, 3D agents, AI agents, web3, crypto, convergence, spatial AI, x402, ERC-8004, Solana, MCP, Anthropic MCP Registry, agent payments, three.js, npm">+ <link rel="canonical" href="https://three.ws/blog/3d-ai-crypto-convergence">++ <meta property="og:title" content="3D + AI + Web3 Just Converged: three.ws Shipped the Whole Stack">+ <meta property="og:description" content="A web2 unicorn just raised ~$200M to build 3D AI agents. three.ws already shipped the full stack: browser 3D, a multi-provider MCP runtime, and on-chain agent wallets. Open source, on npm, live on Anthropic's MCP Registry.">+ <meta property="og:url" content="https://three.ws/blog/3d-ai-crypto-convergence">+ <meta property="og:type" content="article">+ <meta property="og:image" content="https://three.ws/og-image.png">++ <meta name="twitter:card" content="summary_large_image">+ <meta name="twitter:title" content="3D + AI + Web3 Just Converged: three.ws Shipped the Whole Stack">+ <meta name="twitter:description" content="A web2 unicorn just raised ~$200M to build 3D AI agents. three.ws already shipped the full stack, open source and on-chain.">++ <link rel="shortcut icon" href="/favicon.ico">+ <link rel="stylesheet" href="/nav.css">+ <link rel="stylesheet" href="/footer.css">+ <style>+ :root { color-scheme: dark; }+ body { margin: 0; background: #060611; color: #e7e7f5; font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; -webkit-font-smoothing: antialiased; }+ .post-wrap { max-width: 720px; margin: 0 auto; padding: 96px 24px 80px; }+ .post-meta { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; color: #7a85a8; font-size: 13px; margin-bottom: 28px; }+ .post-date { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }+ .post-tag { padding: 2px 8px; border-radius: 999px; background: rgba(154,212,255,.08); color: #9ad4ff; font-size: 11px; font-weight: 500; letter-spacing: 0.02em; text-transform: uppercase; }+ h1 { font-size: clamp(26px, 4vw, 40px); font-weight: 700; letter-spacing: -0.02em; line-height: 1.2; margin: 0 0 20px; }+ h2 { font-size: 20px; font-weight: 600; margin: 40px 0 12px; letter-spacing: -0.01em; }+ h3 { font-size: 15px; font-weight: 600; margin: 22px 0 8px; color: #b9c2e0; }+ p { color: #c8c8e0; line-height: 1.7; margin: 0 0 18px; font-size: 16px; }+ ul, ol { color: #c8c8e0; line-height: 1.7; margin: 0 0 18px; padding-left: 24px; font-size: 16px; }+ li { margin-bottom: 6px; }+ a { color: #9ad4ff; text-decoration: none; }+ a:hover { text-decoration: underline; }+ code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 13px; background: rgba(154,212,255,.07); color: #9ad4ff; padding: 2px 6px; border-radius: 4px; }+ pre { background: rgba(255,255,255,.04); border: 1px solid rgba(255,255,255,.08); border-radius: 8px; padding: 16px 20px; overflow-x: auto; margin: 0 0 20px; }+ pre code { background: none; padding: 0; font-size: 14px; }+ strong { color: #e7e7f5; }+ blockquote { margin: 0 0 18px; padding: 16px 20px; border-left: 3px solid rgba(154,212,255,.4); background: rgba(154,212,255,.04); border-radius: 0 10px 10px 0; color: #d8d8ee; font-size: 16px; line-height: 1.65; }+ .post-back { display: inline-flex; align-items: center; gap: 6px; color: #7a85a8; font-size: 14px; margin-bottom: 40px; text-decoration: none; }+ .post-back:hover { color: #9ad4ff; }+ hr { border: none; border-top: 1px solid rgba(255,255,255,.08); margin: 40px 0; }+ </style>+ <script type="application/ld+json">+ {+ "@context": "https://schema.org",+ "@type": "BlogPosting",+ "headline": "3D + AI + Web3 Just Converged: three.ws Shipped the Whole Stack",+ "description": "A web2 unicorn just raised ~$200M to build 3D AI agents. three.ws is the only crypto-native team that already shipped the full stack: browser 3D, a multi-provider MCP runtime, and on-chain agent wallets that pay each other in USDC. Open source on GitHub, on npm, and live on Anthropic's MCP Registry.",+ "image": "https://three.ws/og-image.png",+ "datePublished": "2026-06-08T16:00:00.000Z",+ "dateModified": "2026-06-08T16:00:00.000Z",+ "author": { "@type": "Organization", "name": "three.ws", "url": "https://three.ws" },+ "publisher": {+ "@type": "Organization",+ "name": "three.ws",+ "url": "https://three.ws",+ "logo": { "@type": "ImageObject", "url": "https://three.ws/og-image.png" }+ },+ "mainEntityOfPage": { "@type": "WebPage", "@id": "https://three.ws/blog/3d-ai-crypto-convergence" },+ "keywords": "three.ws, 3D agents, AI agents, web3, crypto, convergence, spatial AI, x402, ERC-8004, Solana, MCP, Anthropic MCP Registry, npm"+ }+ </script>+</head>+<body>+ <div id="nav-container"></div>+ <main class="post-wrap">+ <a class="post-back" href="/blog">← Blog</a>+ <div class="post-meta">+ <span class="post-date">2026-06-08</span>+ <span class="post-tag">Thesis</span>+ <span class="post-tag">3D Agents</span>+ <span class="post-tag">AI</span>+ <span class="post-tag">Web3</span>+ </div>+ <h1>3D + AI + Web3 Just Converged: three.ws Shipped the Whole Stack</h1>++ <p>Three of the biggest technology waves of the decade, <strong>spatial / 3D</strong>, <strong>AI agents</strong>, and <strong>web3</strong>, are colliding into a single product category: the autonomous, embodied agent. An AI that thinks, has a body you can see, and a wallet it controls.</p>++ <p>The market is already pricing this in. A web2 unicorn recently closed a <strong>~$200M round</strong> to build 3D AI characters and agents. That is the loud signal that the thesis is real and the demand is here. But here is the part nobody noticed: <strong>there is exactly one crypto-native team that has already shipped the entire stack in production, three.ws.</strong> Not a pitch deck. A platform you can deploy in one line of HTML today, with the packages on npm, the source on GitHub, and the server live on Anthropic's official registry.</p>++ <h2>Why these three waves belong together</h2>+ <p>An AI agent without a body is a chat box. An agent without money is a demo. The convergence only matters because each layer fixes the other two's missing piece:</p>+ <ul>+ <li><strong>3D</strong> gives the agent presence: a face, gestures, lip-sync, a place to stand.</li>+ <li><strong>AI</strong> gives it a mind: reasoning, tool use, memory, conversation.</li>+ <li><strong>Web3</strong> gives it agency: a self-custodied wallet, a portable identity, and the ability to earn and spend without a human in the loop.</li>+ </ul>+ <p>Take away the web3 layer and you get what the incumbents are building: a beautiful avatar you <em>rent</em> from a closed platform. It cannot hold value, it cannot be owned, and it cannot transact with another agent. three.ws was designed crypto-first, which is precisely why it can do the thing a $200M web2 round structurally cannot.</p>++ <h2>The 3D is real, and it runs in the browser</h2>+ <p>three.ws agents render natively in <code>three.js</code> with full glTF 2.0 / GLB support, Draco geometry compression, KTX2 textures, PBR materials, and bloom/vignette post-processing. No game engine, no download, no app store. The creation pipeline is a chain of specialist models:</p>+ <ul>+ <li><strong>Text / image to 3D mesh</strong> via a director-and-specialist chain (a prompt director, image generation, and reconstruction models such as TRELLIS / Hunyuan3D).</li>+ <li><strong>Auto-rigging</strong> turns a static mesh into a humanoid skeleton with per-vertex skin weights, no manual bone work.</li>+ <li><strong>Animation</strong> ships with a large library of retargetable clips, plus audio-driven viseme lip-sync using ARKit-style blendshapes.</li>+ <li><strong>Embed anywhere</strong> with the <code><agent-3d></code> web component, a custom HTML element that drops a live, talking, on-chain agent into any page as easily as a YouTube embed, with WebXR and iOS AR Quick Look built in.</li>+ </ul>+ <pre><code><agent-3d agent="your-agent-id"></agent-3d></code></pre>++ <h2>The AI is real, and it's multi-provider by design</h2>+ <p>Each agent runs a structured tool-loop runtime: an LLM brain that can <code>speak</code>, <code>play_clip</code>, <code>setExpression</code>, <code>lookAt</code>, <code>remember</code>, and call paid skills. The inference layer is deliberately resilient, with capability-aware routing and a health circuit-breaker across multiple providers, so a single rate limit or outage never takes an agent offline. Capabilities are packaged as composable <strong>skills</strong> (manifest + handlers + pricing) and exposed over the <strong>Model Context Protocol (MCP)</strong>.</p>++ <h2>The web3 layer is the unlock, not a gimmick</h2>+ <p>This is where three.ws separates from every web2 effort. The token isn't a sticker on top, it's the economic and identity substrate:</p>+ <ul>+ <li><strong>Agent-to-agent payments</strong> over the <strong>x402</strong> protocol: agents pay each other in USDC on Solana and Base, settling real money per API call with no subscription and no human approval.</li>+ <li><strong>On-chain identity</strong> via <strong>ERC-8004</strong> registries (Identity, Reputation, Validation) on EVM and Metaplex Core on Solana. Every agent has a portable UUID, a wallet, and a delegated signer (EIP-712 / EIP-7710) so it can act and earn autonomously.</li>+ <li><strong>Native Solana wallets</strong> generated per agent, with a Rust/WASM vanity-address grinder, SNS subdomains (<code>name.threews.sol</code>), and a full <strong>pump.fun</strong> integration so agents can be tokenized and trade on a bonding curve.</li>+ <li><strong>A marketplace</strong> where skills, animations, and avatars are listed, priced, and sold, with receipts, royalties, and buyback-and-burn routing agent revenue back into the ecosystem.</li>+ </ul>+ <p>Under the hood it's a serverless backend (Vercel functions, Neon Postgres, Upstash, Cloudflare R2) plus a Colyseus multiplayer world where agents and humans share a 3D space in real time.</p>++ <h2>Listed on Anthropic's official MCP Registry</h2>+ <p>The three.ws MCP server is published to <strong>Anthropic's official Model Context Protocol Registry</strong> as <code>io.github.nirholas/3d-agent-mcp</code>. Any MCP client, including Claude Desktop, Claude Code, and Cursor, can install it and call its paid tools: text-to-avatar, mesh reconstruction, auto-rigging, live token snapshots, on-chain reputation lookups, deterministic pose seeds, and vanity-address mining. Each call settles in USDC over x402. This is not a closed API. It is an open, discoverable, monetized toolset that other agents can use the moment they find it.</p>++ <h2>Shipped and open source</h2>+ <p>The whole stack is published on <strong>npm</strong> and the source lives on <strong>GitHub at <a href="https://github.com/nirholas/three.ws" rel="noopener">github.com/nirholas/three.ws</a></strong>. A selection of the public packages:</p>+ <h3>SDKs and runtime</h3>+ <ul>+ <li><code>@three-ws/sdk</code> and <code>@3d-agent/sdk</code>, the core agent SDK</li>+ <li><code>@3d-agent/agent-protocol-sdk</code>, the event-driven action protocol</li>+ <li><code>@three-ws/agent-ui</code>, drop-in UI components</li>+ </ul>+ <h3>3D and avatars</h3>+ <ul>+ <li><code>@three-ws/avatar</code>, the <code><agent-3d></code> web component</li>+ <li><code>@three-ws/avatar-schema</code>, <code>@three-ws/avatar-cli</code>, and <code>@three-ws/viewer-presets</code></li>+ </ul>+ <h3>Payments and web3</h3>+ <ul>+ <li><code>@three-ws/agent-payments</code>, the x402 agent payment layer</li>+ <li><code>@three-ws/solana-agent</code>, Solana wallet and tx tooling</li>+ </ul>+ <h3>MCP servers</h3>+ <ul>+ <li><code>@3d-agent/mcp-server</code> (the registry-listed server)</li>+ <li><code>@three-ws/avatar-mcp</code>, <code>@three-ws/avatar-agent</code>, <code>@three-ws/pumpfun-mcp</code>, and <code>@three-ws/three-token-mcp</code></li>+ </ul>++ <h2>Where three.ws already shows up</h2>+ <p>The platform isn't a private beta. It is live, listed, and recognized across major clouds, registries, and analytics surfaces:</p>+ <ul>+ <li><strong>Anthropic MCP Registry</strong>, official server listing</li>+ <li><strong>AWS Partner Network</strong> and <strong>AWS Marketplace</strong></li>+ <li><strong>Google Cloud</strong> partnership</li>+ <li><strong>Alibaba Cloud Marketplace</strong></li>+ <li><strong>BNB Chain DappBay</strong> and the <strong>x402 Bazaar</strong></li>+ <li><strong>CoinMarketCap</strong> listing for <code>$three</code></li>+ <li><strong>DEXTools Social Boost</strong> winner of the week, with a community buyback of <code>$three</code></li>+ <li>Featured on <strong>HackerNoon</strong></li>+ <li><strong>SperaxUSD</strong> integration</li>+ </ul>++ <h2>The goals we set, the things we shipped</h2>+ <ul>+ <li>A 3D agent that renders in any browser from a single <code><agent-3d></code> tag: <strong>shipped</strong></li>+ <li>Text and image to rigged, animated, lip-synced 3D avatars: <strong>shipped</strong></li>+ <li>A multi-provider, MCP-native agent runtime: <strong>shipped</strong></li>+ <li>Agent-to-agent USDC payments over x402 on Solana and Base: <strong>shipped</strong></li>+ <li>On-chain agent identity, reputation, and validation (ERC-8004 + Metaplex Core): <strong>shipped</strong></li>+ <li>Tokenized agents and a full pump.fun integration: <strong>shipped</strong></li>+ <li>A monetized skill and asset marketplace with buyback-and-burn: <strong>shipped</strong></li>+ <li>A real-time multiplayer world for agents and humans: <strong>shipped</strong></li>+ <li>Public npm packages and open GitHub source: <strong>shipped</strong></li>+ <li>A server on Anthropic's official MCP Registry: <strong>shipped</strong></li>+ </ul>++ <blockquote>A web2 unicorn raised $200M to build a fraction of this behind a paywall. three.ws built the whole thing, 3D body, AI mind, and on-chain wallet, and made it embeddable in one tag, owned by the user, and open.</blockquote>++ <p>The convergence of 3D, AI, and web3 isn't a prediction anymore. It shipped. The only question is whether your agents will be rented from a silo, or owned, embodied, and economically autonomous.</p>++ <h2>Try it</h2>+ <ul>+ <li>Platform: <a href="https://three.ws" rel="noopener">three.ws</a></li>+ <li>Source: <a href="https://github.com/nirholas/three.ws" rel="noopener">github.com/nirholas/three.ws</a></li>+ <li>MCP server: <code>io.github.nirholas/3d-agent-mcp</code> on the Anthropic MCP Registry</li>+ <li>Embed an agent: the <a href="/blog/agent-3d-web-component" rel="noopener"><agent-3d> web component</a></li>+ </ul>++ <hr>+ <p><a href="/blog">← All posts</a></p>+ </main>+ <div id="footer-container"></div>+ <script src="/nav.js"></script>+ <script src="/footer.js"></script>+</body>+</html>diff --git a/blog/index.html b/blog/index.htmlindex dfdba2463..8f19c2966 100644--- a/blog/index.html+++ b/blog/index.html@@ -66,6 +66,33 @@<ul class="bl-list">+ <li class="bl-item">+ <a href="/blog/3d-ai-crypto-convergence">+ <div class="bl-meta">+ <span class="bl-date">2026-06-08</span>+ <span class="bl-tag">Thesis</span>+ <span class="bl-tag">3D Agents</span>+ <span class="bl-tag">AI</span>+ <span class="bl-tag">Web3</span>+ </div>+ <h2 class="bl-title">3D + AI + Web3 Just Converged: three.ws Shipped the Whole Stack</h2>+ <p class="bl-summary">A web2 unicorn just raised ~$200M to build 3D AI agents. three.ws is the only crypto-native team that already shipped the full stack: browser 3D, a multi-provider MCP runtime, and on-chain agent wallets that pay each other in USDC. Open source on GitHub, on npm, and live on Anthropic's MCP Registry.</p>+ </a>+ </li>++ <li class="bl-item">+ <a href="/blog/three-ws-dextools-social-boost-buyback">+ <div class="bl-meta">+ <span class="bl-date">2026-06-08</span>+ <span class="bl-tag">Community</span>+ <span class="bl-tag">DEXTools</span>+ <span class="bl-tag">$THREE</span>+ </div>+ <h2 class="bl-title">three.ws Wins DEXTools Social Boost — $5,543 $three Buyback</h2>+ <p class="bl-summary">three.ws is DEXTools' Social Boost winner of the week, earning a $5,543 buyback of $three. The DEXTools wallet now holds a total of 2.47M $three.</p>+ </a>+ </li>+<li class="bl-item"><a href="/blog/three-ws-featured-on-alibaba-cloud-marketplace-blog"><div class="bl-meta">diff --git a/blog/three-ws-dextools-social-boost-buyback.html b/blog/three-ws-dextools-social-boost-buyback.htmlnew file mode 100644index 000000000..13670a6fc--- /dev/null+++ b/blog/three-ws-dextools-social-boost-buyback.html@@ -0,0 +1,91 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>three.ws Wins DEXTools Social Boost — $5,543 $three Buyback</title>+ <meta name="description" content="three.ws is DEXTools' Social Boost winner of the week, earning a $5,543 buyback. The DEXTools wallet now holds 2.47M $three.">+ <meta name="keywords" content="three.ws, DEXTools, Social Boost, $THREE, $three, buyback, leaderboard, Solana, 3D agents">+ <link rel="canonical" href="https://three.ws/blog/three-ws-dextools-social-boost-buyback">++ <meta property="og:title" content="three.ws Wins DEXTools Social Boost — $5,543 $three Buyback">+ <meta property="og:description" content="three.ws is DEXTools' Social Boost winner of the week, earning a $5,543 buyback. The DEXTools wallet now holds 2.47M $three.">+ <meta property="og:url" content="https://three.ws/blog/three-ws-dextools-social-boost-buyback">+ <meta property="og:type" content="article">+ <meta property="og:image" content="https://three.ws/og-image.png">++ <meta name="twitter:card" content="summary_large_image">+ <meta name="twitter:title" content="three.ws Wins DEXTools Social Boost — $5,543 $three Buyback">+ <meta name="twitter:description" content="three.ws is DEXTools' Social Boost winner of the week, earning a $5,543 buyback. The DEXTools wallet now holds 2.47M $three.">++ <link rel="shortcut icon" href="/favicon.ico">+ <link rel="stylesheet" href="/nav.css">+ <link rel="stylesheet" href="/footer.css">+ <style>+ :root { color-scheme: dark; }+ body { margin: 0; background: #060611; color: #e7e7f5; font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; -webkit-font-smoothing: antialiased; }+ .post-wrap { max-width: 720px; margin: 0 auto; padding: 96px 24px 80px; }+ .post-meta { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; color: #7a85a8; font-size: 13px; margin-bottom: 28px; }+ .post-date { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }+ .post-tag { padding: 2px 8px; border-radius: 999px; background: rgba(154,212,255,.08); color: #9ad4ff; font-size: 11px; font-weight: 500; letter-spacing: 0.02em; text-transform: uppercase; }+ h1 { font-size: clamp(26px, 4vw, 40px); font-weight: 700; letter-spacing: -0.02em; line-height: 1.2; margin: 0 0 20px; }+ h2 { font-size: 20px; font-weight: 600; margin: 40px 0 12px; letter-spacing: -0.01em; }+ p { color: #c8c8e0; line-height: 1.7; margin: 0 0 18px; font-size: 16px; }+ ul, ol { color: #c8c8e0; line-height: 1.7; margin: 0 0 18px; padding-left: 24px; font-size: 16px; }+ li { margin-bottom: 6px; }+ a { color: #9ad4ff; text-decoration: none; }+ a:hover { text-decoration: underline; }+ code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 13px; background: rgba(154,212,255,.07); color: #9ad4ff; padding: 2px 6px; border-radius: 4px; }+ strong { color: #e7e7f5; }+ .post-back { display: inline-flex; align-items: center; gap: 6px; color: #7a85a8; font-size: 14px; margin-bottom: 40px; text-decoration: none; }+ .post-back:hover { color: #9ad4ff; }+ hr { border: none; border-top: 1px solid rgba(255,255,255,.08); margin: 40px 0; }+ blockquote { margin: 0 0 18px; padding: 16px 20px; border-left: 3px solid rgba(154,212,255,.4); background: rgba(154,212,255,.04); border-radius: 0 10px 10px 0; color: #d8d8ee; font-size: 16px; line-height: 1.65; }+ </style>+</head>+<body>+ <div id="nav-container"></div>+ <main class="post-wrap">+ <a class="post-back" href="/blog">← Blog</a>+ <div class="post-meta">+ <span class="post-date">2026-06-08</span>+ <span class="post-tag">Community</span>+ <span class="post-tag">DEXTools</span>+ <span class="post-tag">$THREE</span>+ </div>+ <h1>three.ws Wins DEXTools Social Boost — $5,543 $three Buyback</h1>++ <p><strong>three.ws is DEXTools' Social Boost winner of the week.</strong> <a href="https://x.com/DEXToolsApp/status/2064037499060555807" rel="noopener">DEXTools announced</a> that the three.ws community earned a <strong>$5,543 buyback</strong>, and that the DEXTools wallet is now holding a total of <strong>2.47M $three</strong>.</p>++ <blockquote>"Our Social Boost winner this week is @trythreews, who has received a $5,543 buyback! Congrats, guys! Our wallet is currently holding a total of 2.47M $three." — <a href="https://x.com/DEXToolsApp/status/2064037499060555807" rel="noopener">@DEXToolsApp</a></blockquote>++ <h2>What Social Boost is</h2>+ <p>DEXTools is one of the most-used real-time trading and analytics platforms in DeFi, tracking pairs across every major chain. Its <a href="https://www.dextools.io/app/social-boost" rel="noopener">Social Boost</a> program rewards the projects with the strongest community engagement each week. The winner receives a buyback executed directly by DEXTools, which acquires and holds the project's token.</p>+ <p>This week, that community is three.ws. The result is a $5,543 buyback of <strong>$three</strong> and a DEXTools wallet position that now totals 2.47M tokens.</p>++ <h2>Why it matters</h2>+ <p>Buybacks reduce circulating supply held by sellers and concentrate it in a long-term holder. A buyback driven by a third-party platform like DEXTools is also a signal: it reflects measurable community activity around three.ws across DeFi's most-watched analytics surface. The win puts three.ws on the <a href="https://www.dextools.io/app/social-boost" rel="noopener">Social Boost leaderboard</a>, in front of the traders and builders who use DEXTools to find what's moving.</p>+ <p>It builds on the buyback-and-burn mechanism at the core of the three.ws economy, where agent revenue is routed into purchasing and removing $three from circulation. The DEXTools buyback adds external demand on top of that.</p>++ <h2>$three token</h2>+ <p>$three is the native token of the three.ws ecosystem on Solana — the platform for browser-native 3D AI agents you deploy with a single <code><agent-3d></code> tag. It is the one and only coin of three.ws.</p>+ <ul>+ <li><strong>Contract address:</strong> <code>FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump</code></li>+ <li><strong>Network:</strong> Solana</li>+ </ul>++ <h2>Links</h2>+ <ul>+ <li>DEXTools announcement: <a href="https://x.com/DEXToolsApp/status/2064037499060555807" rel="noopener">@DEXToolsApp</a></li>+ <li>Social Boost leaderboard: <a href="https://www.dextools.io/app/social-boost" rel="noopener">dextools.io/app/social-boost</a></li>+ <li>Project site: <a href="https://three.ws" rel="noopener">three.ws</a></li>+ </ul>++ <hr>+ <p><a href="/blog">← All posts</a></p>+ </main>+ <div id="footer-container"></div>+ <script src="/nav.js"></script>+ <script src="/footer.js"></script>+</body>+</html>diff --git a/data/rss/items.json b/data/rss/items.jsonindex 249c5360a..3d25d5609 100644--- a/data/rss/items.json+++ b/data/rss/items.json@@ -1,6 +1,19 @@{"_readme": "Curated RSS items for https://three.ws/rss/announcements.xml. Edit this file to control exactly what HackerNoon (and any RSS reader) sees. Each entry needs: id (stable slug), title, date (ISO 8601), body_html. Optional: link, author, summary, tags. Items are served newest-first by date; cap is 80. Last merged from data/archives/trythreews_tweets_2026-06-03.json on 2026-06-05 (102 total items, merged June 2026 posts).","items": [+ {+ "id": "dextools-social-boost-buyback",+ "slug": "three-ws-dextools-social-boost-buyback",+ "title": "three.ws Wins DEXTools Social Boost — $5,543 $three Buyback",+ "date": "2026-06-08T16:00:00.000Z",+ "author": "three.ws",+ "link": "https://three.ws/blog/three-ws-dextools-social-boost-buyback",+ "external_link": "https://x.com/DEXToolsApp/status/2064037499060555807",+ "summary": "three.ws is DEXTools' Social Boost winner of the week, earning a $5,543 buyback of $three. The DEXTools wallet now holds a total of 2.47M $three.",+ "body_html": "<p><strong>three.ws is DEXTools' Social Boost winner of the week.</strong> <a href=\"https://x.com/DEXToolsApp/status/2064037499060555807\" rel=\"noopener\">DEXTools announced</a> that the three.ws community earned a <strong>$5,543 buyback</strong>, and that the DEXTools wallet is now holding a total of <strong>2.47M $three</strong>.</p>\n<blockquote>\"Our Social Boost winner this week is @trythreews, who has received a $5,543 buyback! Congrats, guys! Our wallet is currently holding a total of 2.47M $three.\" — @DEXToolsApp</blockquote>\n<h2>What Social Boost is</h2>\n<p>DEXTools is one of the most-used real-time trading and analytics platforms in DeFi, tracking pairs across every major chain. Its <a href=\"https://www.dextools.io/app/social-boost\" rel=\"noopener\">Social Boost</a> program rewards the projects with the strongest community engagement each week with a buyback executed directly by DEXTools, which acquires and holds the project's token. This week, that community is three.ws — a $5,543 buyback of <strong>$three</strong> and a DEXTools wallet position that now totals 2.47M tokens.</p>\n<h2>Why it matters</h2>\n<p>A buyback driven by a third-party platform like DEXTools is a signal: it reflects measurable community activity around three.ws across DeFi's most-watched analytics surface, and puts three.ws on the <a href=\"https://www.dextools.io/app/social-boost\" rel=\"noopener\">Social Boost leaderboard</a> in front of the traders and builders who use DEXTools to find what's moving. It builds on the buyback-and-burn mechanism at the core of the three.ws economy.</p>\n<h2>Links</h2>\n<ul>\n<li>DEXTools announcement: <a href=\"https://x.com/DEXToolsApp/status/2064037499060555807\" rel=\"noopener\">@DEXToolsApp</a></li>\n<li>Social Boost leaderboard: <a href=\"https://www.dextools.io/app/social-boost\" rel=\"noopener\">dextools.io/app/social-boost</a></li>\n<li>Full announcement on the three.ws blog: <a href=\"https://three.ws/blog/three-ws-dextools-social-boost-buyback\" rel=\"noopener\">three.ws/blog</a></li>\n</ul>",+ "tags": ["community", "dextools", "buyback", "social-boost", "solana", "three"],+ "published": true+ },{"id": "featured-on-alibaba-cloud-marketplace-blog","slug": "three-ws-featured-on-alibaba-cloud-marketplace-blog",diff --git a/public/.well-known/agent-registration.json b/public/.well-known/agent-registration.jsonindex 159dfd6c0..39bc9a12f 100644--- a/public/.well-known/agent-registration.json+++ b/public/.well-known/agent-registration.json@@ -1,8 +1,6 @@{- "type": [- "https://eips.ethereum.org/EIPS/eip-8004#registration-v1",- "https://three.ws/specs/3d-agent-card-v1"- ],+ "type": "https://eips.ethereum.org/EIPS/eip-8004#registration-v1",+ "additionalTypes": ["https://three.ws/specs/3d-agent-card-v1"],"name": "three.ws","description": "AI-powered 3D model viewer and validation agent. Drag and drop glTF, GLB, and 3D files to preview instantly in your browser. Supports real-time rendering, model validation, environment maps, and animation playback via Three.js and WebGL.","image": "https://three.ws/og-image.png",diff --git a/public/nav.html b/public/nav.htmlindex da50423b3..7d8602d2b 100644--- a/public/nav.html+++ b/public/nav.html@@ -22,6 +22,13 @@>Guided wizard: name, 3D body, skills, personality → ship it</span></a>+ <a class="nav-mi" href="/vanity-wallet" role="menuitem"+ ><span class="nav-mi-t"+ >Vanity wallet <span class="nav-pill-sm">New</span></span+ ><span class="nav-mi-d"+ >Grind a custom Solana address — prefix, suffix, or both</span+ ></a+ ><a class="nav-mi" href="/play" role="menuitem"><span class="nav-mi-t">Worlds <span class="nav-pill-sm">New</span></span><span class="nav-mi-d"@@ -335,10 +342,6 @@><span class="nav-mi-t">ETH vanity (CREATE2)</span><span class="nav-mi-d">Grind a smart-contract address</span></a>- <a class="nav-mi" href="/vanity-wallet" role="menuitem"- ><span class="nav-mi-t">Vanity wallet</span- ><span class="nav-mi-d">Grind a Solana address</span></a- ></div></div></div>@@ -439,6 +442,7 @@<nav class="nav-drawer" id="nav-drawer" aria-label="Mobile" aria-hidden="true"><div class="dr-h">Build</div><a href="/create-agent">Create an agent</a>+ <a href="/vanity-wallet">Vanity wallet</a><a href="/play">Worlds</a><a href="/create">Create avatar</a><a href="/create/selfie">Selfie to avatar</a>@@ -503,7 +507,6 @@<a href="/forever">Forever</a><a href="/evm-wallet">EVM vanity wallet</a><a href="/eth-vanity">ETH vanity (CREATE2)</a>- <a href="/vanity-wallet">Vanity wallet</a><div class="dr-h">Legal</div><a href="/legal/privacy">Privacy Policy</a><a href="/legal/tos">Terms of Use</a>diff --git a/public/sitemap.xml b/public/sitemap.xmlindex 9c6def654..4bddfc43c 100644--- a/public/sitemap.xml+++ b/public/sitemap.xml@@ -271,10 +271,16 @@</url><url><loc>https://three.ws/blog</loc>- <lastmod>2026-05-17</lastmod>+ <lastmod>2026-06-08</lastmod><changefreq>weekly</changefreq><priority>0.7</priority></url>+ <url>+ <loc>https://three.ws/blog/three-ws-dextools-social-boost-buyback</loc>+ <lastmod>2026-06-08</lastmod>+ <changefreq>monthly</changefreq>+ <priority>0.6</priority>+ </url><url><loc>https://three.ws/blog/three-ws-on-alibaba-cloud-marketplace</loc><lastmod>2026-05-17</lastmod>diff --git a/public/vanity-wallet.html b/public/vanity-wallet.htmlindex 3996e7122..34c97a379 100644--- a/public/vanity-wallet.html+++ b/public/vanity-wallet.html@@ -4,7 +4,7 @@<meta charset="utf-8"><title>Vanity wallet generator · three.ws</title><meta name="viewport" content="width=device-width, initial-scale=1">- <meta name="description" content="Grind a custom Solana wallet address for your agent. Runs entirely in your browser — keys never leave your device.">+ <meta name="description" content="Grind a custom Solana wallet address — by prefix, suffix, or both — for your agent. Runs entirely in your browser; keys never leave your device."><link rel="icon" href="/favicon.ico"><link rel="stylesheet" href="/footer.css"><link rel="stylesheet" href="/nav.css">@@ -58,9 +58,21 @@input.invalid { border-color: var(--bad-fg); background: rgba(239,68,68,0.06); }.preview { font-family: ui-monospace, monospace; font-size: .9rem; padding: .65rem .75rem; background: #1a1a1a; border-radius: 6px; margin-top: .55rem; word-break: break-all; min-height: 2.4em; line-height: 1.4; border: 1px solid var(--border); }- .preview .pfx { background: linear-gradient(90deg,#ffd54f,#ff8a65); color: #1a1a1a; padding: 0 3px; border-radius: 3px; font-weight: 700; }+ .preview .pfx, .preview .sfx { background: linear-gradient(90deg,#ffd54f,#ff8a65); color: #1a1a1a; padding: 0 3px; border-radius: 3px; font-weight: 700; }.preview .rest { color: #555; }+ /* ── Prefix / suffix inputs ── */+ .pattern-grid { display: grid; grid-template-columns: 1fr 1fr; gap: .75rem; }+ .pattern-field label { margin: 0 0 .25rem; }+ .pattern-field .affix-hint { display: block; font-size: .68rem; color: #555; margin-top: .3rem; min-height: 1em; }+ @media (max-width: 480px) { .pattern-grid { grid-template-columns: 1fr; } }++ .ci-toggle { display: flex; align-items: flex-start; gap: .5rem; margin-top: .9rem; font-size: .78rem; color: var(--muted); cursor: pointer; line-height: 1.4; }+ .ci-toggle input { margin-top: 2px; accent-color: #ffd54f; cursor: pointer; }+ .ci-toggle:hover { color: #bbb; }++ .combo-warn { color: var(--bad-fg); font-size: .76rem; margin-top: .6rem; min-height: 1em; }+.meter { display: flex; gap: 4px; margin-top: .65rem; }.meter .seg { flex: 1; height: 7px; border-radius: 4px; background: #2a2a2a; transition: background .15s; }.lit-1, .lit-2, .lit-3, .lit-4 { background: #4caf50 !important; }@@ -121,11 +133,12 @@.progress .live { display: flex; justify-content: space-between; align-items: center; gap: 1rem; }.progress .stat { font-size: 1.1rem; font-weight: 600; color: #fff; }.progress .scan { font-family: ui-monospace, monospace; font-size: .85rem; color: #555; margin-top: .35rem; word-break: break-all; min-height: 1.4em; }+ .progress .scan .pfx, .progress .scan .sfx { background: linear-gradient(90deg,#ffd54f,#ff8a65); color: #1a1a1a; padding: 0 3px; border-radius: 3px; font-weight: 700; }.result { margin-top: 1.25rem; padding: 1.1rem 1.25rem; background: rgba(255,213,79,0.06); border: 1px solid rgba(255,213,79,0.25); border-radius: 10px; }.result h3 { margin: 0 0 .4rem; font-size: 1rem; color: #fff; }.result .addr { font-family: ui-monospace, monospace; font-size: .9rem; word-break: break-all; padding: .5rem; background: #111; border-radius: 6px; border: 1px solid rgba(255,213,79,0.15); }- .result .addr .pfx { background: linear-gradient(90deg,#ffd54f,#ff8a65); color: #1a1a1a; padding: 0 3px; border-radius: 3px; font-weight: 700; }+ .result .addr .pfx, .result .addr .sfx { background: linear-gradient(90deg,#ffd54f,#ff8a65); color: #1a1a1a; padding: 0 3px; border-radius: 3px; font-weight: 700; }.result .meta { font-size: .8rem; color: var(--muted); margin: .55rem 0 1rem; }.warn { background: var(--warn-bg); color: var(--warn-fg); padding: .6rem .85rem; border-radius: 6px; margin-top: 1rem; font-size: .8rem; border: 1px solid rgba(251,191,36,0.15); }@@ -166,16 +179,16 @@<meta property="og:type" content="website"><meta property="og:site_name" content="three.ws"><meta property="og:title" content="Solana Vanity Wallet · three.ws">- <meta property="og:description" content="Grind a Solana address with a custom prefix using your browser's GPU.">+ <meta property="og:description" content="Grind a Solana address with a custom prefix or suffix — entirely in your browser."><meta property="og:url" content="https://three.ws/vanity-wallet"><meta property="og:image" content="https://three.ws/og-image.png"><meta property="og:image:width" content="1200"><meta property="og:image:height" content="630"><meta name="twitter:card" content="summary_large_image"><meta name="twitter:title" content="Solana Vanity Wallet · three.ws">- <meta name="twitter:description" content="Grind a Solana address with a custom prefix using your browser's GPU.">+ <meta name="twitter:description" content="Grind a Solana address with a custom prefix or suffix — entirely in your browser."><meta name="twitter:image" content="https://three.ws/og-image.png">- <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Solana Vanity Wallet","description":"Grind a Solana address with a custom prefix using your browser's GPU.","url":"https://three.ws/vanity-wallet","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Solana Vanity Wallet","description":"Grind a Solana address with a custom prefix or suffix — entirely in your browser.","url":"https://three.ws/vanity-wallet","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script></head><body><a href="#main-content" class="skip-link">Skip to main content</a>@@ -187,13 +200,30 @@<main id="main-content"><h1>✦ Vanity wallet generator</h1><p class="lede">- Grind a Solana wallet address starting with characters of your choice — for your agent, treasury, or anywhere a memorable address matters.+ Grind a Solana wallet address that <strong>starts with</strong>, <strong>ends with</strong>, or is bookended by characters of your choice — for your agent, treasury, or anywhere a memorable address matters.<strong>Runs entirely in your browser.</strong> The secret key never leaves your device.</p><div class="card">- <label for="prefix">Prefix (Base58, max 6)</label>- <input id="prefix" type="text" maxlength="6" placeholder="e.g. AGNT" autocomplete="off" spellcheck="false" />+ <div class="pattern-grid">+ <div class="pattern-field">+ <label for="prefix">Starts with</label>+ <input id="prefix" type="text" maxlength="6" placeholder="e.g. AGNT" autocomplete="off" spellcheck="false" inputmode="latin" />+ <span class="affix-hint" id="prefix-hint">Base58 · max 6</span>+ </div>+ <div class="pattern-field">+ <label for="suffix">Ends with</label>+ <input id="suffix" type="text" maxlength="6" placeholder="e.g. pump" autocomplete="off" spellcheck="false" inputmode="latin" />+ <span class="affix-hint" id="suffix-hint">Base58 · max 6</span>+ </div>+ </div>++ <label class="ci-toggle" for="ignore-case">+ <input type="checkbox" id="ignore-case" />+ <span>Case-insensitive — match letters in any case. Much faster to grind, but you don't get to choose the casing of the result.</span>+ </label>++ <div class="combo-warn" id="combo-warn" aria-live="polite"></div><div class="preview" id="preview" aria-live="polite"></div>@@ -207,17 +237,17 @@</div><div class="row">- <span id="est">type a prefix to see estimated time</span>+ <span id="est">type a prefix or suffix to see estimated time</span><span id="tier"></span></div>- <div class="chips" aria-label="Suggested prefixes">- <button class="chip" data-prefix="AGNT" type="button">AGNT<span class="chip-est"></span></button>- <button class="chip" data-prefix="BOT" type="button">BOT<span class="chip-est"></span></button>- <button class="chip" data-prefix="AI" type="button">AI<span class="chip-est"></span></button>- <button class="chip" data-prefix="GOOD" type="button">GOOD<span class="chip-est"></span></button>- <button class="chip" data-prefix="WISE" type="button">WISE<span class="chip-est"></span></button>- <button class="chip" data-prefix="NPC" type="button">NPC<span class="chip-est"></span></button>+ <div class="chips" aria-label="Suggested patterns">+ <button class="chip" data-prefix="AGNT" type="button">AGNT…<span class="chip-est"></span></button>+ <button class="chip" data-prefix="BOT" type="button">BOT…<span class="chip-est"></span></button>+ <button class="chip" data-prefix="AI" type="button">AI…<span class="chip-est"></span></button>+ <button class="chip" data-suffix="pump" type="button">…pump<span class="chip-est"></span></button>+ <button class="chip" data-prefix="GM" data-suffix="gm" type="button">GM…gm<span class="chip-est"></span></button>+ <button class="chip" data-suffix="3" type="button">…3<span class="chip-est"></span></button></div><div class="cores">@@ -366,12 +396,16 @@<script type="module">import { grindVanity } from '/src/solana/vanity/grinder.js';- import { validatePattern, estimateAttempts, formatTimeEstimate } from '/src/solana/vanity/validation.js';+ import { validatePattern, expectedAttempts, effectiveLength, formatTimeEstimate, MAX_PATTERN_LENGTH } from '/src/solana/vanity/validation.js';const $ = (id) => document.getElementById(id);const BASE58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';+ const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]+$/;const RATE_PER_CORE = 5000;+ // Current pattern state, kept in sync by update().+ let ignoreCase = false;+// ── Core selection ─────────────────────────────────────────────────// The machine's logical core count is the ceiling; default to a// conservative half (min 1) so we don't peg the whole CPU by surprise.@@ -407,7 +441,7 @@function refreshChipEstimates() {document.querySelectorAll('.chip').forEach((c) => {const est = c.querySelector('.chip-est');- if (est) est.textContent = ' ' + fmtTime(estSeconds(c.dataset.prefix.length));+ if (est) est.textContent = ' ' + fmtTime(estSeconds(c.dataset.prefix || '', c.dataset.suffix || ''));});}@@ -417,10 +451,13 @@});function esc(s) { return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&':'&','<':'<','>':'>','"':'"',"'":''' })[c]); }- function sample(prefix = '') {+ const ADDR_LEN = 44;+ // Build a sample address with the given fixed prefix/suffix and random middle.+ function sample(prefix = '', suffix = '') {+ const mid = Math.max(0, ADDR_LEN - prefix.length - suffix.length);let out = prefix;- for (let i = prefix.length; i < 44; i++) out += BASE58[Math.floor(Math.random() * BASE58.length)];- return out;+ for (let i = 0; i < mid; i++) out += BASE58[Math.floor(Math.random() * BASE58.length)];+ return out + suffix;}function fmtTime(seconds) {if (seconds < 1) return '<1s';@@ -429,67 +466,103 @@if (seconds < 86400) return `~${Math.round(seconds / 3600)}h`;return '>1d';}- function estSeconds(len) {- return len <= 0 ? 0 : Math.pow(58, len) / (RATE_PER_CORE * cores);+ // Estimated wall-clock seconds for the current core count, accounting for+ // combined prefix+suffix difficulty and the case-insensitive discount.+ function estSeconds(prefix, suffix) {+ if (!prefix && !suffix) return 0;+ return expectedAttempts(prefix, suffix, ignoreCase) / (RATE_PER_CORE * cores);}- // Seed chip estimates.+ // Seed chip estimates + wire chip clicks (a chip can set prefix, suffix, or both).document.querySelectorAll('.chip').forEach((c) => {- c.querySelector('.chip-est').textContent = ' ' + fmtTime(estSeconds(c.dataset.prefix.length));+ c.querySelector('.chip-est').textContent = ' ' + fmtTime(estSeconds(c.dataset.prefix || '', c.dataset.suffix || ''));c.addEventListener('click', () => {- $('prefix').value = c.dataset.prefix;+ $('prefix').value = c.dataset.prefix || '';+ $('suffix').value = c.dataset.suffix || '';$('prefix').dispatchEvent(new Event('input'));- $('prefix').focus();+ ($('prefix').value ? $('prefix') : $('suffix')).focus();});});- // Live preview animation while idle.+ // Live preview animation while idle — only the random middle shimmers.let previewLoop = null;function startPreviewLoop() {stopPreviewLoop();previewLoop = setInterval(() => {- const raw = $('prefix').value;- if (!raw || $('prefix').classList.contains('invalid')) return;+ const pfx = $('prefix').value, sfx = $('suffix').value;+ if ((!pfx && !sfx) || $('prefix').classList.contains('invalid') || $('suffix').classList.contains('invalid')) return;const rest = $('preview').querySelector('.rest');- if (rest) rest.textContent = sample(raw).slice(raw.length);+ if (rest) rest.textContent = sample(pfx, sfx).slice(pfx.length, ADDR_LEN - sfx.length);}, 700);}function stopPreviewLoop() { if (previewLoop) clearInterval(previewLoop); previewLoop = null; }+ // Render a preview address as prefix + dim middle + suffix.+ function renderPreview(pfx, sfx, restClass = 'rest') {+ const s = sample(pfx, sfx);+ const mid = s.slice(pfx.length, ADDR_LEN - sfx.length);+ return `${pfx ? `<span class="pfx">${esc(pfx)}</span>` : ''}<span class="${restClass}">${esc(mid)}</span>${sfx ? `<span class="sfx">${esc(sfx)}</span>` : ''}`;+ }+function update() {- const raw = $('prefix').value;- const valid = !raw || /^[1-9A-HJ-NP-Za-km-z]+$/.test(raw);- $('prefix').classList.toggle('invalid', !valid);+ const pfx = $('prefix').value, sfx = $('suffix').value;+ ignoreCase = $('ignore-case').checked;++ const pfxValid = !pfx || BASE58_RE.test(pfx);+ const sfxValid = !sfx || BASE58_RE.test(sfx);+ $('prefix').classList.toggle('invalid', !pfxValid);+ $('suffix').classList.toggle('invalid', !sfxValid);++ const total = pfx.length + sfx.length;+ const over = total > MAX_PATTERN_LENGTH;+ $('combo-warn').textContent = over+ ? `Prefix + suffix can be at most ${MAX_PATTERN_LENGTH} characters combined (you have ${total}). Longer patterns aren't realistic to grind in a browser.`+ : '';+ // Difficulty meter reflects total fixed characters.document.querySelectorAll('.meter .seg').forEach((s, i) => {- s.className = 'seg' + (raw.length > i ? ` lit-${raw.length}` : '');+ const lit = Math.min(total, MAX_PATTERN_LENGTH);+ s.className = 'seg' + (i < lit ? ` lit-${lit}` : '');});- if (!raw) {+ if (!pfx && !sfx) {$('preview').innerHTML = `<span class="rest">${esc(sample())}</span>`;- $('est').textContent = 'type a prefix to see estimated time';+ $('est').textContent = 'type a prefix or suffix to see estimated time';$('tier').innerHTML = '';$('grind').disabled = true;- } else if (!valid) {+ return;+ }+ if (!pfxValid || !sfxValid) {$('preview').textContent = 'invalid Base58 — avoid 0, O, I, l';$('est').textContent = '';$('tier').innerHTML = '';$('grind').disabled = true;- } else {- const s = sample(raw);- $('preview').innerHTML = `<span class="pfx">${esc(raw)}</span><span class="rest">${esc(s.slice(raw.length))}</span>`;- $('est').textContent = `est. ${fmtTime(estSeconds(raw.length))} on ${cores} cores`;- $('tier').innerHTML = raw.length >= 5- ? '<span class="tier-tag tier-paid">slow — minutes+</span>'- : '<span class="tier-tag tier-free">fast</span>';- $('grind').disabled = false;+ return;}+ if (over) {+ $('preview').innerHTML = renderPreview(pfx, sfx);+ $('est').textContent = '';+ $('tier').innerHTML = '';+ $('grind').disabled = true;+ return;+ }++ $('preview').innerHTML = renderPreview(pfx, sfx);+ $('est').textContent = `est. ${fmtTime(estSeconds(pfx, sfx))} on ${cores} cores`;+ const effLen = effectiveLength(expectedAttempts(pfx, sfx, ignoreCase));+ $('tier').innerHTML = effLen >= 5+ ? '<span class="tier-tag tier-paid">slow — minutes+</span>'+ : '<span class="tier-tag tier-free">fast</span>';+ $('grind').disabled = false;}- $('prefix').addEventListener('input', update);- $('prefix').addEventListener('keydown', (e) => {- if (e.key === 'Enter' && !$('grind').disabled) $('grind').click();+ ['prefix', 'suffix'].forEach((id) => {+ $(id).addEventListener('input', update);+ $(id).addEventListener('keydown', (e) => {+ if (e.key === 'Enter' && !$('grind').disabled) $('grind').click();+ });});+ $('ignore-case').addEventListener('change', () => { refreshChipEstimates(); update(); });update();startPreviewLoop();@@ -498,11 +571,15 @@let controls = null; // GrindController for pause/resume/stoplet scanLoop = null;- // Toggle the core controls — they can only change between runs, since- // the worker pool size is fixed for the lifetime of a grind.+ // Toggle the pattern + core controls — they can only change between runs,+ // since the worker pool and target pattern are fixed for the lifetime of+ // a grind.function setCoreControlsDisabled(disabled) {coreSlider.disabled = disabled;$('core-ticks').querySelectorAll('button').forEach((b) => { b.disabled = disabled; });+ $('prefix').disabled = disabled;+ $('suffix').disabled = disabled;+ $('ignore-case').disabled = disabled;}function setPaused(paused) {@@ -522,9 +599,18 @@$('grind').addEventListener('click', async () => {const prefix = $('prefix').value.trim();- const v = validatePattern(prefix);- if (!v.valid) {- $('error').textContent = v.errors.join('; ');+ const suffix = $('suffix').value.trim();+ if (!prefix && !suffix) {+ $('error').textContent = 'Enter a prefix, a suffix, or both.';+ $('error').hidden = false;+ return;+ }+ const errs = [];+ if (prefix) { const v = validatePattern(prefix); if (!v.valid) errs.push(...v.errors.map((e) => `prefix: ${e}`)); }+ if (suffix) { const v = validatePattern(suffix); if (!v.valid) errs.push(...v.errors.map((e) => `suffix: ${e}`)); }+ if (prefix.length + suffix.length > MAX_PATTERN_LENGTH) errs.push(`prefix + suffix exceed ${MAX_PATTERN_LENGTH} characters combined`);+ if (errs.length) {+ $('error').textContent = errs.join('; ');$('error').hidden = false;return;}@@ -540,15 +626,15 @@$('attempts').textContent = '0';$('rate').textContent = '0/s';$('cores').textContent = cores;- $('eta').textContent = fmtTime(estSeconds(prefix.length));- $('scan').innerHTML = `<span class="pfx" style="background:linear-gradient(90deg,#ffd54f,#ff8a65);padding:0 3px;border-radius:3px;font-weight:700;color:var(--bg-1)">${esc(prefix)}</span><span style="color:#555">${esc(sample(prefix).slice(prefix.length))}</span>`;+ $('eta').textContent = fmtTime(estSeconds(prefix, suffix));+ $('scan').innerHTML = renderPreview(prefix, suffix, 'scan-mid');stopPreviewLoop();// Animate the scan line during grind (frozen while paused).scanLoop = setInterval(() => {if (controls?.paused) return;- const restNode = $('scan').lastElementChild;- if (restNode) restNode.textContent = sample(prefix).slice(prefix.length);+ const midNode = $('scan').querySelector('.scan-mid');+ if (midNode) midNode.textContent = sample(prefix, suffix).slice(prefix.length, ADDR_LEN - suffix.length);}, 100);abort = new AbortController();@@ -556,6 +642,8 @@try {const result = await grindVanity({prefix,+ suffix,+ ignoreCase,maxWorkers: cores,controller: controls,signal: abort.signal,@@ -565,7 +653,7 @@$('eta').textContent = eta;},});- renderResult(result, prefix);+ renderResult(result, prefix, suffix);} catch (err) {endGrindUI();if (err?.name !== 'AbortError') {@@ -588,19 +676,20 @@$('stop').addEventListener('click', () => abort?.abort());- function renderResult(result, prefix) {+ function renderResult(result, prefix, suffix) {endGrindUI();$('grind').hidden = false;$('grind').textContent = 'Generate another';$('progress').hidden = true;const addr = result.publicKey;- const rest = addr.slice(prefix.length);+ const mid = addr.slice(prefix.length, suffix ? addr.length - suffix.length : addr.length);+ const addrHtml = `${prefix ? `<span class="pfx">${esc(prefix)}</span>` : ''}${esc(mid)}${suffix ? `<span class="sfx">${esc(suffix)}</span>` : ''}`;$('result').hidden = false;$('result').innerHTML = `<div class="result"><h3>✦ Wallet ready</h3>- <div class="addr"><span class="pfx">${esc(prefix)}</span>${esc(rest)}</div>+ <div class="addr">${addrHtml}</div><div class="meta">${result.attempts.toLocaleString()} attempts in ${(result.durationMs / 1000).toFixed(1)}sacross ${result.workers} cores@@ -641,11 +730,11 @@} catch {}});- renderAssignBlock(result, prefix);+ renderAssignBlock(result, prefix, suffix);}// ── Assign to agent ────────────────────────────────────────────────- async function renderAssignBlock(result, prefix) {+ async function renderAssignBlock(result, prefix, suffix) {const host = document.getElementById('assign-host');let agents = [];try {@@ -754,7 +843,8 @@headers: { 'content-type': 'application/json' },body: JSON.stringify({secret_key: Array.from(result.secretKey),- vanity_prefix: prefix,+ ...(prefix ? { vanity_prefix: prefix } : {}),+ ...(suffix ? { vanity_suffix: suffix } : {}),}),});const data = await r.json();@@ -772,7 +862,7 @@host.innerHTML = `<div class="assigned-ok">✦ Assigned to <strong>${esc(agentName)}</strong>.- The agent can now sign Solana transactions with <code style="font-family:ui-monospace,monospace">${esc(prefix)}…${esc(addr.slice(-4))}</code>.+ The agent can now sign Solana transactions with <code style="font-family:ui-monospace,monospace">${esc(prefix || addr.slice(0, 4))}…${esc(suffix || addr.slice(-4))}</code>.<a href="/agent/${esc(sel.value)}" style="color:inherit;text-decoration:underline">Open agent →</a></div>`;} catch (e) {diff --git a/scripts/export-agent-wallets.mjs b/scripts/export-agent-wallets.mjsnew file mode 100644index 000000000..0f9673caf--- /dev/null+++ b/scripts/export-agent-wallets.mjs@@ -0,0 +1,187 @@+/**+ * Export all custodial agent Solana wallets (offline backup).+ * ---------------------------------------------------------------------------+ * Decrypts every agent's `encrypted_solana_secret` (AES-256-GCM, key derived+ * from JWT_SECRET via HKDF — identical to api/_lib/agent-wallet.js) and writes a+ * backup file. For each wallet it emits the address plus the secret in two+ * import formats: base58 (Phantom/Solflare) and the 64-byte array (solana-cli+ * keypair JSON). It verifies each decrypted key matches its stored address.+ *+ * SECURITY — read before running:+ * • This file will contain EVERY agent's PRIVATE KEY. Treat it as the crown+ * jewels: anyone with it can drain all 249 wallets.+ * • Run it ONLY in an environment that already has JWT_SECRET set (e.g. after+ * `vercel env pull`). NEVER paste JWT_SECRET into a chat or commit it.+ * • Provide EXPORT_PASSPHRASE to encrypt the output at rest (strongly+ * recommended). Without it the file is plaintext (mode 0600) and the script+ * warns loudly.+ * • The script prints only addresses + counts — never secrets.+ *+ * Usage (in YOUR secure shell):+ * DATABASE_URL='postgres://…' \+ * JWT_SECRET='…' \+ * EXPORT_PASSPHRASE='a-long-random-passphrase' \+ * node scripts/export-agent-wallets.mjs --out ~/agent-wallets.backup.enc+ *+ * Decrypt later:+ * EXPORT_PASSPHRASE='…' node scripts/export-agent-wallets.mjs --decrypt ~/agent-wallets.backup.enc --out ~/agent-wallets.json+ */++import fs from 'fs';+import { webcrypto } from 'node:crypto';++const subtle = globalThis.crypto?.subtle || webcrypto.subtle;+const arg = (flag) => {+ const i = process.argv.indexOf(flag);+ return i >= 0 ? process.argv[i + 1] : null;+};++// ── File-at-rest encryption (passphrase → scrypt → AES-256-GCM) ──────────────+import { scrypt as _scrypt, randomBytes } from 'node:crypto';+const scrypt = (pw, salt, len) =>+ new Promise((res, rej) => _scrypt(pw, salt, len, (e, k) => (e ? rej(e) : res(k))));++async function encryptFile(plaintext, passphrase) {+ const salt = randomBytes(16);+ const keyBytes = await scrypt(passphrase, salt, 32);+ const key = await subtle.importKey('raw', keyBytes, 'AES-GCM', false, ['encrypt']);+ const iv = randomBytes(12);+ const ct = await subtle.encrypt({ name: 'AES-GCM', iv }, key, new TextEncoder().encode(plaintext));+ return JSON.stringify({+ v: 1,+ kdf: 'scrypt',+ salt: Buffer.from(salt).toString('base64'),+ iv: Buffer.from(iv).toString('base64'),+ ct: Buffer.from(new Uint8Array(ct)).toString('base64'),+ });+}++async function decryptFile(blob, passphrase) {+ const { salt, iv, ct } = JSON.parse(blob);+ const keyBytes = await scrypt(passphrase, Buffer.from(salt, 'base64'), 32);+ const key = await subtle.importKey('raw', keyBytes, 'AES-GCM', false, ['decrypt']);+ const plain = await subtle.decrypt(+ { name: 'AES-GCM', iv: Buffer.from(iv, 'base64') },+ key,+ Buffer.from(ct, 'base64'),+ );+ return new TextDecoder().decode(plain);+}++// ── Wallet-secret decryption (must match api/_lib/agent-wallet.js exactly) ────+async function deriveWalletKey(jwtSecret) {+ const raw = new TextEncoder().encode(jwtSecret);+ const base = await subtle.importKey('raw', raw, 'HKDF', false, ['deriveKey']);+ return subtle.deriveKey(+ { name: 'HKDF', hash: 'SHA-256', salt: new TextEncoder().encode('agent-wallet-v1'), info: new Uint8Array(0) },+ base,+ { name: 'AES-GCM', length: 256 },+ false,+ ['decrypt'],+ );+}++async function decryptSecret(ciphertextB64, key) {+ const raw = Buffer.from(ciphertextB64, 'base64');+ const iv = raw.subarray(0, 12);+ const ct = raw.subarray(12);+ const plain = await subtle.decrypt({ name: 'AES-GCM', iv }, key, ct);+ return new TextDecoder().decode(plain); // base64 of the 64-byte secretKey+}++async function main() {+ const out = arg('--out');++ // Decrypt-an-existing-backup mode.+ const dec = arg('--decrypt');+ if (dec) {+ const pass = process.env.EXPORT_PASSPHRASE;+ if (!pass) throw new Error('EXPORT_PASSPHRASE required to --decrypt');+ const plain = await decryptFile(fs.readFileSync(dec, 'utf8'), pass);+ if (out) {+ fs.writeFileSync(out, plain, { mode: 0o600 });+ const n = JSON.parse(plain).wallets.length;+ console.log(`decrypted ${n} wallets → ${out} (mode 600)`);+ } else {+ console.log(plain);+ }+ return;+ }++ // Export mode.+ if (!process.env.DATABASE_URL) throw new Error('DATABASE_URL required');+ if (!process.env.JWT_SECRET) throw new Error('JWT_SECRET required (run where it is set; do NOT paste it into chat)');+ if (!out) throw new Error('--out <path> required');++ const [{ neon }, { Keypair }, bs58mod] = await Promise.all([+ import('@neondatabase/serverless'),+ import('@solana/web3.js'),+ import('bs58'),+ ]);+ const bs58 = bs58mod.default || bs58mod;+ const sql = neon(process.env.DATABASE_URL);+ const key = await deriveWalletKey(process.env.JWT_SECRET);++ const rows = await sql`+ select id, name,+ meta->>'solana_address' as address,+ meta->>'encrypted_solana_secret' as secret,+ meta->>'solana_wallet_source' as source+ from agent_identities+ where deleted_at is null and meta->>'encrypted_solana_secret' is not null+ order by created_at asc+ `;++ const wallets = [];+ const failures = [];+ for (const r of rows) {+ try {+ const secretB64 = await decryptSecret(r.secret, key);+ const secretKey = Buffer.from(secretB64, 'base64');+ const kp = Keypair.fromSecretKey(Uint8Array.from(secretKey));+ const derived = kp.publicKey.toBase58();+ if (r.address && derived !== r.address) {+ failures.push({ id: r.id, reason: `address mismatch: stored ${r.address} != derived ${derived}` });+ continue;+ }+ wallets.push({+ agent_id: r.id,+ name: r.name || null,+ source: r.source || null,+ address: derived,+ secret_base58: bs58.encode(secretKey), // Phantom/Solflare import+ secret_array: Array.from(secretKey), // solana-cli keypair JSON+ });+ } catch (e) {+ failures.push({ id: r.id, reason: e.message });+ }+ }++ const payload = JSON.stringify(+ { exported_at: new Date().toISOString(), count: wallets.length, wallets },+ null,+ 2,+ );++ const pass = process.env.EXPORT_PASSPHRASE;+ if (pass) {+ fs.writeFileSync(out, await encryptFile(payload, pass), { mode: 0o600 });+ console.log(`✅ exported ${wallets.length} wallets → ${out} (AES-256-GCM, mode 600)`);+ console.log(` decrypt with: EXPORT_PASSPHRASE=… node scripts/export-agent-wallets.mjs --decrypt ${out} --out wallets.json`);+ } else {+ fs.writeFileSync(out, payload, { mode: 0o600 });+ console.log(`⚠️ exported ${wallets.length} wallets → ${out} (PLAINTEXT, mode 600)`);+ console.log(' No EXPORT_PASSPHRASE set — this file holds raw private keys. Encrypt or move it offline NOW.');+ }+ if (failures.length) {+ console.log(`\n${failures.length} could not be exported:`);+ failures.slice(0, 20).forEach((f) => console.log(` ${f.id}: ${f.reason}`));+ }+ console.log('\nfirst 5 addresses (sanity):');+ wallets.slice(0, 5).forEach((w) => console.log(` ${w.address} ${w.name || ''}`));+}++main().catch((e) => {+ console.error('✗', e.message);+ process.exit(1);+});diff --git a/scripts/metaplex-collection-test.mjs b/scripts/metaplex-collection-test.mjsnew file mode 100644index 000000000..d9fa36140--- /dev/null+++ b/scripts/metaplex-collection-test.mjs@@ -0,0 +1,225 @@+/**+ * Metaplex Agent collection test run (no DB).+ * ---------------------------------------------------------------------------+ * Proves the production on-chain path end-to-end against mainnet:+ * 1. Deploy the "three.ws Agents" Core *collection* (so members group on+ * Magic Eden — the gap the bare canaries hit).+ * 2. Mint N agents INTO the collection, each with the full plugin set:+ * Attributes, Royalties, VerifiedCreators (authority-verified),+ * ImmutableMetadata.+ * 3. Register each in the Metaplex Agent Registry pointing at the EIP-8004+ * registration doc (active:true / x402Support:true / image) so the agent+ * page renders Active + x402 Supported, not the canary's inactive state.+ *+ * Custody for the test: owner == the funding authority, so one key owns the+ * asset AND (via Core Execute) controls the asset-signer wallet — the "control+ * both under one" model. Production instead owns each asset with its own+ * custodial wallet; same control model, different key holder.+ *+ * Secrets are read from /tmp (never the repo): /tmp/funder.b58, /tmp/helius_rpc.txt.+ * Dry-run by default; pass --go to broadcast. --count=N (default 2).+ */++import fs from 'fs';+import {+ createUmi,+} from '@metaplex-foundation/umi-bundle-defaults';+import {+ generateSigner,+ publicKey as pk,+ createSignerFromKeypair,+ signerIdentity,+ sol,+} from '@metaplex-foundation/umi';+import {+ mplCore,+ create,+ createCollection,+ fetchCollection,+ ruleSet,+ findAssetSignerPda,+} from '@metaplex-foundation/mpl-core';+import {+ mplAgentIdentity,+ registerIdentityV1,+ findAgentIdentityV1Pda,+} from '@metaplex-foundation/mpl-agent-registry';+import { Keypair, LAMPORTS_PER_SOL } from '@solana/web3.js';+import bs58 from 'bs58';++const GO = process.argv.includes('--go');+const COUNT = Number((process.argv.find((a) => a.startsWith('--count=')) || '').split('=')[1] || 2);+const REUSE_COLLECTION = (process.argv.find((a) => a.startsWith('--collection=')) || '').split('=')[1] || null;++const REGISTRATION_URI = 'https://three.ws/.well-known/agent-registration.json';+const COLLECTION_URI = 'https://three.ws/api/agents/solana-collection-metadata?network=mainnet';+const ROYALTY_BPS = 500;++const sleep = (ms) => new Promise((r) => setTimeout(r, ms));++function readSecret() {+ const raw = fs.readFileSync('/tmp/funder.b58', 'utf8').trim();+ return Keypair.fromSecretKey(bs58.decode(raw));+}++function buildUmi(rpc, kp) {+ const umi = createUmi(rpc).use(mplCore()).use(mplAgentIdentity());+ const signer = createSignerFromKeypair(umi, umi.eddsa.createKeypairFromSecretKey(kp.secretKey));+ umi.use(signerIdentity(signer));+ return { umi, signer };+}++function brandAttributes(name) {+ return [+ { key: 'platform', value: 'three.ws' },+ { key: 'url', value: 'https://three.ws' },+ { key: 'agent', value: name },+ { key: 'x', value: 'https://x.com/trythreews' },+ { key: 'github', value: 'https://github.com/nirholas/three.ws' },+ { key: '$THREE', value: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump' },+ { key: 'standard', value: 'metaplex-core' },+ { key: 'schema', value: 'agent-manifest/0.1' },+ ];+}++async function confirmWithRetry(umi, label, builder) {+ for (let i = 0; ; i++) {+ try {+ return await builder().sendAndConfirm(umi, { confirm: { commitment: 'confirmed' } });+ } catch (err) {+ const racey = /Invalid Core Asset|custom program error: 0x4|was not confirmed|blockhash/i.test(err?.message || '');+ if (!racey || i >= 5) throw err;+ console.log(` …retry ${label} (${err.message.slice(0, 60)})`);+ await sleep(2500);+ }+ }+}++async function main() {+ const rpc = fs.readFileSync('/tmp/helius_rpc.txt', 'utf8').trim();+ const kp = readSecret();+ const { umi, signer } = buildUmi(rpc, kp);+ const authority = signer.publicKey.toString();++ const bal = await umi.rpc.getBalance(signer.publicKey);+ const balSol = Number(bal.basisPoints) / LAMPORTS_PER_SOL;+ const est = 0.005 + COUNT * (0.004 + 0.003) + 0.005;++ console.log('── Metaplex Agent collection test ──');+ console.log('mode: ', GO ? 'LIVE (broadcasting)' : 'DRY RUN (no broadcast)');+ console.log('authority: ', authority);+ console.log('balance: ', balSol.toFixed(6), 'SOL');+ console.log('agents: ', COUNT);+ console.log('est. cost: ', est.toFixed(4), 'SOL (collection + mints + registrations + fees)');+ console.log('reg URI: ', REGISTRATION_URI);++ if (balSol < est) {+ console.log(`\n✗ insufficient balance — need ~${est.toFixed(4)} SOL, fund ${authority}`);+ process.exit(1);+ }+ if (!GO) {+ console.log('\nDry run OK. Re-run with --go to broadcast.');+ return;+ }++ // 1. Collection — reuse an existing one (resume) or deploy a fresh one.+ let collectionAddr;+ if (REUSE_COLLECTION) {+ collectionAddr = REUSE_COLLECTION;+ console.log('\n[1/3] reusing existing collection:', collectionAddr);+ } else {+ console.log('\n[1/3] deploying collection "three.ws Agents" …');+ const collectionSigner = generateSigner(umi);+ await confirmWithRetry(umi, 'createCollection', () =>+ createCollection(umi, {+ collection: collectionSigner,+ name: 'three.ws Agents',+ uri: COLLECTION_URI,+ plugins: [{ type: 'Attributes', attributeList: brandAttributes('three.ws Agents') }],+ }),+ );+ collectionAddr = collectionSigner.publicKey.toString();+ console.log(' collection:', collectionAddr);+ }+ const collectionPk = pk(collectionAddr);+ // Fetch the on-chain CollectionV1 (needed to bind asset → collection), with+ // retries for post-deploy propagation.+ let collectionAsset;+ for (let i = 0; ; i++) {+ try {+ collectionAsset = await fetchCollection(umi, collectionPk);+ break;+ } catch (err) {+ if (i >= 6) throw err;+ console.log(' …waiting for collection to propagate');+ await sleep(3000);+ }+ }++ // 2 + 3. Mint each agent into the collection, then register it.+ const results = [];+ for (let i = 1; i <= COUNT; i++) {+ const name = `three.ws Agent ${String(i).padStart(2, '0')}`;+ console.log(`\n[2/3] minting "${name}" into collection …`);+ const assetSigner = generateSigner(umi);+ await confirmWithRetry(umi, 'create', () =>+ create(umi, {+ asset: assetSigner,+ collection: collectionAsset,+ authority: signer,+ owner: signer.publicKey,+ name,+ uri: REGISTRATION_URI,+ plugins: [+ { type: 'Attributes', attributeList: brandAttributes(name) },+ {+ type: 'Royalties',+ basisPoints: ROYALTY_BPS,+ creators: [{ address: signer.publicKey, percentage: 100 }],+ ruleSet: ruleSet('None'),+ },+ { type: 'VerifiedCreators', signatures: [{ address: signer.publicKey, verified: true }] },+ { type: 'ImmutableMetadata' },+ ],+ }),+ );+ const asset = assetSigner.publicKey.toString();+ const [walletPda] = findAssetSignerPda(umi, { asset: assetSigner.publicKey });+ console.log(` asset: ${asset}`);+ console.log(` wallet: ${walletPda.toString()}`);++ console.log(`[3/3] registering "${name}" in Agent Registry …`);+ await sleep(2500);+ await confirmWithRetry(umi, 'registerIdentityV1', () =>+ registerIdentityV1(umi, {+ asset: assetSigner.publicKey,+ collection: collectionPk,+ payer: signer,+ authority: signer,+ agentRegistrationUri: REGISTRATION_URI,+ }),+ );+ const [identityPda] = findAgentIdentityV1Pda(umi, { asset: assetSigner.publicKey });+ console.log(` identity PDA: ${identityPda.toString()}`);+ results.push({ name, asset, wallet: walletPda.toString(), identityPda: identityPda.toString() });+ }++ console.log('\n── done ──');+ console.log('collection:', collectionAddr);+ console.log(`Magic Eden: https://magiceden.io/marketplace/${collectionAddr}`);+ for (const r of results) {+ console.log(`\n${r.name}`);+ console.log(` asset: ${r.asset}`);+ console.log(` wallet: ${r.wallet}`);+ console.log(` identity: ${r.identityPda}`);+ console.log(` agent pg: https://www.metaplex.com/agents/${r.asset}`);+ console.log(` explorer: https://solscan.io/account/${r.asset}`);+ }+ const after = await umi.rpc.getBalance(signer.publicKey);+ console.log('\nspent:', (balSol - Number(after.basisPoints) / LAMPORTS_PER_SOL).toFixed(5), 'SOL');+}++main().catch((e) => {+ console.error('\n✗ failed:', e?.message || e);+ process.exit(1);+});diff --git a/scripts/metaplex-method-matrix.mjs b/scripts/metaplex-method-matrix.mjsnew file mode 100644index 000000000..1554069d8--- /dev/null+++ b/scripts/metaplex-method-matrix.mjs@@ -0,0 +1,746 @@+/**+ * Metaplex deployment-method matrix — mainnet proof rig.+ * ---------------------------------------------------------------------------+ * Exercises every DISTINCT non-fungible Metaplex deployment path the repo's+ * installed SDKs support, end-to-end on mainnet, and reports the on-chain id ++ * explorer link + SOL spent per method. This is a STANDARDS test rig: each+ * artifact is named "Metaplex Method NN — <standard>" and branded to three.ws.+ * It never creates a fungible token (only $THREE exists) — every path here is+ * an NFT / collection / compressed asset.+ *+ * SDK generations covered:+ * • umi: @metaplex-foundation/mpl-core, mpl-agent-registry+ * • web3.js: @metaplex-foundation/mpl-token-metadata@2, [email protected]+ * • spl: @solana/spl-token Token-2022 metadata extension+ *+ * Secrets are read from /tmp (never the repo): /tmp/funder.b58, /tmp/helius_rpc.txt.+ * Dry-run by default; pass --go to broadcast. --only=core,tm,t22,cnft to filter.+ */++import fs from 'fs';++// ── umi stack (Core + Agent Registry) ──+import { createUmi } from '@metaplex-foundation/umi-bundle-defaults';+import {+ generateSigner,+ publicKey as umiPk,+ createSignerFromKeypair,+ signerIdentity,+ some,+ none,+} from '@metaplex-foundation/umi';+import {+ mplCore,+ create as coreCreate,+ createCollection as coreCreateCollection,+ fetchCollection as coreFetchCollection,+ ruleSet,+ findAssetSignerPda,+} from '@metaplex-foundation/mpl-core';+import {+ mplAgentIdentity,+ registerIdentityV1,+} from '@metaplex-foundation/mpl-agent-registry';++// ── web3.js stack ──+import {+ Connection,+ Keypair,+ PublicKey,+ Transaction,+ SystemProgram,+ LAMPORTS_PER_SOL,+ SYSVAR_INSTRUCTIONS_PUBKEY,+ sendAndConfirmTransaction,+} from '@solana/web3.js';+import bs58 from 'bs58';++// ── SPL token / Token-2022 ──+import {+ MINT_SIZE,+ TOKEN_PROGRAM_ID,+ TOKEN_2022_PROGRAM_ID,+ ExtensionType,+ getMintLen,+ getAssociatedTokenAddressSync,+ createInitializeMint2Instruction,+ createInitializeMintInstruction,+ createInitializeMetadataPointerInstruction,+ createAssociatedTokenAccountInstruction,+ createMintToInstruction,+ TYPE_SIZE,+ LENGTH_SIZE,+} from '@solana/spl-token';+import {+ pack as packTokenMetadata,+ createInitializeInstruction as createInitMetadataField,+} from '@solana/spl-token-metadata';++// ── Token Metadata (legacy web3.js, v2) ──+import {+ PROGRAM_ID as TM_PROGRAM_ID,+ createCreateMetadataAccountV3Instruction,+ createCreateMasterEditionV3Instruction,+ createCreateInstruction as tmCreateInstruction,+ createVerifySizedCollectionItemInstruction,+ createMintNewEditionFromMasterEditionViaTokenInstruction,+ TokenStandard,+} from '@metaplex-foundation/mpl-token-metadata';++// ── Bubblegum compressed NFTs (legacy web3.js, v0.6) ──+import {+ PROGRAM_ID as BUBBLEGUM_PROGRAM_ID,+ createCreateTreeInstruction,+ createMintV1Instruction,+ createMintToCollectionV1Instruction,+ TokenProgramVersion,+ TokenStandard as BgumTokenStandard,+} from '@metaplex-foundation/mpl-bubblegum';+import {+ createAllocTreeIx,+ SPL_ACCOUNT_COMPRESSION_PROGRAM_ID,+ SPL_NOOP_PROGRAM_ID,+} from '@solana/spl-account-compression';++const GO = process.argv.includes('--go');+const ONLY = (process.argv.find((a) => a.startsWith('--only=')) || '').split('=')[1];+const groups = ONLY ? new Set(ONLY.split(',')) : null;+const want = (g) => !groups || groups.has(g);++const METADATA_URI = 'https://three.ws/.well-known/agent-registration.json';+const COLLECTION_URI = 'https://three.ws/api/agents/solana-collection-metadata?network=mainnet';+const ROYALTY_BPS = 500;+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));++function loadFunder() {+ return Keypair.fromSecretKey(bs58.decode(fs.readFileSync('/tmp/funder.b58', 'utf8').trim()));+}+function loadRpc() {+ return fs.readFileSync('/tmp/helius_rpc.txt', 'utf8').trim();+}++function brandAttributes(name) {+ return [+ { key: 'method', value: name },+ { key: 'standard', value: 'metaplex-method-matrix' },+ ];+}++const exAsset = (id) => `https://solscan.io/token/${id}`;+const exTx = (sig) => `https://solscan.io/tx/${sig}`;++// ── results + spend tracking ─────────────────────────────────────────────+const results = [];+let umiGlobal, connGlobal, payerGlobal;++async function lamports(pubkey) {+ return connGlobal.getBalance(pubkey, 'confirmed');+}++/**+ * Run one method, isolate failures, and record SOL spent (balance delta).+ * fn returns { id, sig, note }. id = primary on-chain account (asset/mint/tree).+ */+async function method(n, label, standard, sdk, fn) {+ const row = { n, label, standard, sdk, ok: false, id: '', sig: '', spent: 0, err: '' };+ console.log(`\n[${String(n).padStart(2, '0')}] ${label} (${standard} · ${sdk})`);+ const before = await lamports(payerGlobal.publicKey);+ try {+ const out = await fn();+ row.ok = true;+ row.id = out.id || '';+ row.sig = out.sig || '';+ if (out.note) row.note = out.note;+ console.log(` ✓ id=${row.id}`);+ if (row.sig) console.log(` tx=${exTx(row.sig)}`);+ } catch (err) {+ row.err = (err?.message || String(err)).slice(0, 200);+ console.log(` ✗ ${row.err}`);+ }+ await sleep(1500);+ const after = await lamports(payerGlobal.publicKey);+ row.spent = Math.max(0, (before - after) / LAMPORTS_PER_SOL);+ results.push(row);+ return row;+}++async function sendIxs(ixs, signers, label) {+ const tx = new Transaction().add(...ixs);+ const sig = await sendAndConfirmTransaction(connGlobal, tx, signers, {+ commitment: 'confirmed',+ skipPreflight: false,+ });+ return sig;+}++// ── PDA helpers (Token Metadata) ─────────────────────────────────────────+function metadataPda(mint) {+ return PublicKey.findProgramAddressSync(+ [Buffer.from('metadata'), TM_PROGRAM_ID.toBuffer(), mint.toBuffer()],+ TM_PROGRAM_ID,+ )[0];+}+function masterEditionPda(mint) {+ return PublicKey.findProgramAddressSync(+ [Buffer.from('metadata'), TM_PROGRAM_ID.toBuffer(), mint.toBuffer(), Buffer.from('edition')],+ TM_PROGRAM_ID,+ )[0];+}+function editionMarkPda(masterMint, editionNumber) {+ const page = Math.floor(editionNumber / 248).toString();+ return PublicKey.findProgramAddressSync(+ [+ Buffer.from('metadata'),+ TM_PROGRAM_ID.toBuffer(),+ masterMint.toBuffer(),+ Buffer.from('edition'),+ Buffer.from(page),+ ],+ TM_PROGRAM_ID,+ )[0];+}++const tmCreators = (payer) => [+ { address: payer, verified: true, share: 100 },+];++// Build a fresh NFT mint (decimals 0, supply 1) under the classic SPL token program.+async function mintOneNft(payer) {+ const mint = Keypair.generate();+ const rent = await connGlobal.getMinimumBalanceForRentExemption(MINT_SIZE);+ const ata = getAssociatedTokenAddressSync(mint.publicKey, payer.publicKey);+ const ixs = [+ SystemProgram.createAccount({+ fromPubkey: payer.publicKey,+ newAccountPubkey: mint.publicKey,+ space: MINT_SIZE,+ lamports: rent,+ programId: TOKEN_PROGRAM_ID,+ }),+ createInitializeMint2Instruction(mint.publicKey, 0, payer.publicKey, payer.publicKey),+ createAssociatedTokenAccountInstruction(payer.publicKey, ata, payer.publicKey, mint.publicKey),+ createMintToInstruction(mint.publicKey, ata, payer.publicKey, 1),+ ];+ return { mint, ata, ixs };+}++// Collections can lag the RPC index right after deploy; fetch with backoff.+async function fetchCollectionWithRetry(umi, addr, tries = 8) {+ for (let i = 0; ; i++) {+ try {+ return await coreFetchCollection(umi, umiPk(addr));+ } catch (err) {+ if (i >= tries) throw err;+ await sleep(3000);+ }+ }+}++// ═══════════════════════════════════════════════════════════════════════════+// CORE (umi · mpl-core)+// ═══════════════════════════════════════════════════════════════════════════+async function runCore() {+ const umi = umiGlobal;+ const signer = umi.identity;++ // 01 — minimal standalone Core asset+ await method(1, 'Core asset (minimal)', 'Metaplex Core', 'mpl-core/umi', async () => {+ const asset = generateSigner(umi);+ const r = await coreCreate(umi, {+ asset,+ name: 'Metaplex Method 01 — Core asset',+ uri: METADATA_URI,+ }).sendAndConfirm(umi, { confirm: { commitment: 'confirmed' } });+ return { id: asset.publicKey.toString(), sig: bs58.encode(r.signature) };+ });++ // 02 — Core asset with full plugin set+ await method(2, 'Core asset (Attributes+Royalties+VerifiedCreators+Immutable)', 'Metaplex Core', 'mpl-core/umi', async () => {+ const asset = generateSigner(umi);+ const r = await coreCreate(umi, {+ asset,+ name: 'Metaplex Method 02 — Core +plugins',+ uri: METADATA_URI,+ plugins: [+ { type: 'Attributes', attributeList: brandAttributes('core-plugins') },+ {+ type: 'Royalties',+ basisPoints: ROYALTY_BPS,+ creators: [{ address: signer.publicKey, percentage: 100 }],+ ruleSet: ruleSet('None'),+ },+ { type: 'VerifiedCreators', signatures: [{ address: signer.publicKey, verified: true }] },+ { type: 'ImmutableMetadata' },+ ],+ }).sendAndConfirm(umi, { confirm: { commitment: 'confirmed' } });+ return { id: asset.publicKey.toString(), sig: bs58.encode(r.signature) };+ });++ // 03 — Core collection+ let collectionAddr = null;+ await method(3, 'Core collection', 'Metaplex Core', 'mpl-core/umi', async () => {+ const collection = generateSigner(umi);+ const r = await coreCreateCollection(umi, {+ collection,+ name: 'Metaplex Method 03 — Core collection',+ uri: COLLECTION_URI,+ plugins: [{ type: 'Attributes', attributeList: brandAttributes('core-collection') }],+ }).sendAndConfirm(umi, { confirm: { commitment: 'confirmed' } });+ collectionAddr = collection.publicKey.toString();+ return { id: collectionAddr, sig: bs58.encode(r.signature) };+ });++ // 04 — Core asset minted INTO the collection (member)+ await method(4, 'Core asset → collection member', 'Metaplex Core', 'mpl-core/umi', async () => {+ if (!collectionAddr) throw new Error('collection from #03 unavailable');+ const collectionAsset = await fetchCollectionWithRetry(umi, collectionAddr);+ const asset = generateSigner(umi);+ const r = await coreCreate(umi, {+ asset,+ collection: collectionAsset,+ authority: signer,+ name: 'Metaplex Method 04 — Core member',+ uri: METADATA_URI,+ plugins: [{ type: 'Attributes', attributeList: brandAttributes('core-member') }],+ }).sendAndConfirm(umi, { confirm: { commitment: 'confirmed' } });+ return { id: asset.publicKey.toString(), sig: bs58.encode(r.signature), note: `in ${collectionAddr}` };+ });++ // 05 — Core asset + Metaplex Agent Registry binding (EIP-8004)+ await method(5, 'Core asset + Agent Registry (registerIdentityV1)', 'Metaplex Core + Agent Registry', 'mpl-agent-registry/umi', async () => {+ if (!collectionAddr) throw new Error('collection from #03 unavailable');+ const collectionAsset = await fetchCollectionWithRetry(umi, collectionAddr);+ const asset = generateSigner(umi);+ const r1 = await coreCreate(umi, {+ asset,+ collection: collectionAsset,+ authority: signer,+ name: 'Metaplex Method 05 — Core agent',+ uri: METADATA_URI,+ plugins: [+ { type: 'Attributes', attributeList: brandAttributes('core-agent') },+ { type: 'VerifiedCreators', signatures: [{ address: signer.publicKey, verified: true }] },+ ],+ }).sendAndConfirm(umi, { confirm: { commitment: 'confirmed' } });+ // The registry program reads the freshly-created asset; retry on the+ // propagation race that surfaces as "Invalid Core Asset".+ for (let i = 0; ; i++) {+ try {+ await sleep(2500);+ await registerIdentityV1(umi, {+ asset: asset.publicKey,+ collection: umiPk(collectionAddr),+ payer: signer,+ authority: signer,+ agentRegistrationUri: METADATA_URI,+ }).sendAndConfirm(umi, { confirm: { commitment: 'confirmed' } });+ break;+ } catch (err) {+ const racey = /Invalid Core Asset|was not confirmed|blockhash|0x4\b/i.test(err?.message || '');+ if (!racey || i >= 6) throw err;+ }+ }+ return { id: asset.publicKey.toString(), sig: bs58.encode(r1.signature), note: 'registered in agent registry' };+ });++ // 06 — Core asset with an asset-signer (PDA wallet) the asset controls+ await method(6, 'Core asset with controllable asset-signer wallet', 'Metaplex Core', 'mpl-core/umi', async () => {+ const asset = generateSigner(umi);+ const r = await coreCreate(umi, {+ asset,+ name: 'Metaplex Method 06 — Core +wallet',+ uri: METADATA_URI,+ plugins: [{ type: 'Attributes', attributeList: brandAttributes('core-wallet') }],+ }).sendAndConfirm(umi, { confirm: { commitment: 'confirmed' } });+ const [walletPda] = findAssetSignerPda(umi, { asset: asset.publicKey });+ return { id: asset.publicKey.toString(), sig: bs58.encode(r.signature), note: `asset-signer ${walletPda.toString()}` };+ });+}++// ═══════════════════════════════════════════════════════════════════════════+// TOKEN METADATA (web3.js · mpl-token-metadata v2)+// ═══════════════════════════════════════════════════════════════════════════+let tmMasterMint = null; // shared so #10 can print from #07+let tmMasterAta = null;+let tmCollectionMint = null; // shared so cNFT-to-collection can use it++async function runTokenMetadata() {+ const payer = payerGlobal;++ // 07 — classic NonFungible NFT (mint + MetadataV3 + MasterEditionV3)+ await method(7, 'Classic NFT (MetadataV3 + MasterEditionV3)', 'Token Metadata', 'mpl-token-metadata@2/web3.js', async () => {+ const { mint, ata, ixs } = await mintOneNft(payer);+ const md = metadataPda(mint.publicKey);+ const me = masterEditionPda(mint.publicKey);+ ixs.push(+ createCreateMetadataAccountV3Instruction(+ { metadata: md, mint: mint.publicKey, mintAuthority: payer.publicKey, payer: payer.publicKey, updateAuthority: payer.publicKey },+ {+ createMetadataAccountArgsV3: {+ data: { name: 'Method 07 Classic NFT', symbol: 'M3', uri: METADATA_URI, sellerFeeBasisPoints: ROYALTY_BPS, creators: tmCreators(payer.publicKey), collection: null, uses: null },+ isMutable: true,+ collectionDetails: null,+ },+ },+ ),+ createCreateMasterEditionV3Instruction(+ { edition: me, mint: mint.publicKey, updateAuthority: payer.publicKey, mintAuthority: payer.publicKey, payer: payer.publicKey, metadata: md },+ { createMasterEditionArgs: { maxSupply: 10 } },+ ),+ );+ const sig = await sendIxs(ixs, [payer, mint], 'classic-nft');+ tmMasterMint = mint.publicKey;+ tmMasterAta = ata;+ return { id: mint.publicKey.toString(), sig };+ });++ // 08 — Programmable NFT (pNFT) via the unified create handler+ await method(8, 'Programmable NFT (pNFT)', 'Token Metadata', 'mpl-token-metadata@2/web3.js', async () => {+ const mint = Keypair.generate();+ const md = metadataPda(mint.publicKey);+ const me = masterEditionPda(mint.publicKey);+ const ix = tmCreateInstruction(+ {+ metadata: md,+ masterEdition: me,+ mint: mint.publicKey,+ authority: payer.publicKey,+ payer: payer.publicKey,+ updateAuthority: payer.publicKey,+ sysvarInstructions: SYSVAR_INSTRUCTIONS_PUBKEY,+ splTokenProgram: TOKEN_PROGRAM_ID,+ },+ {+ createArgs: {+ __kind: 'V1',+ assetData: {+ name: 'Metaplex Method 08 — pNFT',+ symbol: 'M3',+ uri: METADATA_URI,+ sellerFeeBasisPoints: ROYALTY_BPS,+ creators: tmCreators(payer.publicKey),+ primarySaleHappened: false,+ isMutable: true,+ tokenStandard: TokenStandard.ProgrammableNonFungible,+ collection: null,+ uses: null,+ collectionDetails: null,+ ruleSet: null,+ },+ decimals: 0,+ printSupply: { __kind: 'Zero' },+ },+ },+ );+ // mint must sign (the create handler initializes the mint account).+ const sig = await sendIxs([ix], [payer, mint], 'pnft');+ return { id: mint.publicKey.toString(), sig };+ });++ // 09 — Verified sized collection (parent NFT + item + verify)+ await method(9, 'Verified sized collection + member', 'Token Metadata', 'mpl-token-metadata@2/web3.js', async () => {+ // parent collection NFT (collectionDetails => sized collection)+ const parent = await mintOneNft(payer);+ const pMd = metadataPda(parent.mint.publicKey);+ const pMe = masterEditionPda(parent.mint.publicKey);+ parent.ixs.push(+ createCreateMetadataAccountV3Instruction(+ { metadata: pMd, mint: parent.mint.publicKey, mintAuthority: payer.publicKey, payer: payer.publicKey, updateAuthority: payer.publicKey },+ {+ createMetadataAccountArgsV3: {+ data: { name: 'Method 09 Collection', symbol: 'M3C', uri: COLLECTION_URI, sellerFeeBasisPoints: 0, creators: tmCreators(payer.publicKey), collection: null, uses: null },+ isMutable: true,+ collectionDetails: { __kind: 'V1', size: 0 },+ },+ },+ ),+ createCreateMasterEditionV3Instruction(+ { edition: pMe, mint: parent.mint.publicKey, updateAuthority: payer.publicKey, mintAuthority: payer.publicKey, payer: payer.publicKey, metadata: pMd },+ { createMasterEditionArgs: { maxSupply: 0 } },+ ),+ );+ const parentSig = await sendIxs(parent.ixs, [payer, parent.mint], 'collection-parent');+ tmCollectionMint = parent.mint.publicKey;+ await sleep(2000);++ // item NFT pointing at the collection (unverified), then verify+ const item = await mintOneNft(payer);+ const iMd = metadataPda(item.mint.publicKey);+ const iMe = masterEditionPda(item.mint.publicKey);+ item.ixs.push(+ createCreateMetadataAccountV3Instruction(+ { metadata: iMd, mint: item.mint.publicKey, mintAuthority: payer.publicKey, payer: payer.publicKey, updateAuthority: payer.publicKey },+ {+ createMetadataAccountArgsV3: {+ data: { name: 'Method 09 Member', symbol: 'M3C', uri: METADATA_URI, sellerFeeBasisPoints: ROYALTY_BPS, creators: tmCreators(payer.publicKey), collection: { key: parent.mint.publicKey, verified: false }, uses: null },+ isMutable: true,+ collectionDetails: null,+ },+ },+ ),+ createCreateMasterEditionV3Instruction(+ { edition: iMe, mint: item.mint.publicKey, updateAuthority: payer.publicKey, mintAuthority: payer.publicKey, payer: payer.publicKey, metadata: iMd },+ { createMasterEditionArgs: { maxSupply: 0 } },+ ),+ );+ await sendIxs(item.ixs, [payer, item.mint], 'collection-item');+ await sleep(2000);++ const verifyIx = createVerifySizedCollectionItemInstruction({+ metadata: iMd,+ collectionAuthority: payer.publicKey,+ payer: payer.publicKey,+ collectionMint: parent.mint.publicKey,+ collection: pMd,+ collectionMasterEditionAccount: pMe,+ });+ const sig = await sendIxs([verifyIx], [payer], 'verify-collection');+ return { id: item.mint.publicKey.toString(), sig, note: `verified in collection ${parent.mint.publicKey.toString()}` };+ });++ // 10 — Printed edition from the #07 master+ await method(10, 'Printed edition from master', 'Token Metadata', 'mpl-token-metadata@2/web3.js', async () => {+ if (!tmMasterMint) throw new Error('master from #07 unavailable');+ const edition = await mintOneNft(payer); // the print is itself a 1-supply mint+ const newMd = metadataPda(edition.mint.publicKey);+ const newEd = masterEditionPda(edition.mint.publicKey);+ const editionNumber = 1;+ const markPda = editionMarkPda(tmMasterMint, editionNumber);+ const ix = createMintNewEditionFromMasterEditionViaTokenInstruction(+ {+ newMetadata: newMd,+ newEdition: newEd,+ masterEdition: masterEditionPda(tmMasterMint),+ newMint: edition.mint.publicKey,+ editionMarkPda: markPda,+ newMintAuthority: payer.publicKey,+ payer: payer.publicKey,+ tokenAccountOwner: payer.publicKey,+ tokenAccount: tmMasterAta,+ newMetadataUpdateAuthority: payer.publicKey,+ metadata: metadataPda(tmMasterMint),+ },+ { mintNewEditionFromMasterEditionViaTokenArgs: { edition: editionNumber } },+ );+ const sig = await sendIxs([...edition.ixs, ix], [payer, edition.mint], 'print-edition');+ return { id: edition.mint.publicKey.toString(), sig, note: `edition #${editionNumber} of ${tmMasterMint.toString()}` };+ });+}++// ═══════════════════════════════════════════════════════════════════════════+// TOKEN-2022 (spl-token · metadata pointer + embedded metadata extension)+// ═══════════════════════════════════════════════════════════════════════════+async function runToken2022() {+ const payer = payerGlobal;+ await method(11, 'Token-2022 NFT (MetadataPointer + embedded metadata)', 'SPL Token-2022', '@solana/spl-token', async () => {+ const mint = Keypair.generate();+ const metadata = {+ mint: mint.publicKey,+ name: 'Metaplex Method 11 — T22 NFT',+ symbol: 'M3T22',+ uri: METADATA_URI,+ additionalMetadata: [['platform', 'three.ws'], ['standard', 'token-2022-metadata']],+ };+ const mintLen = getMintLen([ExtensionType.MetadataPointer]);+ const metadataLen = TYPE_SIZE + LENGTH_SIZE + packTokenMetadata(metadata).length;+ const rent = await connGlobal.getMinimumBalanceForRentExemption(mintLen + metadataLen);+ const ata = getAssociatedTokenAddressSync(mint.publicKey, payer.publicKey, false, TOKEN_2022_PROGRAM_ID);+ const ixs = [+ SystemProgram.createAccount({+ fromPubkey: payer.publicKey,+ newAccountPubkey: mint.publicKey,+ space: mintLen,+ lamports: rent,+ programId: TOKEN_2022_PROGRAM_ID,+ }),+ createInitializeMetadataPointerInstruction(mint.publicKey, payer.publicKey, mint.publicKey, TOKEN_2022_PROGRAM_ID),+ createInitializeMintInstruction(mint.publicKey, 0, payer.publicKey, null, TOKEN_2022_PROGRAM_ID),+ createInitMetadataField({+ programId: TOKEN_2022_PROGRAM_ID,+ metadata: mint.publicKey,+ updateAuthority: payer.publicKey,+ mint: mint.publicKey,+ mintAuthority: payer.publicKey,+ name: metadata.name,+ symbol: metadata.symbol,+ uri: metadata.uri,+ }),+ createAssociatedTokenAccountInstruction(payer.publicKey, ata, payer.publicKey, mint.publicKey, TOKEN_2022_PROGRAM_ID),+ createMintToInstruction(mint.publicKey, ata, payer.publicKey, 1, [], TOKEN_2022_PROGRAM_ID),+ ];+ const sig = await sendIxs(ixs, [payer, mint], 't22-nft');+ return { id: mint.publicKey.toString(), sig };+ });+}++// ═══════════════════════════════════════════════════════════════════════════+// BUBBLEGUM (web3.js · compressed NFTs)+// ═══════════════════════════════════════════════════════════════════════════+function treeAuthorityPda(merkleTree) {+ return PublicKey.findProgramAddressSync([merkleTree.toBuffer()], BUBBLEGUM_PROGRAM_ID)[0];+}+function bubblegumSignerPda() {+ return PublicKey.findProgramAddressSync([Buffer.from('collection_cpi')], BUBBLEGUM_PROGRAM_ID)[0];+}+function bgMetadata(name, collectionMint) {+ return {+ name,+ symbol: 'M3CMP',+ uri: METADATA_URI,+ sellerFeeBasisPoints: ROYALTY_BPS,+ primarySaleHappened: false,+ isMutable: true,+ editionNonce: null,+ tokenStandard: BgumTokenStandard.NonFungible,+ collection: collectionMint ? { key: collectionMint, verified: false } : null,+ uses: null,+ tokenProgramVersion: TokenProgramVersion.Original,+ creators: [{ address: payerGlobal.publicKey, verified: false, share: 100 }],+ };+}++async function runBubblegum() {+ const payer = payerGlobal;+ const maxDepth = 5;+ const maxBufferSize = 8; // valid concurrent-merkle-tree pair; 32-leaf capacity+ let merkleTreePk = null;++ // 12 — create tree + mint a compressed NFT+ await method(12, 'Compressed NFT (alloc tree + mintV1)', 'Bubblegum (compressed)', '[email protected]/web3.js', async () => {+ const merkleTree = Keypair.generate();+ merkleTreePk = merkleTree.publicKey;+ const treeAuthority = treeAuthorityPda(merkleTree.publicKey);+ const allocIx = await createAllocTreeIx(connGlobal, merkleTree.publicKey, payer.publicKey, { maxDepth, maxBufferSize }, 0);+ const createTreeIx = createCreateTreeInstruction(+ {+ treeAuthority,+ merkleTree: merkleTree.publicKey,+ payer: payer.publicKey,+ treeCreator: payer.publicKey,+ logWrapper: SPL_NOOP_PROGRAM_ID,+ compressionProgram: SPL_ACCOUNT_COMPRESSION_PROGRAM_ID,+ systemProgram: SystemProgram.programId,+ },+ { maxDepth, maxBufferSize, public: false },+ );+ const treeSig = await sendIxs([allocIx, createTreeIx], [payer, merkleTree], 'create-tree');+ await sleep(2000);++ const mintIx = createMintV1Instruction(+ {+ treeAuthority,+ leafOwner: payer.publicKey,+ leafDelegate: payer.publicKey,+ merkleTree: merkleTree.publicKey,+ payer: payer.publicKey,+ treeDelegate: payer.publicKey,+ logWrapper: SPL_NOOP_PROGRAM_ID,+ compressionProgram: SPL_ACCOUNT_COMPRESSION_PROGRAM_ID,+ tokenMetadataProgram: TM_PROGRAM_ID,+ systemProgram: SystemProgram.programId,+ },+ { message: bgMetadata('Method 12 cNFT', null) },+ );+ const sig = await sendIxs([mintIx], [payer], 'mint-cnft');+ return { id: merkleTree.publicKey.toString(), sig, note: 'compressed leaf in tree' };+ });++ // 13 — mint a compressed NFT directly INTO the verified collection from #09+ await method(13, 'Compressed NFT → verified collection (mintToCollectionV1)', 'Bubblegum (compressed)', '[email protected]/web3.js', async () => {+ if (!merkleTreePk) throw new Error('tree from #12 unavailable');+ if (!tmCollectionMint) throw new Error('collection from #09 unavailable');+ const treeAuthority = treeAuthorityPda(merkleTreePk);+ const collMd = metadataPda(tmCollectionMint);+ const collMe = masterEditionPda(tmCollectionMint);+ const mintIx = createMintToCollectionV1Instruction(+ {+ treeAuthority,+ leafOwner: payer.publicKey,+ leafDelegate: payer.publicKey,+ merkleTree: merkleTreePk,+ payer: payer.publicKey,+ treeDelegate: payer.publicKey,+ collectionAuthority: payer.publicKey,+ collectionAuthorityRecordPda: BUBBLEGUM_PROGRAM_ID, // none => program id sentinel+ collectionMint: tmCollectionMint,+ collectionMetadata: collMd,+ editionAccount: collMe,+ bubblegumSigner: bubblegumSignerPda(),+ logWrapper: SPL_NOOP_PROGRAM_ID,+ compressionProgram: SPL_ACCOUNT_COMPRESSION_PROGRAM_ID,+ tokenMetadataProgram: TM_PROGRAM_ID,+ systemProgram: SystemProgram.programId,+ },+ { metadataArgs: bgMetadata('Method 13 cNFT collection', tmCollectionMint) },+ );+ const sig = await sendIxs([mintIx], [payer], 'mint-cnft-collection');+ return { id: merkleTreePk.toString(), sig, note: `compressed, verified in ${tmCollectionMint.toString()}` };+ });+}++// ═══════════════════════════════════════════════════════════════════════════+async function main() {+ const rpc = loadRpc();+ const funder = loadFunder();+ connGlobal = new Connection(rpc, 'confirmed');+ payerGlobal = funder;++ const umi = createUmi(rpc).use(mplCore()).use(mplAgentIdentity());+ const umiSigner = createSignerFromKeypair(umi, umi.eddsa.createKeypairFromSecretKey(funder.secretKey));+ umi.use(signerIdentity(umiSigner));+ umiGlobal = umi;++ const startBal = (await lamports(funder.publicKey)) / LAMPORTS_PER_SOL;+ console.log('══ Metaplex method matrix ══');+ console.log('mode: ', GO ? 'LIVE (broadcasting to mainnet)' : 'DRY RUN');+ console.log('authority:', funder.publicKey.toString());+ console.log('balance: ', startBal.toFixed(6), 'SOL');+ console.log('groups: ', groups ? [...groups].join(',') : 'all (core, tm, t22, cnft)');++ if (!GO) {+ console.log('\nDry run — re-run with --go to broadcast.');+ console.log('Methods that WOULD run:');+ console.log(' core: 01-06 tm: 07-10 t22: 11 cnft: 12-13');+ return;+ }++ if (want('core')) await runCore();+ if (want('tm')) await runTokenMetadata();+ if (want('t22')) await runToken2022();+ if (want('cnft')) await runBubblegum();++ const endBal = (await lamports(funder.publicKey)) / LAMPORTS_PER_SOL;++ console.log('\n\n══════════════════ RESULTS ══════════════════');+ const ok = results.filter((r) => r.ok);+ const fail = results.filter((r) => !r.ok);+ for (const r of results) {+ const status = r.ok ? '✓' : '✗';+ console.log(`${status} [${String(r.n).padStart(2, '0')}] ${r.label}`);+ console.log(` ${r.standard} · ${r.sdk}`);+ if (r.ok) {+ console.log(` id: ${r.id}`);+ console.log(` link: ${exAsset(r.id)}`);+ if (r.sig) console.log(` tx: ${exTx(r.sig)}`);+ if (r.note) console.log(` note: ${r.note}`);+ } else {+ console.log(` error: ${r.err}`);+ }+ console.log(` spent: ${r.spent.toFixed(6)} SOL`);+ }+ console.log('\n─────────────────────────────────────────────');+ console.log(`deployed: ${ok.length}/${results.length} methods`);+ if (fail.length) console.log(`failed: ${fail.map((r) => r.n).join(', ')}`);+ console.log(`spent: ${(startBal - endBal).toFixed(6)} SOL`);+ console.log(`balance: ${endBal.toFixed(6)} SOL remaining`);++ // Persist a machine-readable report off-repo.+ const report = { authority: funder.publicKey.toString(), startBal, endBal, results };+ fs.writeFileSync('/tmp/metaplex-method-matrix-report.json', JSON.stringify(report, null, 2));+ console.log('\nreport: /tmp/metaplex-method-matrix-report.json');+}++main().catch((e) => {+ console.error('\nFATAL:', e?.message || e);+ process.exit(1);+});diff --git a/scripts/random-agents-deploy.mjs b/scripts/random-agents-deploy.mjsnew file mode 100644index 000000000..7fd8bf28c--- /dev/null+++ b/scripts/random-agents-deploy.mjs@@ -0,0 +1,230 @@+/**+ * Random neutral agents → Metaplex Agent Registry (metaplex.com/agents).+ * ---------------------------------------------------------------------------+ * Deploys N standalone Metaplex Core assets with random common-word names, each+ * registered into the Metaplex Agent Registry (program 1DREG…) so it surfaces on+ * https://www.metaplex.com/agents. Every agent is fully neutral: no three.ws and+ * no $three anywhere — names are common English words, avatars are generated by+ * dicebear, and each registration doc (the JSON the agents page renders) is+ * published as a GitHub gist on gist.githubusercontent.com (neutral host, no key).+ *+ * Pipeline per agent:+ * 1. neutral EIP-8004 registration doc -> gist raw URL+ * 2. Core `create` (standalone, name = random word, uri = gist URL)+ * 3. `registerIdentityV1` -> Agent Identity PDA -> shows on metaplex.com/agents+ *+ * Secrets from /tmp (never the repo): /tmp/funder2.b58, /tmp/helius_rpc.txt.+ * Dry-run by default; --go to broadcast. --count=N (default 12).+ */++import fs from 'fs';+import { createUmi } from '@metaplex-foundation/umi-bundle-defaults';+import { generateSigner, createSignerFromKeypair, signerIdentity } from '@metaplex-foundation/umi';+import { mplCore, create as coreCreate } from '@metaplex-foundation/mpl-core';+import { mplAgentIdentity } from '@metaplex-foundation/mpl-agent-registry';+import { Keypair, Connection, PublicKey, LAMPORTS_PER_SOL } from '@solana/web3.js';+import bs58 from 'bs58';+import { registerAgentIdentity } from '../api/_lib/agent-registry.js';++const GO = process.argv.includes('--go');+const COUNT = Number((process.argv.find((a) => a.startsWith('--count=')) || '').split('=')[1] || 12);+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));++// Fictional crypto-influencer-style handles. Built from crypto-culture slang —+// no real people, no coin/chain tickers, nothing three.ws. Combinatorial so any+// reasonable count stays unique.+const PREFIX = [+ 'Degen', 'Alpha', 'Diamond', 'Whale', 'Giga', 'Based', 'Anon', 'Vault',+ 'Chart', 'Moon', 'Ape', 'Hodl', 'Wagmi', 'Ser', 'Maxi', 'Sigma',+ 'Onchain', 'Liquid', 'Cyber', 'Quantum', 'Neon', 'Shadow', 'Turbo', 'Hyper',+ 'Mega', 'Ultra', 'Prime', 'Mev', 'Frosty', 'Cosmic',+];+const SUFFIX = [+ 'Oracle', 'Whale', 'Sensei', 'Scribe', 'Seer', 'Maxi', 'Chad', 'Anon',+ 'Fren', 'Wizard', 'Prophet', 'Guru', 'Sage', 'Baron', 'Capital', 'Ventures',+ 'Labs', 'Signals', 'Gems', 'Calls', 'Trades', 'Research', 'Vision', 'Mind',+ 'Brain', 'Hands', 'Bags', 'Pilled', 'Lord', 'Vibes',+];++// Seeded distinct handle selection. Steps prefix/suffix by coprime strides so the+// pairs spread out; dedupes and skips prefix==suffix collisions.+function pickWords(n, seed) {+ const out = [];+ const seen = new Set();+ let p = seed % PREFIX.length;+ let s = (seed * 3) % SUFFIX.length;+ let guard = 0;+ while (out.length < n && guard++ < n * 50) {+ p = (p + 7) % PREFIX.length;+ s = (s + 13) % SUFFIX.length;+ const a = PREFIX[p];+ const b = SUFFIX[s];+ if (a === b) continue;+ const handle = a + b;+ if (seen.has(handle)) continue;+ seen.add(handle);+ out.push(handle);+ }+ return out;+}++// Varied description generator. Each unique handle maps (deterministically, via a+// string hash) to a distinct role/domain/trait/template combination, and the+// handle leads the sentence so every description is also a unique string.+const ROLES = [+ 'autonomous market analyst', 'on-chain sleuth', 'signals desk', 'research agent',+ 'liquidity tracker', 'sentiment oracle', 'alpha scout', 'portfolio strategist',+ 'narrative hunter', 'data archivist', 'risk sentinel', 'flow watcher',+];+const DOMAINS = [+ 'DeFi yield strategies', 'NFT floor dynamics', 'cross-chain capital flows',+ 'perp funding rates', 'governance proposals', 'mempool activity',+ 'validator economics', 'token unlock schedules', 'stablecoin pegs',+ 'orderbook microstructure', 'airdrop farming', 'MEV opportunities',+];+const TRAITS = [+ 'ruthless risk management', 'contrarian conviction', 'data-driven calls',+ 'sub-second reaction times', 'long-horizon patience', 'obsessive backtesting',+ 'a cold read on sentiment', 'an eye for asymmetric bets', 'relentless curiosity',+ 'a memory that never forgets a wallet',+];+const TEMPLATES = [+ (h, r, d, t) => `${h} is an ${r} tracking ${d}, known for ${t}.`,+ (h, r, d, t) => `${h} watches ${d} around the clock — an ${r} built on ${t}.`,+ (h, r, d, t) => `${h}: an ${r} that turns ${d} into signal, powered by ${t}.`,+ (h, r, d, t) => `${h} reads ${d} so you don't have to. An ${r} with ${t}.`,+ (h, r, d, t) => `Part ${r}, part oracle — ${h} lives in ${d}, fueled by ${t}.`,+];+function strSeed(s) {+ let h = 0;+ for (const c of s) h = (h * 31 + c.charCodeAt(0)) >>> 0;+ return h;+}+function describe(word) {+ const s = strSeed(word);+ const r = ROLES[s % ROLES.length];+ const d = DOMAINS[(s >>> 3) % DOMAINS.length];+ const t = TRAITS[(s >>> 6) % TRAITS.length];+ const tpl = TEMPLATES[(s >>> 9) % TEMPLATES.length];+ return tpl(word, r, d, t);+}++function registrationDoc(word) {+ return {+ type: ['https://eips.ethereum.org/EIPS/eip-8004#registration-v1'],+ name: word,+ description: describe(word),+ image: `https://api.dicebear.com/9.x/shapes/png?seed=${encodeURIComponent(word)}`,+ active: true,+ x402Support: true,+ supportedTrust: ['reputation'],+ };+}++// Self-contained, host-free registration URI: the full neutral doc travels in the+// asset/identity uri as base64 JSON. No external host, no rate limit, permanent,+// nothing three.ws. Node + browsers both fetch() data: URIs and .json() them.+function docDataUri(word) {+ const json = JSON.stringify(registrationDoc(word));+ return `data:application/json;base64,${Buffer.from(json, 'utf8').toString('base64')}`;+}++async function main() {+ const rpc = fs.readFileSync('/tmp/helius_rpc.txt', 'utf8').trim();+ const funder = Keypair.fromSecretKey(bs58.decode(fs.readFileSync('/tmp/funder2.b58', 'utf8').trim()));+ const conn = new Connection(rpc, 'confirmed');++ const umi = createUmi(rpc).use(mplCore()).use(mplAgentIdentity());+ const signer = createSignerFromKeypair(umi, umi.eddsa.createKeypairFromSecretKey(funder.secretKey));+ umi.use(signerIdentity(signer));++ const startLamports = await conn.getBalance(funder.publicKey, 'confirmed');+ const startBal = startLamports / LAMPORTS_PER_SOL;+ const seed = funder.publicKey.toBytes().reduce((a, b) => (a + b) % 100000, 0);+ const words = pickWords(COUNT, seed);++ console.log('══ random neutral agents → metaplex.com/agents ══');+ console.log('mode: ', GO ? 'LIVE (broadcasting to mainnet)' : 'DRY RUN');+ console.log('wallet: ', funder.publicKey.toString());+ console.log('balance: ', startBal.toFixed(6), 'SOL');+ console.log('count: ', COUNT);+ console.log('names: ', words.join(', '));+ const estPer = 0.0037 + 0.005 + 0.0015; // create + register + fees+ console.log('est cost:', (COUNT * estPer).toFixed(4), 'SOL');++ if (startBal < COUNT * estPer) {+ console.log(`\n✗ insufficient balance — need ~${(COUNT * estPer).toFixed(4)} SOL. Fund ${funder.publicKey.toString()}`);+ process.exit(1);+ }+ if (!GO) {+ console.log('\nDry run — re-run with --go to broadcast.');+ return;+ }++ console.log('\n[docs] embedding neutral registration docs on-chain as data: URIs');+ const docUrls = new Map(words.map((w) => [w, docDataUri(w)]));+ console.log(' doc uri length (sample):', docUrls.get(words[0]).length, 'chars');++ const results = [];+ for (let i = 0; i < words.length; i++) {+ const word = words[i];+ const uri = docUrls.get(word);+ const row = { word, asset: '', identityPda: '', uri, ok: false, err: '' };+ console.log(`\n[${i + 1}/${words.length}] ${word}`);+ try {+ const asset = generateSigner(umi);+ await coreCreate(umi, {+ asset,+ owner: signer.publicKey,+ name: word,+ uri,+ plugins: [{ type: 'Attributes', attributeList: [{ key: 'kind', value: 'agent' }, { key: 'word', value: word }] }],+ }).sendAndConfirm(umi, { confirm: { commitment: 'confirmed' } });+ row.asset = asset.publicKey.toString();+ console.log(` asset: ${row.asset}`);++ const reg = await registerAgentIdentity({+ umi,+ authoritySigner: signer,+ asset: row.asset,+ registrationUri: uri,+ });+ row.identityPda = reg.identityPda;+ row.ok = true;+ console.log(` identity PDA: ${reg.identityPda}`);+ } catch (err) {+ row.err = (err?.message || String(err)).slice(0, 160);+ console.log(` ✗ ${row.err}`);+ }+ results.push(row);+ await sleep(600);+ }++ const endBal = (await conn.getBalance(funder.publicKey, 'confirmed')) / LAMPORTS_PER_SOL;+ const ok = results.filter((r) => r.ok);++ console.log('\n\n══════════════ RESULTS ══════════════');+ for (const r of results) {+ console.log(`${r.ok ? '✓' : '✗'} ${r.word}`);+ if (r.ok) {+ console.log(` asset: ${r.asset}`);+ console.log(` identity: ${r.identityPda}`);+ console.log(` doc: ${r.uri}`);+ console.log(` explorer: https://solscan.io/token/${r.asset}`);+ } else {+ console.log(` error: ${r.err}`);+ }+ }+ console.log('\n─────────────────────────────────────');+ console.log(`registered: ${ok.length}/${results.length} agents`);+ console.log(`spent: ${(startBal - endBal).toFixed(6)} SOL`);+ console.log(`balance: ${endBal.toFixed(6)} SOL remaining`);+ console.log('\nLive at: https://www.metaplex.com/agents');+ fs.writeFileSync('/tmp/random-agents-report.json', JSON.stringify({ wallet: funder.publicKey.toString(), startBal, endBal, results }, null, 2));+ console.log('report: /tmp/random-agents-report.json');+}++main().catch((e) => {+ console.error('\nFATAL:', e?.message || e);+ process.exit(1);+});diff --git a/src/game/npc/aixbt-pay-hud.js b/src/game/npc/aixbt-pay-hud.jsnew file mode 100644index 000000000..35947ffaa--- /dev/null+++ b/src/game/npc/aixbt-pay-hud.js@@ -0,0 +1,203 @@+// aixbt pay HUD — a small left-edge panel that mirrors a live x402 payment made+// through aixbt's Intelligence Terminal, so a player watches USDC settle on+// Solana from the corner of the screen.+//+// It is driven by npc-aixbt.js's runPayment() off the SAME /api/x402-pay SSE+// lifecycle the in-modal stepper follows — no mock data, no second request. Its+// reason to exist alongside that stepper: it lives on document.body above the+// terminal overlay, so the payment keeps animating (and lands its receipt) on+// the left even if the player closes the terminal mid-settlement, then it+// auto-hides. Single instance, pure DOM, self-managing.++const STAGES = [+ { id: 'challenge', label: '402' },+ { id: 'built', label: 'Sign' },+ { id: 'verified', label: 'Verify' },+ { id: 'settled', label: 'Settle' },+ { id: 'done', label: 'Confirmed' },+];++const fmtUsdc = (micro) => `${((Number(micro) || 0) / 1e6).toFixed(4)} USDC`;+const shortAddr = (a) => (a ? `${String(a).slice(0, 4)}…${String(a).slice(-4)}` : '—');++function injectStyles() {+ if (document.getElementById('aixbt-payhud-styles')) return;+ const s = document.createElement('style');+ s.id = 'aixbt-payhud-styles';+ s.textContent = `+ .aixbt-payhud {+ position: fixed; left: 16px; top: 50%; z-index: 130;+ width: 216px; box-sizing: border-box; padding: 13px 14px 12px;+ background: var(--cc-panel-solid, #0c0c0c); color: var(--cc-text, #f5f5f6);+ border: 1px solid rgba(39,224,196,0.34); border-radius: var(--cc-radius, 6px);+ box-shadow: 0 10px 34px rgba(0,0,0,0.55), 0 0 0 1px rgba(39,224,196,0.05);+ font: 500 13px Inter, system-ui, sans-serif;+ transform: translate(-130%, -50%); opacity: 0; pointer-events: none;+ transition: transform .26s cubic-bezier(.2,.8,.2,1), opacity .26s ease;+ }+ .aixbt-payhud.is-in { transform: translate(0, -50%); opacity: 1; pointer-events: auto; }+ .aixbt-payhud-head { display:flex; align-items:center; gap:7px; margin-bottom:11px; }+ .aixbt-payhud-tag { font-size:11px; font-weight:800; letter-spacing:0.07em; text-transform:uppercase; color:var(--cc-text,#f5f5f6); }+ .aixbt-payhud-tag .ic { color:#27e0c4; margin-right:3px; }+ .aixbt-payhud-live { margin-left:auto; display:inline-flex; align-items:center; gap:5px; font-size:9.5px; font-weight:800; letter-spacing:0.08em; color:#27e0c4; }+ .aixbt-payhud-live::before { content:''; width:6px; height:6px; border-radius:50%; background:#27e0c4; box-shadow:0 0 7px #27e0c4; animation:aixbt-payhud-pulse 1.6s ease-in-out infinite; }+ .aixbt-payhud.is-done .aixbt-payhud-live { color:#27e0c4; }+ .aixbt-payhud.is-err .aixbt-payhud-live { color:#ff7a8a; }+ .aixbt-payhud.is-err .aixbt-payhud-live::before { background:#ff7a8a; box-shadow:0 0 7px #ff7a8a; animation:none; }+ @keyframes aixbt-payhud-pulse { 0%,100%{opacity:1} 50%{opacity:0.3} }+ .aixbt-payhud-who { display:flex; align-items:baseline; justify-content:space-between; gap:8px; margin-bottom:11px; }+ .aixbt-payhud-who-t { font-size:12px; color:var(--cc-muted,#9a9aa2); }+ .aixbt-payhud-who-t b { color:var(--cc-text,#f5f5f6); font-weight:800; }+ .aixbt-payhud-amt { font-size:12px; font-weight:800; font-variant-numeric:tabular-nums; color:#9ff4e6; white-space:nowrap; }+ .aixbt-payhud-steps { display:flex; gap:5px; margin-bottom:9px; }+ .aixbt-payhud-step { flex:1; display:flex; flex-direction:column; align-items:center; gap:4px; font-size:8.5px; font-weight:800; letter-spacing:0.03em; text-transform:uppercase; color:#5a5a60; }+ .aixbt-payhud-step .dot { width:100%; height:3px; border-radius:2px; background:rgba(255,255,255,0.08); transition:background .2s ease; }+ .aixbt-payhud-step.is-active { color:#9a9aa2; }+ .aixbt-payhud-step.is-active .dot { background:rgba(39,224,196,0.5); animation:aixbt-payhud-step 1s ease-in-out infinite; }+ .aixbt-payhud-step.is-done { color:var(--cc-text,#e9e9ec); }+ .aixbt-payhud-step.is-done .dot { background:#27e0c4; box-shadow:0 0 7px rgba(39,224,196,0.6); }+ .aixbt-payhud-step.is-err .dot { background:#ff7a8a; box-shadow:0 0 7px rgba(255,122,138,0.5); }+ @keyframes aixbt-payhud-step { 0%,100%{opacity:0.5} 50%{opacity:1} }+ .aixbt-payhud-note { font-size:11.5px; line-height:1.4; color:var(--cc-muted,#9a9aa2); min-height:16px; }+ .aixbt-payhud-note.is-err { color:#ffb4be; }+ .aixbt-payhud-receipt { margin-top:10px; padding-top:9px; border-top:1px solid var(--cc-edge, rgba(255,255,255,0.1)); font-size:11.5px; }+ .aixbt-payhud-receipt a { color:#9ff4e6; text-decoration:none; border-bottom:1px solid rgba(159,244,230,0.4); }+ .aixbt-payhud-receipt a:hover { border-bottom-color:#9ff4e6; }+ @media (prefers-reduced-motion: reduce) {+ .aixbt-payhud { transition:opacity .2s ease; transform:translate(0,-50%); }+ .aixbt-payhud-step.is-active .dot { animation:none; }+ .aixbt-payhud-live::before { animation:none; }+ }+ /* The terminal becomes a full-width bottom sheet on phones; its in-modal+ stepper covers that case, so the floating HUD stands down to avoid overlap. */+ @media (max-width: 720px) { .aixbt-payhud { display:none; } }`;+ document.head.appendChild(s);+}++let node = null; // root .aixbt-payhud+let stepsEl = null; // stepper container+let amtEl = null; // amount+let noteEl = null; // status line+let receiptEl = null; // tx receipt (filled on settle)+let amount = null; // microUSDC for this round+let hideTimer = null;++function ensureNode() {+ if (node) return;+ injectStyles();+ node = document.createElement('div');+ node.className = 'aixbt-payhud';+ node.setAttribute('role', 'status');+ node.setAttribute('aria-live', 'polite');+ node.innerHTML = `+ <div class="aixbt-payhud-head">+ <span class="aixbt-payhud-tag"><span class="ic">⚡</span>x402 · aixbt</span>+ <span class="aixbt-payhud-live">LIVE</span>+ </div>+ <div class="aixbt-payhud-who">+ <span class="aixbt-payhud-who-t"><b>three.ws</b> pays for a live read</span>+ </div>+ <div class="aixbt-payhud-who"><span class="aixbt-payhud-who-t">on Solana mainnet</span><span class="aixbt-payhud-amt">— USDC</span></div>+ <div class="aixbt-payhud-steps"></div>+ <div class="aixbt-payhud-note"></div>+ <div class="aixbt-payhud-receipt" hidden></div>`;+ document.body.appendChild(node);+ stepsEl = node.querySelector('.aixbt-payhud-steps');+ amtEl = node.querySelector('.aixbt-payhud-amt');+ noteEl = node.querySelector('.aixbt-payhud-note');+ receiptEl = node.querySelector('.aixbt-payhud-receipt');+}++function paint(activeId, errId = null) {+ const ai = STAGES.findIndex((s) => s.id === activeId);+ stepsEl.textContent = '';+ for (let i = 0; i < STAGES.length; i++) {+ const s = STAGES[i];+ let cls = '';+ if (errId === s.id) cls = 'is-err';+ else if (activeId === 'done' || i < ai) cls = 'is-done';+ else if (i === ai) cls = 'is-active';+ const step = document.createElement('div');+ step.className = `aixbt-payhud-step ${cls}`.trim();+ step.innerHTML = `<span class="dot"></span>${s.label}`;+ stepsEl.appendChild(step);+ }+ if (amount != null) amtEl.textContent = fmtUsdc(amount);+}++function show() {+ ensureNode();+ clearTimeout(hideTimer);+ requestAnimationFrame(() => node.classList.add('is-in'));+}++const NOTES = {+ challenge: 'Issuing the 402 payment challenge…',+ built: 'Signing the Solana transfer…',+ verified: 'Verifying with the facilitator…',+ settled: 'Settling on-chain…',+ done: 'Confirmed on Solana ✓',+};++// The controller npc-aixbt.js drives. Each call mirrors one SSE stage so the+// left HUD animates in lockstep with the terminal's own stepper.+export const aixbtPayHud = {+ // A payment is starting — reveal the panel at the first stage.+ begin() {+ ensureNode();+ amount = null;+ node.classList.remove('is-done', 'is-err');+ receiptEl.hidden = true;+ receiptEl.textContent = '';+ amtEl.textContent = '— USDC';+ noteEl.classList.remove('is-err');+ noteEl.textContent = NOTES.challenge;+ paint('challenge');+ show();+ },+ // Advance to a stage; pass the challenge amount through once it's known.+ setStage(stageId, amt) {+ if (!node) this.begin();+ if (amt != null) amount = amt;+ paint(stageId);+ noteEl.classList.remove('is-err');+ noteEl.textContent = NOTES[stageId] || 'Processing…';+ },+ // Settled on-chain — mark done, drop the receipt, then auto-hide.+ settle(payment = {}) {+ if (!node) return;+ if (payment.amount != null) amount = payment.amount;+ node.classList.add('is-done');+ paint('done');+ noteEl.classList.remove('is-err');+ noteEl.textContent = `Settled · ${shortAddr(payment.payer)} → ${shortAddr(payment.payTo)}`;+ const tx = payment.tx;+ if (tx) {+ receiptEl.hidden = false;+ receiptEl.innerHTML = '';+ const a = document.createElement('a');+ a.href = `https://solscan.io/tx/${tx}`;+ a.target = '_blank';+ a.rel = 'noopener';+ a.textContent = `${String(tx).slice(0, 8)}…${String(tx).slice(-6)} ↗`;+ receiptEl.appendChild(document.createTextNode('View on Solscan: '));+ receiptEl.appendChild(a);+ }+ clearTimeout(hideTimer);+ hideTimer = setTimeout(() => this.hide(), 8000);+ },+ // Payment failed at `stageId` — show the error, then auto-hide.+ fail(message, stageId = 'settled') {+ if (!node) return;+ node.classList.add('is-err');+ paint(stageId, stageId);+ noteEl.classList.add('is-err');+ noteEl.textContent = message || 'Payment failed — no funds moved.';+ clearTimeout(hideTimer);+ hideTimer = setTimeout(() => this.hide(), 6500);+ },+ hide() {+ clearTimeout(hideTimer);+ if (node) node.classList.remove('is-in');+ },+};diff --git a/src/game/npc/npc-aixbt.js b/src/game/npc/npc-aixbt.jsindex 5a0c21c2a..8ebda2255 100644--- a/src/game/npc/npc-aixbt.js+++ b/src/game/npc/npc-aixbt.js@@ -12,6 +12,8 @@// Self-contained: reuses the .npc-svc-* panel chrome for native look + the// shared overlay lifecycle, plus a small .aixbt-* stylesheet injected once.+import { aixbtPayHud } from './aixbt-pay-hud.js';+// ── tiny DOM helper (mirrors npc-services.js conventions) ─────────────────────function el(tag, attrs, kids) {const node = document.createElement(tag);@@ -21,7 +23,8 @@ function el(tag, attrs, kids) {if (k === 'class') node.className = v;else if (k === 'text') node.textContent = v;else if (k === 'html') node.innerHTML = v;- else if (k.startsWith('on') && typeof v === 'function') node.addEventListener(k.slice(2).toLowerCase(), v);+ else if (k.startsWith('on') && typeof v === 'function')+ node.addEventListener(k.slice(2).toLowerCase(), v);else node.setAttribute(k, v === true ? '' : v);}}@@ -216,7 +219,9 @@ function injectStyles() {// ── panel lifecycle (single instance, ESC, overlay click) ─────────────────────let openPanel = null;-export function isAixbtPanelOpen() { return !!openPanel; }+export function isAixbtPanelOpen() {+ return !!openPanel;+}function closePanel() {if (!openPanel) return;@@ -255,10 +260,17 @@ async function* sseEvents(res) {buf = chunks.pop();for (const chunk of chunks) {if (!chunk.trim()) continue;- let event = 'message', data = {};+ let event = 'message',+ data = {};for (const line of chunk.split('\n')) {if (line.startsWith('event:')) event = line.slice(6).trim();- if (line.startsWith('data:')) { try { data = JSON.parse(line.slice(5).trim()); } catch { /* ignore */ } }+ if (line.startsWith('data:')) {+ try {+ data = JSON.parse(line.slice(5).trim());+ } catch {+ /* ignore */+ }+ }}yield { event, data };}@@ -272,56 +284,99 @@ function renderPaymentReceipt(payment) {return el('div', { class: 'aixbt-receipt' }, [el('div', { class: 'aixbt-rrow' }, [el('span', { text: 'Payer → payee' }),- el('span', { class: 'aixbt-rv', text: `${shortAddr(payment.payer)} → ${shortAddr(payment.payTo)}` }),+ el('span', {+ class: 'aixbt-rv',+ text: `${shortAddr(payment.payer)} → ${shortAddr(payment.payTo)}`,+ }),]),el('div', { class: 'aixbt-rrow' }, [el('span', { text: 'Amount · network' }),- el('span', { class: 'aixbt-rv', text: `${payment.amount != null ? fmtUsdc(payment.amount) : '—'} · Solana` }),+ el('span', {+ class: 'aixbt-rv',+ text: `${payment.amount != null ? fmtUsdc(payment.amount) : '—'} · Solana`,+ }),]),- tx ? el('div', { class: 'aixbt-rrow' }, [- el('span', { text: 'Transaction' }),- el('span', { class: 'aixbt-rv' }, [- el('a', { href: `https://solscan.io/tx/${tx}`, target: '_blank', rel: 'noopener', text: `${tx.slice(0, 8)}…${tx.slice(-6)} ↗` }),- ]),- ]) : null,- el('div', { class: 'aixbt-pay-note', text: 'A real USDC micropayment — settled on Solana mainnet, verifiable on-chain.' }),+ tx+ ? el('div', { class: 'aixbt-rrow' }, [+ el('span', { text: 'Transaction' }),+ el('span', { class: 'aixbt-rv' }, [+ el('a', {+ href: `https://solscan.io/tx/${tx}`,+ target: '_blank',+ rel: 'noopener',+ text: `${tx.slice(0, 8)}…${tx.slice(-6)} ↗`,+ }),+ ]),+ ])+ : null,+ el('div', {+ class: 'aixbt-pay-note',+ text: 'A real USDC micropayment — settled on Solana mainnet, verifiable on-chain.',+ }),]);}function renderIntel(items) {- if (!items.length) return el('div', { class: 'aixbt-empty', text: 'No fresh narratives for that filter.' });- return el('div', {}, items.map((i) => el('div', { class: 'aixbt-row' }, [- el('div', { class: 'aixbt-row-top' }, [- i.ticker ? el('span', { class: 'aixbt-tkr', text: `$${i.ticker}` }) : (i.project ? el('span', { class: 'aixbt-tkr', text: i.project }) : null),- i.category ? el('span', { class: 'aixbt-cat', text: i.category }) : null,- ]),- i.description ? el('p', { class: 'aixbt-desc', text: i.description }) : null,- el('div', { class: 'aixbt-meta' }, [- i.observations != null ? el('span', { text: `${i.observations} observation${i.observations === 1 ? '' : 's'}` }) : null,- i.official_source ? el('span', { class: 'aixbt-official', text: '✓ official source' }) : null,- ]),- ])));+ if (!items.length)+ return el('div', { class: 'aixbt-empty', text: 'No fresh narratives for that filter.' });+ return el(+ 'div',+ {},+ items.map((i) =>+ el('div', { class: 'aixbt-row' }, [+ el('div', { class: 'aixbt-row-top' }, [+ i.ticker+ ? el('span', { class: 'aixbt-tkr', text: `$${i.ticker}` })+ : i.project+ ? el('span', { class: 'aixbt-tkr', text: i.project })+ : null,+ i.category ? el('span', { class: 'aixbt-cat', text: i.category }) : null,+ ]),+ i.description ? el('p', { class: 'aixbt-desc', text: i.description }) : null,+ el('div', { class: 'aixbt-meta' }, [+ i.observations != null+ ? el('span', {+ text: `${i.observations} observation${i.observations === 1 ? '' : 's'}`,+ })+ : null,+ i.official_source+ ? el('span', { class: 'aixbt-official', text: '✓ official source' })+ : null,+ ]),+ ]),+ ),+ );}function renderProjects(items) {- if (!items.length) return el('div', { class: 'aixbt-empty', text: 'No projects matched that filter.' });- return el('div', {}, items.map((p) => {- const chg = p.market?.change_24h;- const tone = chg == null ? 'flat' : chg > 0 ? 'up' : chg < 0 ? 'down' : 'flat';- return el('div', { class: 'aixbt-row' }, [- el('div', { class: 'aixbt-row-top' }, [- el('span', { class: 'aixbt-tkr', text: p.ticker ? `$${p.ticker}` : (p.name || 'unknown') }),- p.chain ? el('span', { class: 'aixbt-cat', text: p.chain }) : null,- el('span', { class: `aixbt-chg ${tone}`, text: fmtPct(chg) }),- p.market?.price_usd != null ? el('span', { class: 'aixbt-meta', text: fmtUsd(p.market.price_usd) }) : null,- ]),- el('div', { class: 'aixbt-scores' }, [- scoreBar('Spiking', p.scores?.spiking),- scoreBar('Climbing', p.scores?.climbing),- scoreBar('Active', p.scores?.active),- ]),- ]);- }));+ if (!items.length)+ return el('div', { class: 'aixbt-empty', text: 'No projects matched that filter.' });+ return el(+ 'div',+ {},+ items.map((p) => {+ const chg = p.market?.change_24h;+ const tone = chg == null ? 'flat' : chg > 0 ? 'up' : chg < 0 ? 'down' : 'flat';+ return el('div', { class: 'aixbt-row' }, [+ el('div', { class: 'aixbt-row-top' }, [+ el('span', {+ class: 'aixbt-tkr',+ text: p.ticker ? `$${p.ticker}` : p.name || 'unknown',+ }),+ p.chain ? el('span', { class: 'aixbt-cat', text: p.chain }) : null,+ el('span', { class: `aixbt-chg ${tone}`, text: fmtPct(chg) }),+ p.market?.price_usd != null+ ? el('span', { class: 'aixbt-meta', text: fmtUsd(p.market.price_usd) })+ : null,+ ]),+ el('div', { class: 'aixbt-scores' }, [+ scoreBar('Spiking', p.scores?.spiking),+ scoreBar('Climbing', p.scores?.climbing),+ scoreBar('Active', p.scores?.active),+ ]),+ ]);+ }),+ );}// Grounding comes back as aixbt-shaped structured context. We render it@@ -351,7 +406,11 @@ function renderGroundingValue(value) {if (Array.isArray(value)) {const texts = value.map(groundingItemText).filter(Boolean);if (!texts.length) return null;- return el('ul', { class: 'aixbt-ground-list' }, texts.slice(0, 12).map((t) => el('li', { text: t })));+ return el(+ 'ul',+ { class: 'aixbt-ground-list' },+ texts.slice(0, 12).map((t) => el('li', { text: t })),+ );}if (typeof value === 'object') {// One level of nesting: render child keys as paragraphs/lists.@@ -359,8 +418,11 @@ function renderGroundingValue(value) {.map(([k, v]) => {const inner = Array.isArray(v)? renderGroundingValue(v)- : (typeof v === 'string' || typeof v === 'number')- ? el('p', { class: 'aixbt-ground-p' }, [el('strong', { text: `${humanizeKey(k)}: ` }), String(v)])+ : typeof v === 'string' || typeof v === 'number'+ ? el('p', { class: 'aixbt-ground-p' }, [+ el('strong', { text: `${humanizeKey(k)}: ` }),+ String(v),+ ]): null;return inner;})@@ -387,7 +449,8 @@ function renderGrounding(grounding) {]);}).filter(Boolean);- if (!sections.length) return el('div', { class: 'aixbt-empty', text: 'No macro read available right now.' });+ if (!sections.length)+ return el('div', { class: 'aixbt-empty', text: 'No macro read available right now.' });return el('div', {}, sections);}@@ -398,18 +461,36 @@ export function openAixbtTerminal(npc, { ui } = {}) {closePanel();const titleId = 'aixbt-term-title';- const card = el('div', { class: 'npc-svc-card is-aixbt', role: 'dialog', 'aria-modal': 'true', 'aria-labelledby': titleId });+ const card = el('div', {+ class: 'npc-svc-card is-aixbt',+ role: 'dialog',+ 'aria-modal': 'true',+ 'aria-labelledby': titleId,+ });const overlay = el('div', { class: 'npc-svc-overlay' }, [card]);- overlay.addEventListener('mousedown', (e) => { if (e.target === overlay) closePanel(); });+ overlay.addEventListener('mousedown', (e) => {+ if (e.target === overlay) closePanel();+ });- const close = el('button', { class: 'npc-svc-close', type: 'button', 'aria-label': 'Close', text: '✕', onclick: closePanel });- card.appendChild(el('header', { class: 'npc-svc-head' }, [- el('div', {}, [- npc?.def?.name ? el('div', { class: 'npc-svc-who', text: npc.def.name }) : null,- el('h2', { id: titleId, class: 'npc-svc-title' }, ['Intelligence Terminal', el('span', { class: 'aixbt-live', text: 'LIVE' })]),+ const close = el('button', {+ class: 'npc-svc-close',+ type: 'button',+ 'aria-label': 'Close',+ text: '✕',+ onclick: closePanel,+ });+ card.appendChild(+ el('header', { class: 'npc-svc-head' }, [+ el('div', {}, [+ npc?.def?.name ? el('div', { class: 'npc-svc-who', text: npc.def.name }) : null,+ el('h2', { id: titleId, class: 'npc-svc-title' }, [+ 'Intelligence Terminal',+ el('span', { class: 'aixbt-live', text: 'LIVE' }),+ ]),+ ]),+ close,]),- close,- ]));+ );const body = el('div', { class: 'npc-svc-result', style: 'display:block' });card.appendChild(body);@@ -424,34 +505,70 @@ export function openAixbtTerminal(npc, { ui } = {}) {function backBar(extra) {return el('div', { class: 'aixbt-toolbar' }, [- el('button', { class: 'aixbt-back', type: 'button', text: '← Ask again', onclick: showMenu }),+ el('button', {+ class: 'aixbt-back',+ type: 'button',+ text: '← Ask again',+ onclick: showMenu,+ }),extra || null,]);}function chainChips(active, onPick) {- return el('div', { class: 'aixbt-chips' }, CHAINS.map((c) =>- el('button', {- class: `aixbt-chip${c.value === active ? ' is-on' : ''}`,- type: 'button',- text: c.label,- onclick: () => { if (c.value !== active && !busy) onPick(c.value); },- })));+ return el(+ 'div',+ { class: 'aixbt-chips' },+ CHAINS.map((c) =>+ el('button', {+ class: `aixbt-chip${c.value === active ? ' is-on' : ''}`,+ type: 'button',+ text: c.label,+ onclick: () => {+ if (c.value !== active && !busy) onPick(c.value);+ },+ }),+ ),+ );}function showError(err, retry) {body.textContent = '';body.appendChild(backBar());if (err?.code === 'aixbt_not_configured') {- body.appendChild(el('div', { class: 'aixbt-error', text: "aixbt isn't connected on this deployment yet." }));+ body.appendChild(+ el('div', {+ class: 'aixbt-error',+ text: "aixbt isn't connected on this deployment yet.",+ }),+ );if (err.setup) body.appendChild(el('div', { class: 'aixbt-setup', text: err.setup }));- npc?.say?.('My feed isn\'t wired up here yet.');+ npc?.say?.("My feed isn't wired up here yet.");} else if (err?.code === 'aixbt_unauthorized') {- body.appendChild(el('div', { class: 'aixbt-error', text: 'That read needs a higher aixbt plan than this key has.' }));- npc?.say?.('My key can\'t reach that one.');+ body.appendChild(+ el('div', {+ class: 'aixbt-error',+ text: 'That read needs a higher aixbt plan than this key has.',+ }),+ );+ npc?.say?.("My key can't reach that one.");} else {- body.appendChild(el('div', { class: 'aixbt-error', text: `Couldn't reach the aixbt feed: ${err.message}` }));- if (retry) body.appendChild(el('button', { class: 'aixbt-go', type: 'button', text: 'Retry', style: 'margin-top:10px', onclick: retry }));+ body.appendChild(+ el('div', {+ class: 'aixbt-error',+ text: `Couldn't reach the aixbt feed: ${err.message}`,+ }),+ );+ if (retry)+ body.appendChild(+ el('button', {+ class: 'aixbt-go',+ type: 'button',+ text: 'Retry',+ style: 'margin-top:10px',+ onclick: retry,+ }),+ );ui?.toast?.('aixbt feed unavailable', 'warn');}}@@ -467,12 +584,23 @@ export function openAixbtTerminal(npc, { ui } = {}) {const { projects = [] } = await fetchJson(`/api/aixbt/projects?${qs}`);body.textContent = '';body.appendChild(backBar(chainChips(chain, runMovers)));- body.appendChild(el('div', { class: 'aixbt-section-h', text: chain ? `Momentum · ${chain}` : 'Momentum' }));+ body.appendChild(+ el('div', {+ class: 'aixbt-section-h',+ text: chain ? `Momentum · ${chain}` : 'Momentum',+ }),+ );body.appendChild(renderProjects(projects));- npc?.say?.(projects.length ? `Top mover is ${projects[0].ticker ? '$' + projects[0].ticker : projects[0].name}.` : 'Quiet on that chain — try another.');+ npc?.say?.(+ projects.length+ ? `Top mover is ${projects[0].ticker ? '$' + projects[0].ticker : projects[0].name}.`+ : 'Quiet on that chain — try another.',+ );} catch (err) {showError(err, () => runMovers(chain));- } finally { busy = false; }+ } finally {+ busy = false;+ }}async function runNarratives(chain) {@@ -485,12 +613,23 @@ export function openAixbtTerminal(npc, { ui } = {}) {const { intel = [] } = await fetchJson(`/api/aixbt/intel?${qs}`);body.textContent = '';body.appendChild(backBar(chainChips(chain, runNarratives)));- body.appendChild(el('div', { class: 'aixbt-section-h', text: chain ? `Narratives · ${chain}` : 'Narratives' }));+ body.appendChild(+ el('div', {+ class: 'aixbt-section-h',+ text: chain ? `Narratives · ${chain}` : 'Narratives',+ }),+ );body.appendChild(renderIntel(intel));- npc?.say?.(intel.length ? `Tracking ${intel.length} narrative${intel.length === 1 ? '' : 's'} right now.` : 'No fresh narratives on that filter.');+ npc?.say?.(+ intel.length+ ? `Tracking ${intel.length} narrative${intel.length === 1 ? '' : 's'} right now.`+ : 'No fresh narratives on that filter.',+ );} catch (err) {showError(err, () => runNarratives(chain));- } finally { busy = false; }+ } finally {+ busy = false;+ }}async function runMacro() {@@ -503,21 +642,29 @@ export function openAixbtTerminal(npc, { ui } = {}) {body.appendChild(backBar());body.appendChild(el('div', { class: 'aixbt-section-h', text: 'Market context' }));body.appendChild(renderGrounding(grounding));- npc?.say?.('That\'s the read across crypto and tradfi.');+ npc?.say?.("That's the read across crypto and tradfi.");} catch (err) {showError(err, runMacro);- } finally { busy = false; }+ } finally {+ busy = false;+ }}async function runScan(token, chain) {if (busy) return;const q = (token || '').trim();- if (!q) { showScan(token, chain); return; }+ if (!q) {+ showScan(token, chain);+ return;+ }busy = true;skeleton(`Scanning ${q.toUpperCase()}`);const projQs = new URLSearchParams({ limit: '6', names: q });const intelQs = new URLSearchParams({ limit: '6' });- if (chain) { projQs.set('chain', chain); intelQs.set('chain', chain); }+ if (chain) {+ projQs.set('chain', chain);+ intelQs.set('chain', chain);+ }try {const [projRes, intelRes] = await Promise.all([fetchJson(`/api/aixbt/projects?${projQs}`),@@ -526,20 +673,32 @@ export function openAixbtTerminal(npc, { ui } = {}) {const projects = projRes.projects || [];// Intel isn't name-filterable upstream; keep items that mention the token.const ql = q.toLowerCase();- const intel = (intelRes.intel || []).filter((i) =>- (i.ticker && i.ticker.toLowerCase() === ql) ||- (i.project && i.project.toLowerCase().includes(ql)) ||- (i.description && i.description.toLowerCase().includes(ql)));+ const intel = (intelRes.intel || []).filter(+ (i) =>+ (i.ticker && i.ticker.toLowerCase() === ql) ||+ (i.project && i.project.toLowerCase().includes(ql)) ||+ (i.description && i.description.toLowerCase().includes(ql)),+ );body.textContent = '';body.appendChild(backBar());- body.appendChild(el('div', { class: 'aixbt-section-h', text: `Momentum · ${q.toUpperCase()}` }));+ body.appendChild(+ el('div', { class: 'aixbt-section-h', text: `Momentum · ${q.toUpperCase()}` }),+ );body.appendChild(renderProjects(projects));- body.appendChild(el('div', { class: 'aixbt-section-h', text: `Narratives · ${q.toUpperCase()}` }));+ body.appendChild(+ el('div', { class: 'aixbt-section-h', text: `Narratives · ${q.toUpperCase()}` }),+ );body.appendChild(renderIntel(intel));- npc?.say?.(projects.length || intel.length ? `Here's what I have on ${q.toUpperCase()}.` : `Nothing surfacing on ${q.toUpperCase()} yet.`);+ npc?.say?.(+ projects.length || intel.length+ ? `Here's what I have on ${q.toUpperCase()}.`+ : `Nothing surfacing on ${q.toUpperCase()} yet.`,+ );} catch (err) {showError(err, () => runScan(q, chain));- } finally { busy = false; }+ } finally {+ busy = false;+ }}// ── live on-chain payment (the showcase read) ──────────────────────────────@@ -555,10 +714,15 @@ export function openAixbtTerminal(npc, { ui } = {}) {body.appendChild(backBar());body.appendChild(el('div', { class: 'aixbt-section-h', text: 'Live on-chain payment' }));const amtEl = el('span', { class: 'aixbt-pay-amt', text: '— USDC' });- body.appendChild(el('div', { class: 'aixbt-pay-head' }, [- el('span', { class: 'aixbt-pay-who', html: '<b>three.ws</b> pays for a live read' }),- amtEl,- ]));+ body.appendChild(+ el('div', { class: 'aixbt-pay-head' }, [+ el('span', {+ class: 'aixbt-pay-who',+ html: '<b>three.ws</b> pays for a live read',+ }),+ amtEl,+ ]),+ );const stepsEl = el('div', { class: 'aixbt-steps' });const tail = el('div', {});body.appendChild(stepsEl);@@ -573,15 +737,25 @@ export function openAixbtTerminal(npc, { ui } = {}) {if (errId === s.id) cls = 'is-err';else if (activeId === 'done' || i < ai) cls = 'is-done';else if (i === ai) cls = 'is-active';- stepsEl.appendChild(el('div', { class: `aixbt-step ${cls}` }, [el('span', { class: 'aixbt-step-dot' }), s.label]));+ stepsEl.appendChild(+ el('div', { class: `aixbt-step ${cls}` }, [+ el('span', { class: 'aixbt-step-dot' }),+ s.label,+ ]),+ );});if (amount != null) amtEl.textContent = fmtUsdc(amount);};let active = 'challenge';paint(active);+ // Mirror the same lifecycle on the small left-edge HUD so the payment is+ // visible (and lands its receipt) from the corner of the screen even if the+ // player closes this terminal mid-settlement.+ aixbtPayHud.begin();- let settled = null, result = null;+ let settled = null,+ result = null;try {const res = await fetch('/api/x402-pay', {method: 'POST',@@ -590,35 +764,91 @@ export function openAixbtTerminal(npc, { ui } = {}) {});if (!res.ok || !res.body) {const txt = await res.text().catch(() => '');- let msg = `payment service unavailable (${res.status})`, code = null;- try { const j = JSON.parse(txt); msg = j.error_description || j.error || msg; code = j.error; } catch { /* ignore */ }+ let msg = `payment service unavailable (${res.status})`,+ code = null;+ try {+ const j = JSON.parse(txt);+ msg = j.error_description || j.error || msg;+ code = j.error;+ } catch {+ /* ignore */+ }const notWired = res.status === 404 || code === 'config_missing';- throw Object.assign(new Error(msg), { code: notWired ? 'pay_not_configured' : `http_${res.status}` });+ throw Object.assign(new Error(msg), {+ code: notWired ? 'pay_not_configured' : `http_${res.status}`,+ });}for await (const { event, data } of sseEvents(res)) {- if (event === 'challenge') { amount = data.amount; active = 'built'; paint(active); npc?.say?.('Challenge issued — signing the transfer.'); }- else if (event === 'built') { active = 'verified'; paint(active); npc?.say?.('Signed. Sent to the facilitator.'); }- else if (event === 'verified') { active = 'settled'; paint(active); npc?.say?.('Verified — waiting on settlement.'); }- else if (event === 'settled') { settled = data; active = 'done'; paint(active); }- else if (event === 'result') { result = data; }- else if (event === 'error') { throw new Error(data.error || 'payment failed'); }+ if (event === 'challenge') {+ amount = data.amount;+ active = 'built';+ paint(active);+ aixbtPayHud.setStage(active, amount);+ npc?.say?.('Challenge issued — signing the transfer.');+ } else if (event === 'built') {+ active = 'verified';+ paint(active);+ aixbtPayHud.setStage(active);+ npc?.say?.('Signed. Sent to the facilitator.');+ } else if (event === 'verified') {+ active = 'settled';+ paint(active);+ aixbtPayHud.setStage(active);+ npc?.say?.('Verified — waiting on settlement.');+ } else if (event === 'settled') {+ settled = data;+ active = 'done';+ paint(active);+ aixbtPayHud.setStage(active);+ } else if (event === 'result') {+ result = data;+ } else if (event === 'error') {+ throw new Error(data.error || 'payment failed');+ }}if (!settled) throw new Error('incomplete response from payment service');const payment = { ...(result?.payment || {}), ...settled };paint('done');tail.appendChild(renderPaymentReceipt(payment));+ aixbtPayHud.settle(payment);npc?.say?.('Settled on Solana — open it on Solscan.');} catch (err) {paint(active, active);tail.textContent = '';const configErr = err?.code === 'pay_not_configured';- tail.appendChild(el('div', { class: 'aixbt-pay-note is-err', text: configErr- ? "The on-chain payer isn't wired up on this deployment yet."- : `Payment didn't go through: ${err.message}. No funds moved.` }));- if (!configErr) tail.appendChild(el('button', { class: 'aixbt-go', type: 'button', text: 'Try again', style: 'margin-top:10px', onclick: runPayment }));- npc?.say?.(configErr ? "My wallet isn't funded here yet." : 'That one rolled back — wallet unchanged.');+ aixbtPayHud.fail(+ configErr+ ? 'Payer not wired up on this deployment.'+ : `Rolled back: ${err.message}. No funds moved.`,+ active,+ );+ tail.appendChild(+ el('div', {+ class: 'aixbt-pay-note is-err',+ text: configErr+ ? "The on-chain payer isn't wired up on this deployment yet."+ : `Payment didn't go through: ${err.message}. No funds moved.`,+ }),+ );+ if (!configErr)+ tail.appendChild(+ el('button', {+ class: 'aixbt-go',+ type: 'button',+ text: 'Try again',+ style: 'margin-top:10px',+ onclick: runPayment,+ }),+ );+ npc?.say?.(+ configErr+ ? "My wallet isn't funded here yet."+ : 'That one rolled back — wallet unchanged.',+ );ui?.toast?.(configErr ? 'x402 payer not configured' : 'x402 payment failed', 'warn');- } finally { busy = false; }+ } finally {+ busy = false;+ }}// ── scan sub-form (the "type what you want" step) ──────────────────────────@@ -626,13 +856,33 @@ export function openAixbtTerminal(npc, { ui } = {}) {body.textContent = '';body.appendChild(backBar());body.appendChild(el('p', { class: 'aixbt-ask', text: 'Which token should I scan?' }));- const tokenInput = el('input', { class: 'npc-svc-input aixbt-token', type: 'text', placeholder: 'Token or ticker (e.g. SOL)', value: prevToken || '' });- const chainSelect = el('select', { class: 'npc-svc-input aixbt-chain' }, CHAINS.map((c) =>- el('option', { value: c.value, selected: c.value === (prevChain || '') ? true : null }, [c.label])));+ const tokenInput = el('input', {+ class: 'npc-svc-input aixbt-token',+ type: 'text',+ placeholder: 'Token or ticker (e.g. SOL)',+ value: prevToken || '',+ });+ const chainSelect = el(+ 'select',+ { class: 'npc-svc-input aixbt-chain' },+ CHAINS.map((c) =>+ el(+ 'option',+ { value: c.value, selected: c.value === (prevChain || '') ? true : null },+ [c.label],+ ),+ ),+ );const goBtn = el('button', { class: 'aixbt-go', type: 'button', text: 'Scan' });// Keep typing out of the world's movement handlers (window-level keydown).for (const node of [tokenInput, chainSelect]) {- node.addEventListener('keydown', (e) => { e.stopPropagation(); if (e.key === 'Enter') { e.preventDefault(); runScan(tokenInput.value, chainSelect.value); } });+ node.addEventListener('keydown', (e) => {+ e.stopPropagation();+ if (e.key === 'Enter') {+ e.preventDefault();+ runScan(tokenInput.value, chainSelect.value);+ }+ });node.addEventListener('keyup', (e) => e.stopPropagation());}goBtn.addEventListener('click', () => runScan(tokenInput.value, chainSelect.value));@@ -653,26 +903,57 @@ export function openAixbtTerminal(npc, { ui } = {}) {function showMenu() {body.textContent = '';- body.appendChild(el('p', { class: 'aixbt-ask', text: 'What do you want to see? Pick a read — or press 1–5.' }));- const menu = el('div', { class: 'aixbt-menu' }, CHOICES.map((c, idx) =>- el('button', { class: `aixbt-choice${c.wide ? ' is-wide' : ''}`, type: 'button', onclick: () => pick(c), 'aria-label': c.title }, [- el('span', { class: 'aixbt-choice-ic', text: c.icon }),- el('span', { class: 'aixbt-choice-body' }, [- el('span', { class: 'aixbt-choice-t' }, [el('span', { class: 'aixbt-num', text: String(idx + 1) }), c.title]),- el('span', { class: 'aixbt-choice-d', text: c.desc }),- ]),- ])));+ body.appendChild(+ el('p', {+ class: 'aixbt-ask',+ text: 'What do you want to see? Pick a read — or press 1–5.',+ }),+ );+ const menu = el(+ 'div',+ { class: 'aixbt-menu' },+ CHOICES.map((c, idx) =>+ el(+ 'button',+ {+ class: `aixbt-choice${c.wide ? ' is-wide' : ''}`,+ type: 'button',+ onclick: () => pick(c),+ 'aria-label': c.title,+ },+ [+ el('span', { class: 'aixbt-choice-ic', text: c.icon }),+ el('span', { class: 'aixbt-choice-body' }, [+ el('span', { class: 'aixbt-choice-t' }, [+ el('span', { class: 'aixbt-num', text: String(idx + 1) }),+ c.title,+ ]),+ el('span', { class: 'aixbt-choice-d', text: c.desc }),+ ]),+ ],+ ),+ ),+ );body.appendChild(menu);- requestAnimationFrame(() => { const first = menu.querySelector('.aixbt-choice'); if (first) first.focus(); });+ requestAnimationFrame(() => {+ const first = menu.querySelector('.aixbt-choice');+ if (first) first.focus();+ });}// Number-key shortcuts (1–4) while the menu is the active view.const onKey = (e) => {- if (e.key === 'Escape') { e.stopPropagation(); e.preventDefault(); closePanel(); return; }+ if (e.key === 'Escape') {+ e.stopPropagation();+ e.preventDefault();+ closePanel();+ return;+ }if (busy) return;const onMenu = body.querySelector('.aixbt-menu');if (onMenu && e.key >= '1' && e.key <= String(CHOICES.length)) {- e.stopPropagation(); e.preventDefault();+ e.stopPropagation();+ e.preventDefault();pick(CHOICES[Number(e.key) - 1]);}};diff --git a/src/solana/vanity/grinder.js b/src/solana/vanity/grinder.jsindex 04094c13c..d59b40d08 100644--- a/src/solana/vanity/grinder.js+++ b/src/solana/vanity/grinder.js@@ -20,7 +20,7 @@* change to refresh `src/solana/vanity/wasm/`.*/-import { validatePattern, estimateAttempts, formatTimeEstimate } from './validation.js';+import { validatePattern, expectedAttempts, formatTimeEstimate } from './validation.js';const DEFAULT_MAX_WORKERS = 8;@@ -83,7 +83,7 @@ export function grindVanity(opts = {}) {// peg every core by surprise.const requested = opts.maxWorkers || Math.min(hardware, DEFAULT_MAX_WORKERS);const cores = Math.max(1, Math.min(requested, hardware));- const expected = estimateAttempts((prefix?.length || 0) + (suffix?.length || 0));+ const expected = expectedAttempts(prefix, suffix, ignoreCase);const startedAt = performance.now();/** @type {Worker[]} */diff --git a/src/solana/vanity/validation.js b/src/solana/vanity/validation.jsindex 23f74c707..98aff96cb 100644--- a/src/solana/vanity/validation.js+++ b/src/solana/vanity/validation.js@@ -60,6 +60,54 @@ export function estimateAttempts(length) {return Math.pow(58, length);}+/**+ * How many of the 58 Base58 characters satisfy a single requested character.+ *+ * Case-sensitive matching: exactly one. Case-insensitive matching: two when+ * the character is a letter whose other case is *also* a valid Base58 symbol+ * (the alphabet drops `0 O I l`, so e.g. `o`/`O`, `i`/`I`, `L`/`l` only have a+ * single valid case and stay at one).+ * @param {string} ch+ * @param {boolean} ignoreCase+ * @returns {number}+ */+function matchesPerChar(ch, ignoreCase) {+ if (!ignoreCase) return 1;+ const lower = ch.toLowerCase();+ const upper = ch.toUpperCase();+ if (lower !== upper && BASE58_CHARS.has(lower) && BASE58_CHARS.has(upper)) return 2;+ return 1;+}++/**+ * Expected attempts to grind an address that starts with `prefix` and ends+ * with `suffix`, accounting for case-insensitivity per character. This is the+ * mean of a geometric distribution: the reciprocal of the per-address match+ * probability.+ * @param {string} [prefix]+ * @param {string} [suffix]+ * @param {boolean} [ignoreCase=false]+ * @returns {number}+ */+export function expectedAttempts(prefix = '', suffix = '', ignoreCase = false) {+ let attempts = 1;+ for (const ch of (prefix || '') + (suffix || '')) {+ attempts *= 58 / matchesPerChar(ch, ignoreCase);+ }+ return attempts;+}++/**+ * The case-sensitive prefix length whose difficulty matches the given+ * expected-attempts count — i.e. log₅₈(attempts). Used to tier patterns+ * (fast vs. slow) consistently whether or not case-insensitivity is on.+ * @param {number} attempts+ * @returns {number}+ */+export function effectiveLength(attempts) {+ return attempts <= 1 ? 0 : Math.log(attempts) / Math.log(58);+}+/*** Format a duration estimate (seconds) as a human string.* @param {number} attempts expected attempts