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(sigil): start the multi-chain vanity address foundry with its shared grinder math

nirholas1d18a4403774
diff --git a/sigil/.gitignore b/sigil/.gitignore
new file mode 100644
index 000000000..dc40561bb
--- /dev/null
+++ b/sigil/.gitignore
@@ -0,0 +1,5 @@
+node_modules
+dist
+.wrangler
+*.log
+.DS_Store
diff --git a/sigil/LICENSE b/sigil/LICENSE
new file mode 100644
index 000000000..b5ae2a4e1
--- /dev/null
+++ b/sigil/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2026 nirholas
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/sigil/NOTICE b/sigil/NOTICE
new file mode 100644
index 000000000..9f03147ba
--- /dev/null
+++ b/sigil/NOTICE
@@ -0,0 +1,27 @@
+Sigil
+Copyright 2026 nirholas
+
+The open multi-chain vanity address foundry.
+https://github.com/nirholas/sigil
+
+Licensed under the Apache License, Version 2.0. See the LICENSE file in the
+root of this repository for the full terms.
+
+Portions of this project were first developed inside the three.ws monorepo
+(https://github.com/nirholas/three.ws) and are re-licensed here under the same
+Apache License, Version 2.0:
+
+ packages/core/src/difficulty.js base58 leading-character distribution model
+ packages/solana/src/* ed25519 grinding and BIP-39 mnemonic search
+ packages/evm/src/* secp256k1 EOA and CREATE2 salt grinding
+ packages/splitkey/src/ed25519.js trustless split-key grinding for Ed25519
+ packages/attest/src/* proof-of-grind certificate format
+
+Third-party dependencies keep their own licenses:
+
+ @noble/curves, @noble/hashes MIT, Paul Miller
+ bs58, base-x MIT
+ three MIT, three.js authors
+ hono MIT, Yusuke Wada
+
+Nothing in this NOTICE modifies the terms of the Apache License, Version 2.0.
diff --git a/sigil/package.json b/sigil/package.json
new file mode 100644
index 000000000..4746babb1
--- /dev/null
+++ b/sigil/package.json
@@ -0,0 +1,33 @@
+{
+ "name": "sigil",
+ "version": "1.0.0",
+ "private": true,
+ "description": "Sigil: the open multi-chain vanity address foundry. Grind branded Solana and EVM addresses in the browser, prove how they were made, and deploy the same vanity contract address on every chain.",
+ "type": "module",
+ "license": "Apache-2.0",
+ "author": "nirholas <[email protected]>",
+ "homepage": "https://three.ws/sigil",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/nirholas/sigil.git"
+ },
+ "workspaces": [
+ "packages/*",
+ "apps/*"
+ ],
+ "scripts": {
+ "test": "node --test packages/*/test/*.test.js",
+ "dev": "npm run dev --workspace @three-ws/sigil-site",
+ "dev:api": "npm run dev --workspace @three-ws/sigil-api",
+ "build": "npm run build --workspace @three-ws/sigil-site",
+ "lint:pack": "node scripts/check-packages.mjs",
+ "deploy:pages": "npm run build && npx wrangler pages deploy apps/site/dist --project-name sigil",
+ "deploy:worker": "npx wrangler deploy --config apps/api/wrangler.toml"
+ },
+ "engines": {
+ "node": ">=20"
+ },
+ "devDependencies": {
+ "vite": "^7.3.0"
+ }
+}
diff --git a/sigil/packages/core/package.json b/sigil/packages/core/package.json
new file mode 100644
index 000000000..ebd1b4050
--- /dev/null
+++ b/sigil/packages/core/package.json
@@ -0,0 +1,22 @@
+{
+ "name": "@three-ws/sigil-core",
+ "version": "1.0.0",
+ "description": "Exact vanity-address difficulty math for Base58 (Solana) and hex (EVM) address spaces: pattern parsing, probability, expected attempts, ETA, and rarity tiers.",
+ "type": "module",
+ "main": "./src/index.js",
+ "exports": {
+ ".": "./src/index.js",
+ "./base58": "./src/base58.js",
+ "./hex": "./src/hex.js",
+ "./package.json": "./package.json"
+ },
+ "files": ["src", "README.md"],
+ "keywords": ["vanity-address", "base58", "solana", "ethereum", "evm", "difficulty", "probability", "rarity", "sigil"],
+ "license": "Apache-2.0",
+ "author": "nirholas <[email protected]>",
+ "homepage": "https://three.ws/sigil",
+ "repository": { "type": "git", "url": "git+https://github.com/nirholas/sigil.git", "directory": "packages/core" },
+ "engines": { "node": ">=20" },
+ "publishConfig": { "access": "public" },
+ "scripts": { "test": "node --test test/*.test.js" }
+}
diff --git a/sigil/packages/core/src/base58.js b/sigil/packages/core/src/base58.js
new file mode 100644
index 000000000..db45e9c1f
--- /dev/null
+++ b/sigil/packages/core/src/base58.js
@@ -0,0 +1,228 @@
+/**
+ * The true probability distribution of Base58-encoded Solana addresses.
+ *
+ * Part of Sigil (https://github.com/nirholas/sigil). Apache-2.0.
+ * Originally written for three.ws and re-licensed here under the same terms.
+ *
+ * ── Why this module exists ───────────────────────────────────────────────────
+ * Every difficulty, rarity, price and time estimate in the vanity product used
+ * to assume each Base58 character is uniform: probability 1/58 per position, so
+ * an n-character pattern costs 58ⁿ attempts. That is correct for *trailing*
+ * characters and wrong for the *leading* one, because Base58 is a positional
+ * numeral encoding of a 32-byte integer, not a string of independent symbols.
+ *
+ * A Solana key is 32 bytes; once leading zero bytes are stripped it spans
+ * [2²⁴⁸, 2²⁵⁶). Base58 encodes such a value in 44 digits when it is at least
+ * 58⁴³ and 43 digits otherwise, and two ratios carve the alphabet up:
+ *
+ * 2²⁵⁶ / 58⁴³ ≈ 17.05 so 44-digit encodings lead with symbols 1..17
+ * 2²⁴⁸ / 58⁴² ≈ 3.90 so 43-digit encodings lead with symbols 3..57
+ *
+ * which yields six bands, spanning 58× in how hard a leading character is to hit:
+ *
+ * '1' P = 3.906e-3 (a leading zero byte, exactly 1/256)
+ * '2'-'3' P = 5.804e-2 (44-digit encodings only)
+ * '4' P = 5.814e-2 (plus the sliver of 43-digit that clears 2²⁴⁸)
+ * '5'-'H' P = 5.904e-2 (3.43× *easier* than the uniform model claims)
+ * 'J' P = 1.433e-2 (0.83×, where the 44-digit range runs out)
+ * 'K'-'z' P = 1.001e-3 (17.2× *harder* than claimed, 40 of the 58 symbols)
+ *
+ * Measured against the uniform model on the live inventory, the median address
+ * was 17× harder to grind than its stored difficulty claimed, and patterns
+ * leading with '2'-'H' were up to 1.75× easier. Since price and rarity tier are
+ * both derived from difficulty, the whole book was mispriced in both directions.
+ *
+ * ── What this module computes ────────────────────────────────────────────────
+ * `prefixProbability` is *exact*, not an approximation or a fitted table: it
+ * counts, with BigInt interval arithmetic, how many of the 2²⁵⁶ possible keys
+ * encode to a string with the requested prefix. It handles leading-zero bytes
+ * (which encode as '1') and arbitrary prefix lengths.
+ *
+ * Trailing characters genuinely are uniform, the low-order digits of a huge
+ * uniform integer are equidistributed to within O(58ⁿ / 2²⁴⁸), far below double
+ * precision, so `suffixProbability` stays 58⁻ⁿ.
+ *
+ * Pure and isomorphic: no I/O, no crypto, identical in browser and server.
+ * Pinned against direct sampling of real keypairs in test/base58.test.js.
+ */
+
+export const BASE58_ALPHABET =
+ '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
+
+const INDEX = new Map([...BASE58_ALPHABET].map((c, i) => [c, i]));
+
+/** Solana public keys are 32 bytes; the encoded value space is [0, 2²⁵⁶). */
+const KEY_BYTES = 32;
+const TOTAL = 1n << BigInt(8 * KEY_BYTES);
+
+/** Powers of 58 up to the longest encoding a 32-byte value can produce. */
+const POW58 = [1n];
+for (let i = 1; i <= 64; i++) POW58.push(POW58[i - 1] * 58n);
+
+/**
+ * Fixed-point scale for BigInt → Number conversion. 10²⁵ keeps ~16 significant
+ * digits for probabilities as small as 58⁻⁶ × 1e-3 ≈ 3e-14, which is well past
+ * the 6-character `MAX_PATTERN_LENGTH` ceiling.
+ */
+const SCALE = 10n ** 25n;
+const SCALE_N = 1e25;
+
+/**
+ * Count the 32-byte values whose Base58 encoding begins with `prefix`.
+ * @param {string} prefix
+ * @returns {bigint} number of matching values in [0, 2²⁵⁶)
+ */
+function prefixCount(prefix) {
+ if (!prefix) return TOTAL;
+ for (const ch of prefix) {
+ if (!INDEX.has(ch)) return 0n; // not a Base58 symbol, unreachable
+ }
+
+ // Leading '1's are leading *zero bytes*, not digits of the numeral.
+ let zeros = 0;
+ while (zeros < prefix.length && prefix[zeros] === '1') zeros++;
+ if (zeros > KEY_BYTES) return 0n;
+ const rest = prefix.slice(zeros);
+
+ // All-'1' prefix: every value with at least that many leading zero bytes.
+ if (rest === '') return TOTAL >> BigInt(8 * zeros);
+
+ // Otherwise the zero-byte run must be *exactly* `zeros` long: the next
+ // encoded character is rest[0], which is not '1'. So the remaining bytes
+ // form a value with a non-zero leading byte.
+ const width = KEY_BYTES - zeros;
+ if (width < 1) return 0n;
+ const lo = 1n << BigInt(8 * (width - 1));
+ const hi = 1n << BigInt(8 * width);
+
+ let value = 0n;
+ for (const ch of rest) value = value * 58n + BigInt(INDEX.get(ch));
+
+ // Strings of total length L that start with `rest` occupy the contiguous
+ // integer range [value·58^(L-|rest|), (value+1)·58^(L-|rest|)). Those ranges
+ // are disjoint across L, so the matches are their summed overlap with
+ // [lo, hi). rest[0] ≠ '1' guarantees each range sits inside the band of
+ // values that actually encode to length L, so no extra clamping is needed.
+ let count = 0n;
+ for (let pad = 0; pad + rest.length <= 64; pad++) {
+ const unit = POW58[pad];
+ const start = value * unit;
+ if (start >= hi) break;
+ const end = (value + 1n) * unit;
+ const a = start > lo ? start : lo;
+ const b = end < hi ? end : hi;
+ if (b > a) count += b - a;
+ }
+ return count;
+}
+
+/**
+ * Every Base58-valid case spelling of `pattern`.
+ *
+ * The alphabet omits `0 O I l`, so some letters have only one usable case:
+ * a case-insensitive 'I' can only ever match a literal 'i'. Returns an empty
+ * array when a character has no valid spelling at all.
+ * @param {string} pattern
+ * @returns {string[]}
+ */
+export function caseVariants(pattern) {
+ let out = [''];
+ for (const ch of pattern) {
+ const lower = ch.toLowerCase();
+ const upper = ch.toUpperCase();
+ const set = new Set();
+ if (INDEX.has(ch)) set.add(ch);
+ if (lower !== upper) {
+ if (INDEX.has(lower)) set.add(lower);
+ if (INDEX.has(upper)) set.add(upper);
+ }
+ if (set.size === 0) return [];
+ const options = [...set];
+ out = out.flatMap((head) => options.map((c) => head + c));
+ }
+ return out;
+}
+
+/**
+ * Exact probability that a uniformly random Solana address starts with `prefix`.
+ *
+ * @param {string} prefix
+ * @param {boolean} [ignoreCase=false]
+ * @returns {number} probability in [0, 1]; 0 when the prefix is unreachable
+ */
+export function prefixProbability(prefix, ignoreCase = false) {
+ if (!prefix) return 1;
+ const variants = ignoreCase ? caseVariants(prefix) : [prefix];
+ if (variants.length === 0) return 0;
+ // Distinct spellings match disjoint value sets, so the counts simply add.
+ let count = 0n;
+ for (const variant of variants) count += prefixCount(variant);
+ if (count === 0n) return 0;
+ return Number((count * SCALE) / TOTAL) / SCALE_N;
+}
+
+/**
+ * Probability that a uniformly random Solana address ends with `suffix`.
+ *
+ * Unlike the prefix, this really is 58⁻ⁿ: the low-order digits of a uniform
+ * 256-bit integer are equidistributed to within O(58ⁿ / 2²⁴⁸), which is ~1e-64
+ * at the 6-character ceiling, far below double precision.
+ *
+ * @param {string} suffix
+ * @param {boolean} [ignoreCase=false]
+ * @returns {number} probability in [0, 1]
+ */
+export function suffixProbability(suffix, ignoreCase = false) {
+ if (!suffix) return 1;
+ let p = 1;
+ for (const ch of suffix) {
+ const lower = ch.toLowerCase();
+ const upper = ch.toUpperCase();
+ const set = new Set();
+ if (INDEX.has(ch)) set.add(ch);
+ if (lower !== upper && ignoreCase) {
+ if (INDEX.has(lower)) set.add(lower);
+ if (INDEX.has(upper)) set.add(upper);
+ }
+ if (set.size === 0) return 0;
+ p *= set.size / 58;
+ }
+ return p;
+}
+
+/**
+ * Probability that a random address satisfies both ends of a vanity pattern.
+ *
+ * Prefix and suffix are treated as independent. For the 6-character ceiling on
+ * each side that costs at most O(58¹² / 2²⁴⁸) ≈ 1e-53 of relative error.
+ *
+ * @param {object} pattern
+ * @param {string} [pattern.prefix]
+ * @param {string} [pattern.suffix]
+ * @param {boolean} [pattern.ignoreCase=false]
+ * @returns {number} probability in [0, 1]
+ */
+export function patternProbability({ prefix = '', suffix = '', ignoreCase = false } = {}) {
+ return prefixProbability(prefix || '', ignoreCase) * suffixProbability(suffix || '', ignoreCase);
+}
+
+/**
+ * The per-character leading probability table, for docs, UI hints and tests.
+ * Keys are the 58 alphabet symbols; values are exact probabilities summing to 1.
+ * @type {Readonly<Record<string, number>>}
+ */
+export const LEADING_CHAR_PROBABILITY = Object.freeze(
+ Object.fromEntries([...BASE58_ALPHABET].map((c) => [c, prefixProbability(c, false)])),
+);
+
+/**
+ * How much harder (>1) or easier (<1) a leading character is than the naive
+ * uniform-1/58 model claims. Useful for explaining a quote to a buyer.
+ * @param {string} ch
+ * @returns {number}
+ */
+export function leadingCharDifficultyRatio(ch) {
+ const p = LEADING_CHAR_PROBABILITY[ch];
+ if (!p) return Infinity;
+ return (1 / 58) / p;
+}
diff --git a/sigil/packages/core/src/difficulty.js b/sigil/packages/core/src/difficulty.js
new file mode 100644
index 000000000..dd04b66fb
--- /dev/null
+++ b/sigil/packages/core/src/difficulty.js
@@ -0,0 +1,176 @@
+/**
+ * Difficulty, ETA and confidence math shared by every Sigil grinder.
+ *
+ * Part of Sigil (https://github.com/nirholas/sigil). Apache-2.0.
+ *
+ * Grinding is a geometric process: each attempt is an independent Bernoulli
+ * trial with success probability `p`, so the honest answers are
+ *
+ * expected attempts 1 / p
+ * median (50% confidence) ln(0.5) / ln(1 - p)
+ * n attempts get you 1 - (1 - p)ⁿ
+ *
+ * Most vanity tools show only the expected value and let users believe it is a
+ * deadline. It is not: at the expected attempt count you have had a 63.2% chance
+ * of finishing, and one run in twenty takes three times as long. Sigil reports
+ * p50/p90/p99 alongside the mean everywhere, because a buyer deciding whether to
+ * pay for a grind needs the tail, not the average.
+ *
+ * Models are versioned and named in every quote and certificate, so an
+ * attestation issued under an older model still verifies against the model it
+ * was issued under.
+ */
+
+import { patternProbability as base58Probability } from './base58.js';
+import { patternProbability as hexProbability, caseSensitivityCost } from './hex.js';
+
+/** Difficulty model identifiers, embedded in quotes and certificates. */
+export const DIFFICULTY_MODELS = Object.freeze({
+ solana: 'sigil-base58-exact/v1',
+ evm: 'sigil-hex-uniform/v1',
+});
+
+/**
+ * Exact probability that one random address in the pattern's space matches.
+ * @param {import('./pattern.js').Pattern} pattern
+ * @returns {number} probability in [0, 1]
+ */
+export function probability(pattern) {
+ if (!pattern) return 0;
+ if (pattern.space === 'evm') {
+ return hexProbability({
+ prefix: pattern.prefix,
+ suffix: pattern.suffix,
+ caseSensitive: pattern.caseSensitive,
+ });
+ }
+ return base58Probability({
+ prefix: pattern.prefix,
+ suffix: pattern.suffix,
+ ignoreCase: !pattern.caseSensitive,
+ });
+}
+
+/**
+ * Mean number of attempts before a hit. `Infinity` for an unreachable pattern.
+ * @param {number} p
+ * @returns {number}
+ */
+export function expectedAttempts(p) {
+ if (!(p > 0)) return Infinity;
+ return 1 / p;
+}
+
+/**
+ * Attempts needed for a given probability of having found a match.
+ * @param {number} p per-attempt probability
+ * @param {number} confidence in (0, 1), e.g. 0.5 for the median
+ * @returns {number}
+ */
+export function attemptsForConfidence(p, confidence) {
+ if (!(p > 0)) return Infinity;
+ if (!(confidence > 0 && confidence < 1)) throw new RangeError('confidence must be in (0, 1)');
+ if (p >= 1) return 1;
+ return Math.log(1 - confidence) / Math.log(1 - p);
+}
+
+/**
+ * Probability of having found a match after `attempts` tries.
+ * @param {number} p
+ * @param {number} attempts
+ * @returns {number}
+ */
+export function probabilityAfter(p, attempts) {
+ if (!(p > 0)) return 0;
+ if (!(attempts > 0)) return 0;
+ return 1 - Math.pow(1 - p, attempts);
+}
+
+/**
+ * Seconds to reach a confidence level at a measured hash rate.
+ * @param {number} p
+ * @param {number} attemptsPerSecond
+ * @param {number} [confidence=0.5]
+ * @returns {number}
+ */
+export function etaSeconds(p, attemptsPerSecond, confidence = 0.5) {
+ if (!(attemptsPerSecond > 0)) return Infinity;
+ return attemptsForConfidence(p, confidence) / attemptsPerSecond;
+}
+
+/**
+ * The full difficulty picture for a pattern, ready to render.
+ *
+ * @param {import('./pattern.js').Pattern} pattern
+ * @param {object} [opts]
+ * @param {number} [opts.attemptsPerSecond] measured rate, to add wall-clock ETAs
+ * @returns {{
+ * model: string, probability: number, expectedAttempts: number,
+ * p50: number, p90: number, p99: number,
+ * caseCost: number,
+ * eta?: { p50: number, p90: number, p99: number, attemptsPerSecond: number }
+ * }}
+ */
+export function difficulty(pattern, opts = {}) {
+ const p = probability(pattern);
+ const out = {
+ model: DIFFICULTY_MODELS[pattern.space] || DIFFICULTY_MODELS.solana,
+ probability: p,
+ expectedAttempts: expectedAttempts(p),
+ p50: attemptsForConfidence(p, 0.5),
+ p90: attemptsForConfidence(p, 0.9),
+ p99: attemptsForConfidence(p, 0.99),
+ caseCost: pattern.space === 'evm' && pattern.caseSensitive
+ ? caseSensitivityCost({ prefix: pattern.prefix, suffix: pattern.suffix })
+ : 1,
+ };
+ const rate = opts.attemptsPerSecond;
+ if (rate > 0) {
+ out.eta = {
+ attemptsPerSecond: rate,
+ p50: out.p50 / rate,
+ p90: out.p90 / rate,
+ p99: out.p99 / rate,
+ };
+ }
+ return out;
+}
+
+const UNITS = [
+ [1, 'second'], [60, 'minute'], [3600, 'hour'], [86400, 'day'],
+ [86400 * 365.25, 'year'], [86400 * 365.25 * 1000, 'millennium'],
+];
+
+/**
+ * Human duration: "12 seconds", "3.4 hours", "longer than the universe".
+ * @param {number} seconds
+ * @returns {string}
+ */
+export function formatDuration(seconds) {
+ if (!Number.isFinite(seconds)) return 'never';
+ if (seconds < 1) return 'under a second';
+ if (seconds > 86400 * 365.25 * 13.8e9) return 'longer than the universe has existed';
+ let unit = UNITS[0];
+ for (const u of UNITS) if (seconds >= u[0]) unit = u;
+ const value = seconds / unit[0];
+ const rounded = value >= 100 ? Math.round(value) : Number(value.toPrecision(2));
+ const label = unit[1] === 'millennium' ? (rounded === 1 ? 'millennium' : 'millennia') : unit[1];
+ return `${rounded.toLocaleString('en-US')} ${label}${unit[1] !== 'millennium' && rounded !== 1 ? 's' : ''}`;
+}
+
+/**
+ * Human attempt count: "65.5 thousand", "1.2 billion".
+ * @param {number} n
+ * @returns {string}
+ */
+export function formatAttempts(n) {
+ if (!Number.isFinite(n)) return 'unreachable';
+ const steps = [
+ [1e18, 'quintillion'], [1e15, 'quadrillion'], [1e12, 'trillion'],
+ [1e9, 'billion'], [1e6, 'million'], [1e3, 'thousand'],
+ ];
+ for (const [size, label] of steps) {
+ if (n >= size) return `${Number((n / size).toPrecision(3)).toLocaleString('en-US')} ${label}`;
+ }
+ return Math.round(n).toLocaleString('en-US');
+}
diff --git a/sigil/packages/core/src/hex.js b/sigil/packages/core/src/hex.js
new file mode 100644
index 000000000..281fdd054
--- /dev/null
+++ b/sigil/packages/core/src/hex.js
@@ -0,0 +1,123 @@
+/**
+ * The probability distribution of hex-encoded EVM addresses.
+ *
+ * Part of Sigil (https://github.com/nirholas/sigil). Apache-2.0.
+ *
+ * ── Why this is simpler than Base58 ──────────────────────────────────────────
+ * A Solana address is a *numeral* (a 256-bit integer rendered in Base58), so its
+ * leading character is not uniform. An EVM address is not a numeral: it is the
+ * low 20 bytes of a Keccak-256 digest, rendered as a fixed 40-character hex
+ * string with no length variance and no leading-zero stripping. Every one of the
+ * 40 nibbles is independently uniform over 16 symbols, at both ends. So the
+ * honest model here really is 16⁻ⁿ, and `0x0000…` is exactly as hard as
+ * `0xdead…`: 65 536 expected attempts for four nibbles, either way.
+ *
+ * That holds for all three EVM address derivations Sigil grinds:
+ *
+ * EOA address = keccak256(uncompressed pubkey[1:])[12:]
+ * CREATE address = keccak256(rlp([sender, nonce]))[12:]
+ * CREATE2 address = keccak256(0xff ‖ deployer ‖ salt ‖ initCodeHash)[12:]
+ *
+ * ── The case dimension (EIP-55) ──────────────────────────────────────────────
+ * EIP-55 re-cases the hex letters of an address using bits of
+ * keccak256(lowercase address), which behave as fair coin flips. Asking for a
+ * *specific* case spelling therefore costs an extra factor of two per letter in
+ * the pattern: `dead` (4 letters) is 16 times harder to hit as `dEaD` than as
+ * any-case `dead`. Digits 0-9 carry no case and cost nothing extra.
+ *
+ * That is the single most misquoted number in EVM vanity tooling: a mixed-case
+ * request is not "the same speed", it is 2^letters harder, and Sigil prices and
+ * ETAs say so.
+ *
+ * Pure and isomorphic: no I/O, no crypto, identical in browser and server.
+ */
+
+export const HEX_ALPHABET = '0123456789abcdef';
+
+const HEX_SET = new Set([...'0123456789abcdefABCDEF']);
+const LETTER_SET = new Set([...'abcdefABCDEF']);
+
+/** Every EVM address is 20 bytes = 40 hex nibbles. */
+export const EVM_ADDRESS_NIBBLES = 40;
+
+/** @param {string} s @returns {boolean} */
+export function isHexPattern(s) {
+ if (typeof s !== 'string') return false;
+ for (const ch of s) if (!HEX_SET.has(ch)) return false;
+ return true;
+}
+
+/**
+ * Count the case-carrying characters (a-f) in a pattern. Each one doubles the
+ * work when the match is case-sensitive (EIP-55).
+ * @param {string} pattern
+ * @returns {number}
+ */
+export function letterCount(pattern) {
+ let n = 0;
+ for (const ch of pattern || '') if (LETTER_SET.has(ch)) n++;
+ return n;
+}
+
+/**
+ * Probability that a uniformly random EVM address starts with `prefix`.
+ * @param {string} prefix hex characters, without the `0x`
+ * @param {boolean} [caseSensitive=false] match EIP-55 casing exactly
+ * @returns {number} probability in [0, 1]; 0 when the prefix is unreachable
+ */
+export function prefixProbability(prefix, caseSensitive = false) {
+ return sideProbability(prefix, caseSensitive);
+}
+
+/**
+ * Probability that a uniformly random EVM address ends with `suffix`.
+ * Identical model to the prefix: every nibble is uniform.
+ * @param {string} suffix hex characters, without the `0x`
+ * @param {boolean} [caseSensitive=false]
+ * @returns {number} probability in [0, 1]
+ */
+export function suffixProbability(suffix, caseSensitive = false) {
+ return sideProbability(suffix, caseSensitive);
+}
+
+/**
+ * @param {string} side
+ * @param {boolean} caseSensitive
+ * @returns {number}
+ */
+function sideProbability(side, caseSensitive) {
+ if (!side) return 1;
+ if (!isHexPattern(side)) return 0;
+ if (side.length > EVM_ADDRESS_NIBBLES) return 0;
+ const base = Math.pow(16, -side.length);
+ return caseSensitive ? base * Math.pow(2, -letterCount(side)) : base;
+}
+
+/**
+ * Probability that a random EVM address satisfies both ends of a pattern.
+ *
+ * Prefix and suffix cover disjoint nibbles as long as they fit inside the 40
+ * available, so the two probabilities simply multiply. A pattern longer than the
+ * address is unreachable and scores 0.
+ *
+ * @param {object} pattern
+ * @param {string} [pattern.prefix]
+ * @param {string} [pattern.suffix]
+ * @param {boolean} [pattern.caseSensitive=false]
+ * @returns {number} probability in [0, 1]
+ */
+export function patternProbability({ prefix = '', suffix = '', caseSensitive = false } = {}) {
+ if ((prefix?.length || 0) + (suffix?.length || 0) > EVM_ADDRESS_NIBBLES) return 0;
+ return sideProbability(prefix || '', caseSensitive) * sideProbability(suffix || '', caseSensitive);
+}
+
+/**
+ * How much harder a case-sensitive (EIP-55) spelling is than the any-case one.
+ * @param {object} pattern
+ * @param {string} [pattern.prefix]
+ * @param {string} [pattern.suffix]
+ * @returns {number} multiplier ≥ 1
+ */
+export function caseSensitivityCost({ prefix = '', suffix = '' } = {}) {
+ return Math.pow(2, letterCount(prefix) + letterCount(suffix));
+}
diff --git a/sigil/packages/core/src/index.js b/sigil/packages/core/src/index.js
new file mode 100644
index 000000000..dcdc8b070
--- /dev/null
+++ b/sigil/packages/core/src/index.js
@@ -0,0 +1,88 @@
+/**
+ * @three-ws/sigil-core: the shared math behind every Sigil grinder.
+ *
+ * Part of Sigil (https://github.com/nirholas/sigil). Apache-2.0.
+ *
+ * ```js
+ * import { quote } from '@three-ws/sigil-core';
+ *
+ * const q = quote({ space: 'solana', prefix: 'sig', suffix: 'il' });
+ * q.rarity.label; // 'Epic'
+ * q.difficulty.p90; // attempts for a 90% chance
+ * ```
+ */
+
+export {
+ BASE58_ALPHABET,
+ caseVariants,
+ prefixProbability as base58PrefixProbability,
+ suffixProbability as base58SuffixProbability,
+ patternProbability as base58PatternProbability,
+ LEADING_CHAR_PROBABILITY,
+ leadingCharDifficultyRatio,
+} from './base58.js';
+
+export {
+ HEX_ALPHABET,
+ EVM_ADDRESS_NIBBLES,
+ isHexPattern,
+ letterCount,
+ prefixProbability as hexPrefixProbability,
+ suffixProbability as hexSuffixProbability,
+ patternProbability as hexPatternProbability,
+ caseSensitivityCost,
+} from './hex.js';
+
+export {
+ SPACES,
+ MAX_PATTERN_LENGTH,
+ parsePattern,
+ createMatcher,
+ patternKey,
+ parsePatternKey,
+ describePattern,
+} from './pattern.js';
+
+export {
+ DIFFICULTY_MODELS,
+ probability,
+ expectedAttempts,
+ attemptsForConfidence,
+ probabilityAfter,
+ etaSeconds,
+ difficulty,
+ formatDuration,
+ formatAttempts,
+} from './difficulty.js';
+
+export { TIERS, tierFor, rarityScore, machineCost, rarity } from './rarity.js';
+
+import { parsePattern, describePattern, patternKey } from './pattern.js';
+import { difficulty } from './difficulty.js';
+import { rarity } from './rarity.js';
+
+/**
+ * Parse a request and price it in one call: the shape every Sigil surface
+ * (site, CLI, MCP tool, HTTP API) hands back.
+ *
+ * @param {object} input see {@link parsePattern}
+ * @param {object} [opts]
+ * @param {number} [opts.attemptsPerSecond] measured rate, adds wall-clock ETAs
+ * @param {number} [opts.usdPerCoreHour]
+ * @returns {{ ok: boolean, errors: string[], pattern: import('./pattern.js').Pattern,
+ * key: string, describe: string,
+ * difficulty: ReturnType<typeof difficulty>, rarity: ReturnType<typeof rarity> }}
+ */
+export function quote(input, opts = {}) {
+ const parsed = parsePattern(input);
+ const d = difficulty(parsed.pattern, opts);
+ return {
+ ok: parsed.ok,
+ errors: parsed.errors,
+ pattern: parsed.pattern,
+ key: patternKey(parsed.pattern),
+ describe: describePattern(parsed.pattern),
+ difficulty: d,
+ rarity: rarity(d, opts),
+ };
+}
diff --git a/sigil/packages/core/src/pattern.js b/sigil/packages/core/src/pattern.js
new file mode 100644
index 000000000..c03585cee
--- /dev/null
+++ b/sigil/packages/core/src/pattern.js
@@ -0,0 +1,179 @@
+/**
+ * One pattern object for every chain Sigil grinds.
+ *
+ * Part of Sigil (https://github.com/nirholas/sigil). Apache-2.0.
+ *
+ * A vanity request is always the same four facts: which address space, what the
+ * address should start with, what it should end with, and whether the casing has
+ * to match exactly. The two address spaces disagree on everything else. Base58
+ * has a non-uniform leading character and an alphabet with holes (`0 O I l` are
+ * absent), hex is uniform and only 16 wide but carries EIP-55 casing, so this
+ * module normalizes the request once and every other package consumes the
+ * normalized form.
+ *
+ * `parsePattern` never throws: it returns `errors`, so a UI can render the
+ * problem next to the field the user is typing in rather than in a try/catch.
+ */
+
+import { BASE58_ALPHABET, caseVariants } from './base58.js';
+import { isHexPattern, letterCount, EVM_ADDRESS_NIBBLES } from './hex.js';
+
+/** The address spaces Sigil can grind. */
+export const SPACES = /** @type {const} */ (['solana', 'evm']);
+
+/**
+ * Practical ceilings. Above these a browser grind is measured in years, so the
+ * UI refuses rather than showing a progress bar that will never finish; the
+ * distributed/pool path lifts them.
+ */
+export const MAX_PATTERN_LENGTH = Object.freeze({ solana: 8, evm: 12 });
+
+const BASE58_SET = new Set([...BASE58_ALPHABET]);
+
+/**
+ * @typedef {object} Pattern
+ * @property {'solana'|'evm'} space
+ * @property {string} prefix normalized (EVM: lowercase unless caseSensitive)
+ * @property {string} suffix
+ * @property {boolean} caseSensitive
+ * @property {number} length prefix.length + suffix.length
+ */
+
+/**
+ * @typedef {object} ParsedPattern
+ * @property {boolean} ok
+ * @property {string[]} errors
+ * @property {Pattern} pattern
+ */
+
+/**
+ * Normalize and validate a vanity request.
+ *
+ * @param {object} input
+ * @param {'solana'|'evm'} [input.space='solana']
+ * @param {string} [input.prefix]
+ * @param {string} [input.suffix]
+ * @param {boolean} [input.caseSensitive] EVM defaults to "sensitive iff the
+ * pattern contains an uppercase letter"; Solana defaults to true, because
+ * Base58 casing is part of the symbol.
+ * @returns {ParsedPattern}
+ */
+export function parsePattern(input = {}) {
+ const space = input.space === 'evm' ? 'evm' : 'solana';
+ const errors = [];
+
+ let prefix = String(input.prefix ?? '').trim();
+ let suffix = String(input.suffix ?? '').trim();
+
+ if (space === 'evm') {
+ prefix = prefix.replace(/^0x/i, '');
+ suffix = suffix.replace(/^0x/i, '');
+ }
+
+ const hasUpper = /[A-Z]/.test(prefix + suffix);
+ const caseSensitive = typeof input.caseSensitive === 'boolean'
+ ? input.caseSensitive
+ : (space === 'evm' ? hasUpper : true);
+
+ if (space === 'evm' && !caseSensitive) {
+ prefix = prefix.toLowerCase();
+ suffix = suffix.toLowerCase();
+ }
+
+ if (!prefix && !suffix) errors.push('give a prefix, a suffix, or both');
+
+ const max = MAX_PATTERN_LENGTH[space];
+ if (prefix.length + suffix.length > max) {
+ errors.push(`pattern is longer than ${max} characters for ${space}`);
+ }
+
+ if (space === 'solana') {
+ for (const side of [prefix, suffix]) {
+ for (const ch of side) {
+ if (!BASE58_SET.has(ch)) {
+ errors.push(`"${ch}" is not a Base58 character (0, O, I and l do not exist)`);
+ break;
+ }
+ }
+ }
+ if (!caseSensitive) {
+ if (prefix && caseVariants(prefix).length === 0) errors.push('prefix has no valid Base58 spelling');
+ if (suffix && caseVariants(suffix).length === 0) errors.push('suffix has no valid Base58 spelling');
+ }
+ } else {
+ if (prefix && !isHexPattern(prefix)) errors.push('prefix must be hex characters (0-9, a-f)');
+ if (suffix && !isHexPattern(suffix)) errors.push('suffix must be hex characters (0-9, a-f)');
+ if (prefix.length + suffix.length > EVM_ADDRESS_NIBBLES) errors.push('pattern is longer than an EVM address');
+ }
+
+ return {
+ ok: errors.length === 0,
+ errors,
+ pattern: { space, prefix, suffix, caseSensitive, length: prefix.length + suffix.length },
+ };
+}
+
+/**
+ * Build a fast predicate for a normalized pattern.
+ *
+ * The returned function takes an address string in that space's canonical
+ * rendering (Base58 for Solana, `0x`-prefixed hex for EVM, checksummed when the
+ * pattern is case-sensitive) and answers whether it matches.
+ *
+ * @param {Pattern} pattern
+ * @returns {(address: string) => boolean}
+ */
+export function createMatcher(pattern) {
+ const { space, caseSensitive } = pattern;
+ const prefix = caseSensitive ? pattern.prefix : pattern.prefix.toLowerCase();
+ const suffix = caseSensitive ? pattern.suffix : pattern.suffix.toLowerCase();
+ const strip = space === 'evm';
+
+ return (address) => {
+ if (typeof address !== 'string') return false;
+ let body = strip ? address.replace(/^0x/i, '') : address;
+ if (!caseSensitive) body = body.toLowerCase();
+ if (prefix && !body.startsWith(prefix)) return false;
+ if (suffix && !body.endsWith(suffix)) return false;
+ return true;
+ };
+}
+
+/**
+ * A stable, URL-safe string for a pattern. Used as a cache key, a bounty id
+ * component, and the value signed inside a proof-of-grind certificate, so it
+ * must round-trip exactly.
+ * @param {Pattern} pattern
+ * @returns {string}
+ */
+export function patternKey(pattern) {
+ const flags = pattern.caseSensitive ? 'cs' : 'ci';
+ return `${pattern.space}:${pattern.prefix}:${pattern.suffix}:${flags}`;
+}
+
+/**
+ * Parse a `patternKey` back into a pattern.
+ * @param {string} key
+ * @returns {ParsedPattern}
+ */
+export function parsePatternKey(key) {
+ const [space, prefix = '', suffix = '', flags = 'cs'] = String(key).split(':');
+ return parsePattern({ space, prefix, suffix, caseSensitive: flags === 'cs' });
+}
+
+/**
+ * Human summary of a pattern, e.g. `SoL…pump (case-sensitive)`.
+ * @param {Pattern} pattern
+ * @returns {string}
+ */
+export function describePattern(pattern) {
+ const head = pattern.prefix || '';
+ const tail = pattern.suffix || '';
+ const shape = pattern.space === 'evm'
+ ? `0x${head || ''}${head && tail ? '…' : (head ? '…' : '…')}${tail}`
+ : `${head}${head && tail ? '…' : (head ? '…' : '…')}${tail}`;
+ return `${shape} (${pattern.caseSensitive ? 'case-sensitive' : 'any case'})`;
+}
+
+/** How many case-carrying characters a pattern has (EVM only; 0 for Solana). */
+export { letterCount };
diff --git a/sigil/packages/core/src/rarity.js b/sigil/packages/core/src/rarity.js
new file mode 100644
index 000000000..fb6eb55ca
--- /dev/null
+++ b/sigil/packages/core/src/rarity.js
@@ -0,0 +1,97 @@
+/**
+ * Rarity tiers and a cross-chain rarity score.
+ *
+ * Part of Sigil (https://github.com/nirholas/sigil). Apache-2.0.
+ *
+ * Difficulty is the honest number, but "1 in 656 356 768" means nothing to a
+ * buyer looking at two addresses side by side. The score below maps expected
+ * attempts onto a 0-100 scale that is *comparable across address spaces*: a
+ * Solana address and an EVM address with the same score cost the same expected
+ * work, even though one is Base58 and the other hex.
+ *
+ * The scale is logarithmic because the underlying quantity is: every extra
+ * character multiplies the work by 16 (hex) or ~58 (Base58), so a linear score
+ * would put every interesting address in the top percent. 100 is pinned at
+ * 10^18 expected attempts, roughly the point where a single machine cannot
+ * finish inside a human lifetime and only a pool can.
+ */
+
+/** @typedef {'common'|'uncommon'|'rare'|'epic'|'legendary'|'mythic'} Tier */
+
+/** Tier thresholds, in expected attempts. Ordered hardest-first for lookup. */
+export const TIERS = Object.freeze([
+ { tier: 'mythic', minAttempts: 1e12, label: 'Mythic' },
+ { tier: 'legendary', minAttempts: 1e9, label: 'Legendary' },
+ { tier: 'epic', minAttempts: 1e7, label: 'Epic' },
+ { tier: 'rare', minAttempts: 1e5, label: 'Rare' },
+ { tier: 'uncommon', minAttempts: 1e3, label: 'Uncommon' },
+ { tier: 'common', minAttempts: 0, label: 'Common' },
+]);
+
+/**
+ * @param {number} expectedAttempts
+ * @returns {{ tier: Tier, label: string, minAttempts: number }}
+ */
+export function tierFor(expectedAttempts) {
+ if (!Number.isFinite(expectedAttempts)) return { tier: 'mythic', label: 'Mythic', minAttempts: 1e12 };
+ for (const t of TIERS) if (expectedAttempts >= t.minAttempts) return t;
+ return TIERS[TIERS.length - 1];
+}
+
+/** The score at which the scale saturates: 10^18 expected attempts. */
+const SCORE_CEILING_LOG10 = 18;
+
+/**
+ * A 0-100 rarity score, comparable across chains.
+ * @param {number} expectedAttempts
+ * @returns {number} rounded to one decimal
+ */
+export function rarityScore(expectedAttempts) {
+ if (!Number.isFinite(expectedAttempts) || expectedAttempts <= 1) return 0;
+ const raw = (Math.log10(expectedAttempts) / SCORE_CEILING_LOG10) * 100;
+ return Math.round(Math.min(100, Math.max(0, raw)) * 10) / 10;
+}
+
+/**
+ * What the grind would cost in machine time, priced from a reference rate.
+ *
+ * Defaults describe one commodity cloud vCPU running the Sigil WASM grinder:
+ * ~1.1 M attempts/second measured on a Cloud Run 1-vCPU instance, at the current
+ * spot price for that vCPU-hour. Both are inputs, not hidden constants: pass
+ * your own to price against your own fleet.
+ *
+ * @param {number} expectedAttempts
+ * @param {object} [opts]
+ * @param {number} [opts.attemptsPerSecond=1_100_000]
+ * @param {number} [opts.usdPerCoreHour=0.0113]
+ * @returns {{ coreHours: number, usd: number, attemptsPerSecond: number, usdPerCoreHour: number }}
+ */
+export function machineCost(expectedAttempts, opts = {}) {
+ const attemptsPerSecond = opts.attemptsPerSecond ?? 1_100_000;
+ const usdPerCoreHour = opts.usdPerCoreHour ?? 0.0113;
+ const coreHours = expectedAttempts / attemptsPerSecond / 3600;
+ return {
+ coreHours,
+ usd: coreHours * usdPerCoreHour,
+ attemptsPerSecond,
+ usdPerCoreHour,
+ };
+}
+
+/**
+ * The full rarity picture for a difficulty result.
+ * @param {{ expectedAttempts: number }} difficultyResult
+ * @param {object} [costOpts] forwarded to {@link machineCost}
+ * @returns {{ tier: Tier, label: string, score: number, expectedAttempts: number, cost: ReturnType<typeof machineCost> }}
+ */
+export function rarity(difficultyResult, costOpts) {
+ const attempts = difficultyResult.expectedAttempts;
+ const t = tierFor(attempts);
+ return {
+ tier: t.tier,
+ label: t.label,
+ score: rarityScore(attempts),
+ expectedAttempts: attempts,
+ cost: machineCost(attempts, costOpts),
+ };
+}