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(wallet-grinder,create-agent): dashboard vanity grinder, avatar library tab, CSRF on agent-actions

nirholase1449f2089ad
diff --git a/pages/create-agent.html b/pages/create-agent.html
index 84f4b36f4..4d25bb2f9 100644
--- a/pages/create-agent.html
+++ b/pages/create-agent.html
@@ -1099,6 +1099,7 @@
<div class="model-tabs" role="tablist">
<button type="button" class="model-tab is-active" data-pane="starter" role="tab" aria-selected="true">Starter library</button>
+ <button type="button" class="model-tab" data-pane="library" role="tab" aria-selected="false">My avatars</button>
<button type="button" class="model-tab" data-pane="upload" role="tab" aria-selected="false">Upload your own</button>
<button type="button" class="model-tab" data-pane="skip" role="tab" aria-selected="false">Add later</button>
</div>
@@ -1107,6 +1108,10 @@
<div class="starter-grid" id="starter-grid"></div>
</div>
+ <div class="model-pane" data-pane="library">
+ <div class="starter-grid" id="library-grid" aria-live="polite"></div>
+ </div>
+
<div class="model-pane" data-pane="upload">
<div class="dropzone" id="dropzone" role="button" tabindex="0" aria-label="Upload a GLB file">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">
@@ -1131,8 +1136,8 @@
<span class="knob"></span>
</label>
<div class="publish-text">
- <strong>Create without a 3D avatar for now</strong>
- <span>I understand my agent will use a neutral placeholder until I attach a model from its editor.</span>
+ <strong>Don't pick an avatar — use the default body for now</strong>
+ <span>My agent will launch with our default 3D character. I can pick or upload my own anytime from its editor.</span>
</div>
</div>
</div>
diff --git a/pages/dashboard-next/wallet-grinder.html b/pages/dashboard-next/wallet-grinder.html
new file mode 100644
index 000000000..796bc5e1c
--- /dev/null
+++ b/pages/dashboard-next/wallet-grinder.html
@@ -0,0 +1,15 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
+ <title>Wallet Grinder · Dashboard · three.ws</title>
+ <meta name="robots" content="noindex" />
+ <link rel="icon" href="/favicon.ico" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <link rel="stylesheet" href="/dashboard-next/shell.css" />
+ </head>
+ <body>
+ <script type="module" src="/src/dashboard-next/pages/wallet-grinder.js"></script>
+ </body>
+</html>
diff --git a/public/discover/discover.js b/public/discover/discover.js
index 036c2c3e3..cf6473c83 100644
--- a/public/discover/discover.js
+++ b/public/discover/discover.js
@@ -534,7 +534,7 @@ function renderAvatarCard(item) {
.join('');
const viewerUrl = item.viewerUrl || '#';
- const detailUrl = `/agents/${encodeURIComponent(item.avatarId)}`;
+ const detailUrl = `/avatars/${encodeURIComponent(item.avatarId)}`;
card.innerHTML = `
<a class="explore-card-thumb" href="${escapeAttr(detailUrl)}">
@@ -553,7 +553,7 @@ function renderAvatarCard(item) {
${item.viewCount ? `<span class="explore-card-views">${escapeHtml(formatCompact(item.viewCount))} views</span>` : `@${escapeHtml(item.slug || 'avatar')}`}
</span>
<div class="explore-card-actions">
- <a class="explore-card-link" href="${escapeAttr(detailUrl)}">View agent</a>
+ <a class="explore-card-link" href="${escapeAttr(detailUrl)}">View avatar</a>
<button type="button" class="explore-card-link explore-card-link--ghost" data-role="card-embed"
data-kind="avatar"
data-avatar-id="${escapeAttr(String(item.avatarId))}"
diff --git a/src/agent-identity.js b/src/agent-identity.js
index 94ba3c111..99e0844d5 100644
--- a/src/agent-identity.js
+++ b/src/agent-identity.js
@@ -185,20 +185,23 @@ export class AgentIdentity {
* Fire-and-forget — never blocks the caller.
* @param {import('./agent-protocol.js').ActionPayload} action
*/
- recordAction(action) {
+ async recordAction(action) {
if (!this._backendConfirmed) return; // no session — skip to avoid 401 noise
if (!this._owned) return; // viewing someone else's agent — backend would 403
- fetch('/api/agent-actions', {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- credentials: 'include',
- body: JSON.stringify({
- agent_id: this.id,
- type: action.type,
- payload: action.payload,
- source_skill: action.sourceSkill || null,
- }),
- }).catch(() => {}); // non-critical
+ try {
+ const csrf = await csrfHeaders(); // cookie sessions require a CSRF token
+ await fetch('/api/agent-actions', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', ...csrf },
+ credentials: 'include',
+ body: JSON.stringify({
+ agent_id: this.id,
+ type: action.type,
+ payload: action.payload,
+ source_skill: action.sourceSkill || null,
+ }),
+ });
+ } catch {} // non-critical — fire-and-forget
}
/**
diff --git a/src/create-agent.js b/src/create-agent.js
index cb4e5cbfd..afc927c83 100644
--- a/src/create-agent.js
+++ b/src/create-agent.js
@@ -49,6 +49,10 @@ const STARTERS = [
{ id: 'soldier', name: 'Boss', url: '/animations/soldier.glb' },
];
+// Every agent gets a real 3D body. If the user opts to "Add later", we still
+// assign this real default starter on create — an agent is never bodiless.
+const DEFAULT_AVATAR = STARTERS[0];
+
// Core skills every agent gets — matches the API default set. Locked on.
const CORE_SKILLS = [
{ id: 'greet', name: 'Greet', desc: 'Welcomes visitors and opens the conversation.' },
@@ -83,7 +87,17 @@ const state = {
name: '',
description: '',
tags: [],
- model: { mode: 'starter', starterId: '', starterUrl: '', file: null, fileName: '', skipAck: false },
+ model: {
+ mode: 'starter',
+ starterId: '',
+ starterUrl: '',
+ file: null,
+ fileName: '',
+ skipAck: false,
+ avatarId: '',
+ avatarUrl: '',
+ avatarName: '',
+ },
skills: new Set(CORE_SKILLS.map((s) => s.id)),
category: '',
greeting: '',
@@ -259,10 +273,11 @@ function validateStep(n) {
// upload, or an explicit acknowledgment that they're skipping for now.
const hasStarter = state.model.mode === 'starter' && !!state.model.starterUrl;
const hasUpload = state.model.mode === 'upload' && !!state.model.file;
+ const hasLibrary = state.model.mode === 'library' && !!state.model.avatarId;
const acknowledgedSkip = state.model.mode === 'none' && state.model.skipAck;
- if (!hasStarter && !hasUpload && !acknowledgedSkip) {
+ if (!hasStarter && !hasUpload && !hasLibrary && !acknowledgedSkip) {
if (state.model.mode === 'none') {
- setMsg('Tick the box to confirm you want to create this agent without a 3D avatar.', 'err');
+ setMsg('Tick the box to confirm you want to launch with the default 3D body for now.', 'err');
} else {
setMsg('Pick a starter avatar or upload a 3D model — or choose “Add later” and confirm.', 'err');
}
@@ -395,6 +410,102 @@ function selectStarter(id) {
syncModelPreview();
}
+// ── Step 2 (alt): connect an avatar you already own ──────────────────────────
+
+let libraryState = 'idle'; // idle | loading | loaded | error
+let libraryAvatars = [];
+
+async function loadLibraryAvatars() {
+ if (libraryState === 'loaded' || libraryState === 'loading') {
+ renderLibrary();
+ return;
+ }
+ libraryState = 'loading';
+ renderLibrary();
+ try {
+ const res = await apiFetch('/api/avatars?limit=50', { credentials: 'include' });
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ const data = await res.json();
+ libraryAvatars = (data.avatars || []).filter((a) => a && a.id && a.url);
+ libraryState = 'loaded';
+ } catch (err) {
+ log.warn('[create-agent] avatar library load failed', err?.message);
+ libraryState = 'error';
+ }
+ renderLibrary();
+}
+
+function renderLibrary() {
+ const grid = $('library-grid');
+ if (!grid) return;
+ const note = (msg) =>
+ `<p class="panel-help" style="grid-column:1/-1;margin:6px 0 0">${msg}</p>`;
+
+ if (libraryState === 'loading') {
+ grid.innerHTML = note('Loading your avatars…');
+ return;
+ }
+ if (libraryState === 'error') {
+ grid.innerHTML = note(
+ "Couldn't load your avatars. Pick a starter or upload instead — you can connect one later from the editor.",
+ );
+ return;
+ }
+ if (!libraryAvatars.length) {
+ grid.innerHTML = note(
+ "You don't own any avatars yet. Choose a starter or upload your own — it's saved to your library automatically.",
+ );
+ return;
+ }
+
+ grid.innerHTML = '';
+ libraryAvatars.forEach((av) => {
+ const name = av.name || 'Untitled';
+ const card = document.createElement('button');
+ card.type = 'button';
+ card.className = 'starter';
+ card.dataset.avatar = av.id;
+ card.setAttribute('aria-label', `Use your avatar ${name}`);
+ const thumb = av.thumbnail_url
+ ? `<img src="${escapeHtml(av.thumbnail_url)}" alt="" loading="lazy" style="width:100%;height:100%;object-fit:cover" />`
+ : `<model-viewer src="${escapeHtml(av.url)}" alt="${escapeHtml(name)} preview" auto-rotate
+ auto-rotate-delay="0" rotation-per-second="22deg" interaction-prompt="none" disable-zoom disable-pan
+ disable-tap shadow-intensity="0.3" exposure="0.95" environment-image="neutral"
+ camera-orbit="15deg 82deg auto" loading="lazy"></model-viewer>`;
+ card.innerHTML = `<span class="starter-thumb">${thumb}</span><span class="starter-name">${escapeHtml(name)}</span>`;
+ card.addEventListener('click', () => selectLibraryAvatar(av.id));
+ grid.appendChild(card);
+ });
+
+ // Re-apply the highlight when re-rendering with an active selection.
+ if (state.model.mode === 'library' && state.model.avatarId) {
+ grid
+ .querySelectorAll('.starter')
+ .forEach((c) => c.classList.toggle('is-selected', c.dataset.avatar === state.model.avatarId));
+ }
+}
+
+function selectLibraryAvatar(id) {
+ const av = libraryAvatars.find((x) => x.id === id);
+ if (!av) return;
+ state.model = {
+ mode: 'library',
+ starterId: '',
+ starterUrl: '',
+ file: null,
+ fileName: '',
+ skipAck: false,
+ avatarId: av.id,
+ avatarUrl: av.url,
+ avatarName: av.name || 'Untitled',
+ };
+ $('library-grid')
+ .querySelectorAll('.starter')
+ .forEach((c) => c.classList.toggle('is-selected', c.dataset.avatar === id));
+ clearMsg();
+ syncModelPreview();
+}
+
function wireModel() {
// Tabs
document.querySelectorAll('.model-tab').forEach((tab) => {
@@ -416,9 +527,14 @@ function wireModel() {
file: null,
fileName: '',
skipAck: !!$('f-skip-ack')?.checked,
+ avatarId: '',
+ avatarUrl: '',
+ avatarName: '',
};
document.querySelectorAll('.starter').forEach((c) => c.classList.remove('is-selected'));
syncModelPreview();
+ } else if (pane === 'library') {
+ loadLibraryAvatars();
} else if (pane === 'starter' && state.model.mode !== 'starter') {
// re-entering starter tab with nothing chosen — leave unselected
}
@@ -494,9 +610,11 @@ function syncModelPreview() {
const url =
state.model.mode === 'starter'
? state.model.starterUrl
- : state.model.mode === 'upload' && state.model.file
- ? URL.createObjectURL(state.model.file)
- : '';
+ : state.model.mode === 'library'
+ ? state.model.avatarUrl
+ : state.model.mode === 'upload' && state.model.file
+ ? URL.createObjectURL(state.model.file)
+ : '';
// Clear any previous viewer.
el.preview.querySelector('model-viewer')?.remove();
@@ -610,9 +728,11 @@ function renderReview() {
const modelLabel =
state.model.mode === 'starter'
? `${STARTERS.find((s) => s.id === state.model.starterId)?.name || 'Starter'} (starter)`
- : state.model.mode === 'upload'
- ? `${state.model.fileName}.glb (upload)`
- : 'Add later';
+ : state.model.mode === 'library'
+ ? `${state.model.avatarName || 'Avatar'} (your library)`
+ : state.model.mode === 'upload'
+ ? `${state.model.fileName}.glb (upload)`
+ : `${DEFAULT_AVATAR.name} (default — add your own later)`;
const skillNames = [...CORE_SKILLS, ...OPTIONAL_SKILLS]
.filter((s) => state.skills.has(s.id))
@@ -741,6 +861,27 @@ async function submit() {
visibility: 'public',
});
avatarId = av?.id || null;
+ } else if (state.model.mode === 'library' && state.model.avatarId) {
+ // Already an owned avatar — connect it directly, no copy needed.
+ avatarId = state.model.avatarId;
+ }
+
+ // Every agent gets a real 3D body. If the user skipped (or a save above
+ // silently returned nothing), assign the default starter so the agent is
+ // never bodiless — no placeholder, a real owned avatar.
+ if (!avatarId) {
+ setMsg('Setting up a 3D body…', '');
+ const av = await saveRemoteGlbToAccount(DEFAULT_AVATAR.url, {
+ source: 'import',
+ name: state.name.trim(),
+ source_meta: {
+ provider: 'starter-library',
+ source_url: DEFAULT_AVATAR.url,
+ default_assigned: true,
+ },
+ visibility: 'public',
+ });
+ avatarId = av?.id || null;
}
// 2. Create the agent identity.
diff --git a/src/dashboard-next/nav.js b/src/dashboard-next/nav.js
index b7eb849f6..1c1f95d46 100644
--- a/src/dashboard-next/nav.js
+++ b/src/dashboard-next/nav.js
@@ -50,6 +50,7 @@ export const NAV = [
// ── Account ─────────────────────────────────────────────────────────
{ path: '/dashboard/account', label: 'Account', icon: 'user', group: 'Account', tags: ['wallets', 'sns', 'delegation', 'profile', 'action log', 'provider keys'] },
+ { path: '/dashboard/wallet-grinder', label: 'Wallet Grinder', icon: 'sparkle', group: 'Account', tags: ['vanity', 'grind', 'keypair', 'wallet', 'solana', 'evm', 'ethereum', 'base', 'polygon', 'address', 'prefix', 'suffix'] },
{ path: '/dashboard/settings', label: 'Settings', icon: 'settings', group: 'Account', tags: ['sessions', 'notifications', 'preferences', 'storage', 'llm usage', 'vanity'] },
{ path: '/onchain', label: 'On-chain (ERC-8004)', icon: 'chain', group: 'Account', tags: ['erc8004', 'registry', 'onchain', 'identity'], external: true },
];
diff --git a/src/dashboard-next/pages/home.js b/src/dashboard-next/pages/home.js
index 09d292b25..881dc5230 100644
--- a/src/dashboard-next/pages/home.js
+++ b/src/dashboard-next/pages/home.js
@@ -194,7 +194,7 @@ function renderHero(host, avatars, err) {
if (!avatars.length) {
host.innerHTML = `
- <a href="/create/selfie" class="dn-panel dnx-create-cta">
+ <a href="/create" class="dn-panel dnx-create-cta">
<div class="dnx-create-icon">+</div>
<div>
<div class="dn-panel-title" style="margin:0 0 4px;font-size:16px">Create your first avatar</div>
@@ -295,7 +295,7 @@ async function refreshKpis(host, ctx) {
numeric: avatarTotal,
series: avatarSeries,
empty: avatarTotal === 0,
- emptyCta: { label: 'Create from selfie', href: '/create/selfie' },
+ emptyCta: { label: 'Create from selfie', href: '/create' },
},
];
@@ -487,8 +487,8 @@ function renderOnboarding(host, { avatars, agents, widgets }) {
id: 'avatar',
label: 'Create your first avatar',
sub: 'Snap a selfie — your 3D agent is ready in under 60 seconds.',
- href: avatars.length === 0 ? '/create/selfie' : '/create',
- cta: avatars.length === 0 ? 'Snap a selfie →' : 'Create another',
+ href: avatars.length === 0 ? '/start' : '/create',
+ cta: avatars.length === 0 ? 'Start wizard →' : 'Create another',
done: avatars.length > 0,
},
{
@@ -587,7 +587,7 @@ function renderQuickActions(host, { avatars = [], agents = [] } = {}) {
if (firstAvatar) {
defaults.push({ href: `/agents/${encodeURIComponent(firstAvatar.id)}`, title: 'View live agent page', sub: 'See how visitors experience your agent', iconKey: '/dashboard/agents', cat: 'Agents & Identity' });
} else {
- defaults.push({ href: '/create/selfie', title: 'Create avatar from selfie', sub: 'Snap a photo, get a 3D agent in 60 seconds', iconKey: '/create', cat: 'Create & Build' });
+ defaults.push({ href: '/create', title: 'Create avatar from selfie', sub: 'Snap a photo, get a 3D agent in 60 seconds', iconKey: '/create', cat: 'Create & Build' });
}
if (firstAgent) {
defaults.push({ href: `/app?agent=${encodeURIComponent(firstAgent.id)}`, title: 'Open 3D studio', sub: 'Edit, animate, and customize in 3D', iconKey: '/app', cat: '3D & Immersive' });
diff --git a/src/dashboard-next/pages/settings.js b/src/dashboard-next/pages/settings.js
index 93f61cc20..9b1e2b26c 100644
--- a/src/dashboard-next/pages/settings.js
+++ b/src/dashboard-next/pages/settings.js
@@ -370,13 +370,13 @@ function renderVanityTools() {
</div>
<div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:12px">
<div style="padding:16px;border:1px solid var(--nxt-stroke);border-radius:10px">
- <div style="font-weight:600;margin-bottom:6px">Solana vanity ✦</div>
- <div style="font-size:13px;color:var(--nxt-ink-dim);margin-bottom:12px">Generate a Solana keypair where the address starts with text you choose.</div>
- <a class="dn-btn primary" href="/vanity-wallet" target="_blank" rel="noopener">Open tool ↗</a>
+ <div style="font-weight:600;margin-bottom:6px">Solana &amp; EVM wallets ✦</div>
+ <div style="font-size:13px;color:var(--nxt-ink-dim);margin-bottom:12px">Grind a Solana or EVM keypair whose address starts or ends with text you choose — right in the dashboard.</div>
+ <a class="dn-btn primary" href="/dashboard/wallet-grinder">Open grinder →</a>
</div>
<div style="padding:16px;border:1px solid var(--nxt-stroke);border-radius:10px">
- <div style="font-weight:600;margin-bottom:6px">ETH vanity (CREATE2) ✦</div>
- <div style="font-size:13px;color:var(--nxt-ink-dim);margin-bottom:12px">Mine an Ethereum contract address with a custom prefix using CREATE2.</div>
+ <div style="font-weight:600;margin-bottom:6px">ETH contract (CREATE2) ✦</div>
+ <div style="font-size:13px;color:var(--nxt-ink-dim);margin-bottom:12px">Mine an Ethereum contract address with a custom prefix using a CREATE2 salt.</div>
<a class="dn-btn primary" href="/eth-vanity" target="_blank" rel="noopener">Open tool ↗</a>
</div>
</div>
diff --git a/src/dashboard-next/pages/wallet-grinder.js b/src/dashboard-next/pages/wallet-grinder.js
new file mode 100644
index 000000000..b57c190b3
--- /dev/null
+++ b/src/dashboard-next/pages/wallet-grinder.js
@@ -0,0 +1,617 @@
+// dashboard-next — Wallet Grinder.
+//
+// In-dashboard vanity wallet generator for two chains:
+// • Solana — grind a Base58 keypair whose address starts/ends with chosen text.
+// • EVM — grind a secp256k1 keypair whose 0x address matches a hex pattern
+// (Ethereum, Base, Polygon, and every other EVM chain share the
+// same address space, so one key works everywhere).
+//
+// Everything runs in the browser via a pool of Web Workers. The private keys
+// are generated locally and never touch the network — there is no API call in
+// this page that carries key material. The CREATE2 *contract* address grinder
+// is a different tool (it produces a salt, not a key) and is linked out.
+
+import { mountShell } from '../shell.js';
+import { requireUser, esc } from '../api.js';
+import bs58 from 'bs58';
+
+import { grindVanity } from '../../solana/vanity/grinder.js';
+import {
+ validatePattern as validateSol,
+ estimateAttempts as estimateSol,
+ BASE58_ALPHABET,
+ MAX_PATTERN_LENGTH as SOL_MAX,
+} from '../../solana/vanity/validation.js';
+
+import {
+ grindEoaVanity,
+ validatePattern as validateEvm,
+ estimateAttempts as estimateEvm,
+ letterCount as evmLetterCount,
+} from '../../eth/vanity/eoa-grinder.js';
+import { MAX_PATTERN_LENGTH as EVM_MAX } from '../../eth/vanity/validation.js';
+
+const MONO = `'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace`;
+const HW = (typeof navigator !== 'undefined' && navigator.hardwareConcurrency) || 4;
+
+// ── Chain definitions ────────────────────────────────────────────────────────
+
+const CHAINS = {
+ solana: {
+ key: 'solana',
+ label: 'Solana',
+ glyph: '◎',
+ blurb: 'A Solana keypair whose Base58 address matches your pattern.',
+ alphabet: BASE58_ALPHABET,
+ alphabetHint: 'Base58 — case-sensitive. Excludes 0 (zero), O, I, l.',
+ maxLen: SOL_MAX,
+ sample: 'So11111111111111111111111111111111111111112',
+ caseOption: false,
+ keyLabel: 'Secret key',
+ // Solana addresses are intrinsically case-sensitive: every position is
+ // 1-in-58, so the difficulty model is uniform.
+ validate: (p) => {
+ const v = validateSol(p);
+ return { valid: v.valid, errors: v.errors, normalized: p };
+ },
+ expected: (prefix, suffix) => estimateSol((prefix?.length || 0) + (suffix?.length || 0)),
+ run: (opts) => grindVanity(opts),
+ shape: (r) => {
+ const secretArray = Array.from(r.secretKey);
+ return {
+ address: r.publicKey,
+ addressDisplay: r.publicKey,
+ secret: bs58.encode(r.secretKey),
+ secretLabel: 'Secret key (Base58 — import into Phantom/Solflare)',
+ attempts: r.attempts,
+ durationMs: r.durationMs,
+ workers: r.workers,
+ download: {
+ filename: `vanity-${r.publicKey.slice(0, 8)}.json`,
+ mime: 'application/json',
+ body: JSON.stringify(secretArray),
+ hint: 'Solana CLI keypair format (64-byte array)',
+ },
+ };
+ },
+ },
+ evm: {
+ key: 'evm',
+ label: 'EVM',
+ glyph: 'Ξ',
+ blurb: 'A secp256k1 keypair for Ethereum, Base, Polygon, and every EVM chain.',
+ alphabet: '0123456789abcdefABCDEF',
+ alphabetHint: 'Hex — 0-9, a-f. Add uppercase for an EIP-55 checksum match (slower).',
+ maxLen: EVM_MAX,
+ sample: '0x0000000000000000000000000000000000000000',
+ caseOption: false, // casing is inferred from the pattern itself
+ keyLabel: 'Private key',
+ validate: (p) => {
+ const v = validateEvm(p);
+ return { valid: v.valid, errors: v.errors, normalized: v.normalized, caseSensitive: v.caseSensitive };
+ },
+ expected: (prefix, suffix) => {
+ const all = (prefix || '') + (suffix || '');
+ const caseSensitive = /[A-F]/.test(all);
+ return estimateEvm((prefix?.length || 0) + (suffix?.length || 0), evmLetterCount(all), caseSensitive);
+ },
+ run: (opts) => grindEoaVanity(opts),
+ shape: (r) => ({
+ address: r.address,
+ addressDisplay: r.addressChecksum || r.address,
+ secret: r.privateKey,
+ secretLabel: 'Private key (import into MetaMask / Rabbit / any EVM wallet)',
+ attempts: r.attempts,
+ durationMs: r.durationMs,
+ workers: r.workers,
+ download: {
+ filename: `vanity-${(r.addressChecksum || r.address).slice(0, 10)}.json`,
+ mime: 'application/json',
+ body: JSON.stringify({ address: r.addressChecksum || r.address, privateKey: r.privateKey }, null, 2),
+ hint: 'JSON { address, privateKey }',
+ },
+ }),
+ },
+};
+
+// ── Per-tab grind state ──────────────────────────────────────────────────────
+
+const state = {
+ solana: freshTab(),
+ evm: freshTab(),
+};
+let active = 'solana';
+
+function freshTab() {
+ return { prefix: '', suffix: '', workers: Math.min(HW, 8), running: false, paused: false, controller: null, abort: null, result: null, progress: null };
+}
+
+// ── Boot ─────────────────────────────────────────────────────────────────────
+
+(async function boot() {
+ const main = await mountShell();
+ await requireUser();
+ injectStyles();
+
+ main.innerHTML = `
+ <h1 class="dn-h1">Wallet Grinder</h1>
+ <p class="dn-h1-sub">Generate a vanity wallet whose address starts or ends with text you choose. Runs entirely in your browser — keys never leave this device.</p>
+
+ <div class="wg-tabs" role="tablist" aria-label="Chain">
+ ${Object.values(CHAINS).map((c) => `
+ <button class="wg-tab${c.key === active ? ' active' : ''}" role="tab" aria-selected="${c.key === active}" data-tab="${c.key}">
+ <span class="wg-glyph" aria-hidden="true">${c.glyph}</span> ${esc(c.label)}
+ </button>
+ `).join('')}
+ </div>
+
+ <div data-slot="tab"></div>
+
+ <div class="dn-panel wg-create2">
+ <div class="dn-panel-title">Grinding a contract address instead?</div>
+ <div class="dn-panel-sub" style="margin:4px 0 12px">The CREATE2 grinder mines a deployment salt for a deterministic Ethereum <em>contract</em> address — no private key involved.</div>
+ <a class="dn-btn" href="/eth-vanity" target="_blank" rel="noopener">Open CREATE2 grinder ↗</a>
+ </div>
+ `;
+
+ const tabHost = main.querySelector('[data-slot="tab"]');
+ renderTab(tabHost);
+
+ main.querySelectorAll('[data-tab]').forEach((btn) => {
+ btn.addEventListener('click', () => {
+ if (btn.dataset.tab === active) return;
+ active = btn.dataset.tab;
+ main.querySelectorAll('[data-tab]').forEach((b) => {
+ const on = b.dataset.tab === active;
+ b.classList.toggle('active', on);
+ b.setAttribute('aria-selected', String(on));
+ });
+ renderTab(tabHost);
+ });
+ });
+})();
+
+// ── Tab render ───────────────────────────────────────────────────────────────
+
+function renderTab(host) {
+ const chain = CHAINS[active];
+ const t = state[active];
+
+ host.innerHTML = `
+ <div class="dn-panel">
+ <div class="dn-panel-title">${esc(chain.label)} vanity wallet</div>
+ <div class="dn-panel-sub" style="margin:4px 0 16px">${esc(chain.blurb)}</div>
+
+ <div class="wg-grid">
+ <label class="wg-field">
+ <span class="wg-label">Starts with (prefix)</span>
+ <input class="wg-input" data-field="prefix" type="text" inputmode="latin" autocomplete="off" spellcheck="false"
+ maxlength="${chain.maxLen}" placeholder="e.g. ${active === 'solana' ? 'AGNT' : 'dead'}" value="${esc(t.prefix)}" />
+ </label>
+ <label class="wg-field">
+ <span class="wg-label">Ends with (suffix)</span>
+ <input class="wg-input" data-field="suffix" type="text" inputmode="latin" autocomplete="off" spellcheck="false"
+ maxlength="${chain.maxLen}" placeholder="optional" value="${esc(t.suffix)}" />
+ </label>
+ </div>
+ <div class="wg-hint">${esc(chain.alphabetHint)}</div>
+
+ <div class="wg-preview" data-slot="preview"></div>
+ <div class="wg-difficulty" data-slot="difficulty"></div>
+
+ <label class="wg-field" style="margin-top:16px">
+ <span class="wg-label">CPU cores <span class="wg-cores" data-slot="cores-val">${t.workers}</span> / ${HW}</span>
+ <input class="wg-range" data-field="workers" type="range" min="1" max="${HW}" value="${t.workers}" />
+ </label>
+
+ <div class="wg-actions" data-slot="actions"></div>
+ <div data-slot="progress"></div>
+ </div>
+
+ <div data-slot="result"></div>
+
+ <div class="dn-panel wg-safety">
+ <div class="dn-panel-title">🔒 Key safety</div>
+ <ul class="wg-safety-list">
+ <li>Keys are generated locally in your browser and are <strong>never sent to any server</strong>.</li>
+ <li>Anyone with the ${active === 'solana' ? 'secret key' : 'private key'} controls the wallet. Store it in a password manager or hardware wallet.</li>
+ <li>Close this tab after saving — the key is not persisted anywhere on this site.</li>
+ <li>Longer patterns are exponentially slower. ${active === 'solana' ? 'Each Base58 character is 1-in-58.' : 'Each hex character is 1-in-16 (1-in-32 if uppercase).'}</li>
+ </ul>
+ </div>
+ `;
+
+ const fields = {
+ prefix: host.querySelector('[data-field="prefix"]'),
+ suffix: host.querySelector('[data-field="suffix"]'),
+ workers: host.querySelector('[data-field="workers"]'),
+ };
+
+ const refresh = () => {
+ updatePreview(host, chain, t);
+ updateDifficulty(host, chain, t);
+ renderActions(host, chain, t, refresh);
+ };
+
+ fields.prefix.addEventListener('input', () => {
+ t.prefix = sanitize(fields.prefix.value, chain);
+ if (fields.prefix.value !== t.prefix) fields.prefix.value = t.prefix;
+ refresh();
+ });
+ fields.suffix.addEventListener('input', () => {
+ t.suffix = sanitize(fields.suffix.value, chain);
+ if (fields.suffix.value !== t.suffix) fields.suffix.value = t.suffix;
+ refresh();
+ });
+ fields.workers.addEventListener('input', () => {
+ t.workers = Number(fields.workers.value);
+ host.querySelector('[data-slot="cores-val"]').textContent = t.workers;
+ });
+
+ refresh();
+ if (t.result) renderResult(host, chain, t.result);
+ if (t.running && t.progress) renderProgress(host, t.progress);
+}
+
+// ── Input sanitizing & validation ────────────────────────────────────────────
+
+function sanitize(value, chain) {
+ let v = value;
+ if (chain.key === 'evm' && (v.startsWith('0x') || v.startsWith('0X'))) v = v.slice(2);
+ const allowed = new Set(chain.alphabet);
+ v = Array.from(v).filter((c) => allowed.has(c)).join('');
+ return v.slice(0, chain.maxLen);
+}
+
+function validity(chain, t) {
+ const errs = [];
+ if (t.prefix) {
+ const v = chain.validate(t.prefix);
+ if (!v.valid) errs.push(...v.errors);
+ }
+ if (t.suffix) {
+ const v = chain.validate(t.suffix);
+ if (!v.valid) errs.push(...v.errors);
+ }
+ const hasPattern = !!(t.prefix || t.suffix);
+ return { ok: hasPattern && errs.length === 0, hasPattern, errors: errs };
+}
+
+// ── Preview ──────────────────────────────────────────────────────────────────
+
+function updatePreview(host, chain, t) {
+ const el = host.querySelector('[data-slot="preview"]');
+ const addr = chain.sample;
+ const pfx = t.prefix;
+ const sfx = t.suffix;
+
+ if (!pfx && !sfx) {
+ el.innerHTML = `<span class="wg-faded">${esc(addr)}</span>`;
+ return;
+ }
+
+ // Build a synthetic preview: prefix + filler + suffix, fit to sample length.
+ const base = chain.key === 'evm' ? addr.slice(2) : addr;
+ const lead = chain.key === 'evm' ? '0x' : '';
+ const fillLen = Math.max(0, base.length - pfx.length - sfx.length);
+ const filler = base.slice(pfx.length, pfx.length + fillLen);
+ el.innerHTML =
+ `${lead}` +
+ (pfx ? `<span class="wg-match">${esc(pfx)}</span>` : '') +
+ `<span class="wg-faded">${esc(filler)}</span>` +
+ (sfx ? `<span class="wg-match">${esc(sfx)}</span>` : '');
+}
+
+// ── Difficulty estimate ──────────────────────────────────────────────────────
+
+function updateDifficulty(host, chain, t) {
+ const el = host.querySelector('[data-slot="difficulty"]');
+ const v = validity(chain, t);
+
+ if (v.errors.length) {
+ el.innerHTML = `<span class="wg-err">⚠ ${esc(v.errors[0])}</span>`;
+ return;
+ }
+ if (!v.hasPattern) {
+ el.innerHTML = `<span class="wg-faded-sm">Enter a prefix or suffix to begin.</span>`;
+ return;
+ }
+
+ const expected = chain.expected(t.prefix, t.suffix);
+ const caseNote = chain.key === 'evm' && /[A-F]/.test(t.prefix + t.suffix)
+ ? ' · checksum (case-sensitive) match'
+ : '';
+ el.innerHTML = `
+ <span class="wg-tag-diff">1 in ${fmtBig(expected)}</span>
+ <span class="wg-faded-sm">expected attempts${esc(caseNote)}. Time depends on your CPU — start to see a live rate.</span>
+ `;
+}
+
+// ── Actions (start / pause / stop) ───────────────────────────────────────────
+
+function renderActions(host, chain, t, refresh) {
+ const el = host.querySelector('[data-slot="actions"]');
+ const v = validity(chain, t);
+
+ if (!t.running) {
+ el.innerHTML = `<button class="dn-btn primary" data-act="start" ${v.ok ? '' : 'disabled'}>Start grinding</button>`;
+ el.querySelector('[data-act="start"]').addEventListener('click', () => startGrind(host, chain, t, refresh));
+ return;
+ }
+
+ el.innerHTML = `
+ <button class="dn-btn" data-act="pause">${t.paused ? 'Resume' : 'Pause'}</button>
+ <button class="dn-btn danger" data-act="stop">Stop</button>
+ `;
+ el.querySelector('[data-act="pause"]').addEventListener('click', () => {
+ if (!t.controller) return;
+ if (t.paused) { t.controller.resume(); t.paused = false; }
+ else { t.controller.pause(); t.paused = true; }
+ refresh();
+ });
+ el.querySelector('[data-act="stop"]').addEventListener('click', () => {
+ t.abort?.abort();
+ });
+}
+
+async function startGrind(host, chain, t, refresh) {
+ t.running = true;
+ t.paused = false;
+ t.result = null;
+ t.progress = { attempts: 0, rate: 0, eta: 'estimating…', sample: '' };
+ t.controller = {};
+ t.abort = new AbortController();
+
+ host.querySelector('[data-slot="result"]').innerHTML = '';
+ refresh();
+ renderProgress(host, t.progress);
+
+ try {
+ const result = await chain.run({
+ prefix: t.prefix || undefined,
+ suffix: t.suffix || undefined,
+ maxWorkers: t.workers,
+ controller: t.controller,
+ signal: t.abort.signal,
+ onProgress: (p) => {
+ t.progress = p;
+ if (t.running) renderProgress(host, p);
+ },
+ });
+ t.result = chain.shape(result);
+ t.running = false;
+ t.paused = false;
+ refresh();
+ renderResult(host, chain, t.result);
+ toast('Match found ✦');
+ } catch (err) {
+ t.running = false;
+ t.paused = false;
+ refresh();
+ const prog = host.querySelector('[data-slot="progress"]');
+ if (err?.name === 'AbortError') {
+ prog.innerHTML = `<div class="wg-stopped">Stopped after ${fmtNum(t.progress?.attempts || 0)} attempts.</div>`;
+ } else {
+ prog.innerHTML = `<div class="wg-err-box">⚠ ${esc(err?.message || 'Grind failed')}</div>`;
+ }
+ }
+}
+
+// ── Progress ─────────────────────────────────────────────────────────────────
+
+function renderProgress(host, p) {
+ const el = host.querySelector('[data-slot="progress"]');
+ if (!el) return;
+ const rate = p.rate ? `${fmtNum(Math.round(p.rate))}/s` : (p.paused ? 'paused' : '—');
+ el.innerHTML = `
+ <div class="wg-progress">
+ <div class="wg-progress-bar"><div class="wg-progress-fill${p.paused ? ' paused' : ''}"></div></div>
+ <div class="wg-progress-stats">
+ <div><span class="wg-stat">${fmtNum(p.attempts || 0)}</span><span class="wg-stat-label">attempts</span></div>
+ <div><span class="wg-stat">${esc(rate)}</span><span class="wg-stat-label">rate</span></div>
+ <div><span class="wg-stat">${esc(p.eta || '—')}</span><span class="wg-stat-label">est. remaining</span></div>
+ </div>
+ ${p.sample ? `<div class="wg-sample">trying ${esc(p.sample)}</div>` : ''}
+ </div>
+ `;
+}
+
+// ── Result ───────────────────────────────────────────────────────────────────
+
+function renderResult(host, chain, r) {
+ const el = host.querySelector('[data-slot="result"]');
+ const pfx = state[active].prefix;
+ const sfx = state[active].suffix;
+ el.innerHTML = `
+ <div class="dn-panel wg-result">
+ <div class="wg-result-head">
+ <span class="dn-tag success">Match found</span>
+ <span class="wg-faded-sm">${fmtNum(r.attempts)} attempts · ${(r.durationMs / 1000).toFixed(1)}s · ${r.workers} core${r.workers > 1 ? 's' : ''}</span>
+ </div>
+
+ <div class="wg-result-label">Address</div>
+ <div class="wg-addr">${highlightAddr(r.addressDisplay, pfx, sfx)}</div>
+ <button class="dn-btn" data-act="copy-addr" style="margin-top:8px">Copy address</button>
+
+ <div class="wg-result-label" style="margin-top:18px">${esc(r.secretLabel)}</div>
+ <div class="wg-secret-wrap">
+ <div class="wg-secret" data-slot="secret">${'•'.repeat(44)}</div>
+ <div class="wg-secret-actions">
+ <button class="dn-btn" data-act="reveal">Reveal</button>
+ <button class="dn-btn" data-act="copy-secret">Copy</button>
+ <button class="dn-btn primary" data-act="download">Download</button>
+ </div>
+ </div>
+ <div class="wg-faded-sm" style="margin-top:8px">${esc(r.download.hint)} · keep this secret offline.</div>
+ </div>
+ `;
+
+ let revealed = false;
+ const secretEl = el.querySelector('[data-slot="secret"]');
+ el.querySelector('[data-act="reveal"]').addEventListener('click', (e) => {
+ revealed = !revealed;
+ secretEl.textContent = revealed ? r.secret : '•'.repeat(44);
+ secretEl.classList.toggle('shown', revealed);
+ e.currentTarget.textContent = revealed ? 'Hide' : 'Reveal';
+ });
+ el.querySelector('[data-act="copy-addr"]').addEventListener('click', () => copy(r.addressDisplay, 'Address copied'));
+ el.querySelector('[data-act="copy-secret"]').addEventListener('click', () => copy(r.secret, `${chain.keyLabel} copied`));
+ el.querySelector('[data-act="download"]').addEventListener('click', () => download(r.download));
+}
+
+function highlightAddr(addr, pfx, sfx) {
+ const lead = addr.startsWith('0x') ? '0x' : '';
+ const body = lead ? addr.slice(2) : addr;
+ let head = 0;
+ if (pfx && body.toLowerCase().startsWith(pfx.toLowerCase())) head = pfx.length;
+ let tail = 0;
+ if (sfx && body.toLowerCase().endsWith(sfx.toLowerCase())) tail = sfx.length;
+ const start = body.slice(0, head);
+ const mid = body.slice(head, body.length - tail);
+ const end = tail ? body.slice(body.length - tail) : '';
+ return `${lead}` +
+ (start ? `<span class="wg-match">${esc(start)}</span>` : '') +
+ `${esc(mid)}` +
+ (end ? `<span class="wg-match">${esc(end)}</span>` : '');
+}
+
+// ── Helpers ──────────────────────────────────────────────────────────────────
+
+function download({ filename, mime, body }) {
+ const blob = new Blob([body], { type: mime });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = filename;
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+ URL.revokeObjectURL(url);
+ toast('Keypair downloaded');
+}
+
+async function copy(text, msg) {
+ try {
+ await navigator.clipboard.writeText(text);
+ toast(msg);
+ } catch {
+ toast('Copy failed — select manually');
+ }
+}
+
+function fmtNum(n) {
+ return Number(n || 0).toLocaleString('en-US');
+}
+
+function fmtBig(n) {
+ if (!Number.isFinite(n)) return '∞';
+ if (n >= 1e12) return (n / 1e12).toFixed(1).replace(/\.0$/, '') + ' trillion';
+ if (n >= 1e9) return (n / 1e9).toFixed(1).replace(/\.0$/, '') + ' billion';
+ if (n >= 1e6) return (n / 1e6).toFixed(1).replace(/\.0$/, '') + ' million';
+ if (n >= 1e3) return (n / 1e3).toFixed(1).replace(/\.0$/, '') + 'K';
+ return String(Math.round(n));
+}
+
+function toast(msg) {
+ let el = document.getElementById('dn-toast');
+ if (!el) {
+ el = document.createElement('div');
+ el.id = 'dn-toast';
+ el.style.cssText = `
+ position:fixed;left:50%;bottom:32px;transform:translateX(-50%) translateY(20px);
+ background:rgba(20,21,28,0.95);border:1px solid var(--nxt-stroke-strong);
+ color:var(--nxt-ink);padding:9px 16px;border-radius:999px;font-size:13px;
+ z-index:9999;opacity:0;transition:opacity .18s,transform .18s;
+ backdrop-filter:blur(20px);-webkit-backdrop-filter:blur(20px);
+ box-shadow:0 8px 24px rgba(0,0,0,0.4);pointer-events:none;`;
+ document.body.appendChild(el);
+ }
+ el.textContent = msg;
+ requestAnimationFrame(() => {
+ el.style.opacity = '1';
+ el.style.transform = 'translateX(-50%) translateY(0)';
+ });
+ clearTimeout(el._t);
+ el._t = setTimeout(() => {
+ el.style.opacity = '0';
+ el.style.transform = 'translateX(-50%) translateY(20px)';
+ }, 1800);
+}
+
+// ── Styles ───────────────────────────────────────────────────────────────────
+
+function injectStyles() {
+ if (document.getElementById('wg-css')) return;
+ const css = document.createElement('style');
+ css.id = 'wg-css';
+ css.textContent = `
+ .wg-tabs { display:flex; gap:8px; margin:18px 0; }
+ .wg-tab { display:inline-flex; align-items:center; gap:7px; padding:8px 16px; font-size:13.5px;
+ border:1px solid var(--nxt-stroke); background:rgba(255,255,255,0.02); color:var(--nxt-ink-dim);
+ border-radius:999px; cursor:pointer; transition:all .16s; font-family:inherit; }
+ .wg-tab:hover { color:var(--nxt-ink); border-color:var(--nxt-stroke-strong); }
+ .wg-tab.active { background:var(--nxt-accent); color:#000; border-color:var(--nxt-accent); font-weight:600; }
+ .wg-glyph { font-size:15px; }
+
+ .wg-grid { display:grid; grid-template-columns:1fr 1fr; gap:14px; }
+ @media (max-width:600px) { .wg-grid { grid-template-columns:1fr; } }
+ .wg-field { display:flex; flex-direction:column; gap:6px; }
+ .wg-label { font-size:12px; color:var(--nxt-ink-fade); }
+ .wg-cores { color:var(--nxt-ink); font-variant-numeric:tabular-nums; }
+ .wg-input { font-family:${MONO}; font-size:14px; padding:10px 12px; border-radius:var(--nxt-radius-sm);
+ background:rgba(255,255,255,0.03); border:1px solid var(--nxt-stroke); color:var(--nxt-ink);
+ transition:border-color .16s; }
+ .wg-input:focus { outline:none; border-color:var(--nxt-stroke-strong); background:rgba(255,255,255,0.05); }
+ .wg-input::placeholder { color:var(--nxt-ink-fade); }
+ .wg-range { width:100%; accent-color:var(--nxt-accent); cursor:pointer; }
+ .wg-hint { font-size:12px; color:var(--nxt-ink-fade); margin-top:8px; }
+
+ .wg-preview { font-family:${MONO}; font-size:14px; padding:12px 14px; margin-top:14px;
+ background:rgba(0,0,0,0.35); border:1px solid var(--nxt-stroke); border-radius:var(--nxt-radius-sm);
+ word-break:break-all; line-height:1.5; min-height:1.5em; }
+ .wg-match { background:var(--nxt-accent); color:#000; padding:0 2px; border-radius:3px; font-weight:700; }
+ .wg-faded { color:var(--nxt-ink-fade); }
+ .wg-faded-sm { color:var(--nxt-ink-fade); font-size:12.5px; }
+ .wg-difficulty { margin-top:10px; display:flex; align-items:center; gap:10px; flex-wrap:wrap; font-size:12.5px; }
+ .wg-tag-diff { display:inline-flex; padding:3px 10px; border-radius:999px; font-size:12px; font-weight:600;
+ background:rgba(255,255,255,0.06); border:1px solid var(--nxt-stroke); color:var(--nxt-ink);
+ font-variant-numeric:tabular-nums; white-space:nowrap; }
+ .wg-err { color:var(--nxt-danger); }
+
+ .wg-actions { display:flex; gap:10px; margin-top:18px; flex-wrap:wrap; }
+
+ .wg-progress { margin-top:16px; padding:16px; border:1px solid var(--nxt-stroke); border-radius:var(--nxt-radius);
+ background:rgba(0,0,0,0.3); }
+ .wg-progress-bar { height:4px; border-radius:2px; background:var(--nxt-stroke); overflow:hidden; margin-bottom:14px; }
+ .wg-progress-fill { height:100%; width:40%; border-radius:2px; background:var(--nxt-accent);
+ animation:wg-indeterminate 1.1s ease-in-out infinite; }
+ .wg-progress-fill.paused { animation:none; opacity:0.4; }
+ @keyframes wg-indeterminate { 0% { transform:translateX(-120%); } 100% { transform:translateX(320%); } }
+ .wg-progress-stats { display:grid; grid-template-columns:repeat(3,1fr); gap:10px; }
+ .wg-progress-stats > div { display:flex; flex-direction:column; gap:3px; }
+ .wg-stat { font-size:18px; font-weight:700; letter-spacing:-0.01em; font-variant-numeric:tabular-nums; }
+ .wg-stat-label { font-size:11px; color:var(--nxt-ink-fade); text-transform:uppercase; letter-spacing:0.05em; }
+ .wg-sample { margin-top:12px; font-family:${MONO}; font-size:11.5px; color:var(--nxt-ink-fade); word-break:break-all; }
+ .wg-stopped { margin-top:16px; padding:12px 14px; border:1px solid var(--nxt-stroke); border-radius:var(--nxt-radius-sm);
+ color:var(--nxt-ink-dim); font-size:13px; }
+ .wg-err-box { margin-top:16px; padding:12px 14px; border:1px solid var(--nxt-danger); border-radius:var(--nxt-radius-sm);
+ color:var(--nxt-danger); font-size:13px; }
+
+ .wg-result { margin-top:16px; border-color:var(--nxt-stroke-strong); }
+ .wg-result-head { display:flex; align-items:center; gap:12px; flex-wrap:wrap; margin-bottom:16px; }
+ .wg-result-label { font-size:11.5px; color:var(--nxt-ink-fade); text-transform:uppercase; letter-spacing:0.05em; margin-bottom:6px; }
+ .wg-addr { font-family:${MONO}; font-size:15px; word-break:break-all; line-height:1.5; }
+ .wg-secret-wrap { display:flex; flex-direction:column; gap:10px; }
+ .wg-secret { font-family:${MONO}; font-size:13px; padding:12px 14px; border-radius:var(--nxt-radius-sm);
+ background:rgba(0,0,0,0.4); border:1px solid var(--nxt-stroke); color:var(--nxt-ink-fade);
+ word-break:break-all; line-height:1.5; user-select:all; }
+ .wg-secret.shown { color:var(--nxt-ink); border-color:var(--nxt-stroke-strong); }
+ .wg-secret-actions { display:flex; gap:8px; flex-wrap:wrap; }
+
+ .wg-create2, .wg-safety { margin-top:16px; }
+ .wg-safety-list { margin:8px 0 0; padding-left:18px; display:flex; flex-direction:column; gap:7px;
+ font-size:13px; color:var(--nxt-ink-dim); line-height:1.5; }
+ .wg-safety-list strong { color:var(--nxt-ink); }
+ `;
+ document.head.appendChild(css);
+}
diff --git a/src/eth/vanity/eoa-grinder-worker.js b/src/eth/vanity/eoa-grinder-worker.js
new file mode 100644
index 000000000..8483f0860
--- /dev/null
+++ b/src/eth/vanity/eoa-grinder-worker.js
@@ -0,0 +1,158 @@
+/**
+ * EVM externally-owned-account (EOA) vanity grinder Web Worker.
+ *
+ * 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.
+ *
+ * Hot loop — incremental point addition (the standard vanity speed trick):
+ * 1. seed a random base scalar k0 and compute P = k0·G once.
+ * 2. each step, the candidate private key is (k0 + i) mod n and its public
+ * point is the running P. Deriving the next point is a single point
+ * addition P += G — far cheaper than a fresh scalar multiplication.
+ * 3. address = keccak256(uncompressedPubkey[1:])[12:] (last 20 bytes).
+ * 4. case-INsensitive patterns compare the lowercase hex directly; any
+ * 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).
+ */
+
+import { secp256k1 } from '@noble/curves/secp256k1.js';
+import { keccak_256 } from '@noble/hashes/sha3';
+
+const PROGRESS_INTERVAL = 2000;
+const HEX_CHARS = '0123456789abcdef';
+const Point = secp256k1.Point;
+const N = Point.Fn.ORDER;
+
+let running = false;
+let paused = false;
+
+self.onmessage = (e) => {
+ const msg = e.data;
+ if (msg?.type === 'start') {
+ running = true;
+ paused = false;
+ grind(msg);
+ } else if (msg?.type === 'stop') {
+ running = false;
+ } else if (msg?.type === 'pause') {
+ paused = true;
+ } else if (msg?.type === 'resume') {
+ paused = false;
+ }
+};
+
+function bytesToHex(bytes) {
+ let s = '';
+ for (let i = 0; i < bytes.length; i++) {
+ const b = bytes[i];
+ s += HEX_CHARS[b >> 4] + HEX_CHARS[b & 0xf];
+ }
+ return s;
+}
+
+/** EIP-55 checksum of a 40-char lowercase hex address (inlined for the hot loop). */
+function eip55(lowerHex) {
+ const ascii = new Uint8Array(40);
+ for (let i = 0; i < 40; i++) ascii[i] = lowerHex.charCodeAt(i);
+ const h = keccak_256(ascii);
+ let out = '';
+ for (let i = 0; i < 40; i++) {
+ const c = lowerHex.charCodeAt(i);
+ if (c < 0x61) { out += lowerHex[i]; continue; } // digit — never cased
+ const nibble = (i & 1) === 0 ? (h[i >> 1] >> 4) : (h[i >> 1] & 0xf);
+ out += nibble >= 8 ? lowerHex[i].toUpperCase() : lowerHex[i];
+ }
+ return out;
+}
+
+/** A scalar (mod n) → 32 big-endian bytes — the canonical 0x private-key body. */
+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;
+}
+
+/**
+ * @param {{ prefix: string, suffix: string, caseSensitive: boolean }} cfg
+ */
+async function grind(cfg) {
+ const caseSensitive = !!cfg.caseSensitive;
+ const wantPrefix = caseSensitive ? (cfg.prefix || '') : (cfg.prefix || '').toLowerCase();
+ const wantSuffix = caseSensitive ? (cfg.suffix || '') : (cfg.suffix || '').toLowerCase();
+ 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 pt = Point.BASE.multiply(k0);
+ let i = 0n;
+
+ let attempts = 0;
+ let intervalAttempts = 0;
+ let intervalStart = performance.now();
+
+ while (running) {
+ if (paused) {
+ await new Promise((r) => setTimeout(r, 80));
+ intervalStart = performance.now();
+ intervalAttempts = 0;
+ continue;
+ }
+
+ const pub = pt.toBytes(false); // 65 bytes: 0x04 ‖ X ‖ Y
+ const digest = keccak_256(pub.subarray(1));
+ const lowerHex = bytesToHex(digest.subarray(12));
+
+ attempts++;
+ intervalAttempts++;
+
+ const candidate = caseSensitive ? eip55(lowerHex) : lowerHex;
+ const headOk = !pLen || candidate.startsWith(wantPrefix);
+ const tailOk = !sLen || candidate.endsWith(wantSuffix);
+
+ if (headOk && tailOk) {
+ const priv = scalarToBytes(k0 + i);
+ self.postMessage({
+ type: 'match',
+ address: '0x' + lowerHex,
+ addressChecksum: '0x' + eip55(lowerHex),
+ privateKey: '0x' + bytesToHex(priv),
+ attempts,
+ }, [priv.buffer]);
+ running = false;
+ return;
+ }
+
+ pt = pt.add(Point.BASE);
+ i++;
+
+ if (intervalAttempts >= PROGRESS_INTERVAL) {
+ const now = performance.now();
+ const elapsed = (now - intervalStart) / 1000;
+ const rate = elapsed > 0 ? intervalAttempts / elapsed : 0;
+ self.postMessage({
+ type: 'progress',
+ attempts,
+ rate,
+ sample: '0x' + (caseSensitive ? candidate : lowerHex),
+ });
+ intervalStart = now;
+ intervalAttempts = 0;
+ await new Promise((r) => setTimeout(r, 0));
+ }
+ }
+}
diff --git a/src/eth/vanity/eoa-grinder.js b/src/eth/vanity/eoa-grinder.js
new file mode 100644
index 000000000..da91e1ab1
--- /dev/null
+++ b/src/eth/vanity/eoa-grinder.js
@@ -0,0 +1,210 @@
+/**
+ * EVM EOA vanity grinder — main-thread API.
+ *
+ * Spawns a pool of Web Workers (one per logical core, capped) that race to
+ * find a secp256k1 keypair whose Ethereum address matches the requested hex
+ * prefix and/or suffix. First match wins; the rest are terminated.
+ *
+ * Usage:
+ * const { address, addressChecksum, privateKey, attempts, durationMs } =
+ * await grindEoaVanity({
+ * prefix: 'dead',
+ * onProgress: ({ attempts, rate, eta }) => updateUI(...),
+ * controller, // opt-in pause/resume/stop handle
+ * signal,
+ * });
+ *
+ * The returned `privateKey` is a 0x-prefixed 32-byte hex string — drop it
+ * straight into MetaMask, ethers `new Wallet(privateKey)`, or viem
+ * `privateKeyToAccount(privateKey)`. Everything happens in the browser; the
+ * key is never transmitted anywhere.
+ *
+ * Casing of the pattern selects the matching mode (see validation.js):
+ * • all lowercase → case-insensitive match (fastest).
+ * • any uppercase → EIP-55 checksum match (~2× per letter, +1 keccak).
+ */
+
+import {
+ validatePattern,
+ estimateAttempts,
+ formatTimeEstimate,
+ letterCount,
+ eip55Checksum,
+} from './validation.js';
+
+const DEFAULT_MAX_WORKERS = 8;
+
+/**
+ * @typedef {object} GrindOptions
+ * @property {string} [prefix] - Hex prefix (without 0x).
+ * @property {string} [suffix] - Hex suffix (without 0x).
+ * @property {number} [maxWorkers] - 1..hardwareConcurrency. Defaults to min(cores, 8).
+ * @property {AbortSignal} [signal] - Cancel the grind.
+ * @property {GrindController} [controller] - Opt-in pause/resume/stop handle.
+ * @property {(p: { attempts: number, rate: number, eta: string, sample?: string, paused?: boolean }) => void} [onProgress]
+ */
+
+/**
+ * @typedef {object} GrindController
+ * Pass a plain object as `opts.controller`; the methods are attached once the
+ * worker pool is live. Pausing exits each worker's hot loop (cores are freed)
+ * while preserving accumulated attempts so resume picks up where it left off.
+ * @property {() => void} [pause]
+ * @property {() => void} [resume]
+ * @property {() => void} [stop]
+ * @property {boolean} [paused]
+ * @property {number} [workers]
+ */
+
+/**
+ * @typedef {object} GrindResult
+ * @property {string} address - 0x… lowercase address.
+ * @property {string} addressChecksum - 0x… EIP-55 checksummed address.
+ * @property {string} privateKey - 0x… 32-byte private key.
+ * @property {boolean} caseSensitive
+ * @property {number} attempts
+ * @property {number} durationMs
+ * @property {number} workers
+ */
+
+/**
+ * @param {GrindOptions} opts
+ * @returns {Promise<GrindResult>}
+ */
+export function grindEoaVanity(opts = {}) {
+ const { prefix = '', suffix = '', signal, onProgress } = opts;
+
+ if (!prefix && !suffix) {
+ return Promise.reject(new Error('prefix or suffix is required'));
+ }
+
+ let normPrefix = '', normSuffix = '';
+ let caseSensitive = false;
+ if (prefix) {
+ const v = validatePattern(prefix);
+ if (!v.valid) return Promise.reject(new Error(`invalid prefix: ${v.errors.join('; ')}`));
+ normPrefix = v.normalized;
+ if (v.caseSensitive) caseSensitive = true;
+ }
+ if (suffix) {
+ const v = validatePattern(suffix);
+ if (!v.valid) return Promise.reject(new Error(`invalid suffix: ${v.errors.join('; ')}`));
+ normSuffix = v.normalized;
+ if (v.caseSensitive) caseSensitive = true;
+ }
+
+ const hardware = (typeof navigator !== 'undefined' && navigator.hardwareConcurrency) || 4;
+ const requested = opts.maxWorkers || Math.min(hardware, DEFAULT_MAX_WORKERS);
+ const cores = Math.max(1, Math.min(requested, hardware));
+
+ const totalLetters = letterCount(normPrefix) + letterCount(normSuffix);
+ const expected = estimateAttempts(normPrefix.length + normSuffix.length, totalLetters, caseSensitive);
+ const startedAt = performance.now();
+
+ /** @type {Worker[]} */
+ const workers = [];
+ const ratesByWorker = new Array(cores).fill(0);
+ const attemptsByWorker = new Array(cores).fill(0);
+
+ const stopAll = () => {
+ for (const w of workers) {
+ try { w.postMessage({ type: 'stop' }); } catch {}
+ try { w.terminate(); } catch {}
+ }
+ workers.length = 0;
+ };
+
+ return new Promise((resolve, reject) => {
+ const onAbort = () => {
+ stopAll();
+ reject(new DOMException('vanity grind aborted', 'AbortError'));
+ };
+ if (signal) {
+ if (signal.aborted) return onAbort();
+ signal.addEventListener('abort', onAbort, { once: true });
+ }
+
+ for (let idx = 0; idx < cores; idx++) {
+ const w = new Worker(new URL('./eoa-grinder-worker.js', import.meta.url), { type: 'module' });
+ workers.push(w);
+
+ w.onmessage = (e) => {
+ const msg = e.data;
+ if (msg.type === 'match') {
+ 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 : []);
+ resolve({
+ address: msg.address,
+ addressChecksum: msg.addressChecksum || ('0x' + eip55Checksum(msg.address.slice(2))),
+ privateKey: typeof msg.privateKey === 'string' ? msg.privateKey : ('0x' + bytesToHex(priv)),
+ caseSensitive,
+ attempts: totalAttempts,
+ durationMs: performance.now() - startedAt,
+ workers: cores,
+ });
+ } else if (msg.type === 'progress') {
+ attemptsByWorker[idx] = msg.attempts;
+ ratesByWorker[idx] = msg.rate;
+ if (onProgress) {
+ const totalRate = ratesByWorker.reduce((a, b) => a + b, 0);
+ const totalAttempts = attemptsByWorker.reduce((a, b) => a + b, 0);
+ onProgress({
+ attempts: totalAttempts,
+ rate: totalRate,
+ eta: formatTimeEstimate(Math.max(0, expected - totalAttempts), totalRate),
+ sample: msg.sample,
+ });
+ }
+ } else if (msg.type === 'error') {
+ stopAll();
+ if (signal) signal.removeEventListener('abort', onAbort);
+ reject(new Error(msg.message || 'vanity worker reported error'));
+ }
+ };
+
+ w.onerror = (err) => {
+ stopAll();
+ if (signal) signal.removeEventListener('abort', onAbort);
+ reject(err.error || new Error(err.message || 'vanity worker crashed'));
+ };
+
+ w.postMessage({ type: 'start', prefix: normPrefix, suffix: normSuffix, caseSensitive });
+ }
+
+ // Wire the opt-in controller now that the pool is live.
+ const controller = opts.controller;
+ if (controller) {
+ controller.paused = false;
+ controller.workers = cores;
+ controller.pause = () => {
+ if (controller.paused || workers.length === 0) return;
+ controller.paused = true;
+ for (const w of workers) {
+ try { w.postMessage({ type: 'pause' }); } catch {}
+ }
+ if (onProgress) {
+ const totalAttempts = attemptsByWorker.reduce((a, b) => a + b, 0);
+ onProgress({ attempts: totalAttempts, rate: 0, eta: 'paused', paused: true });
+ }
+ };
+ controller.resume = () => {
+ if (!controller.paused || workers.length === 0) return;
+ controller.paused = false;
+ for (const w of workers) {
+ try { w.postMessage({ type: 'resume' }); } catch {}
+ }
+ };
+ controller.stop = onAbort;
+ }
+ });
+}
+
+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/src/eth-eoa-vanity.test.js b/tests/src/eth-eoa-vanity.test.js
new file mode 100644
index 000000000..773d4943c
--- /dev/null
+++ b/tests/src/eth-eoa-vanity.test.js
@@ -0,0 +1,86 @@
+import { describe, it, expect, beforeAll } from 'vitest';
+import { secp256k1 } from '@noble/curves/secp256k1.js';
+import { keccak_256 } from '@noble/hashes/sha3';
+import { computeAddress } from 'ethers';
+
+/**
+ * The EOA vanity grinder worker derives a real keypair: it walks a running
+ * secp256k1 point by incremental addition (P += G) and, on a match,
+ * reconstructs the private key as (k0 + i) mod n. These tests assert two
+ * invariants the worker depends on:
+ *
+ * 1. The address derived from the running point equals the address that
+ * ethers derives from the reconstructed private key (byte-for-byte).
+ * 2. Driving the worker for real produces a key whose address actually
+ * matches the requested prefix and round-trips through ethers.
+ */
+
+function deriveAddress(uncompressedPub) {
+ return '0x' + Buffer.from(keccak_256(uncompressedPub.slice(1)).slice(-20)).toString('hex');
+}
+
+describe('EOA vanity — incremental point addition parity', () => {
+ it('running point matches reconstructed private key over many steps', () => {
+ const Point = secp256k1.Point;
+ const N = Point.Fn.ORDER;
+
+ // Deterministic base scalar so the test is reproducible.
+ const k0 = 0x1234567890abcdef1234567890abcdefn % N;
+ let pt = Point.BASE.multiply(k0);
+
+ for (let i = 0; i < 50; i++) {
+ const addrFromPoint = deriveAddress(pt.toBytes(false));
+
+ const k = (k0 + BigInt(i)) % N;
+ const privHex = k.toString(16).padStart(64, '0');
+ const priv = Uint8Array.from(privHex.match(/../g).map((b) => parseInt(b, 16)));
+ const addrFromKey = deriveAddress(secp256k1.getPublicKey(priv, false));
+
+ expect(addrFromPoint).toBe(addrFromKey);
+ // ethers is the independent reference implementation.
+ expect(addrFromKey.toLowerCase()).toBe(computeAddress('0x' + privHex).toLowerCase());
+
+ pt = pt.add(Point.BASE);
+ }
+ });
+});
+
+describe('EOA vanity — worker grind end-to-end', () => {
+ let matched;
+
+ beforeAll(async () => {
+ matched = await new Promise((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error('grind timed out')), 30000);
+ // Stub the worker globals so the module runs in the node test env.
+ globalThis.self = {
+ onmessage: null,
+ postMessage(msg) {
+ if (msg.type === 'match') {
+ clearTimeout(timer);
+ resolve(msg);
+ } else if (msg.type === 'error') {
+ clearTimeout(timer);
+ reject(new Error(msg.message));
+ }
+ },
+ };
+ import('../../src/eth/vanity/eoa-grinder-worker.js').then(() => {
+ // 'ab' is a 2-char case-insensitive prefix → ~1-in-256, finishes fast.
+ globalThis.self.onmessage({ data: { type: 'start', prefix: 'ab', suffix: '', caseSensitive: false } });
+ });
+ });
+ }, 35000);
+
+ it('returns an address matching the requested prefix', () => {
+ expect(matched.address.slice(2).startsWith('ab')).toBe(true);
+ });
+
+ it('returns a private key that derives exactly that address', () => {
+ expect(computeAddress(matched.privateKey).toLowerCase()).toBe(matched.address.toLowerCase());
+ });
+
+ it('returns a valid EIP-55 checksum for the address', () => {
+ expect(matched.addressChecksum.toLowerCase()).toBe(matched.address.toLowerCase());
+ expect(computeAddress(matched.privateKey)).toBe(matched.addressChecksum);
+ });
+});