@miden-sdk/miden-sdk 0.13.0-next.1

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/dist/index.js ADDED
@@ -0,0 +1,774 @@
1
+ import loadWasm from './wasm.js';
2
+ export { Account, AccountArray, AccountBuilder, AccountBuilderResult, AccountCode, AccountComponent, AccountDelta, AccountFile, AccountHeader, AccountId, AccountIdArray, AccountInterface, AccountStorage, AccountStorageDelta, AccountStorageMode, AccountStorageRequirements, AccountType, AccountVaultDelta, Address, AdviceInputs, AdviceMap, AssetVault, AuthSecretKey, BasicFungibleFaucetComponent, BlockHeader, ConsumableNoteRecord, Endpoint, ExecutedTransaction, Felt, FeltArray, FetchedNote, FlattenedU8Vec, ForeignAccount, ForeignAccountArray, FungibleAsset, FungibleAssetDelta, FungibleAssetDeltaItem, GetProceduresResultItem, InputNote, InputNoteRecord, InputNoteState, InputNotes, IntoUnderlyingByteSource, IntoUnderlyingSink, IntoUnderlyingSource, JsAccountUpdate, JsStateSyncUpdate, JsStorageMapEntry, JsStorageSlot, JsVaultAsset, Library, MerklePath, NetworkId, Note, NoteAndArgs, NoteAndArgsArray, NoteAssets, NoteConsumability, NoteDetails, NoteDetailsAndTag, NoteDetailsAndTagArray, NoteExecutionHint, NoteExecutionMode, NoteFile, NoteFilter, NoteFilterTypes, NoteHeader, NoteId, NoteIdAndArgs, NoteIdAndArgsArray, NoteInclusionProof, NoteInputs, NoteLocation, NoteMetadata, NoteRecipient, NoteRecipientArray, NoteScript, NoteTag, NoteType, OutputNote, OutputNoteArray, OutputNotes, OutputNotesArray, Package, PartialNote, Program, ProvenTransaction, PublicKey, RpcClient, Rpo256, ScriptBuilder, SecretKey, SerializedInputNoteData, SerializedOutputNoteData, SerializedTransactionData, Signature, SigningInputs, SigningInputsType, SlotAndKeys, StorageMap, StorageSlot, StorageSlotArray, SyncSummary, TestUtils, TokenSymbol, TransactionArgs, TransactionFilter, TransactionId, TransactionProver, TransactionRecord, TransactionRequest, TransactionRequestBuilder, TransactionResult, TransactionScript, TransactionScriptInputPair, TransactionScriptInputPairArray, TransactionStatus, TransactionStoreUpdate, TransactionSummary, Word, initSync } from './Cargo-15e14c5a.js';
3
+
4
+ const WorkerAction = Object.freeze({
5
+ INIT: "init",
6
+ CALL_METHOD: "callMethod",
7
+ });
8
+
9
+ const MethodName = Object.freeze({
10
+ CREATE_CLIENT: "createClient",
11
+ NEW_WALLET: "newWallet",
12
+ NEW_FAUCET: "newFaucet",
13
+ EXECUTE_TRANSACTION: "executeTransaction",
14
+ PROVE_TRANSACTION: "proveTransaction",
15
+ SUBMIT_NEW_TRANSACTION: "submitNewTransaction",
16
+ SUBMIT_NEW_TRANSACTION_MOCK: "submitNewTransactionMock",
17
+ SYNC_STATE: "syncState",
18
+ SYNC_STATE_MOCK: "syncStateMock",
19
+ });
20
+
21
+ const buildTypedArraysExport = (exportObject) => {
22
+ return Object.entries(exportObject).reduce(
23
+ (exports, [exportName, _export]) => {
24
+ if (exportName.endsWith("Array")) {
25
+ exports[exportName] = _export;
26
+ }
27
+ return exports;
28
+ },
29
+ {}
30
+ );
31
+ };
32
+
33
+ const MidenArrays = {};
34
+
35
+ let wasmModule = null;
36
+ let wasmLoadPromise = null;
37
+ let webClientStaticsCopied = false;
38
+
39
+ const ensureWasm = async () => {
40
+ if (wasmModule) {
41
+ return wasmModule;
42
+ }
43
+ if (!wasmLoadPromise) {
44
+ wasmLoadPromise = loadWasm().then((module) => {
45
+ wasmModule = module;
46
+ if (module) {
47
+ Object.assign(MidenArrays, buildTypedArraysExport(module));
48
+ if (!webClientStaticsCopied && module.WebClient) {
49
+ copyWebClientStatics(module.WebClient);
50
+ webClientStaticsCopied = true;
51
+ }
52
+ }
53
+ return module;
54
+ });
55
+ }
56
+ return wasmLoadPromise;
57
+ };
58
+
59
+ const getWasmOrThrow = async () => {
60
+ const module = await ensureWasm();
61
+ if (!module) {
62
+ throw new Error(
63
+ "Miden WASM bindings are unavailable in this environment (SSR is disabled)."
64
+ );
65
+ }
66
+ return module;
67
+ };
68
+ /**
69
+ * WebClient is a wrapper around the underlying WASM WebClient object.
70
+ *
71
+ * This wrapper serves several purposes:
72
+ *
73
+ * 1. It creates a dedicated web worker to offload computationally heavy tasks
74
+ * (such as creating accounts, executing transactions, submitting transactions, etc.)
75
+ * from the main thread, helping to prevent UI freezes in the browser.
76
+ *
77
+ * 2. It defines methods that mirror the API of the underlying WASM WebClient,
78
+ * with the intention of executing these functions via the web worker. This allows us
79
+ * to maintain the same API and parameters while benefiting from asynchronous, worker-based computation.
80
+ *
81
+ * 3. It employs a Proxy to forward any calls not designated for web worker computation
82
+ * directly to the underlying WASM WebClient instance.
83
+ *
84
+ * Additionally, the wrapper provides a static createClient function. This static method
85
+ * instantiates the WebClient object and ensures that the necessary createClient calls are
86
+ * performed both in the main thread and within the worker thread. This dual initialization
87
+ * correctly passes user parameters (RPC URL and seed) to both the main-thread
88
+ * WASM WebClient and the worker-side instance.
89
+ *
90
+ * Because of this implementation, the only breaking change for end users is in the way the
91
+ * web client is instantiated. Users should now use the WebClient.createClient static call.
92
+ */
93
+ class WebClient {
94
+ /**
95
+ * Create a WebClient wrapper.
96
+ *
97
+ * @param {string | undefined} rpcUrl - RPC endpoint URL used by the client.
98
+ * @param {Uint8Array | undefined} seed - Optional seed for account initialization.
99
+ * @param {(pubKey: Uint8Array) => Promise<Uint8Array | null | undefined> | Uint8Array | null | undefined} [getKeyCb]
100
+ * - Callback to retrieve the secret key bytes for a given public key. The `pubKey`
101
+ * parameter is the serialized public key (from `PublicKey.serialize()`). Return the
102
+ * corresponding secret key as a `Uint8Array`, or `null`/`undefined` if not found. The
103
+ * return value may be provided synchronously or via a `Promise`.
104
+ * @param {(pubKey: Uint8Array, secretKey: Uint8Array) => Promise<void> | void} [insertKeyCb]
105
+ * - Callback to persist a secret key. `pubKey` is the serialized public key, and
106
+ * `secretKey` is the serialized secret key (from `SecretKey.serialize()`). May return
107
+ * `void` or a `Promise<void>`.
108
+ * @param {(pubKey: Uint8Array, signingInputs: Uint8Array) => Promise<Array<number | string>> | Array<number | string>} [signCb]
109
+ * - Callback to produce signature elements for the provided inputs. `pubKey` is the
110
+ * serialized public key, and `signingInputs` is a `Uint8Array` produced by
111
+ * `SigningInputs.serialize()`. Must return an array of numeric values (numbers or numeric
112
+ * strings) representing the signature elements, either directly or wrapped in a `Promise`.
113
+ */
114
+ constructor(rpcUrl, noteTransportUrl, seed, getKeyCb, insertKeyCb, signCb) {
115
+ this.rpcUrl = rpcUrl;
116
+ this.noteTransportUrl = noteTransportUrl;
117
+ this.seed = seed;
118
+ this.getKeyCb = getKeyCb;
119
+ this.insertKeyCb = insertKeyCb;
120
+ this.signCb = signCb;
121
+
122
+ // Check if Web Workers are available.
123
+ if (
124
+ typeof Worker !== "undefined" &&
125
+ !this.getKeyCb &&
126
+ !this.insertKeyCb &&
127
+ !this.signCb
128
+ ) {
129
+ console.log("WebClient: Web Workers are available.");
130
+ // Create the worker.
131
+ this.worker = new Worker(
132
+ new URL("./workers/web-client-methods-worker.js", import.meta.url),
133
+ { type: "module" }
134
+ );
135
+
136
+ // Map to track pending worker requests.
137
+ this.pendingRequests = new Map();
138
+
139
+ // Promises to track when the worker script is loaded and ready.
140
+ this.loaded = new Promise((resolve) => {
141
+ this.loadedResolver = resolve;
142
+ });
143
+
144
+ // Create a promise that resolves when the worker signals that it is fully initialized.
145
+ this.ready = new Promise((resolve) => {
146
+ this.readyResolver = resolve;
147
+ });
148
+
149
+ // Listen for messages from the worker.
150
+ this.worker.addEventListener("message", (event) => {
151
+ const data = event.data;
152
+
153
+ // Worker script loaded.
154
+ if (data.loaded) {
155
+ this.loadedResolver();
156
+ return;
157
+ }
158
+
159
+ // Worker ready.
160
+ if (data.ready) {
161
+ this.readyResolver();
162
+ return;
163
+ }
164
+
165
+ // Handle responses for method calls.
166
+ const { requestId, error, result, methodName } = data;
167
+ if (requestId && this.pendingRequests.has(requestId)) {
168
+ const { resolve, reject } = this.pendingRequests.get(requestId);
169
+ this.pendingRequests.delete(requestId);
170
+ if (error) {
171
+ console.error(
172
+ `WebClient: Error from worker in ${methodName}:`,
173
+ error
174
+ );
175
+ reject(new Error(error));
176
+ } else {
177
+ resolve(result);
178
+ }
179
+ }
180
+ });
181
+
182
+ // Once the worker script has loaded, initialize the worker.
183
+ this.loaded.then(() => {
184
+ this.worker.postMessage({
185
+ action: WorkerAction.INIT,
186
+ args: [
187
+ this.rpcUrl,
188
+ this.noteTransportUrl,
189
+ this.seed,
190
+ this.getKeyCb,
191
+ this.insertKeyCb,
192
+ this.signCb,
193
+ ],
194
+ });
195
+ });
196
+ } else {
197
+ console.log("WebClient: Web Workers are not available.");
198
+ // Worker not available; set up fallback values.
199
+ this.worker = null;
200
+ this.pendingRequests = null;
201
+ this.loaded = Promise.resolve();
202
+ this.ready = Promise.resolve();
203
+ }
204
+
205
+ // Lazy initialize the underlying WASM WebClient when first requested.
206
+ this.wasmWebClient = null;
207
+ this.wasmWebClientPromise = null;
208
+ }
209
+
210
+ async getWasmWebClient() {
211
+ if (this.wasmWebClient) {
212
+ return this.wasmWebClient;
213
+ }
214
+ if (!this.wasmWebClientPromise) {
215
+ this.wasmWebClientPromise = (async () => {
216
+ const wasm = await getWasmOrThrow();
217
+ const client = new wasm.WebClient();
218
+ this.wasmWebClient = client;
219
+ return client;
220
+ })();
221
+ }
222
+ return this.wasmWebClientPromise;
223
+ }
224
+
225
+ /**
226
+ * Factory method to create and initialize a WebClient instance.
227
+ * This method is async so you can await the asynchronous call to createClient().
228
+ *
229
+ * @param {string} rpcUrl - The RPC URL.
230
+ * @param {string} noteTransportUrl - The note transport URL (optional).
231
+ * @param {string} seed - The seed for the account.
232
+ * @returns {Promise<WebClient>} The fully initialized WebClient.
233
+ */
234
+ static async createClient(rpcUrl, noteTransportUrl, seed) {
235
+ // Construct the instance (synchronously).
236
+ const instance = new WebClient(rpcUrl, noteTransportUrl, seed);
237
+
238
+ // Wait for the underlying wasmWebClient to be initialized.
239
+ const wasmWebClient = await instance.getWasmWebClient();
240
+ await wasmWebClient.createClient(rpcUrl, noteTransportUrl, seed);
241
+
242
+ // Wait for the worker to be ready
243
+ await instance.ready;
244
+
245
+ // Return a proxy that forwards missing properties to wasmWebClient.
246
+ return new Proxy(instance, {
247
+ get(target, prop, receiver) {
248
+ // If the property exists on the wrapper, return it.
249
+ if (prop in target) {
250
+ return Reflect.get(target, prop, receiver);
251
+ }
252
+ // Otherwise, if the wasmWebClient has it, return that.
253
+ if (target.wasmWebClient && prop in target.wasmWebClient) {
254
+ const value = target.wasmWebClient[prop];
255
+ if (typeof value === "function") {
256
+ return value.bind(target.wasmWebClient);
257
+ }
258
+ return value;
259
+ }
260
+ return undefined;
261
+ },
262
+ });
263
+ }
264
+
265
+ /**
266
+ * Factory method to create and initialize a WebClient instance with a remote keystore.
267
+ * This method is async so you can await the asynchronous call to createClientWithExternalKeystore().
268
+ *
269
+ * @param {string} rpcUrl - The RPC URL.
270
+ * @param {string | undefined} noteTransportUrl - The note transport URL (optional).
271
+ * @param {string | undefined} seed - The seed for the account.
272
+ * @param {Function | undefined} getKeyCb - The get key callback.
273
+ * @param {Function | undefined} insertKeyCb - The insert key callback.
274
+ * @param {Function | undefined} signCb - The sign callback.
275
+ * @returns {Promise<WebClient>} The fully initialized WebClient.
276
+ */
277
+ static async createClientWithExternalKeystore(
278
+ rpcUrl,
279
+ noteTransportUrl,
280
+ seed,
281
+ getKeyCb,
282
+ insertKeyCb,
283
+ signCb
284
+ ) {
285
+ // Construct the instance (synchronously).
286
+ const instance = new WebClient(
287
+ rpcUrl,
288
+ noteTransportUrl,
289
+ seed,
290
+ getKeyCb,
291
+ insertKeyCb,
292
+ signCb
293
+ );
294
+ const wasmWebClient = await instance.getWasmWebClient();
295
+ await wasmWebClient.createClientWithExternalKeystore(
296
+ rpcUrl,
297
+ noteTransportUrl,
298
+ seed,
299
+ getKeyCb,
300
+ insertKeyCb,
301
+ signCb
302
+ );
303
+ await instance.ready;
304
+ // Return a proxy that forwards missing properties to wasmWebClient.
305
+ return new Proxy(instance, {
306
+ get(target, prop, receiver) {
307
+ // If the property exists on the wrapper, return it.
308
+ if (prop in target) {
309
+ return Reflect.get(target, prop, receiver);
310
+ }
311
+ // Otherwise, if the wasmWebClient has it, return that.
312
+ if (target.wasmWebClient && prop in target.wasmWebClient) {
313
+ const value = target.wasmWebClient[prop];
314
+ if (typeof value === "function") {
315
+ return value.bind(target.wasmWebClient);
316
+ }
317
+ return value;
318
+ }
319
+ return undefined;
320
+ },
321
+ });
322
+ }
323
+
324
+ /**
325
+ * Call a method via the worker.
326
+ * @param {string} methodName - Name of the method to call.
327
+ * @param {...any} args - Arguments for the method.
328
+ * @returns {Promise<any>}
329
+ */
330
+ async callMethodWithWorker(methodName, ...args) {
331
+ await this.ready;
332
+ // Create a unique request ID.
333
+ const requestId = `${methodName}-${Date.now()}-${Math.random()}`;
334
+ return new Promise((resolve, reject) => {
335
+ // Save the resolve and reject callbacks in the pendingRequests map.
336
+ this.pendingRequests.set(requestId, { resolve, reject });
337
+ // Send the method call request to the worker.
338
+ this.worker.postMessage({
339
+ action: WorkerAction.CALL_METHOD,
340
+ methodName,
341
+ args,
342
+ requestId,
343
+ });
344
+ });
345
+ }
346
+
347
+ // ----- Explicitly Wrapped Methods (Worker-Forwarded) -----
348
+
349
+ async newWallet(storageMode, mutable, authSchemeId, seed) {
350
+ try {
351
+ if (!this.worker) {
352
+ const wasmWebClient = await this.getWasmWebClient();
353
+ return await wasmWebClient.newWallet(
354
+ storageMode,
355
+ mutable,
356
+ authSchemeId,
357
+ seed
358
+ );
359
+ }
360
+ const wasm = await getWasmOrThrow();
361
+ const serializedStorageMode = storageMode.asStr();
362
+ const serializedAccountBytes = await this.callMethodWithWorker(
363
+ MethodName.NEW_WALLET,
364
+ serializedStorageMode,
365
+ mutable,
366
+ authSchemeId,
367
+ seed
368
+ );
369
+ return wasm.Account.deserialize(new Uint8Array(serializedAccountBytes));
370
+ } catch (error) {
371
+ console.error("INDEX.JS: Error in newWallet:", error.toString());
372
+ throw error;
373
+ }
374
+ }
375
+
376
+ async newFaucet(
377
+ storageMode,
378
+ nonFungible,
379
+ tokenSymbol,
380
+ decimals,
381
+ maxSupply,
382
+ authSchemeId
383
+ ) {
384
+ try {
385
+ if (!this.worker) {
386
+ const wasmWebClient = await this.getWasmWebClient();
387
+ return await wasmWebClient.newFaucet(
388
+ storageMode,
389
+ nonFungible,
390
+ tokenSymbol,
391
+ decimals,
392
+ maxSupply,
393
+ authSchemeId
394
+ );
395
+ }
396
+ const wasm = await getWasmOrThrow();
397
+ const serializedStorageMode = storageMode.asStr();
398
+ const serializedMaxSupply = maxSupply.toString();
399
+ const serializedAccountBytes = await this.callMethodWithWorker(
400
+ MethodName.NEW_FAUCET,
401
+ serializedStorageMode,
402
+ nonFungible,
403
+ tokenSymbol,
404
+ decimals,
405
+ serializedMaxSupply,
406
+ authSchemeId
407
+ );
408
+
409
+ return wasm.Account.deserialize(new Uint8Array(serializedAccountBytes));
410
+ } catch (error) {
411
+ console.error("INDEX.JS: Error in newFaucet:", error.toString());
412
+ throw error;
413
+ }
414
+ }
415
+
416
+ async submitNewTransaction(accountId, transactionRequest) {
417
+ try {
418
+ if (!this.worker) {
419
+ const wasmWebClient = await this.getWasmWebClient();
420
+ return await wasmWebClient.submitNewTransaction(
421
+ accountId,
422
+ transactionRequest
423
+ );
424
+ }
425
+
426
+ const wasm = await getWasmOrThrow();
427
+ const serializedTransactionRequest = transactionRequest.serialize();
428
+ const result = await this.callMethodWithWorker(
429
+ MethodName.SUBMIT_NEW_TRANSACTION,
430
+ accountId.toString(),
431
+ serializedTransactionRequest
432
+ );
433
+
434
+ const transactionResult = wasm.TransactionResult.deserialize(
435
+ new Uint8Array(result.serializedTransactionResult)
436
+ );
437
+
438
+ return transactionResult.id();
439
+ } catch (error) {
440
+ console.error(
441
+ "INDEX.JS: Error in submitNewTransaction:",
442
+ error.toString()
443
+ );
444
+ throw error;
445
+ }
446
+ }
447
+
448
+ async executeTransaction(accountId, transactionRequest) {
449
+ try {
450
+ if (!this.worker) {
451
+ const wasmWebClient = await this.getWasmWebClient();
452
+ return await wasmWebClient.executeTransaction(
453
+ accountId,
454
+ transactionRequest
455
+ );
456
+ }
457
+
458
+ const wasm = await getWasmOrThrow();
459
+ const serializedTransactionRequest = transactionRequest.serialize();
460
+ const serializedResultBytes = await this.callMethodWithWorker(
461
+ MethodName.EXECUTE_TRANSACTION,
462
+ accountId.toString(),
463
+ serializedTransactionRequest
464
+ );
465
+
466
+ return wasm.TransactionResult.deserialize(
467
+ new Uint8Array(serializedResultBytes)
468
+ );
469
+ } catch (error) {
470
+ console.error("INDEX.JS: Error in executeTransaction:", error.toString());
471
+ throw error;
472
+ }
473
+ }
474
+
475
+ async submitTransaction(transactionResult, prover) {
476
+ try {
477
+ if (!this.worker) {
478
+ const wasmWebClient = await this.getWasmWebClient();
479
+ const proven = await wasmWebClient.proveTransaction(
480
+ transactionResult,
481
+ prover
482
+ );
483
+ const submissionHeight = await wasmWebClient.submitProvenTransaction(
484
+ proven,
485
+ transactionResult
486
+ );
487
+ return await wasmWebClient.applyTransaction(
488
+ transactionResult,
489
+ submissionHeight
490
+ );
491
+ }
492
+
493
+ const wasm = await getWasmOrThrow();
494
+ const serializedTransactionResult = transactionResult.serialize();
495
+ const proverPayload = prover ? prover.serialize() : null;
496
+
497
+ const { submissionHeight, serializedTransactionUpdate } =
498
+ await this.callMethodWithWorker(
499
+ MethodName.SUBMIT_TRANSACTION,
500
+ serializedTransactionResult,
501
+ proverPayload
502
+ );
503
+
504
+ if (this instanceof MockWebClient) {
505
+ return wasm.TransactionStoreUpdate.deserialize(
506
+ new Uint8Array(serializedTransactionUpdate)
507
+ );
508
+ }
509
+
510
+ const wasmWebClient = await this.getWasmWebClient();
511
+ return await wasmWebClient.applyTransaction(
512
+ transactionResult,
513
+ submissionHeight
514
+ );
515
+ } catch (error) {
516
+ console.error("INDEX.JS: Error in submitTransaction:", error.toString());
517
+ throw error;
518
+ }
519
+ }
520
+
521
+ async proveTransaction(transactionResult, prover) {
522
+ try {
523
+ if (!this.worker) {
524
+ const wasmWebClient = await this.getWasmWebClient();
525
+ return await wasmWebClient.proveTransaction(transactionResult, prover);
526
+ }
527
+
528
+ const wasm = await getWasmOrThrow();
529
+ const serializedTransactionResult = transactionResult.serialize();
530
+ const proverPayload = prover ? prover.serialize() : null;
531
+
532
+ const serializedProvenBytes = await this.callMethodWithWorker(
533
+ MethodName.PROVE_TRANSACTION,
534
+ serializedTransactionResult,
535
+ proverPayload
536
+ );
537
+
538
+ return wasm.ProvenTransaction.deserialize(
539
+ new Uint8Array(serializedProvenBytes)
540
+ );
541
+ } catch (error) {
542
+ console.error("INDEX.JS: Error in proveTransaction:", error.toString());
543
+ throw error;
544
+ }
545
+ }
546
+
547
+ async syncState() {
548
+ try {
549
+ if (!this.worker) {
550
+ const wasmWebClient = await this.getWasmWebClient();
551
+ return await wasmWebClient.syncState();
552
+ }
553
+
554
+ const wasm = await getWasmOrThrow();
555
+ const serializedSyncSummaryBytes = await this.callMethodWithWorker(
556
+ MethodName.SYNC_STATE
557
+ );
558
+
559
+ return wasm.SyncSummary.deserialize(
560
+ new Uint8Array(serializedSyncSummaryBytes)
561
+ );
562
+ } catch (error) {
563
+ console.error("INDEX.JS: Error in syncState:", error.toString());
564
+ throw error;
565
+ }
566
+ }
567
+
568
+ terminate() {
569
+ if (this.worker) {
570
+ this.worker.terminate();
571
+ }
572
+ }
573
+ }
574
+
575
+ class MockWebClient extends WebClient {
576
+ constructor(seed) {
577
+ super(null, seed);
578
+ }
579
+
580
+ /**
581
+ * Factory method to create a WebClient with a mock chain for testing purposes.
582
+ *
583
+ * @param serializedMockChain - Serialized mock chain data (optional). Will use an empty chain if not provided.
584
+ * @param serializedMockNoteTransportNode - Serialized mock note transport node data (optional). Will use a new instance if not provided.
585
+ * @param seed - The seed for the account (optional).
586
+ * @returns A promise that resolves to a MockWebClient.
587
+ */
588
+ static async createClient(
589
+ serializedMockChain,
590
+ serializedMockNoteTransportNode,
591
+ seed
592
+ ) {
593
+ // Construct the instance (synchronously).
594
+ const instance = new MockWebClient(seed);
595
+
596
+ // Wait for the underlying wasmWebClient to be initialized.
597
+ const wasmWebClient = await instance.getWasmWebClient();
598
+ await wasmWebClient.createMockClient(
599
+ seed,
600
+ serializedMockChain,
601
+ serializedMockNoteTransportNode
602
+ );
603
+
604
+ // Wait for the worker to be ready
605
+ await instance.ready;
606
+
607
+ // Return a proxy that forwards missing properties to wasmWebClient.
608
+ return new Proxy(instance, {
609
+ get(target, prop, receiver) {
610
+ // If the property exists on the wrapper, return it.
611
+ if (prop in target) {
612
+ return Reflect.get(target, prop, receiver);
613
+ }
614
+ // Otherwise, if the wasmWebClient has it, return that.
615
+ if (target.wasmWebClient && prop in target.wasmWebClient) {
616
+ const value = target.wasmWebClient[prop];
617
+ if (typeof value === "function") {
618
+ return value.bind(target.wasmWebClient);
619
+ }
620
+ return value;
621
+ }
622
+ return undefined;
623
+ },
624
+ });
625
+ }
626
+
627
+ async syncState() {
628
+ try {
629
+ const wasmWebClient = await this.getWasmWebClient();
630
+ if (!this.worker) {
631
+ return await wasmWebClient.syncState();
632
+ }
633
+
634
+ let serializedMockChain = wasmWebClient.serializeMockChain().buffer;
635
+ let serializedMockNoteTransportNode =
636
+ wasmWebClient.serializeMockNoteTransportNode().buffer;
637
+
638
+ const wasm = await getWasmOrThrow();
639
+
640
+ const serializedSyncSummaryBytes = await this.callMethodWithWorker(
641
+ MethodName.SYNC_STATE_MOCK,
642
+ serializedMockChain,
643
+ serializedMockNoteTransportNode
644
+ );
645
+
646
+ return wasm.SyncSummary.deserialize(
647
+ new Uint8Array(serializedSyncSummaryBytes)
648
+ );
649
+ } catch (error) {
650
+ console.error("INDEX.JS: Error in syncState:", error.toString());
651
+ throw error;
652
+ }
653
+ }
654
+
655
+ async submitTransaction(transactionResult, prover) {
656
+ try {
657
+ if (!this.worker) {
658
+ return await super.submitTransaction(transactionResult, prover);
659
+ }
660
+
661
+ const wasmWebClient = await this.getWasmWebClient();
662
+ const wasm = await getWasmOrThrow();
663
+ const serializedTransactionResult = transactionResult.serialize();
664
+ const proverPayload = prover ? prover.serialize() : null;
665
+ const serializedMockChain = wasmWebClient.serializeMockChain().buffer;
666
+ const serializedMockNoteTransportNode =
667
+ wasmWebClient.serializeMockNoteTransportNode().buffer;
668
+
669
+ const result = await this.callMethodWithWorker(
670
+ MethodName.SUBMIT_TRANSACTION_MOCK,
671
+ serializedTransactionResult,
672
+ proverPayload,
673
+ serializedMockChain,
674
+ serializedMockNoteTransportNode
675
+ );
676
+ const newMockChain = new Uint8Array(result.serializedMockChain);
677
+ const newMockNoteTransportNode = result.serializedMockNoteTransportNode
678
+ ? new Uint8Array(result.serializedMockNoteTransportNode)
679
+ : undefined;
680
+
681
+ if (!(this instanceof MockWebClient)) {
682
+ return await wasmWebClient.applyTransaction(
683
+ transactionResult,
684
+ result.submissionHeight
685
+ );
686
+ }
687
+
688
+ this.wasmWebClient = new wasm.WebClient();
689
+ this.wasmWebClientPromise = Promise.resolve(this.wasmWebClient);
690
+ await this.wasmWebClient.createMockClient(
691
+ this.seed,
692
+ newMockChain,
693
+ newMockNoteTransportNode
694
+ );
695
+
696
+ return wasm.TransactionStoreUpdate.deserialize(
697
+ new Uint8Array(result.serializedTransactionUpdate)
698
+ );
699
+ } catch (error) {
700
+ console.error("INDEX.JS: Error in submitTransaction:", error.toString());
701
+ throw error;
702
+ }
703
+ }
704
+
705
+ async submitNewTransaction(accountId, transactionRequest) {
706
+ try {
707
+ if (!this.worker) {
708
+ return await super.submitNewTransaction(accountId, transactionRequest);
709
+ }
710
+
711
+ const wasmWebClient = await this.getWasmWebClient();
712
+ const wasm = await getWasmOrThrow();
713
+ const serializedTransactionRequest = transactionRequest.serialize();
714
+ const serializedMockChain = wasmWebClient.serializeMockChain().buffer;
715
+ const serializedMockNoteTransportNode =
716
+ wasmWebClient.serializeMockNoteTransportNode().buffer;
717
+
718
+ const result = await this.callMethodWithWorker(
719
+ MethodName.SUBMIT_NEW_TRANSACTION_MOCK,
720
+ accountId.toString(),
721
+ serializedTransactionRequest,
722
+ serializedMockChain,
723
+ serializedMockNoteTransportNode
724
+ );
725
+
726
+ const newMockChain = new Uint8Array(result.serializedMockChain);
727
+ const newMockNoteTransportNode = result.serializedMockNoteTransportNode
728
+ ? new Uint8Array(result.serializedMockNoteTransportNode)
729
+ : undefined;
730
+
731
+ const transactionResult = wasm.TransactionResult.deserialize(
732
+ new Uint8Array(result.serializedTransactionResult)
733
+ );
734
+
735
+ if (!(this instanceof MockWebClient)) {
736
+ return transactionResult.id();
737
+ }
738
+
739
+ this.wasmWebClient = new wasm.WebClient();
740
+ this.wasmWebClientPromise = Promise.resolve(this.wasmWebClient);
741
+ await this.wasmWebClient.createMockClient(
742
+ this.seed,
743
+ newMockChain,
744
+ newMockNoteTransportNode
745
+ );
746
+
747
+ return transactionResult.id();
748
+ } catch (error) {
749
+ console.error(
750
+ "INDEX.JS: Error in submitNewTransaction:",
751
+ error.toString()
752
+ );
753
+ throw error;
754
+ }
755
+ }
756
+ }
757
+
758
+ function copyWebClientStatics(WasmWebClient) {
759
+ if (!WasmWebClient) {
760
+ return;
761
+ }
762
+ Object.getOwnPropertyNames(WasmWebClient).forEach((prop) => {
763
+ if (
764
+ typeof WasmWebClient[prop] === "function" &&
765
+ prop !== "constructor" &&
766
+ prop !== "prototype"
767
+ ) {
768
+ WebClient[prop] = WasmWebClient[prop];
769
+ }
770
+ });
771
+ }
772
+
773
+ export { MidenArrays, MockWebClient, WebClient };
774
+ //# sourceMappingURL=index.js.map