Skip to content

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.

feat(ibm-mcp,evm-wallet,avatar-studio): getting-started MCP tool, EVM wallet page, mesh optimizer

nirholase3498f880540
diff --git a/api/_mcpibm/catalog.js b/api/_mcpibm/catalog.js
index 95f9d8c1b..775809949 100644
--- a/api/_mcpibm/catalog.js
+++ b/api/_mcpibm/catalog.js
@@ -51,6 +51,15 @@ export const TOOL_CATALOG = toolDefs.map((def) => {
return entry;
});
+// Registered tools that carry no price — callable with neither an x402 payment
+// nor an OAuth token. Currently just ibm_granite_getting_started. api/ibm-mcp.js
+// reads this to serve a free, public entry point without the auth/payment gate.
+const FREE_TOOLS = new Set(toolDefs.filter((def) => !priceFor(def.name)).map((def) => def.name));
+
+export function isFreeTool(toolName) {
+ return FREE_TOOLS.has(toolName);
+}
+
// Handler + compiled validator lookup for tools/call.
export const TOOLS = Object.fromEntries(
toolDefs.map((def) => [
diff --git a/api/_mcpibm/dispatch.js b/api/_mcpibm/dispatch.js
index c3610da81..426ec5e36 100644
--- a/api/_mcpibm/dispatch.js
+++ b/api/_mcpibm/dispatch.js
@@ -9,6 +9,7 @@ export { PROTOCOL_VERSION };
const INSTRUCTIONS = [
'x402 pay-per-use IBM Granite AI from three.ws — each tool lists its USDC price; pay per call on Base or Solana, no IBM Cloud account required.',
+ 'New here? Call ibm_granite_getting_started — FREE, no payment or account — for an overview, prices, and the payment flow.',
'ibm_granite_chat(messages) — conversational AI ($0.02).',
'ibm_granite_code(task, prompt) — generate/review/refactor/explain/test/document code ($0.025).',
'ibm_granite_embed(inputs) — batch multilingual embeddings for RAG/search ($0.005).',
diff --git a/api/_mcpibm/tools.js b/api/_mcpibm/tools.js
index 02ecf3ba6..7e1bda92b 100644
--- a/api/_mcpibm/tools.js
+++ b/api/_mcpibm/tools.js
@@ -44,6 +44,111 @@ function toolResult(humanText, structured) {
};
}
+// ──────────────────────── getting started (FREE) ────────────────────────────
+//
+// The one tool with no price. It is deliberately excluded from TOOL_PRICING so
+// graniteX402Amount() returns null and api/ibm-mcp.js serves it without an x402
+// payment or OAuth token — a public entry point any client (including non-x402
+// hosts like watsonx Orchestrate) can call to discover the server before paying.
+// Mirrors the npm package's ibm_granite_getting_started tool.
+
+const GETTING_STARTED_DESCRIPTION =
+ 'FREE — start here. Returns an overview of this server: the IBM Granite tools available, ' +
+ 'their per-call USDC prices, how the x402 pay-per-call flow works, and runnable example calls. ' +
+ 'No payment or account required. Call this first to orient before invoking a paid tool.';
+
+const GS_TOOLS = [
+ { name: 'ibm_granite_chat', price: '$0.02', summary: 'Conversational AI via IBM Granite 3 8B Instruct.' },
+ { name: 'ibm_granite_code', price: '$0.025', summary: 'Code generate / review / refactor / explain / test / document.' },
+ { name: 'ibm_granite_embed', price: '$0.005', summary: 'Batch multilingual text embeddings for RAG and search.' },
+ { name: 'ibm_granite_analyze', price: '$0.04', summary: 'Structured document analysis: entities, sentiment, risk, summary, next steps.' },
+ { name: 'ibm_granite_forecast', price: '$0.05', summary: 'Zero-shot time-series forecasting via IBM Granite TTM.' },
+];
+
+const GS_PAYMENT_FLOW = [
+ 'Call any ibm_granite_* tool. With no payment, the server returns an x402 PaymentRequired envelope quoting the exact USDC price and a pay-to address (Base or Solana).',
+ 'Your x402 client signs a USDC transfer for that amount and retries with the payment attached.',
+ 'The server verifies + settles the payment, runs the IBM watsonx.ai inference, and returns the result with a settlement receipt. x402-capable clients do this automatically.',
+ 'Authenticated three.ws principals (Bearer/OAuth) call the paid tools without per-call payment — the operator-funded path for watsonx Orchestrate connections.',
+];
+
+const GS_LINKS = {
+ homepage: 'https://three.ws',
+ npm: 'https://www.npmjs.com/package/@three-ws/ibm-x402-mcp',
+ source: 'https://github.com/nirholas/three.ws/tree/main/packages/ibm-x402-mcp',
+ support: 'https://three.ws/support',
+ x402: 'https://x402.org',
+};
+
+function gettingStartedPayload(section) {
+ const full = {
+ ok: true,
+ server: 'ibm-x402-mcp',
+ version: '1.0.0',
+ transport: 'streamable-http',
+ overview:
+ 'x402 pay-per-use IBM Granite AI over MCP. Five inference tools, each settled in USDC on ' +
+ 'Base or Solana via the x402 protocol — no IBM Cloud account required for callers. This tool ' +
+ 'is free; every other tool quotes its price below.',
+ tools: GS_TOOLS,
+ pricing: GS_TOOLS.map((t) => `${t.name}: ${t.price}/call`),
+ payment_flow: GS_PAYMENT_FLOW,
+ links: GS_LINKS,
+ next_step:
+ 'Pick a tool, send its arguments, and your x402 client handles the USDC payment automatically. ' +
+ 'Or authenticate with a three.ws Bearer token for the operator-funded path.',
+ };
+ if (section === 'pricing') return { ok: true, pricing: full.pricing, tools: GS_TOOLS };
+ if (section === 'payment') return { ok: true, payment_flow: GS_PAYMENT_FLOW };
+ if (section === 'tools') return { ok: true, tools: GS_TOOLS };
+ if (section === 'links') return { ok: true, links: GS_LINKS };
+ return full;
+}
+
+function gettingStartedText(p) {
+ if (!p.overview) return JSON.stringify(p, null, 2);
+ return [
+ '# IBM Granite x402 MCP — Getting Started',
+ '',
+ p.overview,
+ '',
+ '## Tools (this getting_started tool is free; the rest are pay-per-call)',
+ ...p.tools.map((t) => `- ${t.name} — ${t.price}/call — ${t.summary}`),
+ '',
+ '## How payment works (x402)',
+ ...p.payment_flow.map((s, i) => `${i + 1}. ${s}`),
+ '',
+ '## Links',
+ ...Object.entries(p.links).map(([k, v]) => `- ${k}: ${v}`),
+ '',
+ `Next: ${p.next_step}`,
+ ].join('\n');
+}
+
+const gettingStartedTool = {
+ name: 'ibm_granite_getting_started',
+ title: 'Getting Started (free)',
+ description: GETTING_STARTED_DESCRIPTION,
+ inputSchema: {
+ type: 'object',
+ additionalProperties: false,
+ properties: {
+ section: {
+ type: 'string',
+ enum: ['overview', 'pricing', 'payment', 'tools', 'links'],
+ default: 'overview',
+ description:
+ 'Which part to return. Defaults to "overview" (everything). Use "pricing", "payment", "tools", or "links" to focus.',
+ },
+ },
+ },
+ example: { section: 'overview' },
+ async handler({ section = 'overview' } = {}) {
+ const payload = gettingStartedPayload(section);
+ return toolResult(gettingStartedText(payload), payload);
+ },
+};
+
// ───────────────────────────────── chat ─────────────────────────────────────
const CHAT_DESCRIPTION =
@@ -522,4 +627,11 @@ const forecastTool = {
},
};
-export const toolDefs = [chatTool, codeTool, embedTool, analyzeTool, forecastTool];
+export const toolDefs = [
+ gettingStartedTool,
+ chatTool,
+ codeTool,
+ embedTool,
+ analyzeTool,
+ forecastTool,
+];
diff --git a/api/ibm-mcp.js b/api/ibm-mcp.js
index 4bb49c7b0..e1d8cd976 100644
--- a/api/ibm-mcp.js
+++ b/api/ibm-mcp.js
@@ -3,8 +3,10 @@
//
// The hosted (remote) transport for the @three-ws/ibm-x402-mcp tool suite: five
// IBM Granite tools (chat, code, embed, analyze, forecast) gated by per-call
-// x402 payments. End users pay USDC on Base or Solana per call — no IBM Cloud
-// account required; the operator funds watsonx.ai via WATSONX_* env vars.
+// x402 payments, plus a free ibm_granite_getting_started tool served without any
+// payment or token so any client can discover the server first. End users pay
+// USDC on Base or Solana per paid call — no IBM Cloud account required; the
+// operator funds watsonx.ai via WATSONX_* env vars.
// Authenticated three.ws principals (Bearer / OAuth) call without per-call
// payment — the operator-funded path for watsonx Orchestrate connections.
// Registered with the MCP Registry as io.github.nirholas/ibm-x402-mcp-remote
@@ -14,6 +16,7 @@ import { limits, clientIp } from './_lib/rate-limit.js';
import { settlePayment, encodePaymentResponseHeader } from './_lib/x402-spec.js';
import { PROTOCOL_VERSION, dispatch } from './_mcpibm/dispatch.js';
import { graniteX402Amount } from './_mcpibm/pricing.js';
+import { isFreeTool } from './_mcpibm/catalog.js';
import { GRANITE_CHALLENGE } from './_mcpibm/discovery.js';
import {
send401,
@@ -58,6 +61,27 @@ export default wrap(async (req, res) => {
const { toolName } = peekCalledTool(body);
const x402Amount = toolName ? graniteX402Amount(toolName) : null;
+ // Free, public entry point: a single tools/call to a registered free tool
+ // (ibm_granite_getting_started) skips the x402/OAuth gate so any client —
+ // including non-x402 hosts like watsonx Orchestrate — can discover the server
+ // before paying. IP rate-limited like every other path so it can't be abused.
+ if (toolName && isFreeTool(toolName)) {
+ const ipRl = await limits.mcpIp(clientIp(req));
+ if (!ipRl.success)
+ return sendJsonRpcError(res, null, -32000, 'rate_limited', {
+ retry_after: Math.ceil((ipRl.reset - Date.now()) / 1000),
+ });
+
+ const auth = { userId: null, rateKey: `free:${clientIp(req)}`, scope: '', source: 'free' };
+ const r = await dispatch(Array.isArray(body) ? body[0] : body, auth, req);
+
+ res.statusCode = 200;
+ res.setHeader('content-type', 'application/json; charset=utf-8');
+ res.setHeader('mcp-protocol-version', PROTOCOL_VERSION);
+ res.end(JSON.stringify(Array.isArray(body) ? [r].filter((x) => x !== null) : (r ?? null)));
+ return;
+ }
+
const result = await authenticateRequest(req, res, {
x402Amount,
resourcePath: RESOURCE_PATH,
diff --git a/avatar-sdk/README.md b/avatar-sdk/README.md
index 2597e5ac2..3cf8c76ae 100644
--- a/avatar-sdk/README.md
+++ b/avatar-sdk/README.md
@@ -1,6 +1,6 @@
# @three-ws/avatar
-3D avatar viewer, creator iframe, and emotion + lipsync runtime — a drop-in replacement for the Ready Player Me SDK now that RPM was acquired and is no longer accepting new accounts.
+3D avatar viewer, creator iframe, and emotion + lipsync runtime — a drop-in replacement for legacy hosted avatar SDKs that are winding down or no longer accepting new accounts.
Includes:
@@ -53,9 +53,9 @@ creator.open();
If you have a previously created avatar and want to re-open it for editing, first call your backend's `/api/avatars/:id/session` (which POSTs to Avaturn under the hood) and pass `avaturnSessionUrl` to the constructor.
-## What this gives you that Ready Player Me did
+## What this gives you that legacy avatar SDKs did
-| RPM feature | `@three-ws/avatar` equivalent |
+| Legacy SDK feature | `@three-ws/avatar` equivalent |
|---|---|
| Photo → 3D avatar | `AvatarCreator` → Avaturn pipeline |
| In-browser avatar editor | `AvatarCreator` → [Character Studio](https://studio.three.ws) |
diff --git a/docs/agent-briefs/W-world-online/README.md b/docs/agent-briefs/W-world-online/README.md
index 578ca64a1..80bc24459 100644
--- a/docs/agent-briefs/W-world-online/README.md
+++ b/docs/agent-briefs/W-world-online/README.md
@@ -20,7 +20,7 @@ avatar customization, and living NPCs — wallet-native to `$THREE`.
|-------|---------|------------|
| [W01](W01-open-world-foundation.md) | Open-world foundation (drivable, physics, day/night) | — |
| [W02](W02-vehicles-and-driving.md) | Vehicles & driving (Rapier raycast vehicle, networked) | W01 |
-| [W03](W03-character-avatar-customization.md) | Character & avatar customization (RPM + selfie→3D + wardrobe) | — |
+| [W03](W03-character-avatar-customization.md) | Character & avatar customization (avatar creator + selfie→3D + wardrobe) | — |
| [W04](W04-economy-and-money.md) | Economy & money (cash, bank/ATM, vendors, `$THREE` bridge) | — |
| [W05](W05-jobs-missions-heists.md) | Jobs, missions & heists (data-driven quest engine) | W04 |
| [W06](W06-activities-and-minigames.md) | Activities & minigames (gather/craft loop, races, arcade) | W04 (W02 for races) |
diff --git a/docs/agent-briefs/W-world-online/W00-program-overview.md b/docs/agent-briefs/W-world-online/W00-program-overview.md
index cc2ab5c57..d6dcf218d 100644
--- a/docs/agent-briefs/W-world-online/W00-program-overview.md
+++ b/docs/agent-briefs/W-world-online/W00-program-overview.md
@@ -60,7 +60,7 @@ justification in your brief's PR.
| Authoritative multiplayer | `colyseus` / `@colyseus/schema` | Already in `multiplayer/`. Extend WalkRoom or add sibling rooms. |
| Fast world collision / raycast | `three-mesh-bvh` | For large static world meshes (streets, buildings). |
| NPC navigation | `three-pathfinding` (donmccurdy) | Navmesh for pedestrians, traffic, quest NPCs, mob AI. |
-| Customizable full-body avatars | **Ready Player Me** SDK + our existing GLB/VRM pipeline + `/scan` selfie→3D | We already load GLB/VRM and have a selfie→3D pipeline (memory `scan-to-3d-pipeline`). RPM adds a wardrobe. |
+| Customizable full-body avatars | A third-party full-body avatar SDK + our existing GLB/VRM pipeline + `/scan` selfie→3D | We already load GLB/VRM and have a selfie→3D pipeline (memory `scan-to-3d-pipeline`). The SDK adds a wardrobe. |
| Character animation | three.js `AnimationMixer` + Mixamo clips (already wired in `avatar-rig.js`) | Reuse the emote/anim manifest system. |
| Reference architecture (vehicles + ECS netcode) | [iErcann/Notblox](https://github.com/iErcann/Notblox) | three.js + Node + Rapier + ECS, cars/city/players, GTA/Roblox-like. **Read it for patterns; do not fork wholesale.** |
@@ -144,7 +144,7 @@ Build roughly in this order; later briefs assume earlier foundations.
|-------|---------|------------|
| **W01** | Open-world foundation (drivable streamed world, physics, day/night) | — |
| **W02** | Vehicles & driving (Rapier raycast vehicle, enter/exit, networked) | W01 |
-| **W03** | Character & avatar customization (Ready Player Me + selfie→3D + wardrobe) | — |
+| **W03** | Character & avatar customization (avatar creator + selfie→3D + wardrobe) | — |
| **W04** | Economy & money (cash, bank/ATM, sell/buy vendors, `$THREE` sink/faucet) | — |
| **W05** | Jobs, missions & heists (data-driven quest engine, solo + co-op) | W04 |
| **W06** | Activities & minigames (gather/craft loop, races, arcade) | W04 (W02 for races) |
diff --git a/packages/ibm-x402-mcp/CATALOG.md b/packages/ibm-x402-mcp/CATALOG.md
index 9163a2618..48f68ef3e 100644
--- a/packages/ibm-x402-mcp/CATALOG.md
+++ b/packages/ibm-x402-mcp/CATALOG.md
@@ -32,7 +32,9 @@ Source of truth for the published listing — keep in sync with `server.json`, `
three.ws x402 MCP turns IBM Granite foundation models into pay-per-use tools any AI agent or MCP client (Claude Desktop, Claude Code, Cursor, watsonx Orchestrate) can call. Every call is settled in USDC on Solana via the open x402 payment protocol — end users need no IBM Cloud account and no subscription. The server operator supplies IBM watsonx.ai credentials and a receiving wallet; callers pay only for what they use. When a tool is called without payment, the server returns an x402 PaymentRequired envelope quoting the exact USDC price; x402-capable clients pay and retry automatically.
-Five tools, each independently priced:
+Six tools — one free entry point plus five independently-priced inference tools:
+
+0. **ibm_granite_getting_started — Free, no payment or account.** Start here. Returns a machine-readable overview of the server: every tool with its per-call USDC price, the step-by-step x402 payment flow, setup requirements, and runnable example calls. Optional `section` parameter (overview, pricing, payment, tools, setup) focuses the response. Lets any client — including non-x402 hosts like watsonx Orchestrate — discover the server before paying.
1. **ibm_granite_chat — Conversational AI ($0.02/call).** General-purpose chat completion powered by IBM Granite 3 8B Instruct. Send a conversation as an ordered array of role/content messages (system, user, assistant) and receive the assistant reply plus token usage. Parameters: messages (1–50), optional model override, max_new_tokens (1–4096, default 1024), temperature (0–2, default 0.7). Use for Q&A, drafting, reasoning, and instruction following.
diff --git a/packages/ibm-x402-mcp/README.md b/packages/ibm-x402-mcp/README.md
index 8c7ab21d0..a793d67fe 100644
--- a/packages/ibm-x402-mcp/README.md
+++ b/packages/ibm-x402-mcp/README.md
@@ -25,6 +25,7 @@ The server operator supplies IBM credentials (`WATSONX_*`) and a receiving Solan
| Tool | What it does | Price |
|---|---|---|
+| `ibm_granite_getting_started` | **Start here** — overview, prices, and the x402 payment flow. No payment or IBM account required. | **Free** |
| `ibm_granite_chat` | Conversational AI via IBM Granite 3 8B Instruct | $0.02 USDC |
| `ibm_granite_code` | Code generation, review, refactoring, testing, and documentation | $0.025 USDC |
| `ibm_granite_embed` | Batch text embeddings for RAG, semantic search, and clustering (up to 64 texts) | $0.005 USDC |
diff --git a/packages/ibm-x402-mcp/src/index.js b/packages/ibm-x402-mcp/src/index.js
index 1b0386723..0430b8be0 100644
--- a/packages/ibm-x402-mcp/src/index.js
+++ b/packages/ibm-x402-mcp/src/index.js
@@ -26,12 +26,15 @@ import { buildGraniteCodeTool } from './tools/granite-code.js';
import { buildGraniteEmbedTool } from './tools/granite-embed.js';
import { buildGraniteAnalyzeTool } from './tools/granite-analyze.js';
import { buildGraniteForecastTool } from './tools/granite-forecast.js';
+import { buildGettingStartedTool } from './tools/getting-started.js';
const SERVER_INSTRUCTIONS =
'x402 pay-per-use IBM Granite AI tools from three.ws. Each tool lists its USDC price. ' +
+ 'New here? Call ibm_granite_getting_started (free, no payment) for an overview, prices, and the payment flow. ' +
'Tool calls without an x402 payment payload in _meta return a PaymentRequired envelope ' +
'(v2 MCP transport spec). ' +
- 'Tools: ibm_granite_chat ($0.02 — conversational AI), ' +
+ 'Tools: ibm_granite_getting_started (FREE — overview & how to pay), ' +
+ 'ibm_granite_chat ($0.02 — conversational AI), ' +
'ibm_granite_code ($0.025 — generate/review/refactor/explain/test/document code), ' +
'ibm_granite_embed ($0.005 — batch embeddings for RAG/search), ' +
'ibm_granite_analyze ($0.04 — structured document analysis), ' +
@@ -52,6 +55,7 @@ export async function buildServer(client) {
);
const tools = await Promise.all([
+ buildGettingStartedTool(),
buildGraniteChatTool(client),
buildGraniteCodeTool(client),
buildGraniteEmbedTool(client),
@@ -101,7 +105,7 @@ async function main() {
await server.connect(transport);
console.error(
- `[ibm-x402-mcp] ready — 5 IBM Granite x402 tools registered over stdio ` +
+ `[ibm-x402-mcp] ready — 1 free + 5 paid IBM Granite tools registered over stdio ` +
`(model: ${config.chatModel} @ ${config.url})`,
);
}
diff --git a/packages/ibm-x402-mcp/src/tools/getting-started.js b/packages/ibm-x402-mcp/src/tools/getting-started.js
new file mode 100644
index 000000000..83173876f
--- /dev/null
+++ b/packages/ibm-x402-mcp/src/tools/getting-started.js
@@ -0,0 +1,170 @@
+// `ibm_granite_getting_started` — FREE meta tool: orient a caller before they pay.
+//
+// Unlike the five `ibm_granite_*` inference tools, this one is NOT wrapped in
+// `paid()`. It returns immediately with no x402 PaymentRequired envelope, so any
+// MCP client — including ones that can't (yet) settle USDC on Solana, or hosts
+// like watsonx Orchestrate that aren't x402-capable — can call it to learn what
+// the server offers, what each tool costs, and how the payment flow works.
+
+import { z } from 'zod';
+
+const TOOL_NAME = 'ibm_granite_getting_started';
+const TOOL_DESCRIPTION =
+ 'FREE — start here. Returns an overview of this server: the IBM Granite tools available, ' +
+ 'their per-call USDC prices, how the x402 pay-per-call flow works, setup requirements, and ' +
+ 'runnable example calls. No payment required. Call this first to orient before invoking a paid tool.';
+
+// Single in-file catalog of the paid tools. Kept in sync with src/tools/*.js,
+// SERVER_INSTRUCTIONS in index.js, and README.md / CATALOG.md.
+const TOOLS = [
+ {
+ name: 'ibm_granite_chat',
+ price: '$0.02',
+ summary: 'Conversational AI via IBM Granite 3 8B Instruct.',
+ params: 'messages[] (role/content), model?, max_new_tokens? (≤4096, default 1024), temperature? (0–2, default 0.7)',
+ example: {
+ messages: [{ role: 'user', content: 'Explain quantum entanglement in two sentences.' }],
+ },
+ },
+ {
+ name: 'ibm_granite_code',
+ price: '$0.025',
+ summary: 'Code generate / review / refactor / explain / test / document.',
+ params: 'task (enum), prompt (description or pasted code), language?, context?',
+ example: { task: 'review', prompt: 'def roi(rev, cost): return rev / cost', language: 'Python' },
+ },
+ {
+ name: 'ibm_granite_embed',
+ price: '$0.005',
+ summary: 'Batch text embeddings (granite-embedding-278m-multilingual) for RAG and search.',
+ params: 'inputs[] (1–64 texts, ≤8000 chars each), model?',
+ example: { inputs: ['enterprise data governance', 'cloud-native AI pipeline'] },
+ },
+ {
+ name: 'ibm_granite_analyze',
+ price: '$0.04',
+ summary: 'Structured document analysis: entities, sentiment, risk flags, summary, next steps.',
+ params: 'document (≤24000 chars), analysis_type? (general|contract|financial|technical|medical|sentiment), language?',
+ example: { document: 'This Services Agreement is entered into between...', analysis_type: 'contract' },
+ },
+ {
+ name: 'ibm_granite_forecast',
+ price: '$0.05',
+ summary: 'Zero-shot time-series forecasting via IBM Granite TTM (no training).',
+ params: 'timestamps[] (64–1024, ISO-8601), values[] (same length), freq (e.g. 1h/1D/1W), prediction_length? (≤96), label?',
+ example: { timestamps: ['2025-01-01T00:00:00Z'], values: [1200], freq: '1D', prediction_length: 7 },
+ },
+];
+
+const PAYMENT_FLOW = [
+ 'Call any ibm_granite_* tool. With no payment in _meta, the server replies with an x402 PaymentRequired envelope quoting the exact USDC price and a Solana pay-to address.',
+ 'Your client signs a Solana USDC transfer for that amount and retries the call with the signed payload in _meta["x402/payment"].',
+ 'The server verifies + settles the payment through the x402 facilitator, runs the IBM watsonx.ai inference, and returns the result.',
+ 'The settlement receipt comes back in _meta["x402/payment-response"]. x402-capable MCP clients perform steps 2–4 automatically.',
+];
+
+const SETUP = {
+ endUsers: 'No IBM Cloud account needed. You only need an x402-capable wallet funded with USDC on Solana to pay per call. This getting_started tool is free.',
+ operators: {
+ required: {
+ MCP_SVM_PAYMENT_ADDRESS: 'Your Solana wallet that receives USDC payments.',
+ WATSONX_API_KEY: 'IBM Cloud API key — https://cloud.ibm.com/iam/apikeys',
+ WATSONX_PROJECT_ID: 'watsonx.ai project id (or WATSONX_SPACE_ID).',
+ },
+ optional: 'WATSONX_URL (region, default us-south), WATSONX_MODEL_ID, WATSONX_EMBED_MODEL_ID, X402_FEE_PAYER_SOLANA, X402_FACILITATOR_URL.',
+ run: 'npx @three-ws/ibm-x402-mcp',
+ },
+};
+
+const LINKS = {
+ homepage: 'https://three.ws',
+ npm: 'https://www.npmjs.com/package/@three-ws/ibm-x402-mcp',
+ source: 'https://github.com/nirholas/three.ws/tree/main/packages/ibm-x402-mcp',
+ support: 'https://three.ws/support',
+ x402: 'https://x402.org',
+};
+
+function buildPayload(section) {
+ const overview =
+ 'x402 pay-per-use IBM Granite AI over MCP. Five inference tools, each settled in USDC on ' +
+ 'Solana via the x402 protocol — no IBM Cloud account required for callers. This tool is free; ' +
+ 'every other tool quotes its price below.';
+
+ const full = {
+ ok: true,
+ server: 'ibm-x402-mcp',
+ version: '1.0.0',
+ overview,
+ tools: TOOLS,
+ pricing: TOOLS.map((t) => `${t.name}: ${t.price}/call`),
+ payment_flow: PAYMENT_FLOW,
+ setup: SETUP,
+ links: LINKS,
+ next_step:
+ 'Pick a tool from `tools`, send the shown `example` as arguments, and your x402 client will ' +
+ 'handle the USDC payment automatically.',
+ };
+
+ if (section === 'pricing') return { ok: true, pricing: full.pricing, tools: TOOLS.map(({ name, price, summary }) => ({ name, price, summary })) };
+ if (section === 'payment') return { ok: true, payment_flow: PAYMENT_FLOW, setup: SETUP };
+ if (section === 'tools') return { ok: true, tools: TOOLS };
+ if (section === 'setup') return { ok: true, setup: SETUP, links: LINKS };
+ return full;
+}
+
+function renderText(payload) {
+ if (!payload.overview) {
+ // Focused section — return compact JSON the model can read directly.
+ return JSON.stringify(payload, null, 2);
+ }
+ const lines = [
+ '# IBM Granite x402 MCP — Getting Started',
+ '',
+ payload.overview,
+ '',
+ '## Tools (call any of these; this getting_started tool is free)',
+ ...payload.tools.map(
+ (t) => `- ${t.name} — ${t.price}/call — ${t.summary}\n params: ${t.params}`,
+ ),
+ '',
+ '## How payment works (x402)',
+ ...payload.payment_flow.map((s, i) => `${i + 1}. ${s}`),
+ '',
+ '## Run it (server operator)',
+ `Required env: MCP_SVM_PAYMENT_ADDRESS, WATSONX_API_KEY, WATSONX_PROJECT_ID. Then: ${SETUP.operators.run}`,
+ '',
+ '## Links',
+ ...Object.entries(payload.links).map(([k, v]) => `- ${k}: ${v}`),
+ '',
+ `Next: ${payload.next_step}`,
+ ];
+ return lines.join('\n');
+}
+
+export function buildGettingStartedTool() {
+ const inputSchema = {
+ section: z
+ .enum(['overview', 'pricing', 'payment', 'tools', 'setup'])
+ .optional()
+ .describe(
+ 'Which part to return. Defaults to "overview" (everything). Use "pricing", "payment", "tools", or "setup" to focus.',
+ ),
+ };
+
+ async function handler(args) {
+ const section = args?.section || 'overview';
+ const payload = buildPayload(section);
+ return {
+ content: [{ type: 'text', text: renderText(payload) }],
+ structuredContent: payload,
+ };
+ }
+
+ return {
+ name: TOOL_NAME,
+ title: 'Getting Started (free)',
+ description: TOOL_DESCRIPTION,
+ inputSchema,
+ handler,
+ };
+}
diff --git a/pages/create-character.html b/pages/create-character.html
index a5c63f02e..799f0b5c3 100644
--- a/pages/create-character.html
+++ b/pages/create-character.html
@@ -10,7 +10,7 @@
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<link rel="manifest" href="/site.webmanifest" />
- <meta name="description" content="Build your 3D character — generate it from a photo, a Ready Player Me avatar, or your own model, then dress it in the wardrobe and step into the world." />
+ <meta name="description" content="Build your 3D character — generate it from a photo, a full-body avatar creator, or your own model, then dress it in the wardrobe and step into the world." />
<meta name="robots" content="index, follow" />
<meta property="og:type" content="website" />
@@ -51,8 +51,8 @@
<div class="cc-sources">
<button type="button" class="cc-source" id="cc-src-rpm">
<span class="ic" aria-hidden="true">🧍</span>
- <span class="t">Ready Player Me</span>
- <span class="d">Full-body creator</span>
+ <span class="t">Avatar Creator</span>
+ <span class="d">Full-body builder</span>
</button>
<button type="button" class="cc-source" id="cc-src-selfie">
<span class="ic" aria-hidden="true">📸</span>
@@ -84,11 +84,11 @@
</section>
</main>
- <!-- Ready Player Me modal -->
- <div class="cc-modal" id="cc-rpm-modal" role="dialog" aria-modal="true" aria-label="Ready Player Me avatar creator" hidden>
+ <!-- Avatar creator modal -->
+ <div class="cc-modal" id="cc-rpm-modal" role="dialog" aria-modal="true" aria-label="Avatar creator" hidden>
<div class="cc-modal__inner">
<button type="button" class="cc-modal__close" id="cc-rpm-close">Close</button>
- <iframe id="cc-rpm-frame" title="Ready Player Me" allow="camera *; microphone *; clipboard-write" src="about:blank"></iframe>
+ <iframe id="cc-rpm-frame" title="Avatar creator" allow="camera *; microphone *; clipboard-write" src="about:blank"></iframe>
</div>
</div>
diff --git a/public/evm-wallet.html b/public/evm-wallet.html
new file mode 100644
index 000000000..3bbe0ce9d
--- /dev/null
+++ b/public/evm-wallet.html
@@ -0,0 +1,602 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <title>EVM vanity wallet generator · three.ws</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <meta name="description" content="Grind a custom Ethereum / EVM wallet address with the prefix or suffix of your choice. A real secp256k1 keypair — importable into MetaMask, ethers, viem. Runs entirely in your browser; the private key never leaves your device.">
+ <link rel="icon" href="/favicon.ico">
+ <link rel="stylesheet" href="/footer.css">
+ <link rel="stylesheet" href="/nav.css">
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <script defer src="/footer-newsletter.js"></script>
+ <style>
+ * { box-sizing: border-box; }
+ :root {
+ color-scheme: dark;
+ --fg: #f0f0f0; --muted: #888; --border: rgba(255,255,255,0.08); --bg: #111;
+ --card-bg: #0f0f0f;
+ --ok-bg: rgba(74,222,128,0.12); --ok-fg: #4ade80;
+ --warn-bg: rgba(251,191,36,0.1); --warn-fg: #fbbf24;
+ --bad-bg: rgba(239,68,68,0.1); --bad-fg: #f87171;
+ --header-h: 3.5rem;
+ --font-display: 'Space Grotesk', 'Inter', system-ui, sans-serif;
+ }
+ body {
+ font: 15px/1.5 'Inter', system-ui, -apple-system, sans-serif;
+ background: #000; color: var(--fg); margin: 0;
+ min-height: 100vh; display: flex; flex-direction: column;
+ }
+ main { flex: 1; max-width: 720px; width: 100%; margin: 0 auto; padding: 2.5rem 1rem 4rem; }
+ h1 { font-size: 1.5rem; margin: 0 0 .25rem; font-family: var(--font-display); letter-spacing: -0.02em; }
+ p.lede { color: var(--muted); margin: 0 0 1.5rem; }
+ label { display: block; font-size: .8rem; color: var(--muted); margin: 1rem 0 .25rem; }
+ .card { border: 1px solid var(--border); border-radius: 10px; padding: 1.1rem 1.25rem; background: var(--card-bg); margin-bottom: 1rem; }
+ .card h2 { font-size: .95rem; margin: 0 0 .35rem; font-family: var(--font-display); letter-spacing: -0.01em; }
+ .card .desc { color: var(--muted); font-size: .8rem; margin: 0 0 .35rem; }
+ input[type=text], input[type=password], select {
+ font: inherit; font-family: ui-monospace, monospace; padding: .55rem .7rem;
+ width: 100%; border: 1px solid rgba(255,255,255,0.12); border-radius: 6px;
+ background: #1a1a1a; color: var(--fg);
+ }
+ input:focus, select:focus { outline: none; border-color: rgba(255,255,255,0.3); }
+ input.invalid { border-color: var(--bad-fg); background: rgba(239,68,68,0.06); }
+
+ .row2 { display: grid; grid-template-columns: 1fr 1fr; gap: .75rem; }
+ @media (max-width: 600px) { .row2 { grid-template-columns: 1fr; } }
+
+ .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, .preview .sfx { background: linear-gradient(90deg,#a78bfa,#22d3ee); color: #0a0a0a; padding: 0 3px; border-radius: 3px; font-weight: 700; }
+ .preview .rest { color: #555; }
+
+ .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 { background: #4caf50 !important; }
+ .lit-4, .lit-5 { background: #fb8c00 !important; }
+ .lit-6, .lit-7, .lit-8, .lit-9, .lit-10 { background: #d32f2f !important; }
+
+ .row { display: flex; justify-content: space-between; align-items: center; margin-top: .55rem; font-size: .85rem; color: var(--muted); }
+
+ .preset-row { display: flex; gap: .35rem; flex-wrap: wrap; margin-top: .4rem; }
+ .preset { background: #1a1a1a; border: 1px solid rgba(255,255,255,0.1); border-radius: 999px; padding: .25rem .65rem; cursor: pointer; font-size: .75rem; color: #bbb; }
+ .preset:hover { background: #242424; border-color: rgba(255,255,255,0.2); }
+
+ .case-tag { padding: .12rem .5rem; border-radius: 999px; font-size: .72rem; font-weight: 600; }
+ .case-ci { background: rgba(74,222,128,0.12); color: #4ade80; }
+ .case-cs { background: linear-gradient(90deg,rgba(167,139,250,0.18),rgba(34,211,238,0.18)); color: #c4b5fd; border: 1px solid rgba(167,139,250,0.25); }
+
+ /* Core selector (mirrors the Solana grinder) */
+ .cores { margin-top: 1.1rem; padding-top: 1rem; border-top: 1px solid var(--border); }
+ .cores .cores-head { display: flex; justify-content: space-between; align-items: baseline; }
+ .cores .cores-head label { margin: 0; }
+ .cores .cores-val { font-family: ui-monospace, monospace; font-size: .85rem; color: var(--fg); }
+ .cores .cores-val b { color: #fff; font-size: 1rem; }
+ .cores-row { display: flex; align-items: center; gap: .75rem; margin-top: .55rem; }
+ .cores-row input[type=range] { flex: 1; -webkit-appearance: none; appearance: none; height: 5px; border-radius: 999px; background: #2a2a2a; outline: none; cursor: pointer; margin: 0; }
+ .cores-row input[type=range]::-webkit-slider-thumb { -webkit-appearance: none; appearance: none; width: 18px; height: 18px; border-radius: 50%; background: #fff; cursor: pointer; border: 3px solid #000; box-shadow: 0 0 0 1px rgba(255,255,255,0.2); transition: transform .1s; }
+ .cores-row input[type=range]::-webkit-slider-thumb:hover { transform: scale(1.15); }
+ .cores-row input[type=range]::-moz-range-thumb { width: 18px; height: 18px; border-radius: 50%; background: #fff; cursor: pointer; border: 3px solid #000; box-shadow: 0 0 0 1px rgba(255,255,255,0.2); }
+ .cores-row input[type=range]:disabled { opacity: .4; cursor: not-allowed; }
+ .cores-row input[type=range]:focus-visible { box-shadow: 0 0 0 2px rgba(255,255,255,0.35); }
+ .cores .cores-hint { font-size: .72rem; color: var(--muted); margin-top: .45rem; }
+ .cores-ticks { display: flex; gap: .35rem; margin-top: .55rem; }
+ .cores-ticks button { font: inherit; font-size: .72rem; padding: .2rem .55rem; border-radius: 999px; border: 1px solid rgba(255,255,255,0.1); background: #1a1a1a; color: #bbb; cursor: pointer; }
+ .cores-ticks button:hover { background: #242424; border-color: rgba(255,255,255,0.2); }
+ .cores-ticks button[aria-pressed=true] { background: #fff; color: #000; border-color: #fff; font-weight: 600; }
+
+ .actions { display: flex; gap: .55rem; margin-top: 1.25rem; align-items: center; flex-wrap: wrap; }
+ .btn { font: inherit; padding: .55rem 1.1rem; border-radius: 6px; border: 1px solid rgba(255,255,255,0.12); background: #1a1a1a; color: var(--fg); cursor: pointer; }
+ .btn:hover { background: #222; }
+ .btn.primary { background: #fff; color: #000; border-color: #fff; font-weight: 600; }
+ .btn.primary:hover { background: #e8e8e8; }
+ .btn:disabled { opacity: .35; cursor: not-allowed; }
+
+ .progress { margin-top: 1.25rem; padding: .9rem 1.1rem; background: #111; border-radius: 8px; border: 1px solid var(--border); font-family: ui-monospace, monospace; font-size: .85rem; }
+ .progress.paused { opacity: .75; }
+ .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; }
+ .paused-tag { display: inline-block; padding: .1rem .5rem; border-radius: 999px; font-size: .7rem; font-weight: 600; background: var(--warn-bg); color: var(--warn-fg); border: 1px solid rgba(251,191,36,0.2); margin-left: .5rem; vertical-align: middle; }
+
+ .result { margin-top: 1.25rem; padding: 1.1rem 1.25rem; background: rgba(167,139,250,0.05); border: 1px solid rgba(167,139,250,0.22); border-radius: 10px; }
+ .result h3 { margin: 0 0 .4rem; font-size: 1rem; color: #fff; }
+ .result .out-row { font-family: ui-monospace, monospace; font-size: .82rem; word-break: break-all; padding: .55rem .65rem; background: #111; border-radius: 6px; border: 1px solid rgba(255,255,255,0.08); margin-top: .5rem; display: flex; align-items: baseline; gap: .5rem; }
+ .result .out-row .k { color: #a78bfa; display: inline-block; min-width: 5.5rem; flex: none; }
+ .result .out-row .v { flex: 1; }
+ .result .pfx, .result .sfx { background: linear-gradient(90deg,#a78bfa,#22d3ee); color: #0a0a0a; padding: 0 3px; border-radius: 3px; font-weight: 700; }
+ .result .meta { font-size: .8rem; color: var(--muted); margin: .65rem 0 0; }
+
+ .export { margin-top: 1.1rem; padding-top: 1rem; border-top: 1px solid var(--border); }
+ .export h4 { margin: 0 0 .5rem; font-size: .88rem; color: #fff; font-family: var(--font-display); }
+ .export .sub { font-size: .76rem; color: var(--muted); margin: 0 0 .55rem; }
+ .pk-field { display: flex; gap: .5rem; align-items: stretch; margin-top: .4rem; }
+ .pk-field input { font-size: .8rem; }
+ .pk-blur { filter: blur(5px); user-select: none; transition: filter .15s; }
+
+ .warn { background: var(--warn-bg); color: var(--warn-fg); padding: .65rem .85rem; border-radius: 6px; margin-top: 1rem; font-size: .8rem; border: 1px solid rgba(251,191,36,0.15); }
+ .warn strong { color: #fca5a5; }
+ .error { background: var(--bad-bg); color: var(--bad-fg); padding: .6rem .85rem; border-radius: 6px; margin-top: 1rem; font-size: .85rem; border: 1px solid rgba(239,68,68,0.15); }
+ .ok { background: var(--ok-bg); color: var(--ok-fg); padding: .6rem .85rem; border-radius: 6px; margin-top: .6rem; font-size: .82rem; border: 1px solid rgba(74,222,128,0.15); }
+
+ .secure-note { display: flex; gap: .5rem; align-items: flex-start; font-size: .78rem; color: var(--muted); background: #0a0a0a; border: 1px solid var(--border); border-radius: 8px; padding: .65rem .8rem; margin-bottom: 1rem; }
+ .secure-note svg { flex: none; margin-top: 1px; color: #4ade80; }
+
+ .skip-link { position: absolute; left: -9999px; }
+ .skip-link:focus { left: 1rem; top: 1rem; padding: .5rem 1rem; background: #0c0c0c; border: 1px solid rgba(255,255,255,0.1); border-radius: 6px; z-index: 9999; color: #fff; text-decoration: none; }
+ .wordmark-dot { width: 8px; height: 8px; border-radius: 50%; background: #fff; box-shadow: 0 0 10px rgba(139,92,246,0.6); display: inline-block; }
+ </style>
+
+ <link rel="canonical" href="https://three.ws/evm-wallet">
+ <meta property="og:type" content="website">
+ <meta property="og:site_name" content="three.ws">
+ <meta property="og:title" content="EVM Vanity Wallet · three.ws">
+ <meta property="og:description" content="Grind a custom Ethereum / EVM wallet address in your browser. A real keypair, importable into MetaMask. Keys never leave your device.">
+ <meta property="og:url" content="https://three.ws/evm-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="EVM Vanity Wallet · three.ws">
+ <meta name="twitter:description" content="Grind a custom Ethereum / EVM wallet address in your browser. Keys never leave your device.">
+ <meta name="twitter:image" content="https://three.ws/og-image.png">
+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"EVM Vanity Wallet","description":"Grind a custom Ethereum / EVM wallet address in your browser. A real keypair, importable into MetaMask. Keys never leave your device.","url":"https://three.ws/evm-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>
+ <header>
+ <div id="nav-container"></div>
+ </header>
+ <script src="/nav.js"></script>
+
+ <main id="main-content">
+ <h1>✦ EVM vanity wallet generator</h1>
+ <p class="lede">
+ Grind a real Ethereum / EVM wallet whose address starts or ends with characters of your choice — for your agent, treasury, or anywhere a memorable
+ <code>0x</code> address matters. The result is a normal secp256k1 keypair you can import into <strong>MetaMask</strong>, ethers, viem or Rabby.
+ <strong>Runs entirely in your browser.</strong> The private key is never transmitted anywhere.
+ </p>
+
+ <div class="secure-note">
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="M12 2 4 5v6c0 5 3.4 8.5 8 10 4.6-1.5 8-5 8-10V5l-8-3Z" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round"/><path d="m9 12 2 2 4-4" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></svg>
+ <span>
+ This is an <strong>EOA</strong> grinder — it searches private keys directly, so you own the resulting address.
+ (<a href="/eth-vanity" style="color:#a78bfa">CREATE2</a> is the sibling tool for vanity <em>smart-contract</em> addresses, where you grind a salt instead of a key.)
+ Keys are generated with your browser's CSPRNG, each match is re-derived and verified before it's shown, and the export below is an encrypted keystore by default.
+ </span>
+ </div>
+
+ <div class="card">
+ <h2>Pattern</h2>
+ <p class="desc">
+ Hex characters only (0–9, a–f). Each extra character is 16× harder.
+ <strong>Mixed case</strong> (e.g. <code>BeeF</code>) matches the EIP-55 checksum — visually distinctive, ~2× harder per letter.
+ </p>
+
+ <div class="row2">
+ <div>
+ <label for="prefix">Prefix (after 0x)</label>
+ <input id="prefix" type="text" maxlength="10" placeholder="e.g. beef or BeeF" autocomplete="off" spellcheck="false" />
+ </div>
+ <div>
+ <label for="suffix">Suffix</label>
+ <input id="suffix" type="text" maxlength="10" placeholder="e.g. dead" autocomplete="off" spellcheck="false" />
+ </div>
+ </div>
+
+ <div class="preset-row" id="word-chips" aria-label="Quick-pick patterns" style="margin-top:.6rem"></div>
+
+ <div class="preview" id="preview" aria-live="polite"></div>
+
+ <div class="meter" aria-hidden="true">
+ <div class="seg" data-seg="1"></div><div class="seg" data-seg="2"></div>
+ <div class="seg" data-seg="3"></div><div class="seg" data-seg="4"></div>
+ <div class="seg" data-seg="5"></div><div class="seg" data-seg="6"></div>
+ </div>
+
+ <div class="row">
+ <span id="est">type a pattern to see estimated time</span>
+ <span id="case-tag"></span>
+ </div>
+
+ <div class="cores">
+ <div class="cores-head">
+ <label for="core-count">Compute — CPU cores to use</label>
+ <span class="cores-val"><b id="core-count-val">4</b> / <span id="core-max">8</span></span>
+ </div>
+ <div class="cores-row">
+ <input id="core-count" type="range" min="1" max="8" value="4" step="1" aria-label="Number of CPU cores to use for grinding" />
+ </div>
+ <div class="cores-ticks" id="core-ticks" aria-label="Quick core presets"></div>
+ <div class="cores-hint">More cores = faster, but a heavier load on your machine. Pause anytime to free them.</div>
+ </div>
+
+ <div class="actions">
+ <button id="grind" class="btn primary" type="button" disabled>Generate wallet</button>
+ <button id="pause" class="btn" type="button" hidden>Pause</button>
+ <button id="stop" class="btn" type="button" hidden>Stop</button>
+ </div>
+
+ <div id="progress" hidden class="progress">
+ <div class="live">
+ <div>
+ <div class="stat" id="rate">0/s</div>
+ <div style="font-size:.75rem;color:#555">tries/sec across <span id="cores2">?</span> cores<span id="paused-tag" class="paused-tag" hidden>paused</span></div>
+ </div>
+ <div style="text-align:right">
+ <div class="stat"><span id="attempts">0</span></div>
+ <div style="font-size:.75rem;color:#555">attempts · eta <span id="eta">—</span></div>
+ </div>
+ </div>
+ <div class="scan" id="scan"></div>
+ </div>
+
+ <div id="error" hidden class="error"></div>
+ <div id="result" hidden></div>
+ </div>
+ </main>
+
+ <script type="module">
+ import { Wallet } from 'ethers';
+ import { grindEoaVanity } from '/src/eth/vanity/eoa-grinder.js';
+ import {
+ validatePattern, estimateAttempts, formatTimeEstimate,
+ letterCount, eip55Checksum, MAX_PATTERN_LENGTH,
+ } from '/src/eth/vanity/validation.js';
+ import { PRESET_CHIPS } from '/src/eth/vanity/wordlist.js';
+
+ const $ = (id) => document.getElementById(id);
+ const HEX_ALPHA = '0123456789abcdef';
+ // Order-of-magnitude hot-loop rate for one secp256k1 point-add + keccak in a
+ // worker. Used only for the pre-grind estimate; the live rate is measured.
+ const RATE_PER_CORE = 12_000;
+
+ // ── Core selection ─────────────────────────────────────────────────
+ const HW_CORES = Math.max(1, navigator.hardwareConcurrency || 4);
+ const DEFAULT_CORES = Math.max(1, Math.min(HW_CORES, Math.round(HW_CORES / 2) || 1));
+ let cores = DEFAULT_CORES;
+
+ const coreSlider = $('core-count');
+ coreSlider.max = String(HW_CORES);
+ coreSlider.value = String(DEFAULT_CORES);
+ $('core-max').textContent = HW_CORES;
+ $('core-count-val').textContent = DEFAULT_CORES;
+ $('cores2').textContent = DEFAULT_CORES;
+
+ const presetVals = [...new Set([1, DEFAULT_CORES, HW_CORES])].sort((a, b) => a - b);
+ const presetLabel = (n) => n === 1 ? '1 core' : n === HW_CORES ? `Max (${n})` : `${n}`;
+ $('core-ticks').innerHTML = presetVals
+ .map((n) => `<button type="button" data-cores="${n}" aria-pressed="${n === DEFAULT_CORES}">${presetLabel(n)}</button>`)
+ .join('');
+
+ function setCores(n) {
+ cores = Math.max(1, Math.min(HW_CORES, n | 0));
+ coreSlider.value = String(cores);
+ $('core-count-val').textContent = cores;
+ $('cores2').textContent = cores;
+ $('core-ticks').querySelectorAll('button').forEach((b) => {
+ b.setAttribute('aria-pressed', String(Number(b.dataset.cores) === cores));
+ });
+ update();
+ }
+ coreSlider.addEventListener('input', () => setCores(Number(coreSlider.value)));
+ $('core-ticks').querySelectorAll('button').forEach((b) => {
+ b.addEventListener('click', () => setCores(Number(b.dataset.cores)));
+ });
+
+ function esc(s) { return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;' })[c]); }
+ function sample(prefix = '', suffix = '') {
+ const fillLen = Math.max(0, 40 - prefix.length - suffix.length);
+ let mid = '';
+ for (let i = 0; i < fillLen; i++) mid += HEX_ALPHA[Math.floor(Math.random() * 16)];
+ return prefix + mid + suffix;
+ }
+ function fmtTime(seconds) {
+ if (!isFinite(seconds)) return '—';
+ if (seconds < 1) return '<1s';
+ if (seconds < 60) return `~${Math.round(seconds)}s`;
+ if (seconds < 3600) return `~${Math.round(seconds / 60)}m`;
+ if (seconds < 86400) return `~${Math.round(seconds / 3600)}h`;
+ if (seconds < 31536000) return `~${Math.round(seconds / 86400)}d`;
+ return '>1y';
+ }
+ function estSeconds(p, s) {
+ const total = p.length + s.length;
+ if (total <= 0) return 0;
+ const caseSensitive = /[A-F]/.test(p) || /[A-F]/.test(s);
+ const letters = letterCount(p) + letterCount(s);
+ const expected = estimateAttempts(total, letters, caseSensitive);
+ // EIP-55 mode pays an extra keccak per attempt → ~30% slower hot loop.
+ const ratePerCore = caseSensitive ? RATE_PER_CORE * 0.7 : RATE_PER_CORE;
+ return expected / (ratePerCore * cores);
+ }
+
+ // ── Wordlist chips ─────────────────────────────────────────────────
+ const chipsEl = $('word-chips');
+ PRESET_CHIPS.forEach((w) => {
+ const b = document.createElement('button');
+ b.type = 'button';
+ b.className = 'preset';
+ b.textContent = w;
+ b.addEventListener('click', () => {
+ $('prefix').value = w;
+ $('prefix').dispatchEvent(new Event('input'));
+ $('prefix').focus();
+ });
+ chipsEl.appendChild(b);
+ });
+
+ // ── Live preview / validation ──────────────────────────────────────
+ function readPattern() {
+ const p = $('prefix').value.trim().replace(/^0x/i, '');
+ const s = $('suffix').value.trim();
+ return { p, s };
+ }
+ function patternValid(v) {
+ if (!v) return true;
+ if (v.length > MAX_PATTERN_LENGTH) return false;
+ return /^[0-9a-fA-F]+$/.test(v);
+ }
+
+ let previewLoop = null;
+ function startPreviewLoop() {
+ stopPreviewLoop();
+ previewLoop = setInterval(() => {
+ const { p, s } = readPattern();
+ if ($('prefix').classList.contains('invalid') || $('suffix').classList.contains('invalid')) return;
+ const rest = $('preview').querySelector('.rest');
+ if (rest && (p || s)) rest.textContent = sample('', s).slice(0, 40 - p.length - s.length);
+ }, 700);
+ }
+ function stopPreviewLoop() { if (previewLoop) clearInterval(previewLoop); previewLoop = null; }
+
+ function update() {
+ const { p, s } = readPattern();
+ const pOk = patternValid(p), sOk = patternValid(s);
+ $('prefix').classList.toggle('invalid', !pOk);
+ $('suffix').classList.toggle('invalid', !sOk);
+
+ const total = (p?.length || 0) + (s?.length || 0);
+ document.querySelectorAll('.meter .seg').forEach((seg, i) => {
+ seg.className = 'seg' + (total > i ? ` lit-${Math.min(total, 6)}` : '');
+ });
+
+ const caseSensitive = /[A-F]/.test(p) || /[A-F]/.test(s);
+ if (total > 0 && pOk && sOk) {
+ $('case-tag').innerHTML = caseSensitive
+ ? '<span class="case-tag case-cs">EIP-55 checksum · case-sensitive</span>'
+ : '<span class="case-tag case-ci">case-insensitive</span>';
+ } else {
+ $('case-tag').innerHTML = '';
+ }
+
+ if (!total) {
+ $('preview').innerHTML = `<span class="rest">${esc(sample())}</span>`;
+ $('est').textContent = 'type a pattern to see estimated time';
+ $('grind').disabled = true;
+ return;
+ }
+ if (!pOk || !sOk) {
+ $('preview').textContent = `invalid — hex only (0–9, a–f), max ${MAX_PATTERN_LENGTH} chars each`;
+ $('est').textContent = '';
+ $('grind').disabled = true;
+ return;
+ }
+ const mid = sample('', s).slice(0, 40 - p.length - s.length);
+ $('preview').innerHTML =
+ `<span class="rest">0x</span>` +
+ (p ? `<span class="pfx">${esc(p)}</span>` : '') +
+ `<span class="rest">${esc(mid)}</span>` +
+ (s ? `<span class="sfx">${esc(s)}</span>` : '');
+ $('est').textContent = `est. ${fmtTime(estSeconds(p, s))} on ${cores} cores`;
+ $('grind').disabled = false;
+ }
+
+ $('prefix').addEventListener('input', update);
+ $('suffix').addEventListener('input', update);
+ [$('prefix'), $('suffix')].forEach((el) => el.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter' && !$('grind').disabled) $('grind').click();
+ }));
+ update();
+ startPreviewLoop();
+
+ // ── Grind lifecycle ────────────────────────────────────────────────
+ let abort = null;
+ let controls = null;
+ let scanLoop = null;
+
+ function setCoreControlsDisabled(disabled) {
+ coreSlider.disabled = disabled;
+ $('core-ticks').querySelectorAll('button').forEach((b) => { b.disabled = disabled; });
+ }
+ function setPaused(paused) {
+ $('pause').textContent = paused ? 'Resume' : 'Pause';
+ $('pause').classList.toggle('primary', paused);
+ $('paused-tag').hidden = !paused;
+ $('progress').classList.toggle('paused', paused);
+ }
+ function endGrindUI() {
+ if (scanLoop) { clearInterval(scanLoop); scanLoop = null; }
+ $('pause').hidden = true;
+ $('stop').hidden = true;
+ setPaused(false);
+ setCoreControlsDisabled(false);
+ }
+
+ $('grind').addEventListener('click', async () => {
+ const { p, s } = readPattern();
+ if (p) { const v = validatePattern(p); if (!v.valid) return showError(`invalid prefix: ${v.errors.join('; ')}`); }
+ if (s) { const v = validatePattern(s); if (!v.valid) return showError(`invalid suffix: ${v.errors.join('; ')}`); }
+
+ $('grind').hidden = true;
+ $('pause').hidden = false;
+ $('stop').hidden = false;
+ setPaused(false);
+ setCoreControlsDisabled(true);
+ $('progress').hidden = false;
+ $('result').hidden = true;
+ $('error').hidden = true;
+ $('attempts').textContent = '0';
+ $('rate').textContent = '0/s';
+ $('cores2').textContent = cores;
+ $('eta').textContent = fmtTime(estSeconds(p, s));
+ stopPreviewLoop();
+
+ scanLoop = setInterval(() => {
+ if (controls?.paused) return;
+ const mid = sample('', s).slice(0, 40 - p.length - s.length);
+ $('scan').innerHTML =
+ `<span style="color:#555">0x</span>` +
+ (p ? `<span class="pfx">${esc(p)}</span>` : '') +
+ `<span style="color:#555">${esc(mid)}</span>` +
+ (s ? `<span class="sfx">${esc(s)}</span>` : '');
+ }, 100);
+
+ abort = new AbortController();
+ controls = {};
+ try {
+ const result = await grindEoaVanity({
+ prefix: p || undefined,
+ suffix: s || undefined,
+ maxWorkers: cores,
+ controller: controls,
+ signal: abort.signal,
+ onProgress: ({ attempts, rate, eta, paused }) => {
+ $('attempts').textContent = attempts.toLocaleString();
+ $('rate').textContent = paused ? 'paused' : `${Math.round(rate).toLocaleString()}/s`;
+ $('eta').textContent = eta;
+ },
+ });
+ renderResult(result, p, s);
+ } catch (err) {
+ endGrindUI();
+ if (err?.name !== 'AbortError') showError(`Grind failed: ${err.message || err}`);
+ $('grind').hidden = false;
+ $('progress').hidden = true;
+ startPreviewLoop();
+ } finally {
+ controls = null;
+ }
+ });
+
+ $('pause').addEventListener('click', () => {
+ if (!controls) return;
+ if (controls.paused) { controls.resume(); setPaused(false); }
+ else { controls.pause(); setPaused(true); }
+ });
+ $('stop').addEventListener('click', () => abort?.abort());
+
+ function showError(msg) { $('error').textContent = msg; $('error').hidden = false; }
+
+ // ── Result + secure export ─────────────────────────────────────────
+ function renderResult(result, p, s) {
+ endGrindUI();
+ $('grind').hidden = false;
+ $('grind').textContent = 'Generate another';
+ $('progress').hidden = true;
+
+ const display = result.caseSensitive ? result.addressChecksum : result.address;
+ const body = display.slice(2);
+ // Re-apply the highlight on the (possibly checksummed) address body.
+ const head = p ? `<span class="pfx">${esc(body.slice(0, p.length))}</span>` : '';
+ const tail = s ? `<span class="sfx">${esc(body.slice(body.length - s.length))}</span>` : '';
+ const midText = body.slice(p.length, body.length - s.length);
+
+ const rate = Math.round(result.attempts / (result.durationMs / 1000));
+ $('result').hidden = false;
+ $('result').innerHTML = `
+ <div class="result">
+ <h3>✦ Wallet ready</h3>
+ <div class="out-row"><span class="k">Address</span><span class="v">0x${head}${esc(midText)}${tail}</span></div>
+ <div class="meta">
+ ${result.attempts.toLocaleString()} attempts in ${(result.durationMs / 1000).toFixed(1)}s
+ across ${result.workers} cores (${rate.toLocaleString()}/s)
+ </div>
+
+ <div class="export">
+ <h4>Export — encrypted keystore (recommended)</h4>
+ <p class="sub">Password-encrypted JSON (Web3 Secret Storage / keystore V3, scrypt + AES-128-CTR). Import into MetaMask via <em>Import account → JSON File</em>, or Geth/Foundry.</p>
+ <div class="pk-field">
+ <input id="ks-pass" type="password" placeholder="Choose a strong password" autocomplete="new-password" />
+ <button id="ks-download" class="btn primary" type="button" style="flex:none">⬇ Download keystore</button>
+ </div>
+ <div id="ks-status"></div>
+ </div>
+
+ <div class="export">
+ <h4>Raw private key</h4>
+ <p class="sub">For a quick MetaMask <em>Import account → Private Key</em>. Anyone with this string controls the wallet — never paste it into a website or share it.</p>
+ <div class="out-row"><span class="v pk-blur" id="pk-text">${esc(result.privateKey)}</span></div>
+ <div class="actions" style="margin-top:.5rem">
+ <button id="pk-reveal" class="btn" type="button">Reveal</button>
+ <button id="pk-copy" class="btn" type="button">Copy private key</button>
+ <button id="addr-copy" class="btn" type="button">Copy address</button>
+ </div>
+ </div>
+
+ <div class="warn">
+ <strong>This page does not store your key.</strong>
+ Download the encrypted keystore or copy the private key before you navigate away — once this tab closes, the key is gone.
+ Anyone with the key (or keystore + password) can spend funds at this address.
+ </div>
+ </div>
+ `;
+
+ // Keystore encryption (scrypt is intentionally slow — show progress).
+ $('ks-download').addEventListener('click', async () => {
+ const pass = $('ks-pass').value;
+ if (!pass || pass.length < 8) {
+ $('ks-status').innerHTML = `<div class="error">Use a password of at least 8 characters.</div>`;
+ return;
+ }
+ const btn = $('ks-download');
+ btn.disabled = true;
+ $('ks-status').innerHTML = `<div class="ok" id="ks-prog">Encrypting… 0%</div>`;
+ try {
+ const wallet = new Wallet(result.privateKey);
+ const json = await wallet.encrypt(pass, (pct) => {
+ const el = $('ks-prog');
+ if (el) el.textContent = `Encrypting… ${Math.round(pct * 100)}%`;
+ });
+ const blob = new Blob([json], { type: 'application/json' });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = `UTC--keystore--${result.address.slice(2, 10)}.json`;
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+ URL.revokeObjectURL(url);
+ $('ks-status').innerHTML = `<div class="ok">Downloaded encrypted keystore. Keep the file <em>and</em> the password safe — neither alone is enough to recover the wallet.</div>`;
+ } catch (e) {
+ $('ks-status').innerHTML = `<div class="error">Encryption failed: ${esc(e.message || e)}</div>`;
+ } finally {
+ btn.disabled = false;
+ }
+ });
+
+ let revealed = false;
+ $('pk-reveal').addEventListener('click', () => {
+ revealed = !revealed;
+ $('pk-text').classList.toggle('pk-blur', !revealed);
+ $('pk-reveal').textContent = revealed ? 'Hide' : 'Reveal';
+ });
+ $('pk-copy').addEventListener('click', () => copy(result.privateKey, 'pk-copy', 'Copy private key'));
+ $('addr-copy').addEventListener('click', () => copy(display, 'addr-copy', 'Copy address'));
+ }
+
+ async function copy(text, btnId, restoreLabel) {
+ try {
+ await navigator.clipboard.writeText(text);
+ $(btnId).textContent = 'Copied!';
+ setTimeout(() => { $(btnId).textContent = restoreLabel; }, 1500);
+ } catch {
+ $(btnId).textContent = 'Copy failed';
+ setTimeout(() => { $(btnId).textContent = restoreLabel; }, 1500);
+ }
+ }
+ </script>
+ <script src="/brand.js" defer></script>
+ <div id="footer-container"></div>
+ <script src="/footer.js"></script>
+</body>
+</html>
diff --git a/public/features.json b/public/features.json
index 7770609a5..e41cceb83 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-08T10:39:06.879Z",
+ "generated_at": "2026-06-08T14:11:18.101Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/public/ibm.css b/public/ibm.css
index d0563c384..9f7b8d940 100644
--- a/public/ibm.css
+++ b/public/ibm.css
@@ -87,6 +87,26 @@
--focus-ring-color: var(--brand-blue-light);
--focus-ring-width: 2px;
--focus-ring-offset: 2px;
+
+ /* ---- Canonical IBM Carbon tokens ---------------------------------------
+ * The explicit `--ibm-*` names that pages and the design-system guard pin
+ * to. They map onto the canonical monochrome system + the --brand-blue-*
+ * accent above, so tuning either layer flows through here. */
+ --ibm-bg: #070707;
+ --ibm-panel: var(--surface-1);
+ --ibm-border: var(--stroke);
+ --ibm-text: var(--ink);
+ --ibm-muted: var(--ink-dim);
+ --ibm-blue: var(--brand-blue);
+ --ibm-blue-light: var(--brand-blue-light);
+ --ibm-green: var(--success);
+ --ibm-red: var(--danger);
+ --ibm-amber: var(--warn);
+
+ /* Short blue aliases legacy pages reference as var(--ibm) / --ibm-light. */
+ --ibm: var(--brand-blue);
+ --ibm-light: var(--brand-blue-light);
+ --ibm-dim: var(--brand-blue-dim);
}
/* =============================================================================
diff --git a/public/nav.html b/public/nav.html
index c8cf65c3f..da50423b3 100644
--- a/public/nav.html
+++ b/public/nav.html
@@ -327,6 +327,10 @@
><span class="nav-mi-t">Forever</span
><span class="nav-mi-d">Etch a message into Bitcoin — forever</span></a
>
+ <a class="nav-mi" href="/evm-wallet" role="menuitem"
+ ><span class="nav-mi-t">EVM vanity wallet</span
+ ><span class="nav-mi-d">Grind an Ethereum / EVM address</span></a
+ >
<a class="nav-mi" href="/eth-vanity" role="menuitem"
><span class="nav-mi-t">ETH vanity (CREATE2)</span
><span class="nav-mi-d">Grind a smart-contract address</span></a
@@ -497,6 +501,7 @@
<a href="/providers">x402 Providers</a>
<a href="/unstoppable">Unstoppable Agent</a>
<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>
diff --git a/src/avatar-studio-optimize.js b/src/avatar-studio-optimize.js
new file mode 100644
index 000000000..c8519ace5
--- /dev/null
+++ b/src/avatar-studio-optimize.js
@@ -0,0 +1,148 @@
+/**
+ * Avatar Studio — export optimization + validation.
+ *
+ * The studio exports the live Three.js scene via GLTFExporter with
+ * `embedImages: true`, which produces a correct but heavyweight GLB: textures
+ * are re-embedded uncompressed, vertex buffers are full-precision floats, and
+ * nothing is deduplicated. Uploaded as-is, a customised avatar can be several
+ * times larger than it needs to be — slow to download, slow to first paint.
+ *
+ * This module runs the same conservative glTF-Transform passes the server bake
+ * uses ([api/_lib/bake.js]) directly in the browser, before upload:
+ *
+ * prune → dedup → weld → quantize → meshopt (EXT_meshopt_compression)
+ *
+ * All of these are geometry/structure transforms — no texture re-encode (that
+ * needs sharp, which is Node-only). They are lossless or near-lossless and are
+ * already proven safe on arbitrary user avatars by the server bake. The output
+ * is meshopt-compressed; TalkScene's loader wires the meshopt decoder, so it
+ * loads everywhere the studio's own GLBs already load.
+ *
+ * The result is then validated with the official Khronos glTF-Validator. If the
+ * optimized GLB has hard errors — or somehow ends up larger than the source, or
+ * the pipeline throws — we discard it and fall back to the original export. The
+ * save must never fail because optimization failed.
+ */
+
+import { log } from './shared/log.js';
+
+// Quantization precision — copied verbatim from the server bake so studio
+// exports and server-baked avatars compress identically and predictably.
+const QUANTIZE_OPTS = Object.freeze({
+ quantizePosition: 14,
+ quantizeNormal: 10,
+ quantizeTexcoord: 12,
+ quantizeColor: 8,
+ quantizeWeight: 8,
+ quantizeGeneric: 12,
+});
+
+function fmtBytes(n) {
+ if (!Number.isFinite(n)) return '';
+ if (n < 1024) return `${n} B`;
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(0)} KB`;
+ return `${(n / (1024 * 1024)).toFixed(1)} MB`;
+}
+
+/**
+ * Compress and validate a freshly-exported avatar GLB.
+ *
+ * @param {Blob} blob — the GLTFExporter output (binary GLB).
+ * @param {{ onStatus?: (sublabel: string) => void }} [opts]
+ * @returns {Promise<{ blob: Blob, optimized: boolean, sourceBytes: number, outputBytes: number, report: object|null }>}
+ * Always resolves. `optimized` is false when we fell back to the
+ * original blob for any reason.
+ */
+export async function optimizeAndValidateGlb(blob, opts = {}) {
+ const { onStatus } = opts;
+ const sourceBytes = blob.size;
+ const fallback = (report = null) => ({
+ blob,
+ optimized: false,
+ sourceBytes,
+ outputBytes: sourceBytes,
+ report,
+ });
+
+ let optimizedBytes;
+ try {
+ // Lazy-load the heavy transform + encoder modules only at save time so
+ // they never weigh down the initial studio load.
+ const [{ WebIO }, { ALL_EXTENSIONS }, fns, { MeshoptEncoder, MeshoptDecoder }] =
+ await Promise.all([
+ import('@gltf-transform/core'),
+ import('@gltf-transform/extensions'),
+ import('@gltf-transform/functions'),
+ import('meshoptimizer'),
+ ]);
+ const { prune, dedup, weld, quantize, meshopt } = fns;
+
+ await Promise.all([MeshoptEncoder.ready, MeshoptDecoder.ready]);
+
+ const io = new WebIO().registerExtensions(ALL_EXTENSIONS).registerDependencies({
+ 'meshopt.encoder': MeshoptEncoder,
+ 'meshopt.decoder': MeshoptDecoder,
+ });
+
+ const srcBuf = new Uint8Array(await blob.arrayBuffer());
+ const doc = await io.readBinary(srcBuf);
+
+ await doc.transform(
+ prune(),
+ dedup(),
+ weld(),
+ quantize(QUANTIZE_OPTS),
+ meshopt({ encoder: MeshoptEncoder, level: 'medium' }),
+ );
+
+ optimizedBytes = await io.writeBinary(doc);
+ } catch (err) {
+ log.warn(
+ '[avatar-studio] GLB optimization failed; uploading original export:',
+ err?.message,
+ );
+ return fallback();
+ }
+
+ // A larger output means the source was already tight (or pathological); keep
+ // the original rather than ship a regression.
+ if (optimizedBytes.byteLength >= sourceBytes) {
+ log.warn('[avatar-studio] optimized GLB not smaller; keeping original export');
+ return fallback();
+ }
+
+ // Validate the optimized bytes with the official Khronos validator. Hard
+ // errors mean a transform produced an invalid GLB — discard and fall back.
+ let report = null;
+ try {
+ const { validateBytes } = await import('gltf-validator');
+ report = await validateBytes(optimizedBytes);
+ const numErrors = report?.issues?.numErrors ?? 0;
+ if (numErrors > 0) {
+ log.warn(
+ `[avatar-studio] optimized GLB failed validation (${numErrors} errors); uploading original export`,
+ );
+ return fallback(report);
+ }
+ } catch (err) {
+ // Validator itself threw — treat as a hard failure of the optimized path
+ // and fall back to the trusted original export.
+ log.warn('[avatar-studio] GLB validation threw; uploading original export:', err?.message);
+ return fallback();
+ }
+
+ const outputBytes = optimizedBytes.byteLength;
+ onStatus?.(`${fmtBytes(sourceBytes)} → ${fmtBytes(outputBytes)}`);
+ log.info(
+ `[avatar-studio] optimized GLB ${fmtBytes(sourceBytes)} → ${fmtBytes(outputBytes)} ` +
+ `(${Math.round((1 - outputBytes / sourceBytes) * 100)}% smaller)`,
+ );
+
+ return {
+ blob: new Blob([optimizedBytes], { type: 'model/gltf-binary' }),
+ optimized: true,
+ sourceBytes,
+ outputBytes,
+ report,
+ };
+}
diff --git a/src/avatar-studio.js b/src/avatar-studio.js
index 841d91008..df1e77ff3 100644
--- a/src/avatar-studio.js
+++ b/src/avatar-studio.js
@@ -25,6 +25,7 @@ import { IdleAnimation } from './idle-animation.js';
import { renderSculptPanel, applyMorphsToRoot } from './avatar-sculpt.js';
import { saveRemoteGlbToAccount, apiFetch } from './account.js';
import { uploadAvatarSnapshot } from './voice/avatar-snapshot.js';
+import { optimizeAndValidateGlb } from './avatar-studio-optimize.js';
import {
collapseAppearance,
hydrateAppearance,
@@ -1148,7 +1149,18 @@ async function saveAvatar() {
// This captures all colours, morphs, and accessories already applied
// to the Three.js scene — no server-side bake needed.
updateSaveOverlay('Exporting model...', 'Capturing colours and accessories');
- const glbBlob = await exportSceneGlb();
+ const rawGlbBlob = await exportSceneGlb();
+ updateProgress(15);
+
+ // ── Step 1b: Compress + validate before upload ──────────────
+ // GLTFExporter output is correct but heavy (uncompressed buffers,
+ // re-embedded textures). Run the same conservative glTF-Transform passes
+ // the server bake uses, then validate. Non-fatal: on any failure this
+ // returns the original export untouched, so the save always completes.
+ updateSaveOverlay('Optimizing model...', 'Compressing geometry for fast loads');
+ const { blob: glbBlob } = await optimizeAndValidateGlb(rawGlbBlob, {
+ onStatus: (sub) => updateSaveOverlay('Optimizing model...', sub),
+ });
updateProgress(20);
// ── Step 2: Upload the GLB + create/update the DB record ────
diff --git a/src/create-prompt.js b/src/create-prompt.js
index a5960aaf3..03a561484 100644
--- a/src/create-prompt.js
+++ b/src/create-prompt.js
@@ -165,13 +165,19 @@ function friendlyJobError(raw) {
}
function mapSubmitError(status, data) {
- const code = data?.error?.code || data?.code;
+ // The API error envelope is { error: <code string>, error_description: <message> }
+ // (see api/_lib/http.js error()). Read those fields directly — older code that
+ // reached for data.error.code / data.message never matched and collapsed every
+ // failure into the generic fallback, hiding the real reason from the user.
+ const code = typeof data?.error === 'string' ? data.error : data?.code;
+ const description = data?.error_description;
if (status === 429) return 'You\'re generating too fast — wait a moment and try again.';
if (code === 'regen_unconfigured' || code === 'txt2img_unconfigured') {
return 'The avatar generator isn\'t configured on this deployment yet. Try the <a href="/scan">selfie scanner</a> instead.';
}
if (code === 'txt2img_error') return 'Couldn\'t render a reference image from that prompt. Try rewording it.';
- return data?.error?.message || data?.message || `The avatar engine returned ${status}. Try again.`;
+ if (code === 'regen_provider_error') return 'The avatar engine rejected this job. Try again in a moment.';
+ return description || `The avatar engine returned ${status}. Try again.`;
}
async function pollUntilDone(jobId) {
@@ -188,7 +194,7 @@ async function pollUntilDone(jobId) {
throw new ApiError('redirecting');
}
data = await res.json().catch(() => ({}));
- if (!res.ok) throw new ApiError(data?.error?.message || `status ${res.status}`);
+ if (!res.ok) throw new ApiError(data?.error_description || `status ${res.status}`);
} catch (err) {
if (err instanceof ApiError) throw err;
// Transient network blip — keep polling until the deadline.
diff --git a/src/eth/vanity/eoa-grinder-worker.js b/src/eth/vanity/eoa-grinder-worker.js
index 8483f0860..c29c80dd8 100644
--- a/src/eth/vanity/eoa-grinder-worker.js
+++ b/src/eth/vanity/eoa-grinder-worker.js
@@ -4,7 +4,9 @@
* Unlike the CREATE2 grinder (which searches salts for a deterministic
* *contract* address and never touches a private key), this worker searches
* for a real keypair: a secp256k1 private key whose derived Ethereum address
- * matches the requested hex prefix/suffix.
+ * matches the requested hex prefix/suffix. The key is a normal wallet you can
+ * import into MetaMask, ethers, viem, Rabby, a hardware-wallet seedless slot,
+ * anything that accepts a raw private key.
*
* Hot loop — incremental point addition (the standard vanity speed trick):
* 1. seed a random base scalar k0 and compute P = k0·G once.
@@ -16,15 +18,33 @@
* uppercase in the pattern switches to an EIP-55 checksum compare
* (one extra keccak over the 40-char ASCII address).
*
- * The recovered private key is reconstructed from the scalar only when a
- * match is found, so the per-attempt cost stays at one point-add + one
- * keccak (+ the affine inversion inside toBytes).
+ * Security model
+ * ──────────────
+ * • Entropy. The base scalar k0 is drawn from `crypto.getRandomValues` over a
+ * full 32 bytes, then reduced mod n. This is the entire defence against the
+ * 2022 "Profanity" disaster, where a 32-bit seed made every ground key
+ * brute-forceable. We never narrow the seed — the unknown to an attacker is
+ * a full 256-bit secret.
+ * • Bounded linear walk. The (k0+i) sequence is only as secret as k0, so a
+ * long walk is cryptographically fine — but we still re-seed every
+ * RESEED_INTERVAL steps so no single run extends one arithmetic progression
+ * indefinitely. Cheap insurance, no correctness cost.
+ * • Independent self-verification. Before a match leaves this worker, the
+ * reconstructed private key is run through a *separate* derivation path
+ * (`getPublicKey` from scratch, not the running point) and the resulting
+ * address is checked against the one we matched. A key that does not control
+ * the advertised address is never emitted — it would be a footgun worth
+ * real money. A zero scalar (probability ~2^-256) is rejected outright.
+ * • No exfiltration. The key exists only in this worker and the one postMessage
+ * that returns it to the page that spawned us. Nothing is transmitted.
*/
import { secp256k1 } from '@noble/curves/secp256k1.js';
import { keccak_256 } from '@noble/hashes/sha3';
const PROGRESS_INTERVAL = 2000;
+/** Re-draw the base scalar after this many attempts (defence-in-depth). */
+const RESEED_INTERVAL = 1_000_000;
const HEX_CHARS = '0123456789abcdef';
const Point = secp256k1.Point;
const N = Point.Fn.ORDER;
@@ -80,6 +100,29 @@ function scalarToBytes(k) {
return out;
}
+/** keccak256(pubkey[1:])[12:] as 40 lowercase hex chars — the address body. */
+function addressOfPubkey(uncompressed) {
+ return bytesToHex(keccak_256(uncompressed.subarray(1)).subarray(12));
+}
+
+/** True iff all 32 bytes are zero (a scalar of 0 mod n — never a valid key). */
+function isZeroKey(bytes) {
+ for (let i = 0; i < bytes.length; i++) if (bytes[i] !== 0) return false;
+ return true;
+}
+
+/** Draw a uniform base scalar in [1, n) from the CSPRNG. */
+function freshBaseScalar() {
+ const seed = new Uint8Array(32);
+ crypto.getRandomValues(seed);
+ let k0 = 0n;
+ for (let i = 0; i < seed.length; i++) k0 = (k0 << 8n) | BigInt(seed[i]);
+ k0 = k0 % N;
+ if (k0 === 0n) k0 = 1n;
+ seed.fill(0);
+ return k0;
+}
+
/**
* @param {{ prefix: string, suffix: string, caseSensitive: boolean }} cfg
*/
@@ -90,20 +133,14 @@ async function grind(cfg) {
const pLen = wantPrefix.length;
const sLen = wantSuffix.length;
- // Random base scalar k0 ∈ [1, n). 24 bytes of entropy is ample; we keep 32.
- const seed = new Uint8Array(32);
- crypto.getRandomValues(seed);
- let k0 = 0n;
- for (let i = 0; i < seed.length; i++) k0 = (k0 << 8n) | BigInt(seed[i]);
- k0 = k0 % N;
- if (k0 === 0n) k0 = 1n;
-
+ let k0 = freshBaseScalar();
let pt = Point.BASE.multiply(k0);
let i = 0n;
let attempts = 0;
let intervalAttempts = 0;
let intervalStart = performance.now();
+ let sinceReseed = 0;
while (running) {
if (paused) {
@@ -114,11 +151,11 @@ async function grind(cfg) {
}
const pub = pt.toBytes(false); // 65 bytes: 0x04 ‖ X ‖ Y
- const digest = keccak_256(pub.subarray(1));
- const lowerHex = bytesToHex(digest.subarray(12));
+ const lowerHex = addressOfPubkey(pub);
attempts++;
intervalAttempts++;
+ sinceReseed++;
const candidate = caseSensitive ? eip55(lowerHex) : lowerHex;
const headOk = !pLen || candidate.startsWith(wantPrefix);
@@ -126,13 +163,30 @@ async function grind(cfg) {
if (headOk && tailOk) {
const priv = scalarToBytes(k0 + i);
+
+ // Independent self-verification: re-derive the address from the
+ // reconstructed key via a fresh code path (not the running point).
+ // A mismatch or zero key would mean a spendable address we cannot
+ // actually control — never emit it; treat as a glitch and reseed.
+ const verifyHex = addressOfPubkey(secp256k1.getPublicKey(priv, false));
+ if (isZeroKey(priv) || verifyHex !== lowerHex) {
+ priv.fill(0);
+ k0 = freshBaseScalar();
+ pt = Point.BASE.multiply(k0);
+ i = 0n;
+ sinceReseed = 0;
+ continue;
+ }
+
+ const privHex = '0x' + bytesToHex(priv);
+ priv.fill(0);
self.postMessage({
type: 'match',
address: '0x' + lowerHex,
addressChecksum: '0x' + eip55(lowerHex),
- privateKey: '0x' + bytesToHex(priv),
+ privateKey: privHex,
attempts,
- }, [priv.buffer]);
+ });
running = false;
return;
}
@@ -140,6 +194,14 @@ async function grind(cfg) {
pt = pt.add(Point.BASE);
i++;
+ // Periodically restart the arithmetic progression from fresh entropy.
+ if (sinceReseed >= RESEED_INTERVAL) {
+ k0 = freshBaseScalar();
+ pt = Point.BASE.multiply(k0);
+ i = 0n;
+ sinceReseed = 0;
+ }
+
if (intervalAttempts >= PROGRESS_INTERVAL) {
const now = performance.now();
const elapsed = (now - intervalStart) / 1000;
diff --git a/src/eth/vanity/eoa-grinder.js b/src/eth/vanity/eoa-grinder.js
index da91e1ab1..baa3ee566 100644
--- a/src/eth/vanity/eoa-grinder.js
+++ b/src/eth/vanity/eoa-grinder.js
@@ -134,11 +134,17 @@ export function grindEoaVanity(opts = {}) {
stopAll();
if (signal) signal.removeEventListener('abort', onAbort);
const totalAttempts = attemptsByWorker.reduce((a, b) => a + b, 0) + msg.attempts;
- const priv = new Uint8Array(msg.privateKey?.buffer ? msg.privateKey : []);
+ // The worker already self-verifies the key against the address;
+ // re-assert the shape here so a malformed message can never reach
+ // the UI as a "wallet". privateKey is always a 0x 32-byte string.
+ if (!/^0x[0-9a-f]{64}$/i.test(msg.privateKey || '') || !/^0x[0-9a-f]{40}$/i.test(msg.address || '')) {
+ reject(new Error('vanity worker returned a malformed key'));
+ return;
+ }
resolve({
address: msg.address,
addressChecksum: msg.addressChecksum || ('0x' + eip55Checksum(msg.address.slice(2))),
- privateKey: typeof msg.privateKey === 'string' ? msg.privateKey : ('0x' + bytesToHex(priv)),
+ privateKey: msg.privateKey,
caseSensitive,
attempts: totalAttempts,
durationMs: performance.now() - startedAt,
@@ -201,10 +207,4 @@ export function grindEoaVanity(opts = {}) {
});
}
-function bytesToHex(bytes) {
- let s = '';
- for (let i = 0; i < bytes.length; i++) s += bytes[i].toString(16).padStart(2, '0');
- return s;
-}
-
export { validatePattern, estimateAttempts, formatTimeEstimate, letterCount, eip55Checksum };
diff --git a/tests/api/ibm-mcp.test.js b/tests/api/ibm-mcp.test.js
index 9b8581584..86e3c34f7 100644
--- a/tests/api/ibm-mcp.test.js
+++ b/tests/api/ibm-mcp.test.js
@@ -56,6 +56,7 @@ vi.mock('../../api/_lib/usage.js', () => ({
const { dispatch, PROTOCOL_VERSION } = await import('../../api/_mcpibm/dispatch.js');
const { graniteX402Amount, priceFor } = await import('../../api/_mcpibm/pricing.js');
+const { isFreeTool } = await import('../../api/_mcpibm/catalog.js');
const AUTH = { userId: null, rateKey: 'test', scope: '', source: 'x402', x402Paid: true };
const call = (name, args) =>
@@ -82,10 +83,11 @@ beforeEach(() => {
});
describe('IBM Granite MCP — dispatch', () => {
- it('lists the five Granite tools with per-call pricing', async () => {
+ it('lists the free getting-started tool plus the five paid Granite tools', async () => {
const r = await dispatch({ jsonrpc: '2.0', id: 1, method: 'tools/list' }, AUTH);
const names = r.result.tools.map((t) => t.name);
expect(names).toEqual([
+ 'ibm_granite_getting_started',
'ibm_granite_chat',
'ibm_granite_code',
'ibm_granite_embed',
@@ -98,6 +100,40 @@ describe('IBM Granite MCP — dispatch', () => {
expect(chat.inputSchema.required).toContain('messages');
});
+ it('getting_started is free: no pricing and no bazaar discovery extension', async () => {
+ const r = await dispatch({ jsonrpc: '2.0', id: 1, method: 'tools/list' }, AUTH);
+ const gs = r.result.tools.find((t) => t.name === 'ibm_granite_getting_started');
+ expect(gs).toBeTruthy();
+ expect(gs.pricing).toBeUndefined();
+ expect(gs.extensions).toBeUndefined();
+ });
+
+ it('isFreeTool flags only the getting-started tool', () => {
+ expect(isFreeTool('ibm_granite_getting_started')).toBe(true);
+ expect(isFreeTool('ibm_granite_chat')).toBe(false);
+ expect(isFreeTool('nonexistent_tool')).toBe(false);
+ expect(graniteX402Amount('ibm_granite_getting_started')).toBeNull();
+ });
+
+ it('getting_started returns the overview with tools, prices, and payment flow — no payment', async () => {
+ const r = await call('ibm_granite_getting_started', {});
+ const out = r.result.structuredContent;
+ expect(out.ok).toBe(true);
+ expect(out.server).toBe('ibm-x402-mcp');
+ expect(out.pricing).toContain('ibm_granite_chat: $0.02/call');
+ expect(out.payment_flow.length).toBeGreaterThan(0);
+ expect(r.result.content[0].text).toContain('Getting Started');
+ // No watsonx call — this tool never touches IBM inference.
+ expect(wx.chat).not.toHaveBeenCalled();
+ });
+
+ it('getting_started focuses on a requested section', async () => {
+ const r = await call('ibm_granite_getting_started', { section: 'pricing' });
+ const out = r.result.structuredContent;
+ expect(out.pricing).toBeTruthy();
+ expect(out.overview).toBeUndefined();
+ });
+
it('initialize advertises the ibm-x402-mcp server', async () => {
const r = await dispatch({ jsonrpc: '2.0', id: 1, method: 'initialize' }, AUTH);
expect(r.result.serverInfo.name).toBe('ibm-x402-mcp');
diff --git a/tests/avatar-studio-optimize.test.js b/tests/avatar-studio-optimize.test.js
new file mode 100644
index 000000000..963d9c195
--- /dev/null
+++ b/tests/avatar-studio-optimize.test.js
@@ -0,0 +1,68 @@
+/**
+ * Tests for the Avatar Studio export optimizer.
+ *
+ * The save flow's central contract is: optimization is best-effort and must
+ * NEVER make the save fail. These tests pin that guarantee — on invalid input
+ * the optimizer falls back to the original blob instead of throwing — and that
+ * a real, structurally-valid GLB round-trips smaller through the pipeline.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { optimizeAndValidateGlb } from '../src/avatar-studio-optimize.js';
+
+// Minimal valid GLB: a 12-byte header + JSON chunk describing an empty asset.
+// The glTF-Transform reader accepts this; it has no meshes, so the compression
+// passes are no-ops and the output is not smaller — exercising the
+// "not smaller → keep original" branch.
+function emptyGlb() {
+ const json = JSON.stringify({ asset: { version: '2.0' } });
+ const enc = new TextEncoder();
+ let jsonBytes = enc.encode(json);
+ // JSON chunk must be 4-byte aligned, padded with spaces.
+ const pad = (4 - (jsonBytes.length % 4)) % 4;
+ if (pad) {
+ const padded = new Uint8Array(jsonBytes.length + pad).fill(0x20);
+ padded.set(jsonBytes);
+ jsonBytes = padded;
+ }
+ const total = 12 + 8 + jsonBytes.length;
+ const buf = new ArrayBuffer(total);
+ const dv = new DataView(buf);
+ dv.setUint32(0, 0x46546c67, true); // 'glTF'
+ dv.setUint32(4, 2, true); // version
+ dv.setUint32(8, total, true); // total length
+ dv.setUint32(12, jsonBytes.length, true); // chunk length
+ dv.setUint32(16, 0x4e4f534a, true); // 'JSON'
+ new Uint8Array(buf, 20).set(jsonBytes);
+ return new Blob([buf], { type: 'model/gltf-binary' });
+}
+
+describe('optimizeAndValidateGlb', () => {
+ it('falls back to the original blob on non-GLB input without throwing', async () => {
+ const garbage = new Blob([new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8])], {
+ type: 'model/gltf-binary',
+ });
+ const result = await optimizeAndValidateGlb(garbage);
+ expect(result.optimized).toBe(false);
+ expect(result.blob).toBe(garbage); // same reference — original returned untouched
+ expect(result.sourceBytes).toBe(garbage.size);
+ expect(result.outputBytes).toBe(garbage.size);
+ });
+
+ it('keeps the original when the optimized output is not smaller', async () => {
+ const glb = emptyGlb();
+ const result = await optimizeAndValidateGlb(glb);
+ // An empty asset has nothing to compress; the meshopt re-encode never
+ // beats the tiny source, so we keep the original rather than regress.
+ expect(result.optimized).toBe(false);
+ expect(result.blob).toBe(glb);
+ });
+
+ it('always resolves to a Blob and consistent size fields', async () => {
+ const glb = emptyGlb();
+ const result = await optimizeAndValidateGlb(glb);
+ expect(result.blob).toBeInstanceOf(Blob);
+ expect(result.outputBytes).toBe(result.blob.size);
+ expect(typeof result.sourceBytes).toBe('number');
+ });
+});
diff --git a/tests/embed-bridge-origin.test.js b/tests/embed-bridge-origin.test.js
index 5cb437d92..d297c5e3a 100644
--- a/tests/embed-bridge-origin.test.js
+++ b/tests/embed-bridge-origin.test.js
@@ -11,6 +11,7 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { EmbedHostBridge } from '../src/embed-host-bridge.js';
import { EmbedActionBridge } from '../src/embed-action-bridge.js';
+import { log } from '../src/shared/log.js';
// ── Tiny fakes ──────────────────────────────────────────────────────────────
@@ -204,7 +205,7 @@ describe('EmbedActionBridge — origin lockdown (iframe side)', () => {
const win = makeFakeWindow();
win.document.referrer = ''; // no seed
win.parent = win; // simulate top-level (not actually iframed)
- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const warn = vi.spyOn(log, 'warn').mockImplementation(() => {});
// Restore parent to a proper poster but keep referrer empty for the seed.
win.parent = {
postMessage(data, targetOrigin) { win._postedToParent.push({ data, targetOrigin }); },
diff --git a/tests/memory-modes.test.js b/tests/memory-modes.test.js
index 5f5fd2abb..2dda05601 100644
--- a/tests/memory-modes.test.js
+++ b/tests/memory-modes.test.js
@@ -1,4 +1,5 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { log } from '../src/shared/log.js';
// localStorage shim — the file-based Memory persists synchronously to
// localStorage for `local` mode, so the Node test env needs a stand-in.
@@ -135,7 +136,7 @@ describe('Memory.load — remote', () => {
describe('Memory.load — unknown mode fallback', () => {
it('warns once and returns a usable local-mode memory', async () => {
- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const warn = vi.spyOn(log, 'warn').mockImplementation(() => {});
const mem = await Memory.load({ mode: 'who-knows', namespace: 'agent-uuid' });
expect(mem.mode).toBe('local');
expect(warn).toHaveBeenCalledOnce();
diff --git a/tests/skill-manifest.test.js b/tests/skill-manifest.test.js
index f578a8339..42663e248 100644
--- a/tests/skill-manifest.test.js
+++ b/tests/skill-manifest.test.js
@@ -1,5 +1,6 @@
import { describe, it, expect, vi } from 'vitest';
import { buildSkillManifest } from '../src/skill-manifest.js';
+import { log } from '../src/shared/log.js';
// Mock the pumpfun skill registrars so the test doesn't need Solana SDK deps
vi.mock('../src/agent-skills-pumpfun.js', () => ({ registerPumpFunSkills: () => {} }));
@@ -51,7 +52,7 @@ describe('buildSkillManifest', () => {
});
it('omits skills without a description and emits a warning', () => {
- const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const warnSpy = vi.spyOn(log, 'warn').mockImplementation(() => {});
const manifest = buildSkillManifest({
agentId: 'test-agent',
version: '1.0.0',
diff --git a/tests/src/evm-eoa-grinder.test.js b/tests/src/evm-eoa-grinder.test.js
new file mode 100644
index 000000000..f16bbc8f5
--- /dev/null
+++ b/tests/src/evm-eoa-grinder.test.js
@@ -0,0 +1,155 @@
+import { describe, it, expect } from 'vitest';
+import { secp256k1 } from '@noble/curves/secp256k1.js';
+import { keccak_256 } from '@noble/hashes/sha3';
+import { computeAddress, Wallet } from 'ethers';
+import {
+ validatePattern,
+ estimateAttempts,
+ letterCount,
+ eip55Checksum,
+} from '../../src/eth/vanity/validation.js';
+
+/**
+ * The EOA grinder worker runs in a Web Worker that vitest can't spawn, so we
+ * re-implement its hot loop here byte-for-byte and assert:
+ * • the derived address equals ethers (the canonical reference),
+ * • the incremental point-addition trick stays consistent with a fresh
+ * scalar multiply (the thing that could silently drift and hand a user a
+ * key that doesn't control the advertised address),
+ * • a real grind actually produces a key that controls its address,
+ * • the encrypted-keystore export path round-trips.
+ */
+
+const Point = secp256k1.Point;
+const N = Point.Fn.ORDER;
+const HEX = '0123456789abcdef';
+
+function bytesToHex(b) {
+ let s = '';
+ for (let i = 0; i < b.length; i++) s += HEX[b[i] >> 4] + HEX[b[i] & 0xf];
+ return s;
+}
+function scalarToBytes(k) {
+ let hex = (((k % N) + N) % N).toString(16);
+ if (hex.length < 64) hex = '0'.repeat(64 - hex.length) + hex;
+ const out = new Uint8Array(32);
+ for (let i = 0; i < 32; i++) out[i] = parseInt(hex.substring(i * 2, i * 2 + 2), 16);
+ return out;
+}
+/** keccak256(pubkey[1:])[12:] → 40 lowercase hex chars. */
+function addressOfPubkey(uncompressed) {
+ return bytesToHex(keccak_256(uncompressed.subarray(1)).subarray(12));
+}
+function addressOfScalar(k) {
+ return addressOfPubkey(Point.BASE.multiply(k).toBytes(false));
+}
+
+/** Mirror the worker hot loop: incremental walk from a base scalar. */
+function grindInProcess({ prefix = '', suffix = '', caseSensitive = false, maxSteps = 5_000_000 }) {
+ const wantP = caseSensitive ? prefix : prefix.toLowerCase();
+ const wantS = caseSensitive ? suffix : suffix.toLowerCase();
+ // Deterministic base so the test is reproducible (the real worker uses CSPRNG).
+ let k0 = 0x9e3779b97f4a7c15n;
+ let pt = Point.BASE.multiply(k0);
+ for (let i = 0n; i < BigInt(maxSteps); i++) {
+ const lowerHex = addressOfPubkey(pt.toBytes(false));
+ const candidate = caseSensitive ? '0x' + eip55Checksum(lowerHex) : lowerHex;
+ const cand = caseSensitive ? candidate.slice(2) : candidate;
+ const headOk = !wantP || cand.startsWith(wantP);
+ const tailOk = !wantS || cand.endsWith(wantS);
+ if (headOk && tailOk) {
+ const priv = scalarToBytes(k0 + i);
+ return { address: '0x' + lowerHex, privateKey: '0x' + bytesToHex(priv), steps: Number(i) + 1 };
+ }
+ pt = pt.add(Point.BASE);
+ }
+ throw new Error('no match within maxSteps');
+}
+
+describe('evm eoa grinder · derivation parity', () => {
+ it('matches ethers for the canonical privkey=1 / =2 vectors', () => {
+ expect(addressOfScalar(1n)).toBe('7e5f4552091a69125d5dfcb7b8c2659029395bdf');
+ expect('0x' + addressOfScalar(1n)).toBe(computeAddress('0x' + '00'.repeat(31) + '01').toLowerCase());
+ expect('0x' + addressOfScalar(2n)).toBe(computeAddress('0x' + '00'.repeat(31) + '02').toLowerCase());
+ });
+
+ it('incremental point-add stays consistent with a fresh scalar multiply', () => {
+ let k0 = 0x1234_5678_9abc_def0n;
+ let pt = Point.BASE.multiply(k0);
+ for (let i = 0n; i < 200n; i++) {
+ // Running point must equal multiply(k0+i); the address must equal ethers'.
+ expect(pt.toHex()).toBe(Point.BASE.multiply(k0 + i).toHex());
+ const addr = '0x' + addressOfPubkey(pt.toBytes(false));
+ const priv = '0x' + bytesToHex(scalarToBytes(k0 + i));
+ expect(addr).toBe(computeAddress(priv).toLowerCase());
+ pt = pt.add(Point.BASE);
+ }
+ });
+});
+
+describe('evm eoa grinder · self-verification invariant', () => {
+ it('every reconstructed key controls its address via an independent path', () => {
+ // The worker self-verifies with getPublicKey (fresh), not the running point.
+ for (const k of [1n, 7n, 999_983n, N - 1n]) {
+ const priv = scalarToBytes(k);
+ const viaRunningPoint = addressOfScalar(k);
+ const viaGetPublicKey = addressOfPubkey(secp256k1.getPublicKey(priv, false));
+ expect(viaGetPublicKey).toBe(viaRunningPoint);
+ expect('0x' + viaGetPublicKey).toBe(new Wallet('0x' + bytesToHex(priv)).address.toLowerCase());
+ }
+ });
+});
+
+describe('evm eoa grinder · end-to-end grind', () => {
+ it('finds a 2-hex prefix and returns a key that owns the address', () => {
+ const { address, privateKey, steps } = grindInProcess({ prefix: 'ee' });
+ expect(address.slice(2).startsWith('ee')).toBe(true);
+ // The single source of truth: ethers derives the SAME address from the key.
+ expect(computeAddress(privateKey).toLowerCase()).toBe(address);
+ expect(steps).toBeGreaterThan(0);
+ });
+
+ it('finds a prefix + suffix together', () => {
+ const { address, privateKey } = grindInProcess({ prefix: 'a', suffix: 'b' });
+ const body = address.slice(2);
+ expect(body.startsWith('a')).toBe(true);
+ expect(body.endsWith('b')).toBe(true);
+ expect(computeAddress(privateKey).toLowerCase()).toBe(address);
+ });
+
+ it('honours an EIP-55 checksum (mixed-case) prefix', () => {
+ const { address, privateKey } = grindInProcess({ prefix: 'A', caseSensitive: true });
+ // The checksummed address must actually start with uppercase A.
+ const checksummed = computeAddress(privateKey); // ethers returns EIP-55
+ expect(checksummed).toBe('0x' + eip55Checksum(address.slice(2)));
+ expect(checksummed.slice(2).startsWith('A')).toBe(true);
+ });
+});
+
+describe('evm eoa grinder · pattern validation', () => {
+ it('lowercase is case-insensitive, mixed case is checksum mode', () => {
+ expect(validatePattern('beef')).toMatchObject({ valid: true, caseSensitive: false, normalized: 'beef' });
+ expect(validatePattern('BeeF')).toMatchObject({ valid: true, caseSensitive: true, normalized: 'BeeF' });
+ });
+ it('rejects non-hex and over-length', () => {
+ expect(validatePattern('xyz').valid).toBe(false);
+ expect(validatePattern('abcdef01234').valid).toBe(false); // 11 > MAX 10
+ });
+ it('estimates checksum patterns as harder per letter', () => {
+ const ci = estimateAttempts(4, letterCount('beef'), false);
+ const cs = estimateAttempts(4, letterCount('beef'), true);
+ expect(cs).toBe(ci * Math.pow(2, 4)); // 4 letters → 2^4 tax
+ });
+});
+
+describe('evm eoa grinder · encrypted keystore export round-trip', () => {
+ it('encrypt → fromEncryptedJson recovers the same key (the UI export path)', async () => {
+ const { address, privateKey } = grindInProcess({ prefix: 'f' });
+ const wallet = new Wallet(privateKey);
+ const json = await wallet.encrypt('correct horse battery staple');
+ const recovered = await Wallet.fromEncryptedJson(json, 'correct horse battery staple');
+ expect(recovered.address.toLowerCase()).toBe(address);
+ // Wrong password must fail — never silently return a different key.
+ await expect(Wallet.fromEncryptedJson(json, 'wrong')).rejects.toThrow();
+ }, 30_000);
+});
diff --git a/tests/src/usdz-pipeline.test.js b/tests/src/usdz-pipeline.test.js
index cd7af7731..4d622a8b0 100644
--- a/tests/src/usdz-pipeline.test.js
+++ b/tests/src/usdz-pipeline.test.js
@@ -32,6 +32,21 @@ if (typeof URL.createObjectURL !== 'function' || URL.createObjectURL.toString().
URL.revokeObjectURL = (id) => { _objectUrlMap.delete(id); };
}
+// jsdom's Blob lacks the standard async `arrayBuffer()` method that the SUT
+// (and the test's own blobBytes helper) rely on. Polyfill it via FileReader,
+// which jsdom does implement. Browser/runtime Blobs already have it, so this
+// only fills the jsdom gap — the source stays untouched per the contract above.
+if (typeof Blob !== 'undefined' && typeof Blob.prototype.arrayBuffer !== 'function') {
+ Blob.prototype.arrayBuffer = function () {
+ return new Promise((resolve, reject) => {
+ const fr = new FileReader();
+ fr.onload = () => resolve(fr.result);
+ fr.onerror = () => reject(fr.error);
+ fr.readAsArrayBuffer(this);
+ });
+ };
+}
+
// jsdom's HTMLImageElement does not actually load `blob:` URLs — onload
// never fires, which deadlocks GLTFLoader's TextureLoader (which awaits
// an Image() per texture). Patch the src setter so it fires onload on
diff --git a/vercel.json b/vercel.json
index 846ac8700..54c9acc84 100644
--- a/vercel.json
+++ b/vercel.json
@@ -70,7 +70,7 @@
},
"routes": [
{
- "src": "/(login|register|forgot-password|reset-password|account|settings|wallet|pay|paywall|vanity-wallet|eth-vanity|dashboard|dashboard-next|dashboard-classic)(/.*)?$",
+ "src": "/(login|register|forgot-password|reset-password|account|settings|wallet|pay|paywall|vanity-wallet|eth-vanity|evm-wallet|dashboard|dashboard-next|dashboard-classic)(/.*)?$",
"headers": {
"content-security-policy": "frame-ancestors 'self'",
"x-frame-options": "SAMEORIGIN"
@@ -199,13 +199,11 @@
},
{
"src": "/ibm",
- "status": 308,
- "headers": { "Location": "/ibm/galaxy" }
+ "dest": "/ibm/index.html"
},
{
"src": "/ibm/",
- "status": 308,
- "headers": { "Location": "/ibm/galaxy" }
+ "dest": "/ibm/index.html"
},
{
"src": "/support",
@@ -435,6 +433,14 @@
"src": "/eth-vanity/",
"dest": "/eth-vanity.html"
},
+ {
+ "src": "/evm-wallet",
+ "dest": "/evm-wallet.html"
+ },
+ {
+ "src": "/evm-wallet/",
+ "dest": "/evm-wallet.html"
+ },
{
"src": "/strategy-lab",
"dest": "/strategy-lab.html"
diff --git a/vite.config.js b/vite.config.js
index 1711105e7..1bd91d545 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -376,6 +376,7 @@ const appConfig = {
// END:DISCOVER_ROUTE
'vanity-wallet': resolve(__dirname, 'public/vanity-wallet.html'),
'eth-vanity': resolve(__dirname, 'public/eth-vanity.html'),
+ 'evm-wallet': resolve(__dirname, 'public/evm-wallet.html'),
pay: resolve(__dirname, 'public/pay/index.html'),
'pay-calls': resolve(__dirname, 'public/pay/calls/index.html'),
'pay-checkout': resolve(__dirname, 'public/pay/c/index.html'),
@@ -431,6 +432,7 @@ const appConfig = {
'aws-marketplace-welcome': resolve(__dirname, 'pages/aws-marketplace/welcome.html'),
aws: resolve(__dirname, 'pages/aws/index.html'),
'agent-trade': resolve(__dirname, 'pages/agent-trade.html'),
+ 'ibm-index': resolve(__dirname, 'pages/ibm/index.html'),
'ibm-galaxy': resolve(__dirname, 'pages/ibm/galaxy.html'),
'ibm-trust-layer': resolve(__dirname, 'pages/ibm/trust-layer.html'),
'ibm-oracle': resolve(__dirname, 'pages/ibm/oracle.html'),
@@ -725,6 +727,8 @@ const appConfig = {
'/p/': resolve(root, 'public/p/index.html'),
'/eth-vanity': resolve(root, 'public/eth-vanity.html'),
'/eth-vanity/': resolve(root, 'public/eth-vanity.html'),
+ '/evm-wallet': resolve(root, 'public/evm-wallet.html'),
+ '/evm-wallet/': resolve(root, 'public/evm-wallet.html'),
'/strategy-lab': resolve(root, 'public/strategy-lab.html'),
'/strategy-lab/': resolve(root, 'public/strategy-lab.html'),
'/sitemap': resolve(root, 'public/sitemap/index.html'),
@@ -1455,6 +1459,7 @@ const appConfig = {
['dist/public/demos/button.html', 'dist/demos/button.html'],
['dist/public/demos/3d-home.html', 'dist/demos/3d-home.html'],
['dist/public/eth-vanity.html', 'dist/eth-vanity.html'],
+ ['dist/public/evm-wallet.html', 'dist/evm-wallet.html'],
];
for (const [from, to] of pairs) {
const src = resolve(__dirname, from);