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: ETH vanity grinder worker and UI updates

nirholas16eb52783344
diff --git a/public/eth-vanity.html b/public/eth-vanity.html
index 454346183..829a7a601 100644
--- a/public/eth-vanity.html
+++ b/public/eth-vanity.html
@@ -46,9 +46,58 @@
@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: #ffffff; color: #000; padding: 0 3px; border-radius: 3px; font-weight: 700; }
+ .preview .pfx, .preview .sfx { background: linear-gradient(90deg,#ffd54f,#ff8a65); color: #1a1a1a; padding: 0 3px; border-radius: 3px; font-weight: 700; }
.preview .rest { color: #555; }
+ /* ── Difficulty meter ── */
+ .meter { display: flex; gap: 4px; margin-top: .65rem; }
+ .meter .seg { flex: 1; height: 7px; border-radius: 4px; background: #2a2a2a; transition: background .15s; }
+ .lit-1, .lit-2, .lit-3, .lit-4 { background: #4caf50 !important; }
+ .lit-5 { background: #fb8c00 !important; }
+ .lit-6 { background: #d32f2f !important; }
+
+ .tier-tag { padding: .15rem .55rem; border-radius: 999px; font-size: .75rem; font-weight: 600; }
+ .tier-free { background: rgba(74,222,128,0.12); color: #4ade80; }
+ .tier-paid { background: linear-gradient(90deg,rgba(255,213,79,0.15),rgba(255,138,101,0.15)); color: #fbbf24; border: 1px solid rgba(255,213,79,0.2); }
+
+ /* ── Compute / core selector ── */
+ .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; }
+
+ .progress.paused { opacity: .75; }
+ .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; }
+
+ .chip-est { color: #555; margin-left: .35rem; font-family: system-ui, sans-serif; font-size: .7rem; }
+
.row { display: flex; justify-content: space-between; align-items: center; margin-top: .55rem; font-size: .85rem; color: var(--muted); }
.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; }
@@ -61,12 +110,13 @@
.progress .live { display: flex; justify-content: space-between; align-items: center; gap: 1rem; }
.progress .stat { font-size: 1.1rem; font-weight: 600; color: #fff; }
.progress .scan { font-family: ui-monospace, monospace; font-size: .85rem; color: #555; margin-top: .35rem; word-break: break-all; min-height: 1.4em; }
+ .progress .scan .pfx, .progress .scan .sfx { background: linear-gradient(90deg,#ffd54f,#ff8a65); color: #1a1a1a; padding: 0 3px; border-radius: 3px; font-weight: 700; }
- .result { margin-top: 1.25rem; padding: 1.1rem 1.25rem; background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.12); border-radius: 10px; }
+ .result { margin-top: 1.25rem; padding: 1.1rem 1.25rem; background: rgba(255,213,79,0.06); border: 1px solid rgba(255,213,79,0.25); border-radius: 10px; }
.result h3 { margin: 0 0 .4rem; font-size: 1rem; color: #fff; }
- .result .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; }
+ .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,213,79,0.15); margin-top: .5rem; }
.result .out-row .k { color: #ffffff; display: inline-block; min-width: 5.5rem; }
- .result .pfx, .result .sfx { background: #ffffff; color: #000; padding: 0 3px; border-radius: 3px; font-weight: 700; }
+ .result .pfx, .result .sfx { background: linear-gradient(90deg,#ffd54f,#ff8a65); color: #1a1a1a; padding: 0 3px; border-radius: 3px; font-weight: 700; }
.result .meta { font-size: .8rem; color: var(--muted); margin: .65rem 0 0; }
.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); }
@@ -169,21 +219,44 @@
<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="cores-row">cores: <span id="cores">?</span> <span id="case-tag" style="margin-left:.5rem"></span></span>
+ <span><span id="case-tag"></span> <span id="tier"></span></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" id="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>Grind salt</button>
- <button id="cancel" class="btn" type="button" hidden>Cancel</button>
+ <button id="pause" class="btn" type="button" hidden>Pause</button>
+ <button id="cancel" 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</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>
@@ -211,9 +284,50 @@
const $ = (id) => document.getElementById(id);
const HEX_ALPHA = '0123456789abcdef';
const RATE_PER_CORE = 60_000; // measured order-of-magnitude for keccak_256 on 85 bytes in a worker
- const cores = Math.max(1, Math.min(navigator.hardwareConcurrency || 4, 8));
- $('cores').textContent = cores;
- $('cores2').textContent = cores;
+ // ── Core selection ─────────────────────────────────────────────────
+ // The machine's logical core count is the ceiling; default to a
+ // conservative half (min 1) so we don't peg the whole CPU by surprise.
+ 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;
+
+ // Quick presets: 1, half, max — deduped for low-core machines.
+ 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;
+ $('core-ticks').querySelectorAll('button').forEach((b) => {
+ b.setAttribute('aria-pressed', String(Number(b.dataset.cores) === cores));
+ });
+ refreshChipEstimates();
+ update();
+ }
+
+ coreSlider.addEventListener('input', () => setCores(Number(coreSlider.value)));
+ $('core-ticks').querySelectorAll('button').forEach((b) => {
+ b.addEventListener('click', () => setCores(Number(b.dataset.cores)));
+ });
+
+ function refreshChipEstimates() {
+ $('word-chips').querySelectorAll('.preset').forEach((c) => {
+ const w = c.dataset.word || '';
+ const est = c.querySelector('.chip-est');
+ if (est) est.textContent = ' ' + fmtTime(estSeconds(w.length, 0, letterCount(w), /[A-F]/.test(w)));
+ });
+ }
function esc(s) { return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;' })[c]); }
function sample(prefix = '', suffix = '') {
@@ -232,6 +346,18 @@
if (seconds < 31536000) return `~${Math.round(seconds/86400)}d`;
return '>1y';
}
+ // Map estimated wall-clock seconds → 1..6 difficulty "heat" for the meter
+ // (and the fast/slow tier). Cores-dependent, so easing the slider visibly
+ // cools the meter — the same live feedback as the Solana grinder.
+ function heatLevel(seconds) {
+ if (seconds <= 0) return 0;
+ if (seconds < 5) return 1;
+ if (seconds < 30) return 2;
+ if (seconds < 120) return 3;
+ if (seconds < 600) return 4;
+ if (seconds < 3600) return 5;
+ return 6;
+ }
function estSeconds(prefixLen, suffixLen, letters = 0, caseSensitive = false) {
const total = prefixLen + suffixLen;
if (total <= 0) return 0;
@@ -271,7 +397,8 @@
const b = document.createElement('button');
b.type = 'button';
b.className = 'preset';
- b.textContent = w;
+ b.dataset.word = w;
+ b.innerHTML = `${esc(w)}<span class="chip-est"></span>`;
b.addEventListener('click', () => {
$('prefix').value = w;
$('prefix').dispatchEvent(new Event('input'));
@@ -279,6 +406,7 @@
});
chipsEl.appendChild(b);
});
+ refreshChipEstimates();
// ── Auto-hash raw initCode → fill initcode-hash ────────────────────
$('initcode-raw').addEventListener('input', () => {
@@ -326,10 +454,20 @@
const total = (pv.valid ? p.length : 0) + (sv.valid ? s.length : 0);
const letters = letterCount(p) + letterCount(s);
+ const secs = total === 0 ? 0 : estSeconds(p.length, s.length, letters, caseSensitive);
+ const heat = heatLevel(secs);
+
+ // Difficulty meter — segments light by estimated wall-clock heat at
+ // the current core count, green → orange → red.
+ document.querySelectorAll('.meter .seg').forEach((seg, i) => {
+ seg.className = 'seg' + (i < heat ? ` lit-${heat}` : '');
+ });
+
if (total === 0) {
$('preview').innerHTML = `<span class="rest">0x${esc(sample())}</span>`;
$('est').textContent = 'type a pattern to see estimated time';
$('case-tag').innerHTML = '';
+ $('tier').innerHTML = '';
} else {
const mid = sample('', '').slice(0, 40 - p.length - s.length);
$('preview').innerHTML =
@@ -337,10 +475,13 @@
(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.length, s.length, letters, caseSensitive))} on ${cores} cores`;
+ $('est').textContent = `rough estimate: ${fmtTime(secs)} on ${cores} cores`;
$('case-tag').innerHTML = caseSensitive
? `<span style="background:rgba(255,255,255,0.07);color:#888888;border:1px solid rgba(255,255,255,0.14);padding:.05rem .4rem;border-radius:999px;font-size:.7rem">EIP-55 case-sensitive</span>`
: '';
+ $('tier').innerHTML = heat >= 4
+ ? '<span class="tier-tag tier-paid">slow — minutes+</span>'
+ : '<span class="tier-tag tier-free">fast</span>';
}
$('grind').disabled =
@@ -359,6 +500,41 @@
// ── Grind ──────────────────────────────────────────────────────────
let abort = null;
+ let controls = null; // GrindController for pause/resume/stop
+ let scanLoop = null;
+
+ // Render a shimmering scan line: 0x + highlighted prefix + dim middle + suffix.
+ function renderScan(p, s) {
+ const mid = sample('', '').slice(0, 40 - p.length - s.length);
+ return `0x${p ? `<span class="pfx">${esc(p)}</span>` : ''}<span class="scan-mid" style="color:#555">${esc(mid)}</span>${s ? `<span class="sfx">${esc(s)}</span>` : ''}`;
+ }
+
+ // Pattern + core controls can only change between runs — the worker pool
+ // and target pattern are fixed for the lifetime of a grind.
+ function setCoreControlsDisabled(disabled) {
+ coreSlider.disabled = disabled;
+ $('core-ticks').querySelectorAll('button').forEach((b) => { b.disabled = disabled; });
+ $('prefix').disabled = disabled;
+ $('suffix').disabled = disabled;
+ $('deployer').disabled = disabled;
+ $('initcode-hash').disabled = disabled;
+ $('initcode-raw').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;
+ $('cancel').hidden = true;
+ setPaused(false);
+ setCoreControlsDisabled(false);
+ }
$('grind').addEventListener('click', async () => {
const { p, s, caseSensitive } = readPattern();
@@ -368,44 +544,60 @@
if (!ich.valid) { showError(ich.error); return; }
$('grind').hidden = true;
+ $('pause').hidden = false;
$('cancel').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.length, s.length, letterCount(p) + letterCount(s), caseSensitive));
- $('scan').textContent = `0x${sample(p, s)}`;
+ $('scan').innerHTML = renderScan(p, s);
stopPreviewLoop();
- const scanLoop = setInterval(() => {
- $('scan').textContent = `0x${sample(p, s)}`;
+ // Animate the scan-line middle during grind (frozen while paused).
+ scanLoop = setInterval(() => {
+ if (controls?.paused) return;
+ const midNode = $('scan').querySelector('.scan-mid');
+ if (midNode) midNode.textContent = sample('', '').slice(0, 40 - p.length - s.length);
}, 100);
abort = new AbortController();
+ controls = {};
try {
const result = await grindCreate2Vanity({
deployer: dv.normalized,
initCodeHash: ich.normalized,
prefix: p || undefined,
suffix: s || undefined,
+ maxWorkers: cores,
+ controller: controls,
signal: abort.signal,
- onProgress: ({ attempts, rate, eta, sample: sm }) => {
+ onProgress: ({ attempts, rate, eta, paused }) => {
$('attempts').textContent = attempts.toLocaleString();
- $('rate').textContent = `${Math.round(rate).toLocaleString()}/s`;
+ $('rate').textContent = paused ? 'paused' : `${Math.round(rate).toLocaleString()}/s`;
$('eta').textContent = eta;
- if (sm) $('scan').textContent = sm;
},
});
- clearInterval(scanLoop);
renderResult(result, p, s);
} catch (err) {
- clearInterval(scanLoop);
if (err?.name !== 'AbortError') showError(`Grind failed: ${err.message || err}`);
resetIdle();
+ } finally {
+ controls = null;
+ if (scanLoop) { clearInterval(scanLoop); scanLoop = null; }
}
});
+ $('pause').addEventListener('click', () => {
+ if (!controls) return;
+ if (controls.paused) { controls.resume(); setPaused(false); }
+ else { controls.pause(); setPaused(true); }
+ });
+
$('cancel').addEventListener('click', () => abort?.abort());
function showError(msg) {
@@ -413,14 +605,14 @@
$('error').hidden = false;
}
function resetIdle() {
+ endGrindUI();
$('grind').hidden = false;
- $('cancel').hidden = true;
$('progress').hidden = true;
startPreviewLoop();
}
function renderResult(result, p, s) {
- $('cancel').hidden = true;
+ endGrindUI();
$('grind').hidden = false;
$('grind').textContent = 'Grind another';
$('progress').hidden = true;
diff --git a/src/eth/vanity/grinder-worker.js b/src/eth/vanity/grinder-worker.js
index 7f8acce7e..89f6e604b 100644
--- a/src/eth/vanity/grinder-worker.js
+++ b/src/eth/vanity/grinder-worker.js
@@ -22,17 +22,35 @@ const PROGRESS_INTERVAL = 5000;
const HEX_CHARS = '0123456789abcdef';
let running = false;
+// Guards against two grind loops racing if 'resume' arrives before the
+// previous loop has fully unwound.
+let looping = false;
+// Grind state hoisted to module scope so 'pause' can exit the hot loop —
+// genuinely freeing the core — while 'resume' re-enters and continues the
+// same salt search with a monotonic attempt count. Parity with the Solana
+// worker's pause/resume contract.
+let state = null;
self.onmessage = (e) => {
const msg = e.data;
if (msg?.type === 'start') {
+ state = initState(msg);
+ running = !!state;
+ if (running) kick();
+ } else if (msg?.type === 'resume') {
+ if (!state) return;
running = true;
- grind(msg);
- } else if (msg?.type === 'stop') {
+ kick();
+ } else if (msg?.type === 'pause' || msg?.type === 'stop') {
running = false;
}
};
+/** Start the hot loop unless one is already in flight. */
+function kick() {
+ if (!looping) grindLoop();
+}
+
function hexToBytes(hex) {
let h = hex.startsWith('0x') || hex.startsWith('0X') ? hex.slice(2) : hex;
if (h.length % 2) h = '0' + h;
@@ -71,14 +89,16 @@ function eip55(lowerHex) {
}
/**
+ * Build the persistent grind state for a fresh 'start'. Returns null (after
+ * posting an error) if the deployer/initCodeHash are malformed.
* @param {{ deployer: string, initCodeHash: string,
* prefix: string, suffix: string, caseSensitive: boolean }} cfg
*/
-async function grind(cfg) {
+function initState(cfg) {
const deployer = hexToBytes(cfg.deployer);
const initCodeHash = hexToBytes(cfg.initCodeHash);
- if (deployer.length !== 20) return self.postMessage({ type: 'error', message: 'deployer must be 20 bytes' });
- if (initCodeHash.length !== 32) return self.postMessage({ type: 'error', message: 'initCodeHash must be 32 bytes' });
+ if (deployer.length !== 20) { self.postMessage({ type: 'error', message: 'deployer must be 20 bytes' }); return null; }
+ if (initCodeHash.length !== 32) { self.postMessage({ type: 'error', message: 'initCodeHash must be 32 bytes' }); return null; }
// Pre-build the 85-byte CREATE2 preimage. Only bytes 21..52 (salt) change.
const buf = new Uint8Array(1 + 20 + 32 + 32);
@@ -90,31 +110,41 @@ 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;
// Seed salt with crypto-random bytes; per-iteration we increment a
// 64-bit counter at salt[24..32], leaving 24 bytes of fresh entropy.
crypto.getRandomValues(saltView);
const counter = new DataView(buf.buffer, buf.byteOffset + 1 + 20 + 24, 8);
- let lo = counter.getUint32(4, false);
- let hi = counter.getUint32(0, false);
- let attempts = 0;
+ return {
+ buf, saltView, counter, caseSensitive,
+ wantPrefix, wantSuffix,
+ pLen: wantPrefix.length, sLen: wantSuffix.length,
+ lo: counter.getUint32(4, false),
+ hi: counter.getUint32(0, false),
+ attempts: 0,
+ };
+}
+
+async function grindLoop() {
+ looping = true;
+ const s = state;
+ const { buf, saltView, counter, caseSensitive, wantPrefix, wantSuffix, pLen, sLen } = s;
+
let intervalAttempts = 0;
let intervalStart = performance.now();
- while (running) {
+ while (running && state === s) {
// Bump 64-bit counter (big-endian) at salt[24..32].
- lo = (lo + 1) >>> 0;
- if (lo === 0) hi = (hi + 1) >>> 0;
- counter.setUint32(0, hi, false);
- counter.setUint32(4, lo, false);
+ s.lo = (s.lo + 1) >>> 0;
+ if (s.lo === 0) s.hi = (s.hi + 1) >>> 0;
+ counter.setUint32(0, s.hi, false);
+ counter.setUint32(4, s.lo, false);
const digest = keccak_256(buf);
const lowerHex = bytesToHex(digest.subarray(12));
- attempts++;
+ s.attempts++;
intervalAttempts++;
const candidate = caseSensitive ? eip55(lowerHex) : lowerHex;
@@ -129,10 +159,10 @@ async function grind(cfg) {
address: '0x' + lowerHex, // canonical lowercase
addressChecksum: '0x' + (caseSensitive ? candidate : eip55(lowerHex)),
salt: '0x' + bytesToHex(saltOut),
- attempts,
+ attempts: s.attempts,
}, [saltOut.buffer]);
running = false;
- return;
+ break;
}
if (intervalAttempts >= PROGRESS_INTERVAL) {
@@ -141,13 +171,16 @@ async function grind(cfg) {
const rate = elapsed > 0 ? intervalAttempts / elapsed : 0;
self.postMessage({
type: 'progress',
- attempts,
+ attempts: s.attempts,
rate,
sample: '0x' + (caseSensitive ? candidate : lowerHex),
});
intervalStart = now;
intervalAttempts = 0;
+ // Yield to the event loop so 'pause'/'stop' messages get processed.
await new Promise((r) => setTimeout(r, 0));
}
}
+
+ looping = false;
}
diff --git a/src/eth/vanity/grinder.js b/src/eth/vanity/grinder.js
index a9b5583bf..2c2addbfb 100644
--- a/src/eth/vanity/grinder.js
+++ b/src/eth/vanity/grinder.js
@@ -39,7 +39,21 @@ const DEFAULT_MAX_WORKERS = 8;
* @property {string} [suffix] - Hex suffix (without 0x), case-insensitive.
* @property {number} [maxWorkers]
* @property {AbortSignal} [signal]
- * @property {(p: { attempts: number, rate: number, eta: string, sample?: string }) => void} [onProgress]
+ * @property {GrindController} [controller] - Opt-in handle for pause/resume/stop. Methods are wired in once workers spawn.
+ * @property {(p: { attempts: number, rate: number, eta: string, sample?: string, paused?: boolean }) => void} [onProgress]
+ */
+
+/**
+ * @typedef {object} GrindController
+ * Pass a plain object as `opts.controller`; grindCreate2Vanity attaches the
+ * methods below once the worker pool is live. Pausing exits each worker's hot
+ * loop — the cores are genuinely freed — while preserving accumulated attempts
+ * so resume picks up the same salt search where it left off.
+ * @property {() => void} [pause] - Suspend all workers (no-op if already paused/finished).
+ * @property {() => void} [resume] - Resume all workers (no-op if not paused).
+ * @property {() => void} [stop] - Abort the grind (rejects the promise with AbortError).
+ * @property {boolean} [paused] - Current paused state.
+ * @property {number} [workers] - Number of workers actually spawned.
*/
/**
@@ -170,6 +184,32 @@ export function grindCreate2Vanity(opts = {}) {
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;
+ }
});
}