@getpara/web-sdk 2.0.0-dev.0 → 2.0.0-dev.2

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.
@@ -19,905 +19,15 @@ var __async = (__this, __arguments, generator) => {
19
19
  step((generator = generator.apply(__this, __arguments)).next());
20
20
  });
21
21
  };
22
-
23
- // src/wasm/wasm_exec.js
24
- (() => {
25
- const enosys = () => {
26
- const err = new Error("not implemented");
27
- err.code = "ENOSYS";
28
- return err;
29
- };
30
- if (!globalThis.fs) {
31
- let outputBuf = "";
32
- globalThis.fs = {
33
- constants: { O_WRONLY: -1, O_RDWR: -1, O_CREAT: -1, O_TRUNC: -1, O_APPEND: -1, O_EXCL: -1 },
34
- // unused
35
- writeSync(fd, buf) {
36
- outputBuf += decoder.decode(buf);
37
- const nl = outputBuf.lastIndexOf("\n");
38
- if (nl != -1) {
39
- console.log(outputBuf.substring(0, nl));
40
- outputBuf = outputBuf.substring(nl + 1);
41
- }
42
- return buf.length;
43
- },
44
- write(fd, buf, offset, length, position, callback) {
45
- if (offset !== 0 || length !== buf.length || position !== null) {
46
- callback(enosys());
47
- return;
48
- }
49
- const n = this.writeSync(fd, buf);
50
- callback(null, n);
51
- },
52
- chmod(path, mode, callback) {
53
- callback(enosys());
54
- },
55
- chown(path, uid, gid, callback) {
56
- callback(enosys());
57
- },
58
- close(fd, callback) {
59
- callback(enosys());
60
- },
61
- fchmod(fd, mode, callback) {
62
- callback(enosys());
63
- },
64
- fchown(fd, uid, gid, callback) {
65
- callback(enosys());
66
- },
67
- fstat(fd, callback) {
68
- callback(enosys());
69
- },
70
- fsync(fd, callback) {
71
- callback(null);
72
- },
73
- ftruncate(fd, length, callback) {
74
- callback(enosys());
75
- },
76
- lchown(path, uid, gid, callback) {
77
- callback(enosys());
78
- },
79
- link(path, link, callback) {
80
- callback(enosys());
81
- },
82
- lstat(path, callback) {
83
- callback(enosys());
84
- },
85
- mkdir(path, perm, callback) {
86
- callback(enosys());
87
- },
88
- open(path, flags, mode, callback) {
89
- callback(enosys());
90
- },
91
- read(fd, buffer, offset, length, position, callback) {
92
- callback(enosys());
93
- },
94
- readdir(path, callback) {
95
- callback(enosys());
96
- },
97
- readlink(path, callback) {
98
- callback(enosys());
99
- },
100
- rename(from, to, callback) {
101
- callback(enosys());
102
- },
103
- rmdir(path, callback) {
104
- callback(enosys());
105
- },
106
- stat(path, callback) {
107
- callback(enosys());
108
- },
109
- symlink(path, link, callback) {
110
- callback(enosys());
111
- },
112
- truncate(path, length, callback) {
113
- callback(enosys());
114
- },
115
- unlink(path, callback) {
116
- callback(enosys());
117
- },
118
- utimes(path, atime, mtime, callback) {
119
- callback(enosys());
120
- }
121
- };
122
- }
123
- if (!globalThis.process) {
124
- globalThis.process = {
125
- getuid() {
126
- return -1;
127
- },
128
- getgid() {
129
- return -1;
130
- },
131
- geteuid() {
132
- return -1;
133
- },
134
- getegid() {
135
- return -1;
136
- },
137
- getgroups() {
138
- throw enosys();
139
- },
140
- pid: -1,
141
- ppid: -1,
142
- umask() {
143
- throw enosys();
144
- },
145
- cwd() {
146
- throw enosys();
147
- },
148
- chdir() {
149
- throw enosys();
150
- }
151
- };
152
- }
153
- if (!globalThis.crypto) {
154
- throw new Error("globalThis.crypto is not available, polyfill required (crypto.getRandomValues only)");
155
- }
156
- if (!globalThis.performance) {
157
- globalThis.performance = Date;
158
- }
159
- if (!globalThis.TextEncoder) {
160
- throw new Error("globalThis.TextEncoder is not available, polyfill required");
161
- }
162
- if (!globalThis.TextDecoder) {
163
- throw new Error("globalThis.TextDecoder is not available, polyfill required");
164
- }
165
- const encoder = new TextEncoder("utf-8");
166
- const decoder = new TextDecoder("utf-8");
167
- globalThis.Go = class {
168
- constructor() {
169
- this.argv = ["js"];
170
- this.env = {};
171
- this.exit = (code) => {
172
- if (code !== 0) {
173
- console.warn("exit code:", code);
174
- }
175
- };
176
- this._exitPromise = new Promise((resolve) => {
177
- this._resolveExitPromise = resolve;
178
- });
179
- this._pendingEvent = null;
180
- this._scheduledTimeouts = /* @__PURE__ */ new Map();
181
- this._nextCallbackTimeoutID = 1;
182
- const setInt64 = (addr, v) => {
183
- this.mem.setUint32(addr + 0, v, true);
184
- this.mem.setUint32(addr + 4, Math.floor(v / 4294967296), true);
185
- };
186
- const setInt32 = (addr, v) => {
187
- this.mem.setUint32(addr + 0, v, true);
188
- };
189
- const getInt64 = (addr) => {
190
- const low = this.mem.getUint32(addr + 0, true);
191
- const high = this.mem.getInt32(addr + 4, true);
192
- return low + high * 4294967296;
193
- };
194
- const loadValue = (addr) => {
195
- const f = this.mem.getFloat64(addr, true);
196
- if (f === 0) {
197
- return void 0;
198
- }
199
- if (!isNaN(f)) {
200
- return f;
201
- }
202
- const id = this.mem.getUint32(addr, true);
203
- return this._values[id];
204
- };
205
- const storeValue = (addr, v) => {
206
- const nanHead = 2146959360;
207
- if (typeof v === "number" && v !== 0) {
208
- if (isNaN(v)) {
209
- this.mem.setUint32(addr + 4, nanHead, true);
210
- this.mem.setUint32(addr, 0, true);
211
- return;
212
- }
213
- this.mem.setFloat64(addr, v, true);
214
- return;
215
- }
216
- if (v === void 0) {
217
- this.mem.setFloat64(addr, 0, true);
218
- return;
219
- }
220
- let id = this._ids.get(v);
221
- if (id === void 0) {
222
- id = this._idPool.pop();
223
- if (id === void 0) {
224
- id = this._values.length;
225
- }
226
- this._values[id] = v;
227
- this._goRefCounts[id] = 0;
228
- this._ids.set(v, id);
229
- }
230
- this._goRefCounts[id]++;
231
- let typeFlag = 0;
232
- switch (typeof v) {
233
- case "object":
234
- if (v !== null) {
235
- typeFlag = 1;
236
- }
237
- break;
238
- case "string":
239
- typeFlag = 2;
240
- break;
241
- case "symbol":
242
- typeFlag = 3;
243
- break;
244
- case "function":
245
- typeFlag = 4;
246
- break;
247
- }
248
- this.mem.setUint32(addr + 4, nanHead | typeFlag, true);
249
- this.mem.setUint32(addr, id, true);
250
- };
251
- const loadSlice = (addr) => {
252
- const array = getInt64(addr + 0);
253
- const len = getInt64(addr + 8);
254
- return new Uint8Array(this._inst.exports.mem.buffer, array, len);
255
- };
256
- const loadSliceOfValues = (addr) => {
257
- const array = getInt64(addr + 0);
258
- const len = getInt64(addr + 8);
259
- const a = new Array(len);
260
- for (let i = 0; i < len; i++) {
261
- a[i] = loadValue(array + i * 8);
262
- }
263
- return a;
264
- };
265
- const loadString = (addr) => {
266
- const saddr = getInt64(addr + 0);
267
- const len = getInt64(addr + 8);
268
- return decoder.decode(new DataView(this._inst.exports.mem.buffer, saddr, len));
269
- };
270
- const timeOrigin = Date.now() - performance.now();
271
- this.importObject = {
272
- _gotest: {
273
- add: (a, b) => a + b
274
- },
275
- gojs: {
276
- // Go's SP does not change as long as no Go code is running. Some operations (e.g. calls, getters and setters)
277
- // may synchronously trigger a Go event handler. This makes Go code get executed in the middle of the imported
278
- // function. A goroutine can switch to a new stack if the current stack is too small (see morestack function).
279
- // This changes the SP, thus we have to update the SP used by the imported function.
280
- // func wasmExit(code int32)
281
- "runtime.wasmExit": (sp) => {
282
- sp >>>= 0;
283
- const code = this.mem.getInt32(sp + 8, true);
284
- this.exited = true;
285
- delete this._inst;
286
- delete this._values;
287
- delete this._goRefCounts;
288
- delete this._ids;
289
- delete this._idPool;
290
- this.exit(code);
291
- },
292
- // func wasmWrite(fd uintptr, p unsafe.Pointer, n int32)
293
- "runtime.wasmWrite": (sp) => {
294
- sp >>>= 0;
295
- const fd = getInt64(sp + 8);
296
- const p = getInt64(sp + 16);
297
- const n = this.mem.getInt32(sp + 24, true);
298
- fs.writeSync(fd, new Uint8Array(this._inst.exports.mem.buffer, p, n));
299
- },
300
- // func resetMemoryDataView()
301
- "runtime.resetMemoryDataView": (sp) => {
302
- sp >>>= 0;
303
- this.mem = new DataView(this._inst.exports.mem.buffer);
304
- },
305
- // func nanotime1() int64
306
- "runtime.nanotime1": (sp) => {
307
- sp >>>= 0;
308
- setInt64(sp + 8, (timeOrigin + performance.now()) * 1e6);
309
- },
310
- // func walltime() (sec int64, nsec int32)
311
- "runtime.walltime": (sp) => {
312
- sp >>>= 0;
313
- const msec = (/* @__PURE__ */ new Date()).getTime();
314
- setInt64(sp + 8, msec / 1e3);
315
- this.mem.setInt32(sp + 16, msec % 1e3 * 1e6, true);
316
- },
317
- // func scheduleTimeoutEvent(delay int64) int32
318
- "runtime.scheduleTimeoutEvent": (sp) => {
319
- sp >>>= 0;
320
- const id = this._nextCallbackTimeoutID;
321
- this._nextCallbackTimeoutID++;
322
- this._scheduledTimeouts.set(id, setTimeout(
323
- () => {
324
- this._resume();
325
- while (this._scheduledTimeouts.has(id)) {
326
- console.warn("scheduleTimeoutEvent: missed timeout event");
327
- this._resume();
328
- }
329
- },
330
- getInt64(sp + 8)
331
- ));
332
- this.mem.setInt32(sp + 16, id, true);
333
- },
334
- // func clearTimeoutEvent(id int32)
335
- "runtime.clearTimeoutEvent": (sp) => {
336
- sp >>>= 0;
337
- const id = this.mem.getInt32(sp + 8, true);
338
- clearTimeout(this._scheduledTimeouts.get(id));
339
- this._scheduledTimeouts.delete(id);
340
- },
341
- // func getRandomData(r []byte)
342
- "runtime.getRandomData": (sp) => {
343
- sp >>>= 0;
344
- crypto.getRandomValues(loadSlice(sp + 8));
345
- },
346
- // func finalizeRef(v ref)
347
- "syscall/js.finalizeRef": (sp) => {
348
- sp >>>= 0;
349
- const id = this.mem.getUint32(sp + 8, true);
350
- this._goRefCounts[id]--;
351
- if (this._goRefCounts[id] === 0) {
352
- const v = this._values[id];
353
- this._values[id] = null;
354
- this._ids.delete(v);
355
- this._idPool.push(id);
356
- }
357
- },
358
- // func stringVal(value string) ref
359
- "syscall/js.stringVal": (sp) => {
360
- sp >>>= 0;
361
- storeValue(sp + 24, loadString(sp + 8));
362
- },
363
- // func valueGet(v ref, p string) ref
364
- "syscall/js.valueGet": (sp) => {
365
- sp >>>= 0;
366
- const result = Reflect.get(loadValue(sp + 8), loadString(sp + 16));
367
- sp = this._inst.exports.getsp() >>> 0;
368
- storeValue(sp + 32, result);
369
- },
370
- // func valueSet(v ref, p string, x ref)
371
- "syscall/js.valueSet": (sp) => {
372
- sp >>>= 0;
373
- Reflect.set(loadValue(sp + 8), loadString(sp + 16), loadValue(sp + 32));
374
- },
375
- // func valueDelete(v ref, p string)
376
- "syscall/js.valueDelete": (sp) => {
377
- sp >>>= 0;
378
- Reflect.deleteProperty(loadValue(sp + 8), loadString(sp + 16));
379
- },
380
- // func valueIndex(v ref, i int) ref
381
- "syscall/js.valueIndex": (sp) => {
382
- sp >>>= 0;
383
- storeValue(sp + 24, Reflect.get(loadValue(sp + 8), getInt64(sp + 16)));
384
- },
385
- // valueSetIndex(v ref, i int, x ref)
386
- "syscall/js.valueSetIndex": (sp) => {
387
- sp >>>= 0;
388
- Reflect.set(loadValue(sp + 8), getInt64(sp + 16), loadValue(sp + 24));
389
- },
390
- // func valueCall(v ref, m string, args []ref) (ref, bool)
391
- "syscall/js.valueCall": (sp) => {
392
- sp >>>= 0;
393
- try {
394
- const v = loadValue(sp + 8);
395
- const m = Reflect.get(v, loadString(sp + 16));
396
- const args = loadSliceOfValues(sp + 32);
397
- const result = Reflect.apply(m, v, args);
398
- sp = this._inst.exports.getsp() >>> 0;
399
- storeValue(sp + 56, result);
400
- this.mem.setUint8(sp + 64, 1);
401
- } catch (err) {
402
- sp = this._inst.exports.getsp() >>> 0;
403
- storeValue(sp + 56, err);
404
- this.mem.setUint8(sp + 64, 0);
405
- }
406
- },
407
- // func valueInvoke(v ref, args []ref) (ref, bool)
408
- "syscall/js.valueInvoke": (sp) => {
409
- sp >>>= 0;
410
- try {
411
- const v = loadValue(sp + 8);
412
- const args = loadSliceOfValues(sp + 16);
413
- const result = Reflect.apply(v, void 0, args);
414
- sp = this._inst.exports.getsp() >>> 0;
415
- storeValue(sp + 40, result);
416
- this.mem.setUint8(sp + 48, 1);
417
- } catch (err) {
418
- sp = this._inst.exports.getsp() >>> 0;
419
- storeValue(sp + 40, err);
420
- this.mem.setUint8(sp + 48, 0);
421
- }
422
- },
423
- // func valueNew(v ref, args []ref) (ref, bool)
424
- "syscall/js.valueNew": (sp) => {
425
- sp >>>= 0;
426
- try {
427
- const v = loadValue(sp + 8);
428
- const args = loadSliceOfValues(sp + 16);
429
- const result = Reflect.construct(v, args);
430
- sp = this._inst.exports.getsp() >>> 0;
431
- storeValue(sp + 40, result);
432
- this.mem.setUint8(sp + 48, 1);
433
- } catch (err) {
434
- sp = this._inst.exports.getsp() >>> 0;
435
- storeValue(sp + 40, err);
436
- this.mem.setUint8(sp + 48, 0);
437
- }
438
- },
439
- // func valueLength(v ref) int
440
- "syscall/js.valueLength": (sp) => {
441
- sp >>>= 0;
442
- setInt64(sp + 16, parseInt(loadValue(sp + 8).length));
443
- },
444
- // valuePrepareString(v ref) (ref, int)
445
- "syscall/js.valuePrepareString": (sp) => {
446
- sp >>>= 0;
447
- const str = encoder.encode(String(loadValue(sp + 8)));
448
- storeValue(sp + 16, str);
449
- setInt64(sp + 24, str.length);
450
- },
451
- // valueLoadString(v ref, b []byte)
452
- "syscall/js.valueLoadString": (sp) => {
453
- sp >>>= 0;
454
- const str = loadValue(sp + 8);
455
- loadSlice(sp + 16).set(str);
456
- },
457
- // func valueInstanceOf(v ref, t ref) bool
458
- "syscall/js.valueInstanceOf": (sp) => {
459
- sp >>>= 0;
460
- this.mem.setUint8(sp + 24, loadValue(sp + 8) instanceof loadValue(sp + 16) ? 1 : 0);
461
- },
462
- // func copyBytesToGo(dst []byte, src ref) (int, bool)
463
- "syscall/js.copyBytesToGo": (sp) => {
464
- sp >>>= 0;
465
- const dst = loadSlice(sp + 8);
466
- const src = loadValue(sp + 32);
467
- if (!(src instanceof Uint8Array || src instanceof Uint8ClampedArray)) {
468
- this.mem.setUint8(sp + 48, 0);
469
- return;
470
- }
471
- const toCopy = src.subarray(0, dst.length);
472
- dst.set(toCopy);
473
- setInt64(sp + 40, toCopy.length);
474
- this.mem.setUint8(sp + 48, 1);
475
- },
476
- // func copyBytesToJS(dst ref, src []byte) (int, bool)
477
- "syscall/js.copyBytesToJS": (sp) => {
478
- sp >>>= 0;
479
- const dst = loadValue(sp + 8);
480
- const src = loadSlice(sp + 16);
481
- if (!(dst instanceof Uint8Array || dst instanceof Uint8ClampedArray)) {
482
- this.mem.setUint8(sp + 48, 0);
483
- return;
484
- }
485
- const toCopy = src.subarray(0, dst.length);
486
- dst.set(toCopy);
487
- setInt64(sp + 40, toCopy.length);
488
- this.mem.setUint8(sp + 48, 1);
489
- },
490
- "debug": (value) => {
491
- console.log(value);
492
- }
493
- }
494
- };
495
- }
496
- run(instance) {
497
- return __async(this, null, function* () {
498
- if (!(instance instanceof WebAssembly.Instance)) {
499
- throw new Error("Go.run: WebAssembly.Instance expected");
500
- }
501
- this._inst = instance;
502
- this.mem = new DataView(this._inst.exports.mem.buffer);
503
- this._values = [
504
- // JS values that Go currently has references to, indexed by reference id
505
- NaN,
506
- 0,
507
- null,
508
- true,
509
- false,
510
- globalThis,
511
- this
512
- ];
513
- this._goRefCounts = new Array(this._values.length).fill(Infinity);
514
- this._ids = /* @__PURE__ */ new Map([
515
- // mapping from JS values to reference ids
516
- [0, 1],
517
- [null, 2],
518
- [true, 3],
519
- [false, 4],
520
- [globalThis, 5],
521
- [this, 6]
522
- ]);
523
- this._idPool = [];
524
- this.exited = false;
525
- let offset = 4096;
526
- const strPtr = (str) => {
527
- const ptr = offset;
528
- const bytes = encoder.encode(str + "\0");
529
- new Uint8Array(this.mem.buffer, offset, bytes.length).set(bytes);
530
- offset += bytes.length;
531
- if (offset % 8 !== 0) {
532
- offset += 8 - offset % 8;
533
- }
534
- return ptr;
535
- };
536
- const argc = this.argv.length;
537
- const argvPtrs = [];
538
- this.argv.forEach((arg) => {
539
- argvPtrs.push(strPtr(arg));
540
- });
541
- argvPtrs.push(0);
542
- const keys = Object.keys(this.env).sort();
543
- keys.forEach((key) => {
544
- argvPtrs.push(strPtr(`${key}=${this.env[key]}`));
545
- });
546
- argvPtrs.push(0);
547
- const argv = offset;
548
- argvPtrs.forEach((ptr) => {
549
- this.mem.setUint32(offset, ptr, true);
550
- this.mem.setUint32(offset + 4, 0, true);
551
- offset += 8;
552
- });
553
- const wasmMinDataAddr = 4096 + 8192;
554
- if (offset >= wasmMinDataAddr) {
555
- throw new Error("total length of command line and environment variables exceeds limit");
556
- }
557
- this._inst.exports.run(argc, argv);
558
- if (this.exited) {
559
- this._resolveExitPromise();
560
- }
561
- yield this._exitPromise;
562
- });
563
- }
564
- _resume() {
565
- if (this.exited) {
566
- throw new Error("Go program has already exited");
567
- }
568
- this._inst.exports.resume();
569
- if (this.exited) {
570
- this._resolveExitPromise();
571
- }
572
- }
573
- _makeFuncWrapper(id) {
574
- const go = this;
575
- return function() {
576
- const event = { id, this: this, args: arguments };
577
- go._pendingEvent = event;
578
- go._resume();
579
- return event.result;
580
- };
581
- }
582
- };
583
- })();
584
-
585
- // src/workers/walletUtils.ts
586
- import { getBaseMPCNetworkUrl, WalletScheme, WalletType } from "@getpara/core-sdk";
587
- var configCGGMPBase = (serverUrl, walletId, id) => `{"ServerUrl":"${serverUrl}", "WalletId": "${walletId}", "Id":"${id}", "Ids":["USER","CAPSULE"], "Threshold":1}`;
588
- var configDKLSBase = (walletId, id, disableWebSockets) => `{"walletId": "${walletId}", "id":"${id}", "otherId":"CAPSULE", "isReceiver": false, "disableWebSockets": ${disableWebSockets}}`;
589
- function keygenRequest(ctx, userId, walletId, protocolId) {
590
- return __async(this, null, function* () {
591
- const { data } = yield ctx.mpcComputationClient.post("/wallets", {
592
- userId,
593
- walletId,
594
- protocolId
595
- });
596
- return data;
597
- });
598
- }
599
- function signMessageRequest(ctx, userId, walletId, protocolId, message, signer) {
600
- return __async(this, null, function* () {
601
- const { data } = yield ctx.mpcComputationClient.post(`/wallets/${walletId}/messages/sign`, {
602
- userId,
603
- protocolId,
604
- message,
605
- signer
606
- });
607
- return data;
608
- });
609
- }
610
- function sendTransactionRequest(ctx, userId, walletId, protocolId, transaction, signer, chainId) {
611
- return __async(this, null, function* () {
612
- const { data } = yield ctx.mpcComputationClient.post(`/wallets/${walletId}/transactions/send`, {
613
- userId,
614
- protocolId,
615
- transaction,
616
- signer,
617
- chainId
618
- });
619
- return data;
620
- });
621
- }
622
- function ed25519Keygen(ctx, userId) {
623
- return __async(this, null, function* () {
624
- const { walletId, protocolId } = yield ctx.client.createWallet(userId, {
625
- scheme: WalletScheme.ED25519,
626
- type: WalletType.SOLANA
627
- });
628
- const serverUrl = getBaseMPCNetworkUrl(ctx.env, !ctx.disableWebSockets);
629
- try {
630
- const newSigner = yield new Promise(
631
- (resolve, reject) => globalThis.ed25519CreateAccount(serverUrl, walletId, protocolId, (err, result) => {
632
- if (err) {
633
- reject(err);
634
- }
635
- resolve(result);
636
- })
637
- );
638
- return { signer: newSigner, walletId };
639
- } catch (e) {
640
- throw new Error(`error creating account of type SOLANA with userId ${userId} and walletId ${walletId}`);
641
- }
642
- });
643
- }
644
- function ed25519PreKeygen(ctx, pregenIdentifier, pregenIdentifierType) {
645
- return __async(this, null, function* () {
646
- const { walletId, protocolId } = yield ctx.client.createPregenWallet({
647
- pregenIdentifier,
648
- pregenIdentifierType,
649
- scheme: WalletScheme.ED25519,
650
- type: WalletType.SOLANA
651
- });
652
- const serverUrl = getBaseMPCNetworkUrl(ctx.env, !ctx.disableWebSockets);
653
- try {
654
- const newSigner = yield new Promise(
655
- (resolve, reject) => globalThis.ed25519CreateAccount(serverUrl, walletId, protocolId, (err, result) => {
656
- if (err) {
657
- reject(err);
658
- }
659
- resolve(result);
660
- })
661
- );
662
- return { signer: newSigner, walletId };
663
- } catch (e) {
664
- throw new Error(`error creating account of type SOLANA with walletId ${walletId}`);
665
- }
666
- });
667
- }
668
- function ed25519Sign(ctx, share, userId, walletId, base64Bytes) {
669
- return __async(this, null, function* () {
670
- const { protocolId } = yield ctx.client.preSignMessage(userId, walletId, base64Bytes, WalletScheme.ED25519);
671
- try {
672
- const base64Sig = yield new Promise(
673
- (resolve, reject) => globalThis.ed25519Sign(share, protocolId, base64Bytes, (err, result) => {
674
- if (err) {
675
- reject(err);
676
- }
677
- resolve(result);
678
- })
679
- );
680
- return { signature: base64Sig };
681
- } catch (e) {
682
- throw new Error(`error signing for account of type SOLANA with userId ${userId} and walletId ${walletId}`);
683
- }
684
- });
685
- }
686
- function keygen(ctx, userId, type, secretKey) {
687
- return __async(this, null, function* () {
688
- const { walletId, protocolId } = yield ctx.client.createWallet(userId, {
689
- useTwoSigners: true,
690
- scheme: ctx.useDKLS ? WalletScheme.DKLS : WalletScheme.CGGMP,
691
- type,
692
- cosmosPrefix: type === WalletType.COSMOS ? ctx.cosmosPrefix : void 0
693
- });
694
- if (ctx.offloadMPCComputationURL && !ctx.useDKLS) {
695
- return {
696
- signer: (yield keygenRequest(ctx, userId, walletId, protocolId)).signer,
697
- walletId
698
- };
699
- }
700
- const serverUrl = getBaseMPCNetworkUrl(ctx.env, !ctx.disableWebSockets);
701
- const signerConfigUser = ctx.useDKLS ? configDKLSBase(walletId, "USER", ctx.disableWebSockets) : configCGGMPBase(serverUrl, walletId, "USER");
702
- const createAccountFn = ctx.useDKLS ? globalThis.dklsCreateAccount : globalThis.createAccountV2;
703
- try {
704
- const newSigner = yield new Promise(
705
- (resolve, reject) => createAccountFn(
706
- signerConfigUser,
707
- serverUrl,
708
- protocolId,
709
- secretKey,
710
- () => {
711
- },
712
- // no-op for deprecated callback to update progress percentage
713
- (err, result) => {
714
- if (err) {
715
- reject(err);
716
- }
717
- resolve(result);
718
- }
719
- )
720
- );
721
- return { signer: newSigner, walletId };
722
- } catch (e) {
723
- throw new Error(`error creating account of type ${type} with userId ${userId} and walletId ${walletId}`);
724
- }
725
- });
726
- }
727
- function preKeygen(ctx, _partnerId, pregenIdentifier, pregenIdentifierType, type, secretKey) {
728
- return __async(this, null, function* () {
729
- const { walletId, protocolId } = yield ctx.client.createPregenWallet({
730
- pregenIdentifier,
731
- pregenIdentifierType,
732
- type,
733
- cosmosPrefix: type === WalletType.COSMOS ? ctx.cosmosPrefix : void 0
734
- });
735
- const serverUrl = getBaseMPCNetworkUrl(ctx.env, !ctx.disableWebSockets);
736
- const signerConfigUser = configDKLSBase(walletId, "USER", ctx.disableWebSockets);
737
- try {
738
- const newSigner = yield new Promise(
739
- (resolve, reject) => globalThis.dklsCreateAccount(
740
- signerConfigUser,
741
- serverUrl,
742
- protocolId,
743
- secretKey,
744
- () => {
745
- },
746
- // no-op for deprecated callback to update progress percentage
747
- (err, result) => {
748
- if (err) {
749
- reject(err);
750
- }
751
- resolve(result);
752
- }
753
- )
754
- );
755
- return { signer: newSigner, walletId };
756
- } catch (e) {
757
- throw new Error(`error creating account of type ${type} with walletId ${walletId}`);
758
- }
759
- });
760
- }
761
- function signMessage(ctx, share, walletId, userId, message, cosmosSignDoc) {
762
- return __async(this, null, function* () {
763
- const { protocolId, pendingTransactionId } = yield ctx.client.preSignMessage(
764
- userId,
765
- walletId,
766
- message,
767
- null,
768
- cosmosSignDoc
769
- );
770
- if (pendingTransactionId) {
771
- return { pendingTransactionId };
772
- }
773
- if (ctx.offloadMPCComputationURL && !ctx.useDKLS) {
774
- return signMessageRequest(ctx, userId, walletId, protocolId, message, share);
775
- }
776
- const serverUrl = getBaseMPCNetworkUrl(ctx.env, !ctx.disableWebSockets);
777
- const signMessageFn = ctx.useDKLS ? globalThis.dklsSignMessage : globalThis.signMessage;
778
- const parsedShare = JSON.parse(share);
779
- if (!parsedShare.disableWebSockets !== !ctx.disableWebSockets) {
780
- parsedShare.disableWebSockets = ctx.disableWebSockets;
781
- }
782
- share = JSON.stringify(parsedShare);
783
- try {
784
- return yield new Promise(
785
- (resolve, reject) => signMessageFn(share, serverUrl, message, protocolId, (err, result) => {
786
- if (err) {
787
- reject(err);
788
- }
789
- resolve({ signature: result });
790
- })
791
- );
792
- } catch (e) {
793
- throw new Error(`error signing for account with userId ${userId} and walletId ${walletId}`);
794
- }
795
- });
796
- }
797
- function signTransaction(ctx, share, walletId, userId, tx, chainId) {
798
- return __async(this, null, function* () {
799
- const {
800
- data: { protocolId, pendingTransactionId }
801
- } = yield ctx.client.signTransaction(userId, walletId, { transaction: tx, chainId });
802
- if (pendingTransactionId) {
803
- return { pendingTransactionId };
804
- }
805
- if (ctx.offloadMPCComputationURL && !ctx.useDKLS) {
806
- return sendTransactionRequest(ctx, userId, walletId, protocolId, tx, share, chainId);
807
- }
808
- const serverUrl = getBaseMPCNetworkUrl(ctx.env, !ctx.disableWebSockets);
809
- const signTransactionFn = ctx.useDKLS ? globalThis.dklsSendTransaction : globalThis.sendTransaction;
810
- const parsedShare = JSON.parse(share);
811
- if (!parsedShare.disableWebSockets !== !ctx.disableWebSockets) {
812
- parsedShare.disableWebSockets = ctx.disableWebSockets;
813
- }
814
- share = JSON.stringify(parsedShare);
815
- try {
816
- return yield new Promise(
817
- (resolve, reject) => signTransactionFn(share, serverUrl, tx, chainId, protocolId, (err, result) => {
818
- if (err) {
819
- reject(err);
820
- }
821
- resolve({ signature: result });
822
- })
823
- );
824
- } catch (e) {
825
- throw new Error(`error signing transaction for account with userId ${userId} and walletId ${walletId}`);
826
- }
827
- });
828
- }
829
- function sendTransaction(ctx, share, walletId, userId, tx, chainId) {
830
- return __async(this, null, function* () {
831
- const {
832
- data: { protocolId, pendingTransactionId }
833
- } = yield ctx.client.sendTransaction(userId, walletId, { transaction: tx, chainId });
834
- if (pendingTransactionId) {
835
- return { pendingTransactionId };
836
- }
837
- if (ctx.offloadMPCComputationURL && !ctx.useDKLS) {
838
- return sendTransactionRequest(ctx, userId, walletId, protocolId, tx, share, chainId);
839
- }
840
- const serverUrl = getBaseMPCNetworkUrl(ctx.env, !ctx.disableWebSockets);
841
- const sendTransactionFn = ctx.useDKLS ? globalThis.dklsSendTransaction : globalThis.sendTransaction;
842
- const parsedShare = JSON.parse(share);
843
- if (!parsedShare.disableWebSockets !== !ctx.disableWebSockets) {
844
- parsedShare.disableWebSockets = ctx.disableWebSockets;
845
- }
846
- share = JSON.stringify(parsedShare);
847
- try {
848
- return yield new Promise(
849
- (resolve, reject) => sendTransactionFn(share, serverUrl, tx, chainId, protocolId, (err, result) => {
850
- if (err) {
851
- reject(err);
852
- }
853
- resolve({ signature: result });
854
- })
855
- );
856
- } catch (e) {
857
- throw new Error(`error signing transaction to send for account with userId ${userId} and walletId ${walletId}`);
858
- }
859
- });
860
- }
861
- function refresh(ctx, share, walletId, userId, oldPartnerId, newPartnerId, keyShareProtocolId) {
862
- return __async(this, null, function* () {
863
- const {
864
- data: { protocolId }
865
- } = yield ctx.client.refreshKeys(userId, walletId, oldPartnerId, newPartnerId, keyShareProtocolId);
866
- const serverUrl = getBaseMPCNetworkUrl(ctx.env, !ctx.disableWebSockets);
867
- const refreshFn = ctx.useDKLS ? globalThis.dklsRefresh : globalThis.refresh;
868
- const parsedShare = JSON.parse(share);
869
- if (!parsedShare.disableWebSockets !== !ctx.disableWebSockets) {
870
- parsedShare.disableWebSockets = ctx.disableWebSockets;
871
- }
872
- share = JSON.stringify(parsedShare);
873
- try {
874
- return yield new Promise(
875
- (resolve, reject) => refreshFn(share, serverUrl, protocolId, (err, result) => {
876
- if (err) {
877
- reject(err);
878
- }
879
- resolve({ protocolId, signer: result });
880
- })
881
- );
882
- } catch (e) {
883
- throw new Error(`error refreshing keys for account with userId ${userId} and walletId ${walletId}`);
884
- }
885
- });
886
- }
887
- function getPrivateKey(ctx, share, walletId, userId) {
888
- return __async(this, null, function* () {
889
- const paraShare = yield ctx.client.getParaShare(userId, walletId);
890
- if (!paraShare) {
891
- return "";
892
- }
893
- try {
894
- return yield new Promise(
895
- (resolve, reject) => globalThis.getPrivateKey(share, paraShare, (err, result) => {
896
- if (err) {
897
- reject(err);
898
- }
899
- resolve(result);
900
- })
901
- );
902
- } catch (e) {
903
- throw new Error(`error getting private key for account with userId ${userId} and walletId ${walletId}`);
904
- }
905
- });
906
- }
907
-
908
- // src/workers/worker.ts
909
- import {
910
- getPortalBaseURL,
911
- initClient,
912
- mpcComputationClient,
913
- paraVersion,
914
- WalletType as WalletType2
915
- } from "@getpara/core-sdk";
22
+ import * as walletUtils from "./walletUtils.js";
23
+ import { getPortalBaseURL, initClient, mpcComputationClient, paraVersion } from "@getpara/core-sdk";
24
+ let wasmLoaded = false;
916
25
  function loadWasm(ctx, wasmOverride) {
917
26
  return __async(this, null, function* () {
918
27
  if (typeof self === "undefined") {
919
28
  return;
920
29
  }
30
+ yield import("../wasm/wasm_exec.js");
921
31
  const goWasm = new self.Go();
922
32
  let wasmArrayBuffer = wasmOverride;
923
33
  if (!wasmArrayBuffer) {
@@ -936,25 +46,25 @@ function executeMessage(ctx, message) {
936
46
  const { functionType, params, returnObject } = message;
937
47
  switch (functionType) {
938
48
  case "KEYGEN": {
939
- const { userId, secretKey, type = WalletType2.EVM } = params;
940
- const keygenRes = yield keygen(ctx, userId, type, secretKey);
49
+ const { userId, secretKey, type = "EVM" } = params;
50
+ const keygenRes = yield walletUtils.keygen(ctx, userId, type, secretKey);
941
51
  return keygenRes;
942
52
  }
943
53
  case "SIGN_TRANSACTION": {
944
54
  const { share, walletId, userId, tx, chainId } = params;
945
- return signTransaction(ctx, share, walletId, userId, tx, chainId);
55
+ return withRetry(() => walletUtils.signTransaction(ctx, share, walletId, userId, tx, chainId));
946
56
  }
947
57
  case "SEND_TRANSACTION": {
948
58
  const { share, walletId, userId, tx, chainId } = params;
949
- return sendTransaction(ctx, share, walletId, userId, tx, chainId);
59
+ return withRetry(() => walletUtils.sendTransaction(ctx, share, walletId, userId, tx, chainId));
950
60
  }
951
61
  case "SIGN_MESSAGE": {
952
62
  const { share, walletId, userId, message: message2, cosmosSignDoc } = params;
953
- return signMessage(ctx, share, walletId, userId, message2, cosmosSignDoc);
63
+ return withRetry(() => walletUtils.signMessage(ctx, share, walletId, userId, message2, cosmosSignDoc));
954
64
  }
955
65
  case "REFRESH": {
956
66
  const { share, walletId, userId, oldPartnerId, newPartnerId, keyShareProtocolId } = params;
957
- const { protocolId, signer } = yield refresh(
67
+ const { protocolId, signer } = yield walletUtils.refresh(
958
68
  ctx,
959
69
  share,
960
70
  walletId,
@@ -966,26 +76,26 @@ function executeMessage(ctx, message) {
966
76
  return returnObject ? { protocolId, signer } : signer;
967
77
  }
968
78
  case "PREKEYGEN": {
969
- const { email, partnerId, secretKey, type = WalletType2.EVM } = params;
79
+ const { email, partnerId, secretKey, type = "EVM" } = params;
970
80
  let { pregenIdentifier, pregenIdentifierType } = params;
971
81
  if (email !== "null" && email !== "undefined" && email !== "" && email != null) {
972
82
  pregenIdentifier = email;
973
83
  pregenIdentifierType = "EMAIL";
974
84
  }
975
- const keygenRes = yield preKeygen(ctx, partnerId, pregenIdentifier, pregenIdentifierType, type, secretKey);
85
+ const keygenRes = yield walletUtils.preKeygen(ctx, partnerId, pregenIdentifier, pregenIdentifierType, type, secretKey);
976
86
  return keygenRes;
977
87
  }
978
88
  case "GET_PRIVATE_KEY": {
979
89
  const { share, walletId, userId } = params;
980
- return yield getPrivateKey(ctx, share, walletId, userId);
90
+ return yield walletUtils.getPrivateKey(ctx, share, walletId, userId);
981
91
  }
982
92
  case "ED25519_KEYGEN": {
983
93
  const { userId } = params;
984
- return ed25519Keygen(ctx, userId);
94
+ return walletUtils.ed25519Keygen(ctx, userId);
985
95
  }
986
96
  case "ED25519_SIGN": {
987
97
  const { share, walletId, userId, base64Bytes } = params;
988
- return ed25519Sign(ctx, share, userId, walletId, base64Bytes);
98
+ return withRetry(() => walletUtils.ed25519Sign(ctx, share, userId, walletId, base64Bytes));
989
99
  }
990
100
  case "ED25519_PREKEYGEN": {
991
101
  const { email } = params;
@@ -994,7 +104,7 @@ function executeMessage(ctx, message) {
994
104
  pregenIdentifier = email;
995
105
  pregenIdentifierType = "EMAIL";
996
106
  }
997
- return ed25519PreKeygen(ctx, pregenIdentifier, pregenIdentifierType);
107
+ return walletUtils.ed25519PreKeygen(ctx, pregenIdentifier, pregenIdentifierType);
998
108
  }
999
109
  default: {
1000
110
  throw new Error(`functionType: ${functionType} not supported`);
@@ -1002,6 +112,29 @@ function executeMessage(ctx, message) {
1002
112
  }
1003
113
  });
1004
114
  }
115
+ function withRetry(operation, maxRetries = 2, timeoutMs = 1e4) {
116
+ return __async(this, null, function* () {
117
+ let retries = 0;
118
+ while (true) {
119
+ try {
120
+ const operationPromise = operation();
121
+ const timeoutPromise = new Promise((_, reject) => {
122
+ const timeoutId = setTimeout(() => {
123
+ reject(new Error(`Operation timed out after ${timeoutMs}ms`));
124
+ }, timeoutMs);
125
+ operationPromise.finally(() => clearTimeout(timeoutId));
126
+ });
127
+ return yield Promise.race([operationPromise, timeoutPromise]);
128
+ } catch (error) {
129
+ retries++;
130
+ if (retries > maxRetries) {
131
+ throw error;
132
+ }
133
+ console.warn(`Operation failed (attempt ${retries}/${maxRetries}), retrying...`, error);
134
+ }
135
+ }
136
+ });
137
+ }
1005
138
  function handleMessage(e, postMessage, useFetchAdapter) {
1006
139
  return __async(this, null, function* () {
1007
140
  const {
@@ -1013,7 +146,8 @@ function handleMessage(e, postMessage, useFetchAdapter) {
1013
146
  sessionCookie,
1014
147
  useDKLS,
1015
148
  disableWebSockets,
1016
- wasmOverride
149
+ wasmOverride,
150
+ workId
1017
151
  } = e.data;
1018
152
  if (!env) {
1019
153
  return true;
@@ -1035,14 +169,32 @@ function handleMessage(e, postMessage, useFetchAdapter) {
1035
169
  disableWebSockets: !!disableWebSockets,
1036
170
  wasmOverride
1037
171
  };
1038
- if (!ctx.offloadMPCComputationURL || ctx.useDKLS) {
172
+ if (!wasmLoaded && (!ctx.offloadMPCComputationURL || ctx.useDKLS)) {
1039
173
  yield loadWasm(ctx, wasmOverride);
174
+ if (globalThis.initWasm) {
175
+ yield new Promise(
176
+ (resolve, reject) => {
177
+ var _a;
178
+ return (_a = globalThis.initWasm) == null ? void 0 : _a.call(globalThis, (err, result2) => {
179
+ if (err) {
180
+ reject(err);
181
+ }
182
+ resolve(result2);
183
+ });
184
+ }
185
+ );
186
+ }
187
+ wasmLoaded = true;
1040
188
  }
1041
189
  const result = yield executeMessage(ctx, e.data);
190
+ if (workId) {
191
+ result.workId = workId;
192
+ }
1042
193
  postMessage(result);
1043
- return false;
194
+ return !!workId;
1044
195
  });
1045
196
  }
1046
197
  export {
1047
- handleMessage
198
+ handleMessage,
199
+ withRetry
1048
200
  };