@miden-sdk/miden-sdk 0.15.0-alpha.4 → 0.15.0-alpha.6

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.
Files changed (59) hide show
  1. package/README.md +139 -9
  2. package/dist/mt/Cargo-C9UbiAcT.js +26202 -0
  3. package/dist/mt/Cargo-C9UbiAcT.js.map +1 -0
  4. package/dist/{api-types.d.ts → mt/api-types.d.ts} +160 -6
  5. package/dist/mt/assets/miden_client_web.wasm +0 -0
  6. package/dist/mt/crates/miden_client_web.d.ts +4821 -0
  7. package/dist/mt/eager.js +38 -0
  8. package/dist/mt/eager.js.map +1 -0
  9. package/dist/{index.d.ts → mt/index.d.ts} +6 -3
  10. package/dist/mt/index.js +3811 -0
  11. package/dist/mt/index.js.map +1 -0
  12. package/dist/{wasm.js → mt/wasm.js} +1 -1
  13. package/dist/mt/wasm.js.map +1 -0
  14. package/dist/mt/workerHelpers.js +28 -0
  15. package/dist/mt/workers/Cargo-C9UbiAcT-Z344cyB1.js +26203 -0
  16. package/dist/mt/workers/Cargo-C9UbiAcT-Z344cyB1.js.map +1 -0
  17. package/dist/mt/workers/assets/miden_client_web.wasm +0 -0
  18. package/dist/mt/workers/web-client-methods-worker.js +26996 -0
  19. package/dist/mt/workers/web-client-methods-worker.js.map +1 -0
  20. package/dist/{workers → mt/workers}/web-client-methods-worker.module.js +71 -2
  21. package/dist/mt/workers/web-client-methods-worker.module.js.map +1 -0
  22. package/dist/mt/workers/workerHelpers.js +28 -0
  23. package/dist/{Cargo-CVlXCH_2.js → st/Cargo-OZMlHpic.js} +721 -496
  24. package/dist/st/Cargo-OZMlHpic.js.map +1 -0
  25. package/dist/st/api-types.d.ts +1144 -0
  26. package/dist/{workers → st}/assets/miden_client_web.wasm +0 -0
  27. package/dist/{crates → st/crates}/miden_client_web.d.ts +357 -197
  28. package/dist/st/docs-entry.d.ts +38 -0
  29. package/dist/{eager.js → st/eager.js} +2 -2
  30. package/dist/st/eager.js.map +1 -0
  31. package/dist/st/index.d.ts +183 -0
  32. package/dist/{index.js → st/index.js} +723 -284
  33. package/dist/st/index.js.map +1 -0
  34. package/dist/st/wasm.js +23 -0
  35. package/dist/st/wasm.js.map +1 -0
  36. package/dist/{workers/Cargo-CVlXCH_2-CWA-5vlh.js → st/workers/Cargo-OZMlHpic-DZjvJlWc.js} +721 -496
  37. package/dist/st/workers/Cargo-OZMlHpic-DZjvJlWc.js.map +1 -0
  38. package/dist/{assets → st/workers/assets}/miden_client_web.wasm +0 -0
  39. package/dist/{workers → st/workers}/web-client-methods-worker.js +792 -498
  40. package/dist/st/workers/web-client-methods-worker.js.map +1 -0
  41. package/dist/st/workers/web-client-methods-worker.module.js +628 -0
  42. package/dist/st/workers/web-client-methods-worker.module.js.map +1 -0
  43. package/js/client.js +190 -7
  44. package/js/node/napi-compat.js +22 -3
  45. package/js/node-index.js +0 -1
  46. package/js/resources/accounts.js +4 -6
  47. package/js/resources/transactions.js +138 -1
  48. package/lazy/package.json +2 -2
  49. package/mt/lazy/package.json +4 -0
  50. package/mt/package.json +4 -0
  51. package/package.json +30 -15
  52. package/dist/Cargo-CVlXCH_2.js.map +0 -1
  53. package/dist/eager.js.map +0 -1
  54. package/dist/index.js.map +0 -1
  55. package/dist/wasm.js.map +0 -1
  56. package/dist/workers/Cargo-CVlXCH_2-CWA-5vlh.js.map +0 -1
  57. package/dist/workers/web-client-methods-worker.js.map +0 -1
  58. package/dist/workers/web-client-methods-worker.module.js.map +0 -1
  59. /package/dist/{docs-entry.d.ts → mt/docs-entry.d.ts} +0 -0
@@ -0,0 +1,628 @@
1
+ // This is a documented workaround that should avoid issues with Vite projects
2
+ // https://github.com/wasm-tool/rollup-plugin-rust?tab=readme-ov-file#usage-with-vite
3
+ // Also, this effectively disables SSR.
4
+ async function loadWasm() {
5
+ let wasmModule;
6
+ if (!import.meta.env || (import.meta.env && !import.meta.env.SSR)) {
7
+ wasmModule = await import('./Cargo-OZMlHpic-DZjvJlWc.js');
8
+ // The Cargo glue's __wbg_init TLA is stripped by the rollup build to
9
+ // prevent blocking WKWebView module evaluation. Call it explicitly here
10
+ // with the WASM URL that the Cargo glue pre-resolves (relative to its
11
+ // own import.meta.url, which downstream bundlers handle correctly).
12
+ if (wasmModule && typeof wasmModule.__wbg_init === "function") {
13
+ await wasmModule.__wbg_init({
14
+ // eslint-disable-next-line camelcase -- wasm-bindgen init API parameter name
15
+ module_or_path: wasmModule.__wasm_url,
16
+ });
17
+ }
18
+ }
19
+ return wasmModule;
20
+ }
21
+
22
+ const WorkerAction = Object.freeze({
23
+ INIT: "init",
24
+ INIT_MOCK: "initMock",
25
+ INIT_THREAD_POOL: "initThreadPool",
26
+ CALL_METHOD: "callMethod",
27
+ EXECUTE_CALLBACK: "executeCallback",
28
+ });
29
+
30
+ const CallbackType = Object.freeze({
31
+ GET_KEY: "getKey",
32
+ INSERT_KEY: "insertKey",
33
+ SIGN: "sign",
34
+ });
35
+
36
+ const MethodName = Object.freeze({
37
+ CREATE_CLIENT: "createClient",
38
+ APPLY_TRANSACTION: "applyTransaction",
39
+ EXECUTE_TRANSACTION: "executeTransaction",
40
+ PROVE_TRANSACTION: "proveTransaction",
41
+ SUBMIT_NEW_TRANSACTION: "submitNewTransaction",
42
+ SUBMIT_NEW_TRANSACTION_MOCK: "submitNewTransactionMock",
43
+ SUBMIT_NEW_TRANSACTION_WITH_PROVER: "submitNewTransactionWithProver",
44
+ SUBMIT_NEW_TRANSACTION_WITH_PROVER_MOCK: "submitNewTransactionWithProverMock",
45
+ SYNC_STATE: "syncState",
46
+ SYNC_STATE_MOCK: "syncStateMock",
47
+ SYNC_CHAIN: "syncChain",
48
+ SYNC_CHAIN_MOCK: "syncChainMock",
49
+ SYNC_NOTE_TRANSPORT: "syncNoteTransport",
50
+ SYNC_NOTE_TRANSPORT_MOCK: "syncNoteTransportMock",
51
+ });
52
+
53
+ let wasmModule = null;
54
+
55
+ const getWasmOrThrow = async () => {
56
+ if (!wasmModule) {
57
+ wasmModule = await loadWasm();
58
+ }
59
+ if (!wasmModule) {
60
+ throw new Error(
61
+ "Miden WASM bindings are unavailable in the worker environment."
62
+ );
63
+ }
64
+ return wasmModule;
65
+ };
66
+
67
+ const serializeUnknown = (value) => {
68
+ if (typeof value === "string") {
69
+ return value;
70
+ }
71
+ try {
72
+ return JSON.stringify(value);
73
+ } catch {
74
+ return String(value);
75
+ }
76
+ };
77
+
78
+ const serializeError = (error) => {
79
+ if (error instanceof Error) {
80
+ return {
81
+ name: error.name,
82
+ message: error.message,
83
+ stack: error.stack,
84
+ cause: error.cause ? serializeError(error.cause) : undefined,
85
+ code: error.code,
86
+ };
87
+ }
88
+
89
+ if (typeof error === "object" && error !== null) {
90
+ return {
91
+ name: error.name ?? "Error",
92
+ message: error.message ?? serializeUnknown(error),
93
+ };
94
+ }
95
+
96
+ return {
97
+ name: "Error",
98
+ message: serializeUnknown(error),
99
+ };
100
+ };
101
+
102
+ /**
103
+ * Worker for executing WebClient methods in a separate thread.
104
+ *
105
+ * This worker offloads computationally heavy tasks from the main thread by handling
106
+ * WebClient operations asynchronously. It imports the WASM module and instantiates a
107
+ * WASM WebClient, then listens for messages from the main thread to perform one of two actions:
108
+ *
109
+ * 1. **Initialization (init):**
110
+ * - The worker receives an "init" message along with user parameters (RPC URL and seed).
111
+ * - It instantiates the WASM WebClient and calls its createClient method.
112
+ * - Once initialization is complete, the worker sends a `{ ready: true }` message back to signal
113
+ * that it is fully initialized.
114
+ *
115
+ * 2. **Method Invocation (callMethod):**
116
+ * - The worker receives a "callMethod" message with a specific method name and arguments.
117
+ * - It uses a mapping (defined in `methodHandlers`) to route the call to the corresponding WASM WebClient method.
118
+ * - Complex data is serialized before being sent and deserialized upon return.
119
+ * - The result (or any error) is then posted back to the main thread.
120
+ *
121
+ * The worker uses a message queue to process incoming messages sequentially, ensuring that only one message
122
+ * is handled at a time.
123
+ *
124
+ * Additionally, the worker immediately sends a `{ loaded: true }` message upon script load. This informs the main
125
+ * thread that the worker script is loaded and ready to receive the "init" message.
126
+ *
127
+ * Supported actions (defined in `WorkerAction`):
128
+ * - "init" : Initialize the WASM WebClient with provided parameters.
129
+ * - "callMethod" : Invoke a designated method on the WASM WebClient.
130
+ *
131
+ * Supported method names are defined in the `MethodName` constant.
132
+ */
133
+
134
+ // Global state variables.
135
+ let wasmWebClient = null;
136
+ let wasmSeed = null; // Seed for the WASM WebClient, if needed.
137
+ let ready = false; // Indicates if the worker is fully initialized.
138
+ let messageQueue = []; // Queue for sequential processing.
139
+ let processing = false; // Flag to ensure one message is processed at a time.
140
+
141
+ // Track pending callback requests
142
+ let pendingCallbacks = new Map();
143
+
144
+ // Timeout for pending callbacks (30 seconds)
145
+ const CALLBACK_TIMEOUT_MS = 30000;
146
+
147
+ // Define proxy functions for callbacks that communicate with main thread
148
+ const callbackProxies = {
149
+ getKey: async (pubKey) => {
150
+ return new Promise((resolve, reject) => {
151
+ const requestId = `${CallbackType.GET_KEY}-${Date.now()}-${Math.random()}`;
152
+ const timeoutId = setTimeout(() => {
153
+ if (pendingCallbacks.has(requestId)) {
154
+ pendingCallbacks.delete(requestId);
155
+ reject(new Error(`Callback ${requestId} timed out`));
156
+ }
157
+ }, CALLBACK_TIMEOUT_MS);
158
+ pendingCallbacks.set(requestId, { resolve, reject, timeoutId });
159
+
160
+ self.postMessage({
161
+ action: WorkerAction.EXECUTE_CALLBACK,
162
+ callbackType: CallbackType.GET_KEY,
163
+ args: [pubKey],
164
+ requestId,
165
+ });
166
+ });
167
+ },
168
+ insertKey: async (pubKey, secretKey) => {
169
+ return new Promise((resolve, reject) => {
170
+ const requestId = `${CallbackType.INSERT_KEY}-${Date.now()}-${Math.random()}`;
171
+ const timeoutId = setTimeout(() => {
172
+ if (pendingCallbacks.has(requestId)) {
173
+ pendingCallbacks.delete(requestId);
174
+ reject(new Error(`Callback ${requestId} timed out`));
175
+ }
176
+ }, CALLBACK_TIMEOUT_MS);
177
+ pendingCallbacks.set(requestId, { resolve, reject, timeoutId });
178
+
179
+ self.postMessage({
180
+ action: WorkerAction.EXECUTE_CALLBACK,
181
+ callbackType: CallbackType.INSERT_KEY,
182
+ args: [pubKey, secretKey],
183
+ requestId,
184
+ });
185
+ });
186
+ },
187
+ sign: async (pubKey, signingInputs) => {
188
+ return new Promise((resolve, reject) => {
189
+ const requestId = `${CallbackType.SIGN}-${Date.now()}-${Math.random()}`;
190
+ const timeoutId = setTimeout(() => {
191
+ if (pendingCallbacks.has(requestId)) {
192
+ pendingCallbacks.delete(requestId);
193
+ reject(new Error(`Callback ${requestId} timed out`));
194
+ }
195
+ }, CALLBACK_TIMEOUT_MS);
196
+ pendingCallbacks.set(requestId, { resolve, reject, timeoutId });
197
+
198
+ self.postMessage({
199
+ action: WorkerAction.EXECUTE_CALLBACK,
200
+ callbackType: CallbackType.SIGN,
201
+ args: [pubKey, signingInputs],
202
+ requestId,
203
+ });
204
+ });
205
+ },
206
+ };
207
+
208
+ // Define a mapping from method names to handler functions.
209
+ const methodHandlers = {
210
+ [MethodName.SYNC_STATE]: async () => {
211
+ // Call the internal WASM method (sync lock is handled at the JS wrapper level)
212
+ const syncSummary = await wasmWebClient.syncStateImpl();
213
+ const serializedSyncSummary = syncSummary.serialize();
214
+ return serializedSyncSummary.buffer;
215
+ },
216
+ [MethodName.SYNC_NOTE_TRANSPORT]: async () => {
217
+ await wasmWebClient.syncNoteTransportImpl();
218
+ },
219
+ [MethodName.SYNC_CHAIN]: async () => {
220
+ const syncSummary = await wasmWebClient.syncChainImpl();
221
+ const serializedSyncSummary = syncSummary.serialize();
222
+ return serializedSyncSummary.buffer;
223
+ },
224
+ [MethodName.APPLY_TRANSACTION]: async (args) => {
225
+ const wasm = await getWasmOrThrow();
226
+ const [serializedTransactionResult, submissionHeight] = args;
227
+ const transactionResultBytes = new Uint8Array(serializedTransactionResult);
228
+ const transactionResult = wasm.TransactionResult.deserialize(
229
+ transactionResultBytes
230
+ );
231
+ const transactionUpdate = await wasmWebClient.applyTransaction(
232
+ transactionResult,
233
+ submissionHeight
234
+ );
235
+ const serializedUpdate = transactionUpdate.serialize();
236
+ return serializedUpdate.buffer;
237
+ },
238
+ [MethodName.EXECUTE_TRANSACTION]: async (args) => {
239
+ const wasm = await getWasmOrThrow();
240
+ const [accountIdHex, serializedTransactionRequest] = args;
241
+ const accountId = wasm.AccountId.fromHex(accountIdHex);
242
+ const transactionRequestBytes = new Uint8Array(
243
+ serializedTransactionRequest
244
+ );
245
+ const transactionRequest = wasm.TransactionRequest.deserialize(
246
+ transactionRequestBytes
247
+ );
248
+ const result = await wasmWebClient.executeTransaction(
249
+ accountId,
250
+ transactionRequest
251
+ );
252
+ const serializedResult = result.serialize();
253
+ return serializedResult.buffer;
254
+ },
255
+ [MethodName.PROVE_TRANSACTION]: async (args) => {
256
+ const wasm = await getWasmOrThrow();
257
+ const [serializedTransactionResult, proverPayload] = args;
258
+ const transactionResultBytes = new Uint8Array(serializedTransactionResult);
259
+ const transactionResult = wasm.TransactionResult.deserialize(
260
+ transactionResultBytes
261
+ );
262
+
263
+ const prover = proverPayload
264
+ ? wasm.TransactionProver.deserialize(proverPayload)
265
+ : undefined;
266
+
267
+ const proven = await wasmWebClient.proveTransaction(
268
+ transactionResult,
269
+ prover
270
+ );
271
+ const serializedProven = proven.serialize();
272
+ return serializedProven.buffer;
273
+ },
274
+ [MethodName.SUBMIT_NEW_TRANSACTION]: async (args) => {
275
+ const wasm = await getWasmOrThrow();
276
+ const [accountIdHex, serializedTransactionRequest] = args;
277
+ const accountId = wasm.AccountId.fromHex(accountIdHex);
278
+ const transactionRequestBytes = new Uint8Array(
279
+ serializedTransactionRequest
280
+ );
281
+ const transactionRequest = wasm.TransactionRequest.deserialize(
282
+ transactionRequestBytes
283
+ );
284
+
285
+ const result = await wasmWebClient.executeTransaction(
286
+ accountId,
287
+ transactionRequest
288
+ );
289
+
290
+ const transactionId = result.id().toHex();
291
+
292
+ const proven = await wasmWebClient.proveTransaction(result);
293
+ const submissionHeight = await wasmWebClient.submitProvenTransaction(
294
+ proven,
295
+ result
296
+ );
297
+ const transactionUpdate = await wasmWebClient.applyTransaction(
298
+ result,
299
+ submissionHeight
300
+ );
301
+
302
+ return {
303
+ transactionId,
304
+ submissionHeight,
305
+ serializedTransactionResult: result.serialize().buffer,
306
+ serializedTransactionUpdate: transactionUpdate.serialize().buffer,
307
+ };
308
+ },
309
+ [MethodName.SUBMIT_NEW_TRANSACTION_WITH_PROVER]: async (args) => {
310
+ const wasm = await getWasmOrThrow();
311
+ const [accountIdHex, serializedTransactionRequest, proverPayload] = args;
312
+ const accountId = wasm.AccountId.fromHex(accountIdHex);
313
+ const transactionRequestBytes = new Uint8Array(
314
+ serializedTransactionRequest
315
+ );
316
+ const transactionRequest = wasm.TransactionRequest.deserialize(
317
+ transactionRequestBytes
318
+ );
319
+
320
+ // Deserialize the prover from the serialized payload
321
+ const prover = proverPayload
322
+ ? wasm.TransactionProver.deserialize(proverPayload)
323
+ : undefined;
324
+
325
+ const result = await wasmWebClient.executeTransaction(
326
+ accountId,
327
+ transactionRequest
328
+ );
329
+
330
+ const transactionId = result.id().toHex();
331
+
332
+ const proven = await wasmWebClient.proveTransaction(result, prover);
333
+ const submissionHeight = await wasmWebClient.submitProvenTransaction(
334
+ proven,
335
+ result
336
+ );
337
+ const transactionUpdate = await wasmWebClient.applyTransaction(
338
+ result,
339
+ submissionHeight
340
+ );
341
+
342
+ return {
343
+ transactionId,
344
+ submissionHeight,
345
+ serializedTransactionResult: result.serialize().buffer,
346
+ serializedTransactionUpdate: transactionUpdate.serialize().buffer,
347
+ };
348
+ },
349
+ };
350
+
351
+ // Add mock methods to the handler mapping.
352
+ methodHandlers[MethodName.SYNC_STATE_MOCK] = async (args) => {
353
+ let [serializedMockChain, serializedMockNoteTransportNode] = args;
354
+ serializedMockChain = new Uint8Array(serializedMockChain);
355
+ serializedMockNoteTransportNode = serializedMockNoteTransportNode
356
+ ? new Uint8Array(serializedMockNoteTransportNode)
357
+ : null;
358
+ await wasmWebClient.createMockClient(
359
+ wasmSeed,
360
+ serializedMockChain,
361
+ serializedMockNoteTransportNode
362
+ );
363
+
364
+ return await methodHandlers[MethodName.SYNC_STATE]();
365
+ };
366
+
367
+ methodHandlers[MethodName.SYNC_CHAIN_MOCK] = async (args) => {
368
+ let [serializedMockChain, serializedMockNoteTransportNode] = args;
369
+ serializedMockChain = new Uint8Array(serializedMockChain);
370
+ serializedMockNoteTransportNode = serializedMockNoteTransportNode
371
+ ? new Uint8Array(serializedMockNoteTransportNode)
372
+ : null;
373
+ await wasmWebClient.createMockClient(
374
+ wasmSeed,
375
+ serializedMockChain,
376
+ serializedMockNoteTransportNode
377
+ );
378
+
379
+ return await methodHandlers[MethodName.SYNC_CHAIN]();
380
+ };
381
+
382
+ methodHandlers[MethodName.SYNC_NOTE_TRANSPORT_MOCK] = async (args) => {
383
+ let [serializedMockChain, serializedMockNoteTransportNode] = args;
384
+ serializedMockChain = new Uint8Array(serializedMockChain);
385
+ serializedMockNoteTransportNode = serializedMockNoteTransportNode
386
+ ? new Uint8Array(serializedMockNoteTransportNode)
387
+ : null;
388
+ await wasmWebClient.createMockClient(
389
+ wasmSeed,
390
+ serializedMockChain,
391
+ serializedMockNoteTransportNode
392
+ );
393
+
394
+ return await methodHandlers[MethodName.SYNC_NOTE_TRANSPORT]();
395
+ };
396
+
397
+ methodHandlers[MethodName.SUBMIT_NEW_TRANSACTION_MOCK] = async (args) => {
398
+ const wasm = await getWasmOrThrow();
399
+ let serializedMockNoteTransportNode = args.pop();
400
+ let serializedMockChain = args.pop();
401
+ serializedMockChain = new Uint8Array(serializedMockChain);
402
+ serializedMockNoteTransportNode = serializedMockNoteTransportNode
403
+ ? new Uint8Array(serializedMockNoteTransportNode)
404
+ : null;
405
+
406
+ wasmWebClient = new wasm.WebClient();
407
+ await wasmWebClient.createMockClient(
408
+ wasmSeed,
409
+ serializedMockChain,
410
+ serializedMockNoteTransportNode
411
+ );
412
+
413
+ const result = await methodHandlers[MethodName.SUBMIT_NEW_TRANSACTION](args);
414
+
415
+ const updatedMockChain = (await wasmWebClient.serializeMockChain()).buffer;
416
+ const updatedMockNoteTransportNode = (
417
+ await wasmWebClient.serializeMockNoteTransportNode()
418
+ ).buffer;
419
+
420
+ return {
421
+ transactionId: result.transactionId,
422
+ submissionHeight: result.submissionHeight,
423
+ serializedTransactionResult: result.serializedTransactionResult,
424
+ serializedTransactionUpdate: result.serializedTransactionUpdate,
425
+ serializedMockChain: updatedMockChain,
426
+ serializedMockNoteTransportNode: updatedMockNoteTransportNode,
427
+ };
428
+ };
429
+
430
+ methodHandlers[MethodName.SUBMIT_NEW_TRANSACTION_WITH_PROVER_MOCK] = async (
431
+ args
432
+ ) => {
433
+ const wasm = await getWasmOrThrow();
434
+ let serializedMockNoteTransportNode = args.pop();
435
+ let serializedMockChain = args.pop();
436
+ serializedMockChain = new Uint8Array(serializedMockChain);
437
+ serializedMockNoteTransportNode = serializedMockNoteTransportNode
438
+ ? new Uint8Array(serializedMockNoteTransportNode)
439
+ : null;
440
+
441
+ wasmWebClient = new wasm.WebClient();
442
+ await wasmWebClient.createMockClient(
443
+ wasmSeed,
444
+ serializedMockChain,
445
+ serializedMockNoteTransportNode
446
+ );
447
+
448
+ const result =
449
+ await methodHandlers[MethodName.SUBMIT_NEW_TRANSACTION_WITH_PROVER](args);
450
+
451
+ const updatedMockChain = (await wasmWebClient.serializeMockChain()).buffer;
452
+ const updatedMockNoteTransportNode = (
453
+ await wasmWebClient.serializeMockNoteTransportNode()
454
+ ).buffer;
455
+
456
+ return {
457
+ transactionId: result.transactionId,
458
+ submissionHeight: result.submissionHeight,
459
+ serializedTransactionResult: result.serializedTransactionResult,
460
+ serializedTransactionUpdate: result.serializedTransactionUpdate,
461
+ serializedMockChain: updatedMockChain,
462
+ serializedMockNoteTransportNode: updatedMockNoteTransportNode,
463
+ };
464
+ };
465
+
466
+ /**
467
+ * Process a single message event.
468
+ */
469
+ async function processMessage(event) {
470
+ const { action, args, methodName, requestId } = event.data;
471
+ try {
472
+ if (action === WorkerAction.INIT) {
473
+ const [
474
+ rpcUrl,
475
+ noteTransportUrl,
476
+ seed,
477
+ storeName,
478
+ hasGetKeyCb,
479
+ hasInsertKeyCb,
480
+ hasSignCb,
481
+ logLevel,
482
+ numThreads,
483
+ ] = args;
484
+ const wasm = await getWasmOrThrow();
485
+
486
+ if (logLevel) {
487
+ wasm.setupLogging(logLevel);
488
+ }
489
+
490
+ // Initialize rayon's thread pool inside THIS worker's WASM instance.
491
+ // The SDK runs every prove call here (NOT on the main thread), so a
492
+ // pool initialized only in main-thread WASM does not parallelize the
493
+ // prove. Without this, par_iter()/par_chunks() in miden-crypto +
494
+ // p3-maybe-rayon return rayon::current_num_threads() == 1 and fall
495
+ // through to sequential code despite the parallel features being on.
496
+ if (
497
+ numThreads &&
498
+ numThreads > 1 &&
499
+ typeof wasm.initThreadPool === "function"
500
+ ) {
501
+ await wasm.initThreadPool(numThreads);
502
+ }
503
+
504
+ wasmWebClient = new wasm.WebClient();
505
+
506
+ // Check if any callbacks are provided
507
+ const useExternalKeystore = hasGetKeyCb || hasInsertKeyCb || hasSignCb;
508
+
509
+ if (useExternalKeystore) {
510
+ // Use callback proxies that communicate with the main thread
511
+ await wasmWebClient.createClientWithExternalKeystore(
512
+ rpcUrl,
513
+ noteTransportUrl,
514
+ seed,
515
+ storeName,
516
+ hasGetKeyCb ? callbackProxies.getKey : undefined,
517
+ hasInsertKeyCb ? callbackProxies.insertKey : undefined,
518
+ hasSignCb ? callbackProxies.sign : undefined
519
+ );
520
+ } else {
521
+ await wasmWebClient.createClient(
522
+ rpcUrl,
523
+ noteTransportUrl,
524
+ seed,
525
+ storeName
526
+ );
527
+ }
528
+
529
+ wasmSeed = seed;
530
+ ready = true;
531
+ self.postMessage({ ready: true });
532
+ return;
533
+ } else if (action === WorkerAction.INIT_MOCK) {
534
+ const [seed, logLevel, numThreads] = args;
535
+ const wasm = await getWasmOrThrow();
536
+
537
+ if (logLevel) {
538
+ wasm.setupLogging(logLevel);
539
+ }
540
+
541
+ // Initialize rayon's pool inside THIS worker's WASM instance — same
542
+ // rationale as the INIT path above: all proving executes here, and a
543
+ // pool initialized in any other instance does not parallelize it.
544
+ if (
545
+ numThreads &&
546
+ numThreads > 1 &&
547
+ typeof wasm.initThreadPool === "function"
548
+ ) {
549
+ await wasm.initThreadPool(numThreads);
550
+ }
551
+
552
+ wasmWebClient = new wasm.WebClient();
553
+ await wasmWebClient.createMockClient(seed, undefined, undefined);
554
+
555
+ wasmSeed = seed;
556
+ ready = true;
557
+ self.postMessage({ ready: true });
558
+ return;
559
+ } else if (action === WorkerAction.CALL_METHOD) {
560
+ if (!ready) {
561
+ throw new Error("Worker is not ready. Please initialize first.");
562
+ }
563
+ if (!wasmWebClient) {
564
+ throw new Error("WebClient not initialized in worker.");
565
+ }
566
+ // Look up the handler from the mapping.
567
+ const handler = methodHandlers[methodName];
568
+ if (!handler) {
569
+ throw new Error(`Unsupported method: ${methodName}`);
570
+ }
571
+ const result = await handler(args);
572
+ self.postMessage({ requestId, result, methodName });
573
+ return;
574
+ } else {
575
+ throw new Error(`Unsupported action: ${action}`);
576
+ }
577
+ } catch (error) {
578
+ const serializedError = serializeError(error);
579
+ console.error(
580
+ "WORKER: Error occurred - %s",
581
+ serializedError.message,
582
+ error
583
+ );
584
+ self.postMessage({ requestId, error: serializedError, methodName });
585
+ }
586
+ }
587
+
588
+ /**
589
+ * Process messages one at a time from the messageQueue.
590
+ */
591
+ async function processQueue() {
592
+ if (processing || messageQueue.length === 0) return;
593
+ processing = true;
594
+ const event = messageQueue.shift();
595
+ try {
596
+ await processMessage(event);
597
+ } finally {
598
+ processing = false;
599
+ processQueue(); // Process next message in queue.
600
+ }
601
+ }
602
+
603
+ // Enqueue incoming messages and process them sequentially.
604
+ self.onmessage = (event) => {
605
+ if (
606
+ event.data.callbackRequestId &&
607
+ pendingCallbacks.has(event.data.callbackRequestId)
608
+ ) {
609
+ const { callbackRequestId, callbackResult, callbackError } = event.data;
610
+ const { resolve, reject, timeoutId } =
611
+ pendingCallbacks.get(callbackRequestId);
612
+ clearTimeout(timeoutId);
613
+ pendingCallbacks.delete(callbackRequestId);
614
+ if (!callbackError) {
615
+ resolve(callbackResult);
616
+ } else {
617
+ reject(new Error(callbackError));
618
+ }
619
+ return;
620
+ }
621
+ messageQueue.push(event);
622
+ processQueue();
623
+ };
624
+
625
+ // Immediately signal that the worker script has loaded.
626
+ // This tells the main thread that the file is fully loaded before sending the "init" message.
627
+ self.postMessage({ loaded: true });
628
+ //# sourceMappingURL=web-client-methods-worker.module.js.map