zeldhash-miner 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Zeldhash
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
package/README.md ADDED
@@ -0,0 +1,244 @@
1
+ # zeldhash-miner (TypeScript SDK)
2
+
3
+ TypeScript SDK for Zeldhash mining in the browser. This package wraps the Rust/WASM miner, exposes a simple API for mining vanity Bitcoin txids, and supports optional WebGPU acceleration.
4
+
5
+ > Requires Node.js 20+ and an ES module-capable bundler (Vite, webpack 5, etc.).
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ npm install zeldhash-miner
11
+ ```
12
+
13
+ If you are developing locally from the monorepo, run the full pipeline to regenerate WASM bindings, library bundle, and demo:
14
+
15
+ ```bash
16
+ ./scripts/build-all.sh
17
+ ```
18
+
19
+ ## Quick Start
20
+
21
+ ```ts
22
+ import { ZeldMiner, ZeldMinerErrorCode } from "zeldhash-miner";
23
+
24
+ const miner = new ZeldMiner({
25
+ network: "mainnet",
26
+ batchSize: 10_000,
27
+ useWebGPU: true, // automatically falls back to CPU if unavailable
28
+ workerThreads: 4,
29
+ satsPerVbyte: 12,
30
+ });
31
+
32
+ miner.on("progress", ({ hashRate, hashesProcessed }) => {
33
+ console.log("hash rate", hashRate, "hashes", hashesProcessed.toString());
34
+ });
35
+
36
+ miner.on("found", ({ psbt, nonce, txid }) => {
37
+ console.log("nonce found", nonce.toString());
38
+ console.log("txid", txid);
39
+ console.log("psbt", psbt);
40
+ });
41
+
42
+ miner.on("error", (err) => {
43
+ if (err.code === ZeldMinerErrorCode.INVALID_INPUT) {
44
+ console.error("bad inputs", err.details);
45
+ } else {
46
+ console.error(err);
47
+ }
48
+ });
49
+
50
+ await miner.mineTransaction({
51
+ inputs: [
52
+ {
53
+ txid: "1f81ad6116ac6045b5bc4941afc212456770ab389c05973c088f22063a2aff37",
54
+ vout: 0,
55
+ scriptPubKey: "0014ea9d20bfb938b2a0d778a5d8d8bc2aaff755c395",
56
+ amount: 100000,
57
+ },
58
+ ],
59
+ outputs: [
60
+ { address: "bc1qa2wjp0ae8ze2p4mc5hvd30p24lm4tsu479mw0r", amount: 90000, change: false },
61
+ { address: "bc1q...change", change: true }, // amount auto-calculated
62
+ ],
63
+ targetZeros: 6,
64
+ distribution: [600n, 300n, 100n], // optional ZELD distribution
65
+ });
66
+ ```
67
+
68
+ ## API Reference
69
+
70
+ ### `new ZeldMiner(options)`
71
+
72
+ Creates a new miner instance.
73
+
74
+ **Options:**
75
+ - `network`: `"mainnet" | "testnet" | "signet" | "regtest"`
76
+ - `batchSize`: `number` — Base batch size per worker
77
+ - `useWebGPU`: `boolean` — Attempt GPU backend (falls back to CPU)
78
+ - `workerThreads`: `number` — Worker count for CPU or GPU tasks
79
+ - `satsPerVbyte`: `number` — Fee rate for PSBT construction
80
+
81
+ ### Methods
82
+
83
+ | Method | Description |
84
+ |--------|-------------|
85
+ | `mineTransaction(params): Promise<MineResult>` | Mines for a nonce and returns an unsigned PSBT |
86
+ | `pause(): void` | Pause the current mining session |
87
+ | `resume(): Promise<void>` | Resume after pause |
88
+ | `stop(): void` | Abort and reject the mining promise |
89
+ | `on(event, handler)` | Subscribe to miner events |
90
+ | `off(event, handler)` | Unsubscribe from events |
91
+
92
+ ### Mining Parameters
93
+
94
+ ```ts
95
+ interface MineParams {
96
+ inputs: TxInput[]; // UTXOs to spend
97
+ outputs: TxOutput[]; // Destinations (one must be change: true)
98
+ targetZeros: number; // Leading zero hex digits (1–32)
99
+ startNonce?: bigint; // Starting point (default 0n)
100
+ batchSize?: number; // Override instance batch size
101
+ distribution?: bigint[]; // Optional ZELD distribution values
102
+ signal?: AbortSignal; // Abort controller signal
103
+ }
104
+
105
+ interface TxInput {
106
+ txid: string;
107
+ vout: number;
108
+ scriptPubKey: string;
109
+ amount: number;
110
+ }
111
+
112
+ interface TxOutput {
113
+ address: string;
114
+ amount?: number; // Required unless change: true
115
+ change: boolean;
116
+ }
117
+ ```
118
+
119
+ ### Events
120
+
121
+ | Event | Payload | Description |
122
+ |-------|---------|-------------|
123
+ | `progress` | `ProgressStats` | Periodic mining progress |
124
+ | `found` | `MineResult` | Nonce found, PSBT ready |
125
+ | `error` | `ZeldMinerError` | Mining error occurred |
126
+ | `stopped` | `void` | Mining was stopped |
127
+
128
+ ```ts
129
+ interface ProgressStats {
130
+ hashesProcessed: bigint;
131
+ hashRate: number;
132
+ elapsedMs?: number;
133
+ lastNonce?: bigint;
134
+ workerId?: number;
135
+ }
136
+
137
+ interface MineResult {
138
+ psbt: string; // Base64-encoded unsigned PSBT
139
+ txid: string; // Transaction ID with leading zeros
140
+ nonce: bigint; // Winning nonce
141
+ attempts: bigint; // Total hashes computed
142
+ duration: number; // Elapsed milliseconds
143
+ hashRate: number; // Hashes per second
144
+ }
145
+ ```
146
+
147
+ ## ZELD Distribution Mode
148
+
149
+ When `distribution` is provided, the OP_RETURN payload becomes:
150
+
151
+ ```
152
+ OP_RETURN | push | "ZELD" | CBOR([distribution..., nonce])
153
+ ```
154
+
155
+ The nonce is appended as the final CBOR element. Bitcoin nodes truncate the CBOR array to match the count of spendable outputs, so the nonce is automatically ignored by downstream wallets while still affecting the txid for mining.
156
+
157
+ ```ts
158
+ await miner.mineTransaction({
159
+ // ...
160
+ distribution: [600n, 300n, 100n], // 3 outputs → 3 values
161
+ });
162
+ ```
163
+
164
+ ## Error Handling
165
+
166
+ ```ts
167
+ import { ZeldMinerError, ZeldMinerErrorCode } from "zeldhash-miner";
168
+
169
+ try {
170
+ await miner.mineTransaction(params);
171
+ } catch (err) {
172
+ if (err instanceof ZeldMinerError) {
173
+ switch (err.code) {
174
+ case ZeldMinerErrorCode.INSUFFICIENT_FUNDS:
175
+ console.error("Not enough sats");
176
+ break;
177
+ case ZeldMinerErrorCode.INVALID_ADDRESS:
178
+ console.error("Bad address:", err.message);
179
+ break;
180
+ case ZeldMinerErrorCode.MINING_ABORTED:
181
+ console.error("Stopped by user");
182
+ break;
183
+ default:
184
+ console.error(err);
185
+ }
186
+ }
187
+ }
188
+ ```
189
+
190
+ ### Error Codes
191
+
192
+ | Code | Description |
193
+ |------|-------------|
194
+ | `INVALID_ADDRESS` | Address parsing failed |
195
+ | `UNSUPPORTED_ADDRESS_TYPE` | Only P2WPKH and P2TR supported |
196
+ | `INSUFFICIENT_FUNDS` | Inputs don't cover outputs + fees |
197
+ | `NO_CHANGE_OUTPUT` | No output marked as change |
198
+ | `MULTIPLE_CHANGE_OUTPUTS` | More than one change output |
199
+ | `INVALID_INPUT` | Bad parameter |
200
+ | `WEBGPU_NOT_AVAILABLE` | WebGPU requested but unavailable |
201
+ | `WORKER_ERROR` | Internal worker failure |
202
+ | `MINING_ABORTED` | Mining was stopped |
203
+ | `DUST_OUTPUT` | Output below dust limit (310 sats P2WPKH / 330 sats P2TR) |
204
+
205
+ ## Runtime Notes
206
+
207
+ - The WASM artifacts live in `node_modules/zeldhash-miner/wasm`. Most modern bundlers copy them automatically because the SDK loads them via `new URL("./wasm/zeldhash_miner_wasm_bg.wasm", import.meta.url)`.
208
+ - If your bundler does not copy assets automatically, copy the `wasm/` folder to your public/static assets.
209
+ - WebGPU is optional. When `useWebGPU` is `true`, the miner auto-detects support and silently falls back to CPU.
210
+
211
+ ## Build & Test
212
+
213
+ ```bash
214
+ # Install dependencies
215
+ npm install
216
+
217
+ # Build the package
218
+ npm run build
219
+
220
+ # Run tests
221
+ npm test
222
+ ```
223
+
224
+ ## Publishing
225
+
226
+ The package is configured for the public npm registry with `"publishConfig.access": "public"`.
227
+
228
+ ```bash
229
+ # From the monorepo root
230
+ ./scripts/build-all.sh
231
+ cd facades/typescript && npm publish
232
+ ```
233
+
234
+ Release flows are documented in [docs/RELEASING.md](../../docs/RELEASING.md).
235
+
236
+ ## License
237
+
238
+ MIT
239
+
240
+ ### Framework Integration
241
+
242
+ For detailed setup instructions for different frameworks (Vite, Next.js, CRA, etc.), see:
243
+
244
+ 📖 **[docs/INTEGRATION.md](../../docs/INTEGRATION.md)**
@@ -0,0 +1,218 @@
1
+ declare type CoordinatorEvent = "ready" | "progress" | "found" | "error" | "stopped";
2
+
3
+ declare type CoordinatorEventMap = {
4
+ ready: void;
5
+ progress: ProgressEvent_2;
6
+ found: MineResult;
7
+ error: ZeldMinerError;
8
+ stopped: void;
9
+ };
10
+
11
+ declare type CoordinatorListener<K extends CoordinatorEvent> = (payload: CoordinatorEventMap[K]) => void;
12
+
13
+ export declare const createMinerError: (code: ZeldMinerErrorCode, message: string, details?: ZeldMinerErrorDetails) => ZeldMinerError;
14
+
15
+ export declare interface MineParams {
16
+ inputs: TxInput[];
17
+ outputs: TxOutput[];
18
+ targetZeros: number;
19
+ startNonce?: bigint;
20
+ batchSize?: number;
21
+ signal?: AbortSignal;
22
+ distribution?: bigint[];
23
+ }
24
+
25
+ export declare interface MineResult {
26
+ psbt: string;
27
+ txid: string;
28
+ nonce: bigint;
29
+ attempts: bigint;
30
+ duration: number;
31
+ hashRate: number;
32
+ }
33
+
34
+ export declare class MiningCoordinator {
35
+ private readonly mode;
36
+ private readonly batchSize;
37
+ private readonly workerCount;
38
+ private readonly listeners;
39
+ private readonly workers;
40
+ private readonly readyPromise;
41
+ private readonly abortHandler;
42
+ private stride;
43
+ private cleanupExternalAbort;
44
+ private running;
45
+ private paused;
46
+ private startedAt;
47
+ private txInputs?;
48
+ private txOutputs?;
49
+ private txNetwork?;
50
+ private satsPerVbyte?;
51
+ private template?;
52
+ private targetZeros?;
53
+ private startNonce;
54
+ private txDistribution?;
55
+ private externalAbort?;
56
+ private terminated;
57
+ constructor(options: MiningCoordinatorOptions);
58
+ on<K extends CoordinatorEvent>(event: K, handler: CoordinatorListener<K>): void;
59
+ off<K extends CoordinatorEvent>(event: K, handler: CoordinatorListener<K>): void;
60
+ private emit;
61
+ private spawnWorkers;
62
+ private handleWorkerMessage;
63
+ private emitProgress;
64
+ private computeNextNonce;
65
+ private stopWorkers;
66
+ private terminateWorkers;
67
+ start(params: StartParams): Promise<void>;
68
+ pause(): void;
69
+ resume(): Promise<void>;
70
+ stop(): void;
71
+ }
72
+
73
+ declare interface MiningCoordinatorOptions {
74
+ mode: WorkerMode;
75
+ batchSize: number;
76
+ workerThreads: number;
77
+ }
78
+
79
+ declare interface MiningTemplate {
80
+ prefix: Uint8Array;
81
+ suffix: Uint8Array;
82
+ useCborNonce?: boolean;
83
+ }
84
+
85
+ export declare type Network = "mainnet" | "testnet" | "signet" | "regtest";
86
+
87
+ declare interface ProgressEvent_2 {
88
+ hashesProcessed: bigint;
89
+ hashRate: number;
90
+ elapsedMs?: number;
91
+ lastNonce?: bigint;
92
+ workerId?: string;
93
+ }
94
+
95
+ export declare type ProgressStats = ProgressEvent_2;
96
+
97
+ declare interface StartParams {
98
+ inputs: TxInput[];
99
+ outputs: TxOutput[];
100
+ network: Network;
101
+ satsPerVbyte: number;
102
+ template: WorkerTemplate;
103
+ targetZeros: number;
104
+ startNonce?: bigint;
105
+ signal?: AbortSignal;
106
+ distribution?: bigint[];
107
+ }
108
+
109
+ export declare const toZeldMinerError: (err: unknown, fallbackCode?: ZeldMinerErrorCode, details?: ZeldMinerErrorDetails) => ZeldMinerError;
110
+
111
+ export declare class TransactionBuilder {
112
+ private readonly network;
113
+ private readonly satsPerVbyte;
114
+ constructor(network: Network, satsPerVbyte: number);
115
+ private getWasm;
116
+ private assertNonceRange;
117
+ private cloneInputs;
118
+ private cloneOutputs;
119
+ private validateInputs;
120
+ private validateAddressResult;
121
+ private validateOutputs;
122
+ private validateDistribution;
123
+ buildMiningTemplate(params: {
124
+ inputs: TxInput[];
125
+ outputs: TxOutput[];
126
+ startNonce: bigint;
127
+ batchSize: number;
128
+ distribution?: bigint[];
129
+ }): Promise<MiningTemplate & {
130
+ nonceLength: number;
131
+ }>;
132
+ buildPsbt(params: {
133
+ inputs: TxInput[];
134
+ outputs: TxOutput[];
135
+ nonce: bigint;
136
+ distribution?: bigint[];
137
+ }): Promise<string>;
138
+ }
139
+
140
+ export declare interface TxInput {
141
+ txid: string;
142
+ vout: number;
143
+ scriptPubKey: string;
144
+ amount: number;
145
+ }
146
+
147
+ export declare interface TxOutput {
148
+ address: string;
149
+ amount?: number;
150
+ change: boolean;
151
+ }
152
+
153
+ declare type WorkerMode = "cpu" | "gpu";
154
+
155
+ declare interface WorkerTemplate extends MiningTemplate {
156
+ nonceLength: number;
157
+ useCborNonce?: boolean;
158
+ }
159
+
160
+ export declare class ZeldMiner {
161
+ private readonly options;
162
+ private readonly builder;
163
+ private coordinator;
164
+ private readonly listeners;
165
+ private state;
166
+ private stopRequested;
167
+ constructor(options: ZeldMinerOptions);
168
+ on<K extends ZeldMinerEvent>(event: K, handler: (payload: ZeldMinerEventMap[K]) => void): void;
169
+ off<K extends ZeldMinerEvent>(event: K, handler: (payload: ZeldMinerEventMap[K]) => void): void;
170
+ private emit;
171
+ private validateOptions;
172
+ private selectBackend;
173
+ private clearCoordinatorHandlers;
174
+ mineTransaction(params: MineParams): Promise<MineResult>;
175
+ stop(): void;
176
+ pause(): void;
177
+ resume(): Promise<void>;
178
+ }
179
+
180
+ export declare class ZeldMinerError extends Error {
181
+ readonly code: ZeldMinerErrorCode;
182
+ readonly details?: ZeldMinerErrorDetails;
183
+ constructor(code: ZeldMinerErrorCode, message: string, details?: ZeldMinerErrorDetails);
184
+ }
185
+
186
+ export declare enum ZeldMinerErrorCode {
187
+ INVALID_ADDRESS = "INVALID_ADDRESS",
188
+ UNSUPPORTED_ADDRESS_TYPE = "UNSUPPORTED_ADDRESS_TYPE",
189
+ INSUFFICIENT_FUNDS = "INSUFFICIENT_FUNDS",
190
+ NO_CHANGE_OUTPUT = "NO_CHANGE_OUTPUT",
191
+ MULTIPLE_CHANGE_OUTPUTS = "MULTIPLE_CHANGE_OUTPUTS",
192
+ INVALID_INPUT = "INVALID_INPUT",
193
+ WEBGPU_NOT_AVAILABLE = "WEBGPU_NOT_AVAILABLE",
194
+ WORKER_ERROR = "WORKER_ERROR",
195
+ MINING_ABORTED = "MINING_ABORTED",
196
+ DUST_OUTPUT = "DUST_OUTPUT"
197
+ }
198
+
199
+ declare type ZeldMinerErrorDetails = Record<string, unknown>;
200
+
201
+ declare type ZeldMinerEvent = "progress" | "found" | "error" | "stopped";
202
+
203
+ declare type ZeldMinerEventMap = {
204
+ progress: ProgressStats;
205
+ found: MineResult;
206
+ error: ZeldMinerError;
207
+ stopped: void;
208
+ };
209
+
210
+ export declare interface ZeldMinerOptions {
211
+ network: Network;
212
+ batchSize: number;
213
+ useWebGPU: boolean;
214
+ workerThreads: number;
215
+ satsPerVbyte: number;
216
+ }
217
+
218
+ export { }