@getpara/core-sdk 1.5.0 → 1.6.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/dist/esm/index.js CHANGED
@@ -1,8 +1,65 @@
1
1
  var __defProp = Object.defineProperty;
2
+ var __defProps = Object.defineProperties;
3
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
7
+ var __typeError = (msg) => {
8
+ throw TypeError(msg);
9
+ };
10
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
11
+ var __spreadValues = (a, b) => {
12
+ for (var prop in b || (b = {}))
13
+ if (__hasOwnProp.call(b, prop))
14
+ __defNormalProp(a, prop, b[prop]);
15
+ if (__getOwnPropSymbols)
16
+ for (var prop of __getOwnPropSymbols(b)) {
17
+ if (__propIsEnum.call(b, prop))
18
+ __defNormalProp(a, prop, b[prop]);
19
+ }
20
+ return a;
21
+ };
22
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
23
+ var __objRest = (source, exclude) => {
24
+ var target = {};
25
+ for (var prop in source)
26
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
27
+ target[prop] = source[prop];
28
+ if (source != null && __getOwnPropSymbols)
29
+ for (var prop of __getOwnPropSymbols(source)) {
30
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
31
+ target[prop] = source[prop];
32
+ }
33
+ return target;
34
+ };
2
35
  var __export = (target, all) => {
3
36
  for (var name in all)
4
37
  __defProp(target, name, { get: all[name], enumerable: true });
5
38
  };
39
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
40
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
41
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
42
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
43
+ var __async = (__this, __arguments, generator) => {
44
+ return new Promise((resolve, reject) => {
45
+ var fulfilled = (value) => {
46
+ try {
47
+ step(generator.next(value));
48
+ } catch (e) {
49
+ reject(e);
50
+ }
51
+ };
52
+ var rejected = (value) => {
53
+ try {
54
+ step(generator.throw(value));
55
+ } catch (e) {
56
+ reject(e);
57
+ }
58
+ };
59
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
60
+ step((generator = generator.apply(__this, __arguments)).next());
61
+ });
62
+ };
6
63
 
7
64
  // src/ParaCore.ts
8
65
  import { Buffer as NodeBuffer } from "buffer";
@@ -26,7 +83,7 @@ import forge from "node-forge";
26
83
  // src/utils/events.ts
27
84
  function dispatchEvent(type, data, error) {
28
85
  typeof window !== "undefined" && !!window.dispatchEvent && window.dispatchEvent(
29
- new CustomEvent(type, { detail: { data, ...error && { error: new Error(error) } } })
86
+ new CustomEvent(type, { detail: __spreadValues({ data }, error && { error: new Error(error) }) })
30
87
  );
31
88
  }
32
89
 
@@ -93,7 +150,8 @@ function truncateAddress(str, addressType, { prefix = addressType === "COSMOS" ?
93
150
  return `${str.slice(0, headLength)}...${str.slice(-4)}`;
94
151
  }
95
152
  function stringToPhoneNumber(str) {
96
- return parsePhoneNumberFromString(str)?.formatInternational().replace(/[^\d+]/g, "");
153
+ var _a;
154
+ return (_a = parsePhoneNumberFromString(str)) == null ? void 0 : _a.formatInternational().replace(/[^\d+]/g, "");
97
155
  }
98
156
  function normalizePhoneNumber(countryCode, number) {
99
157
  return stringToPhoneNumber(`${countryCode[0] !== "+" ? "+" : ""}${countryCode}${number}`);
@@ -136,26 +194,28 @@ function getOnRampAssets(data, {
136
194
  }
137
195
 
138
196
  // src/utils/polling.ts
139
- async function waitUntilTrue(condition, timeoutMs, intervalMs) {
140
- const start = Date.now();
141
- while (Date.now() - start < timeoutMs) {
142
- if (await condition()) {
143
- return true;
197
+ function waitUntilTrue(condition, timeoutMs, intervalMs) {
198
+ return __async(this, null, function* () {
199
+ const start = Date.now();
200
+ while (Date.now() - start < timeoutMs) {
201
+ if (yield condition()) {
202
+ return true;
203
+ }
204
+ yield new Promise((resolve) => setTimeout(resolve, intervalMs));
144
205
  }
145
- await new Promise((resolve) => setTimeout(resolve, intervalMs));
146
- }
147
- return false;
206
+ return false;
207
+ });
148
208
  }
149
209
 
150
210
  // src/types/config.ts
151
- var Environment = /* @__PURE__ */ ((Environment3) => {
152
- Environment3["DEV"] = "DEV";
153
- Environment3["SANDBOX"] = "SANDBOX";
154
- Environment3["BETA"] = "BETA";
155
- Environment3["PROD"] = "PROD";
156
- Environment3["DEVELOPMENT"] = "BETA";
157
- Environment3["PRODUCTION"] = "PROD";
158
- return Environment3;
211
+ var Environment = /* @__PURE__ */ ((Environment2) => {
212
+ Environment2["DEV"] = "DEV";
213
+ Environment2["SANDBOX"] = "SANDBOX";
214
+ Environment2["BETA"] = "BETA";
215
+ Environment2["PROD"] = "PROD";
216
+ Environment2["DEVELOPMENT"] = "BETA";
217
+ Environment2["PRODUCTION"] = "PROD";
218
+ return Environment2;
159
219
  })(Environment || {});
160
220
  var EnabledFlow = /* @__PURE__ */ ((EnabledFlow2) => {
161
221
  EnabledFlow2["BUY"] = "BUY";
@@ -318,7 +378,10 @@ function isPregenIdentifierMatch(a, b, type) {
318
378
  }
319
379
  }
320
380
  function isWalletSupported(types, wallet) {
321
- return types.some((walletType) => !!WalletSchemeTypeMap[wallet?.scheme]?.[walletType]);
381
+ return types.some((walletType) => {
382
+ var _a;
383
+ return !!((_a = WalletSchemeTypeMap[wallet == null ? void 0 : wallet.scheme]) == null ? void 0 : _a[walletType]);
384
+ });
322
385
  }
323
386
  function getSchemes(types) {
324
387
  return Object.keys(WalletSchemeTypeMap).filter((scheme) => {
@@ -341,12 +404,11 @@ function getEquivalentTypes(types) {
341
404
  return getWalletTypes(getSchemes((Array.isArray(types) ? types : [types]).map((t) => WalletType[t])));
342
405
  }
343
406
  function entityToWallet(w) {
344
- return {
345
- ...w,
407
+ return __spreadProps(__spreadValues({}, w), {
346
408
  scheme: w.scheme,
347
409
  type: w.type,
348
410
  pregenIdentifierType: w.pregenIdentifierType
349
- };
411
+ });
350
412
  }
351
413
  function migrateWallet(obj) {
352
414
  if (["USER", "PREGEN"].includes(obj.type)) {
@@ -388,79 +450,87 @@ function decodePrivateKeyPemHex(privateKeyPemHex) {
388
450
  const pem = Buffer.from(privateKeyPemHex, "hex").toString("utf-8");
389
451
  return forge.pki.privateKeyFromPem(pem);
390
452
  }
391
- async function encryptPrivateKey(keyPair, key) {
392
- const privateKeyPemHex = encodePrivateKeyToPemHex(keyPair);
393
- const cryptoKey = await window.crypto.subtle.importKey(
394
- "raw",
395
- Buffer.from(key, "base64"),
396
- {
397
- name: "AES-GCM",
398
- length: 256
399
- },
400
- true,
401
- ["encrypt", "decrypt"]
402
- );
403
- const encodedPlaintext = new TextEncoder().encode(privateKeyPemHex);
404
- const ciphertext = await window.crypto.subtle.encrypt(
405
- { name: "AES-GCM", iv: CONSTANT_IV_AES },
406
- cryptoKey,
407
- encodedPlaintext
408
- );
409
- return Buffer.from(ciphertext).toString("base64");
453
+ function encryptPrivateKey(keyPair, key) {
454
+ return __async(this, null, function* () {
455
+ const privateKeyPemHex = encodePrivateKeyToPemHex(keyPair);
456
+ const cryptoKey = yield window.crypto.subtle.importKey(
457
+ "raw",
458
+ Buffer.from(key, "base64"),
459
+ {
460
+ name: "AES-GCM",
461
+ length: 256
462
+ },
463
+ true,
464
+ ["encrypt", "decrypt"]
465
+ );
466
+ const encodedPlaintext = new TextEncoder().encode(privateKeyPemHex);
467
+ const ciphertext = yield window.crypto.subtle.encrypt(
468
+ { name: "AES-GCM", iv: CONSTANT_IV_AES },
469
+ cryptoKey,
470
+ encodedPlaintext
471
+ );
472
+ return Buffer.from(ciphertext).toString("base64");
473
+ });
410
474
  }
411
- async function decryptPrivateKey(encryptedPrivateKeyPemHex, key) {
412
- const secretKey = await crypto.subtle.importKey(
413
- "raw",
414
- Buffer.from(key, "base64"),
415
- {
416
- name: "AES-GCM",
417
- length: 256
418
- },
419
- true,
420
- ["encrypt", "decrypt"]
421
- );
422
- const cleartext = await crypto.subtle.decrypt(
423
- { name: "AES-GCM", iv: CONSTANT_IV_AES },
424
- secretKey,
425
- Buffer.from(encryptedPrivateKeyPemHex, "base64")
426
- );
427
- const privateKeyPemHex = new TextDecoder().decode(cleartext);
428
- const privateKey = decodePrivateKeyPemHex(privateKeyPemHex);
429
- return privateKey;
475
+ function decryptPrivateKey(encryptedPrivateKeyPemHex, key) {
476
+ return __async(this, null, function* () {
477
+ const secretKey = yield crypto.subtle.importKey(
478
+ "raw",
479
+ Buffer.from(key, "base64"),
480
+ {
481
+ name: "AES-GCM",
482
+ length: 256
483
+ },
484
+ true,
485
+ ["encrypt", "decrypt"]
486
+ );
487
+ const cleartext = yield crypto.subtle.decrypt(
488
+ { name: "AES-GCM", iv: CONSTANT_IV_AES },
489
+ secretKey,
490
+ Buffer.from(encryptedPrivateKeyPemHex, "base64")
491
+ );
492
+ const privateKeyPemHex = new TextDecoder().decode(cleartext);
493
+ const privateKey = decodePrivateKeyPemHex(privateKeyPemHex);
494
+ return privateKey;
495
+ });
430
496
  }
431
- async function getAsymmetricKeyPair(ctx, seedValue) {
432
- const prng = forge.random.createInstance();
433
- if (seedValue) {
434
- prng.seedFileSync = (_n) => seedValue;
435
- prng.seedFile = (_n, cb) => {
436
- cb(null, seedValue);
497
+ function getAsymmetricKeyPair(ctx, seedValue) {
498
+ return __async(this, null, function* () {
499
+ const prng = forge.random.createInstance();
500
+ if (seedValue) {
501
+ prng.seedFileSync = (_n) => seedValue;
502
+ prng.seedFile = (_n, cb) => {
503
+ cb(null, seedValue);
504
+ };
505
+ }
506
+ const options = {
507
+ bits: 2048,
508
+ e: 65537,
509
+ prng
437
510
  };
438
- }
439
- const options = {
440
- bits: 2048,
441
- e: 65537,
442
- prng
443
- };
444
- if (!ctx.disableWorkers) {
445
- options.workLoad = 100;
446
- options.workers = seedValue ? 1 : -1;
447
- const workerRes = await fetch(`${getPortalBaseURL(ctx)}/static/js/prime.worker.min.js`);
448
- const workerBlob = new Blob([await workerRes.text()], { type: "application/javascript" });
449
- options.workerScript = URL.createObjectURL(workerBlob);
450
- }
451
- return new Promise(
452
- (resolve, reject) => rsa.generateKeyPair(options, (err, keypair) => {
453
- if (err) {
454
- reject(err);
455
- }
456
- resolve(keypair);
457
- })
458
- );
511
+ if (!ctx.disableWorkers) {
512
+ options.workLoad = 100;
513
+ options.workers = seedValue ? 1 : -1;
514
+ const workerRes = yield fetch(`${getPortalBaseURL(ctx)}/static/js/prime.worker.min.js`);
515
+ const workerBlob = new Blob([yield workerRes.text()], { type: "application/javascript" });
516
+ options.workerScript = URL.createObjectURL(workerBlob);
517
+ }
518
+ return new Promise(
519
+ (resolve, reject) => rsa.generateKeyPair(options, (err, keypair) => {
520
+ if (err) {
521
+ reject(err);
522
+ }
523
+ resolve(keypair);
524
+ })
525
+ );
526
+ });
459
527
  }
460
- async function getPublicKeyFromSignature(ctx, userHandle) {
461
- const encodedUserHandle = base64url.encode(userHandle);
462
- const keyPair = await getAsymmetricKeyPair(ctx, encodedUserHandle);
463
- return getPublicKeyHex(keyPair);
528
+ function getPublicKeyFromSignature(ctx, userHandle) {
529
+ return __async(this, null, function* () {
530
+ const encodedUserHandle = base64url.encode(userHandle);
531
+ const keyPair = yield getAsymmetricKeyPair(ctx, encodedUserHandle);
532
+ return getPublicKeyHex(keyPair);
533
+ });
464
534
  }
465
535
  function symmetricKeyEncryptMessage(message) {
466
536
  const key = forge.random.getBytesSync(16);
@@ -488,49 +558,57 @@ function decryptWithPrivateKey(privateKey, encryptedMessageHex, encryptedKeyHex)
488
558
  const key = privateKey.decrypt(encryptedKey, RSA_ENCRYPTION_SCHEME);
489
559
  return decipherEncryptedMessageHex(key, encryptedMessageHex);
490
560
  }
491
- async function decryptWithDerivedPrivateKey(ctx, {
492
- seedValue,
493
- encryptedMessageHex,
494
- encryptedKeyHex
495
- }) {
496
- const keyPair = await getAsymmetricKeyPair(ctx, seedValue);
497
- return decryptWithPrivateKey(keyPair.privateKey, encryptedMessageHex, encryptedKeyHex);
561
+ function decryptWithDerivedPrivateKey(_0, _1) {
562
+ return __async(this, arguments, function* (ctx, {
563
+ seedValue,
564
+ encryptedMessageHex,
565
+ encryptedKeyHex
566
+ }) {
567
+ const keyPair = yield getAsymmetricKeyPair(ctx, seedValue);
568
+ return decryptWithPrivateKey(keyPair.privateKey, encryptedMessageHex, encryptedKeyHex);
569
+ });
570
+ }
571
+ function getDerivedPrivateKeyAndDecrypt(ctx, seedValue, encryptedShares) {
572
+ return __async(this, null, function* () {
573
+ return Promise.all(
574
+ encryptedShares.map((share) => __async(this, null, function* () {
575
+ return {
576
+ walletId: share.walletId,
577
+ walletScheme: share.walletScheme,
578
+ partnerId: share.partnerId,
579
+ signer: yield decryptWithDerivedPrivateKey(ctx, {
580
+ seedValue,
581
+ encryptedMessageHex: share.encryptedShare,
582
+ encryptedKeyHex: share.encryptedKey
583
+ }),
584
+ protocolId: share.protocolId
585
+ };
586
+ }))
587
+ );
588
+ });
498
589
  }
499
- async function getDerivedPrivateKeyAndDecrypt(ctx, seedValue, encryptedShares) {
500
- return Promise.all(
501
- encryptedShares.map(async (share) => ({
590
+ function decryptPrivateKeyAndDecryptShare(encryptionKey, encryptedShares, encryptedPrivateKey) {
591
+ return __async(this, null, function* () {
592
+ let privateKey;
593
+ try {
594
+ privateKey = yield decryptPrivateKey(encryptedPrivateKey, encryptionKey);
595
+ } catch (e) {
596
+ }
597
+ try {
598
+ privateKey = yield decryptPrivateKeyWithPassword(encryptedPrivateKey, encryptionKey);
599
+ } catch (e) {
600
+ }
601
+ if (!privateKey) {
602
+ throw new Error("Could not decrypt private key");
603
+ }
604
+ return encryptedShares.map((share) => ({
502
605
  walletId: share.walletId,
503
606
  walletScheme: share.walletScheme,
504
607
  partnerId: share.partnerId,
505
- signer: await decryptWithDerivedPrivateKey(ctx, {
506
- seedValue,
507
- encryptedMessageHex: share.encryptedShare,
508
- encryptedKeyHex: share.encryptedKey
509
- }),
608
+ signer: decryptWithPrivateKey(privateKey, share.encryptedShare, share.encryptedKey),
510
609
  protocolId: share.protocolId
511
- }))
512
- );
513
- }
514
- async function decryptPrivateKeyAndDecryptShare(encryptionKey, encryptedShares, encryptedPrivateKey) {
515
- let privateKey;
516
- try {
517
- privateKey = await decryptPrivateKey(encryptedPrivateKey, encryptionKey);
518
- } catch (e) {
519
- }
520
- try {
521
- privateKey = await decryptPrivateKeyWithPassword(encryptedPrivateKey, encryptionKey);
522
- } catch (e) {
523
- }
524
- if (!privateKey) {
525
- throw new Error("Could not decrypt private key");
526
- }
527
- return encryptedShares.map((share) => ({
528
- walletId: share.walletId,
529
- walletScheme: share.walletScheme,
530
- partnerId: share.partnerId,
531
- signer: decryptWithPrivateKey(privateKey, share.encryptedShare, share.encryptedKey),
532
- protocolId: share.protocolId
533
- }));
610
+ }));
611
+ });
534
612
  }
535
613
  function encryptWithDerivedPublicKey(publicKeyHex, message) {
536
614
  const { key, encryptedMessageHex } = symmetricKeyEncryptMessage(message);
@@ -549,49 +627,55 @@ function hashPasswordWithSalt(password) {
549
627
  function generateSalt(length = 16) {
550
628
  return forge.util.bytesToHex(forge.random.getBytesSync(length));
551
629
  }
552
- async function deriveCryptoKeyFromPassword(hashedPassword) {
553
- const keyBuffer = Buffer.from(hashedPassword, "hex");
554
- return await window.crypto.subtle.importKey(
555
- "raw",
556
- keyBuffer,
557
- {
558
- name: "AES-GCM",
559
- length: 256
560
- },
561
- true,
562
- ["encrypt", "decrypt"]
563
- );
630
+ function deriveCryptoKeyFromPassword(hashedPassword) {
631
+ return __async(this, null, function* () {
632
+ const keyBuffer = Buffer.from(hashedPassword, "hex");
633
+ return yield window.crypto.subtle.importKey(
634
+ "raw",
635
+ keyBuffer,
636
+ {
637
+ name: "AES-GCM",
638
+ length: 256
639
+ },
640
+ true,
641
+ ["encrypt", "decrypt"]
642
+ );
643
+ });
564
644
  }
565
- async function encryptPrivateKeyWithPassword(keyPair, hashedPassword) {
566
- const cryptoKey = await deriveCryptoKeyFromPassword(hashedPassword);
567
- const privateKeyPemHex = encodePrivateKeyToPemHex(keyPair);
568
- const encodedPlaintext = new TextEncoder().encode(privateKeyPemHex);
569
- const ciphertext = await window.crypto.subtle.encrypt(
570
- { name: "AES-GCM", iv: CONSTANT_IV_AES },
571
- cryptoKey,
572
- encodedPlaintext
573
- );
574
- return Buffer.from(ciphertext).toString("base64");
645
+ function encryptPrivateKeyWithPassword(keyPair, hashedPassword) {
646
+ return __async(this, null, function* () {
647
+ const cryptoKey = yield deriveCryptoKeyFromPassword(hashedPassword);
648
+ const privateKeyPemHex = encodePrivateKeyToPemHex(keyPair);
649
+ const encodedPlaintext = new TextEncoder().encode(privateKeyPemHex);
650
+ const ciphertext = yield window.crypto.subtle.encrypt(
651
+ { name: "AES-GCM", iv: CONSTANT_IV_AES },
652
+ cryptoKey,
653
+ encodedPlaintext
654
+ );
655
+ return Buffer.from(ciphertext).toString("base64");
656
+ });
575
657
  }
576
- async function decryptPrivateKeyWithPassword(encryptedPrivateKeyPemHex, hashedPassword) {
577
- const secretKey = await crypto.subtle.importKey(
578
- "raw",
579
- Buffer.from(hashedPassword, "hex"),
580
- {
581
- name: "AES-GCM",
582
- length: 256
583
- },
584
- true,
585
- ["encrypt", "decrypt"]
586
- );
587
- const cleartext = await crypto.subtle.decrypt(
588
- { name: "AES-GCM", iv: CONSTANT_IV_AES },
589
- secretKey,
590
- Buffer.from(encryptedPrivateKeyPemHex, "base64")
591
- );
592
- const privateKeyPemHex = new TextDecoder().decode(cleartext);
593
- const privateKey = decodePrivateKeyPemHex(privateKeyPemHex);
594
- return privateKey;
658
+ function decryptPrivateKeyWithPassword(encryptedPrivateKeyPemHex, hashedPassword) {
659
+ return __async(this, null, function* () {
660
+ const secretKey = yield crypto.subtle.importKey(
661
+ "raw",
662
+ Buffer.from(hashedPassword, "hex"),
663
+ {
664
+ name: "AES-GCM",
665
+ length: 256
666
+ },
667
+ true,
668
+ ["encrypt", "decrypt"]
669
+ );
670
+ const cleartext = yield crypto.subtle.decrypt(
671
+ { name: "AES-GCM", iv: CONSTANT_IV_AES },
672
+ secretKey,
673
+ Buffer.from(encryptedPrivateKeyPemHex, "base64")
674
+ );
675
+ const privateKeyPemHex = new TextDecoder().decode(cleartext);
676
+ const privateKey = decodePrivateKeyPemHex(privateKeyPemHex);
677
+ return privateKey;
678
+ });
595
679
  }
596
680
 
597
681
  // src/external/userManagementClient.ts
@@ -753,125 +837,126 @@ var KeyContainer = class _KeyContainer {
753
837
  };
754
838
 
755
839
  // src/shares/recovery.ts
756
- async function sendRecoveryForShare({
757
- ctx,
758
- userId,
759
- walletId,
760
- otherEncryptedShares = [],
761
- userSigner,
762
- ignoreRedistributingBackupEncryptedShare = false,
763
- emailProps = {},
764
- forceRefresh = false
765
- }) {
766
- if (ignoreRedistributingBackupEncryptedShare) {
767
- await ctx.client.uploadUserKeyShares(
768
- userId,
769
- otherEncryptedShares.map((share) => ({
770
- walletId,
771
- ...share
772
- }))
773
- );
774
- return "";
775
- }
776
- let userBackupKeyShareOptsArr;
777
- let recoveryPrivateKeyContainer;
778
- const { recoveryPublicKeys } = await ctx.client.getRecoveryPublicKeys(userId);
779
- if (forceRefresh || !recoveryPublicKeys?.length) {
780
- recoveryPrivateKeyContainer = new KeyContainer(walletId, "", "");
781
- const { recoveryPublicKeys: recoveryPublicKeys2 } = await ctx.client.persistRecoveryPublicKeys(userId, [
782
- recoveryPrivateKeyContainer.getPublicEncryptionKeyHex()
783
- ]);
784
- const encryptedUserBackup = recoveryPrivateKeyContainer.encryptForSelf(userSigner);
785
- userBackupKeyShareOptsArr = [
786
- {
787
- walletId,
788
- encryptedShare: encryptedUserBackup,
789
- type: KeyShareType.USER,
790
- encryptor: EncryptorType.RECOVERY,
791
- recoveryPublicKeyId: recoveryPublicKeys2[0].id
792
- }
793
- ];
794
- } else {
795
- userBackupKeyShareOptsArr = recoveryPublicKeys.map((recoveryPublicKey) => {
796
- const { id: recoveryPublicKeyId, publicKey } = recoveryPublicKey;
797
- const encryptedUserBackup = KeyContainer.encryptWithPublicKey(Buffer.from(publicKey, "hex"), userSigner);
798
- return {
799
- walletId,
800
- encryptedShare: encryptedUserBackup,
801
- type: KeyShareType.USER,
802
- encryptor: EncryptorType.RECOVERY,
803
- recoveryPublicKeyId
804
- };
805
- });
806
- }
807
- await ctx.client.uploadUserKeyShares(userId, [
808
- ...otherEncryptedShares.map((share) => ({
809
- walletId,
810
- ...share
811
- })),
812
- ...ignoreRedistributingBackupEncryptedShare ? [] : userBackupKeyShareOptsArr
813
- ]);
814
- await ctx.client.distributeParaShare({
840
+ function sendRecoveryForShare(_0) {
841
+ return __async(this, arguments, function* ({
842
+ ctx,
815
843
  userId,
816
844
  walletId,
817
- useDKLS: ctx.useDKLS,
818
- ...emailProps
845
+ otherEncryptedShares = [],
846
+ userSigner,
847
+ ignoreRedistributingBackupEncryptedShare = false,
848
+ emailProps = {},
849
+ forceRefresh = false
850
+ }) {
851
+ if (ignoreRedistributingBackupEncryptedShare) {
852
+ yield ctx.client.uploadUserKeyShares(
853
+ userId,
854
+ otherEncryptedShares.map((share) => __spreadValues({
855
+ walletId
856
+ }, share))
857
+ );
858
+ return "";
859
+ }
860
+ let userBackupKeyShareOptsArr;
861
+ let recoveryPrivateKeyContainer;
862
+ const { recoveryPublicKeys } = yield ctx.client.getRecoveryPublicKeys(userId);
863
+ if (forceRefresh || !(recoveryPublicKeys == null ? void 0 : recoveryPublicKeys.length)) {
864
+ recoveryPrivateKeyContainer = new KeyContainer(walletId, "", "");
865
+ const { recoveryPublicKeys: recoveryPublicKeys2 } = yield ctx.client.persistRecoveryPublicKeys(userId, [
866
+ recoveryPrivateKeyContainer.getPublicEncryptionKeyHex()
867
+ ]);
868
+ const encryptedUserBackup = recoveryPrivateKeyContainer.encryptForSelf(userSigner);
869
+ userBackupKeyShareOptsArr = [
870
+ {
871
+ walletId,
872
+ encryptedShare: encryptedUserBackup,
873
+ type: KeyShareType.USER,
874
+ encryptor: EncryptorType.RECOVERY,
875
+ recoveryPublicKeyId: recoveryPublicKeys2[0].id
876
+ }
877
+ ];
878
+ } else {
879
+ userBackupKeyShareOptsArr = recoveryPublicKeys.map((recoveryPublicKey) => {
880
+ const { id: recoveryPublicKeyId, publicKey } = recoveryPublicKey;
881
+ const encryptedUserBackup = KeyContainer.encryptWithPublicKey(Buffer.from(publicKey, "hex"), userSigner);
882
+ return {
883
+ walletId,
884
+ encryptedShare: encryptedUserBackup,
885
+ type: KeyShareType.USER,
886
+ encryptor: EncryptorType.RECOVERY,
887
+ recoveryPublicKeyId
888
+ };
889
+ });
890
+ }
891
+ yield ctx.client.uploadUserKeyShares(userId, [
892
+ ...otherEncryptedShares.map((share) => __spreadValues({
893
+ walletId
894
+ }, share)),
895
+ ...ignoreRedistributingBackupEncryptedShare ? [] : userBackupKeyShareOptsArr
896
+ ]);
897
+ yield ctx.client.distributeParaShare(__spreadValues({
898
+ userId,
899
+ walletId,
900
+ useDKLS: ctx.useDKLS
901
+ }, emailProps));
902
+ return recoveryPrivateKeyContainer ? JSON.stringify(recoveryPrivateKeyContainer) : "";
819
903
  });
820
- return recoveryPrivateKeyContainer ? JSON.stringify(recoveryPrivateKeyContainer) : "";
821
904
  }
822
905
 
823
906
  // src/shares/shareDistribution.ts
824
- async function distributeNewShare({
825
- ctx,
826
- userId,
827
- walletId,
828
- userShare,
829
- ignoreRedistributingBackupEncryptedShare = false,
830
- emailProps = {},
831
- partnerId,
832
- protocolId
833
- }) {
834
- const publicKeysRes = await ctx.client.getSessionPublicKeys(userId);
835
- const biometricEncryptedShares = publicKeysRes.data.keys.map((key) => {
836
- if (!key.publicKey) {
837
- return;
838
- }
839
- const { encryptedMessageHex, encryptedKeyHex } = encryptWithDerivedPublicKey(key.sigDerivedPublicKey, userShare);
840
- return {
841
- encryptedShare: encryptedMessageHex,
842
- encryptedKey: encryptedKeyHex,
843
- type: KeyShareType2.USER,
844
- encryptor: EncryptorType2.BIOMETRICS,
845
- biometricPublicKey: key.sigDerivedPublicKey,
846
- partnerId,
847
- protocolId
848
- };
849
- }).filter(Boolean);
850
- const passwords = await ctx.client.getPasswords({ userId });
851
- const passwordEncryptedShares = passwords.map((password) => {
852
- if (password.status === "PENDING") {
853
- return;
854
- }
855
- const { encryptedMessageHex, encryptedKeyHex } = encryptWithDerivedPublicKey(password.sigDerivedPublicKey, userShare);
856
- return {
857
- encryptedShare: encryptedMessageHex,
858
- encryptedKey: encryptedKeyHex,
859
- type: KeyShareType2.USER,
860
- encryptor: EncryptorType2.PASSWORD,
861
- passwordId: password.id,
862
- partnerId,
863
- protocolId
864
- };
865
- }).filter(Boolean);
866
- const allEncryptedShares = [...biometricEncryptedShares, ...passwordEncryptedShares];
867
- return await sendRecoveryForShare({
907
+ function distributeNewShare(_0) {
908
+ return __async(this, arguments, function* ({
868
909
  ctx,
869
910
  userId,
870
911
  walletId,
871
- otherEncryptedShares: allEncryptedShares,
872
- userSigner: userShare,
873
- ignoreRedistributingBackupEncryptedShare,
874
- emailProps
912
+ userShare,
913
+ ignoreRedistributingBackupEncryptedShare = false,
914
+ emailProps = {},
915
+ partnerId,
916
+ protocolId
917
+ }) {
918
+ const publicKeysRes = yield ctx.client.getSessionPublicKeys(userId);
919
+ const biometricEncryptedShares = publicKeysRes.data.keys.map((key) => {
920
+ if (!key.publicKey) {
921
+ return;
922
+ }
923
+ const { encryptedMessageHex, encryptedKeyHex } = encryptWithDerivedPublicKey(key.sigDerivedPublicKey, userShare);
924
+ return {
925
+ encryptedShare: encryptedMessageHex,
926
+ encryptedKey: encryptedKeyHex,
927
+ type: KeyShareType2.USER,
928
+ encryptor: EncryptorType2.BIOMETRICS,
929
+ biometricPublicKey: key.sigDerivedPublicKey,
930
+ partnerId,
931
+ protocolId
932
+ };
933
+ }).filter(Boolean);
934
+ const passwords = yield ctx.client.getPasswords({ userId });
935
+ const passwordEncryptedShares = passwords.map((password) => {
936
+ if (password.status === "PENDING") {
937
+ return;
938
+ }
939
+ const { encryptedMessageHex, encryptedKeyHex } = encryptWithDerivedPublicKey(password.sigDerivedPublicKey, userShare);
940
+ return {
941
+ encryptedShare: encryptedMessageHex,
942
+ encryptedKey: encryptedKeyHex,
943
+ type: KeyShareType2.USER,
944
+ encryptor: EncryptorType2.PASSWORD,
945
+ passwordId: password.id,
946
+ partnerId,
947
+ protocolId
948
+ };
949
+ }).filter(Boolean);
950
+ const allEncryptedShares = [...biometricEncryptedShares, ...passwordEncryptedShares];
951
+ return yield sendRecoveryForShare({
952
+ ctx,
953
+ userId,
954
+ walletId,
955
+ otherEncryptedShares: allEncryptedShares,
956
+ userSigner: userShare,
957
+ ignoreRedistributingBackupEncryptedShare,
958
+ emailProps
959
+ });
875
960
  });
876
961
  }
877
962
 
@@ -880,32 +965,36 @@ import { Encrypt as ECIESEncrypt2, Decrypt as ECIESDecrypt2 } from "@celo/utils/
880
965
  import { Buffer as Buffer2 } from "buffer";
881
966
  import * as eutil2 from "ethereumjs-util";
882
967
  import { randomBytes } from "crypto";
883
- async function upload(message, userManagementClient) {
884
- let secret;
885
- let publicKeyUint8Array;
886
- while (true) {
887
- try {
888
- secret = randomBytes(32).toString("hex");
889
- publicKeyUint8Array = eutil2.privateToPublic(Buffer2.from(secret, "hex"));
890
- break;
891
- } catch (e) {
892
- continue;
968
+ function upload(message, userManagementClient) {
969
+ return __async(this, null, function* () {
970
+ let secret;
971
+ let publicKeyUint8Array;
972
+ while (true) {
973
+ try {
974
+ secret = randomBytes(32).toString("hex");
975
+ publicKeyUint8Array = eutil2.privateToPublic(Buffer2.from(secret, "hex"));
976
+ break;
977
+ } catch (e) {
978
+ continue;
979
+ }
893
980
  }
894
- }
895
- const pubkey = Buffer2.from(publicKeyUint8Array);
896
- const data = ECIESEncrypt2(pubkey, Buffer2.from(message, "ucs2")).toString("base64");
897
- const {
898
- data: { id }
899
- } = await userManagementClient.tempTrasmissionInit(data);
900
- return encodeURIComponent(id + "|" + secret);
981
+ const pubkey = Buffer2.from(publicKeyUint8Array);
982
+ const data = ECIESEncrypt2(pubkey, Buffer2.from(message, "ucs2")).toString("base64");
983
+ const {
984
+ data: { id }
985
+ } = yield userManagementClient.tempTrasmissionInit(data);
986
+ return encodeURIComponent(id + "|" + secret);
987
+ });
901
988
  }
902
- async function retrieve(uriEncodedMessage, userManagementClient) {
903
- const [id, secret] = decodeURIComponent(uriEncodedMessage).split("|");
904
- const response = await userManagementClient.tempTrasmission(id);
905
- const data = response.data.message;
906
- const buf = Buffer2.from(data, "base64");
907
- const res = Buffer2.from(ECIESDecrypt2(Buffer2.from(secret, "hex"), buf).buffer).toString("ucs2");
908
- return res;
989
+ function retrieve(uriEncodedMessage, userManagementClient) {
990
+ return __async(this, null, function* () {
991
+ const [id, secret] = decodeURIComponent(uriEncodedMessage).split("|");
992
+ const response = yield userManagementClient.tempTrasmission(id);
993
+ const data = response.data.message;
994
+ const buf = Buffer2.from(data, "base64");
995
+ const res = Buffer2.from(ECIESDecrypt2(Buffer2.from(secret, "hex"), buf).buffer).toString("ucs2");
996
+ return res;
997
+ });
909
998
  }
910
999
 
911
1000
  // src/errors.ts
@@ -932,7 +1021,7 @@ var TransactionReviewTimeout = class extends Error {
932
1021
  };
933
1022
 
934
1023
  // src/constants.ts
935
- var PARA_CORE_VERSION = '1.5.0';
1024
+ var PARA_CORE_VERSION = '1.6.0';
936
1025
  var PREFIX = "@CAPSULE/";
937
1026
  var LOCAL_STORAGE_EMAIL = `${PREFIX}e-mail`;
938
1027
  var LOCAL_STORAGE_PHONE = `${PREFIX}phone`;
@@ -1003,7 +1092,8 @@ if (typeof global !== "undefined") {
1003
1092
  self.global = self.global || self;
1004
1093
  }
1005
1094
  var { pki, jsbn } = forge3;
1006
- var ParaCore = class _ParaCore {
1095
+ var _supportedWalletTypes, _supportedWalletTypesOpt;
1096
+ var _ParaCore = class _ParaCore {
1007
1097
  /**
1008
1098
  * Constructs a new `ParaCore` instance.
1009
1099
  * @param env - `Environment` to use.
@@ -1020,8 +1110,8 @@ var ParaCore = class _ParaCore {
1020
1110
  * The IDs of the currently active wallets, for each supported wallet type. Any signer integrations will default to the first viable wallet ID in this dictionary.
1021
1111
  */
1022
1112
  this.currentWalletIds = {};
1023
- this.#supportedWalletTypes = void 0;
1024
- this.#supportedWalletTypesOpt = void 0;
1113
+ __privateAdd(this, _supportedWalletTypes);
1114
+ __privateAdd(this, _supportedWalletTypesOpt);
1025
1115
  this.localStorageGetItem = (key) => {
1026
1116
  return this.platformUtils.localStorage.get(key);
1027
1117
  };
@@ -1044,14 +1134,14 @@ var ParaCore = class _ParaCore {
1044
1134
  * Remove all local storage and prefixed session storage.
1045
1135
  * @param {'local' | 'session' | 'secure' | 'all'} type - Type of storage to clear. Defaults to 'all'.
1046
1136
  */
1047
- this.clearStorage = async (type = "all") => {
1137
+ this.clearStorage = (type = "all") => __async(this, null, function* () {
1048
1138
  const isAll = type === "all";
1049
1139
  (isAll || type === "local") && this.platformUtils.localStorage.clear(PREFIX);
1050
1140
  (isAll || type === "session") && this.platformUtils.sessionStorage.clear(PREFIX);
1051
1141
  if ((isAll || type === "secure") && this.platformUtils.secureStorage) {
1052
1142
  this.platformUtils.secureStorage.clear(PREFIX);
1053
1143
  }
1054
- };
1144
+ });
1055
1145
  this.initializeFromStorage = () => {
1056
1146
  this.updateEmailFromStorage();
1057
1147
  this.updateCountryCodeFromStorage();
@@ -1079,18 +1169,16 @@ var ParaCore = class _ParaCore {
1079
1169
  this.updateEmailFromStorage = () => {
1080
1170
  this.email = this.localStorageGetItem(LOCAL_STORAGE_EMAIL) || void 0;
1081
1171
  };
1082
- this.updateWalletsFromStorage = async () => {
1083
- const _currentWalletIds = this.localStorageGetItem(LOCAL_STORAGE_CURRENT_WALLET_IDS) ?? void 0;
1172
+ this.updateWalletsFromStorage = () => __async(this, null, function* () {
1173
+ var _a;
1174
+ const _currentWalletIds = (_a = this.localStorageGetItem(LOCAL_STORAGE_CURRENT_WALLET_IDS)) != null ? _a : void 0;
1084
1175
  const currentWalletIds = [void 0, null, "undefined"].includes(_currentWalletIds) ? {} : (() => {
1085
1176
  const fromJson = JSON.parse(_currentWalletIds);
1086
1177
  return Array.isArray(fromJson) ? Object.keys(WalletType2).reduce((acc, type) => {
1087
1178
  const wallet = Object.values(this.wallets).find(
1088
1179
  (w) => fromJson.includes(w.id) && WalletSchemeTypeMap[w.scheme][type]
1089
1180
  );
1090
- return {
1091
- ...acc,
1092
- ...wallet && !acc[type] ? { [type]: [wallet.id] } : {}
1093
- };
1181
+ return __spreadValues(__spreadValues({}, acc), wallet && !acc[type] ? { [type]: [wallet.id] } : {});
1094
1182
  }, {}) : fromJson;
1095
1183
  })();
1096
1184
  this.setCurrentWalletIds(currentWalletIds);
@@ -1098,34 +1186,25 @@ var ParaCore = class _ParaCore {
1098
1186
  const _wallets = JSON.parse(stringWallets || "{}");
1099
1187
  const stringEd25519Wallets = this.platformUtils.secureStorage ? this.platformUtils.secureStorage.get(LOCAL_STORAGE_ED25519_WALLETS) : this.localStorageGetItem(LOCAL_STORAGE_ED25519_WALLETS);
1100
1188
  const _ed25519Wallets = JSON.parse(stringEd25519Wallets || "{}");
1101
- const wallets = {
1102
- ...Object.keys(_wallets).reduce((res, key) => {
1103
- return {
1104
- ...res,
1105
- [key]: migrateWallet(_wallets[key])
1106
- };
1107
- }, {}),
1108
- ...Object.keys(_ed25519Wallets).reduce((res, key) => {
1109
- return {
1110
- ...res,
1111
- ...!res[key] ? { [key]: migrateWallet(_ed25519Wallets[key]) } : {}
1112
- };
1113
- }, {})
1114
- };
1189
+ const wallets = __spreadValues(__spreadValues({}, Object.keys(_wallets).reduce((res, key) => {
1190
+ return __spreadProps(__spreadValues({}, res), {
1191
+ [key]: migrateWallet(_wallets[key])
1192
+ });
1193
+ }, {})), Object.keys(_ed25519Wallets).reduce((res, key) => {
1194
+ return __spreadValues(__spreadValues({}, res), !res[key] ? { [key]: migrateWallet(_ed25519Wallets[key]) } : {});
1195
+ }, {}));
1115
1196
  this.setWallets(wallets);
1116
- };
1197
+ });
1117
1198
  this.updateWalletIdsFromStorage = () => {
1118
- const _currentWalletIds = this.localStorageGetItem(LOCAL_STORAGE_CURRENT_WALLET_IDS) ?? void 0;
1199
+ var _a;
1200
+ const _currentWalletIds = (_a = this.localStorageGetItem(LOCAL_STORAGE_CURRENT_WALLET_IDS)) != null ? _a : void 0;
1119
1201
  const currentWalletIds = [void 0, null, "undefined"].includes(_currentWalletIds) ? {} : (() => {
1120
1202
  const fromJson = JSON.parse(_currentWalletIds);
1121
1203
  return Array.isArray(fromJson) ? Object.keys(WalletType2).reduce((acc, type) => {
1122
1204
  const wallet = Object.values(this.wallets).find(
1123
1205
  (w) => fromJson.includes(w.id) && WalletSchemeTypeMap[w.scheme][type]
1124
1206
  );
1125
- return {
1126
- ...acc,
1127
- ...wallet && !acc[type] ? { [type]: [wallet.id] } : {}
1128
- };
1207
+ return __spreadValues(__spreadValues({}, acc), wallet && !acc[type] ? { [type]: [wallet.id] } : {});
1129
1208
  }, {}) : fromJson;
1130
1209
  })();
1131
1210
  this.setCurrentWalletIds(currentWalletIds);
@@ -1157,6 +1236,11 @@ var ParaCore = class _ParaCore {
1157
1236
  **/
1158
1237
  this.createWalletPerMissingType = this.createWalletPerType;
1159
1238
  if (!opts) opts = {};
1239
+ let isE2E = false;
1240
+ if (env === "E2E") {
1241
+ isE2E = true;
1242
+ env = "SANDBOX" /* SANDBOX */;
1243
+ }
1160
1244
  this.emailPrimaryColor = opts.emailPrimaryColor;
1161
1245
  this.emailTheme = opts.emailTheme;
1162
1246
  this.homepageUrl = opts.homepageUrl;
@@ -1208,13 +1292,14 @@ var ParaCore = class _ParaCore {
1208
1292
  useDKLS: opts.useDKLSForCreation || !opts.offloadMPCComputationURL,
1209
1293
  disableWebSockets: !!opts.disableWebSockets,
1210
1294
  wasmOverride: opts.wasmOverride,
1211
- cosmosPrefix: this.cosmosPrefix
1295
+ cosmosPrefix: this.cosmosPrefix,
1296
+ isE2E
1212
1297
  };
1213
1298
  if (opts.offloadMPCComputationURL) {
1214
1299
  this.ctx.mpcComputationClient = initClient2(opts.offloadMPCComputationURL, opts.disableWorkers);
1215
1300
  }
1216
1301
  try {
1217
- this.#supportedWalletTypes = opts.supportedWalletTypes ? (() => {
1302
+ __privateSet(this, _supportedWalletTypes, opts.supportedWalletTypes ? (() => {
1218
1303
  if (Object.values(opts.supportedWalletTypes).every(
1219
1304
  (config) => !!config && typeof config === "object" && config.optional
1220
1305
  )) {
@@ -1223,19 +1308,20 @@ var ParaCore = class _ParaCore {
1223
1308
  if (!Object.keys(opts.supportedWalletTypes).every((type) => Object.values(WalletType2).includes(type))) {
1224
1309
  throw new Error("unsupported wallet type");
1225
1310
  }
1226
- this.#supportedWalletTypesOpt = opts.supportedWalletTypes;
1311
+ __privateSet(this, _supportedWalletTypesOpt, opts.supportedWalletTypes);
1227
1312
  return Object.entries(opts.supportedWalletTypes).reduce((acc, [key, value]) => {
1313
+ var _a;
1228
1314
  if (!value) {
1229
1315
  return acc;
1230
1316
  }
1231
1317
  if (key === WalletType2.COSMOS && typeof value === "object" && !!value.prefix) {
1232
1318
  this.cosmosPrefix = value.prefix;
1233
1319
  }
1234
- return [...acc, { type: key, optional: value === true ? false : value.optional ?? false }];
1320
+ return [...acc, { type: key, optional: value === true ? false : (_a = value.optional) != null ? _a : false }];
1235
1321
  }, []);
1236
- })() : void 0;
1322
+ })() : void 0);
1237
1323
  } catch (e) {
1238
- this.#supportedWalletTypes = void 0;
1324
+ __privateSet(this, _supportedWalletTypes, void 0);
1239
1325
  }
1240
1326
  if (!this.platformUtils.isSyncStorage || opts.useStorageOverrides) {
1241
1327
  return;
@@ -1243,9 +1329,6 @@ var ParaCore = class _ParaCore {
1243
1329
  this.initializeFromStorage();
1244
1330
  setupListeners.bind(this)();
1245
1331
  }
1246
- static {
1247
- this.version = PARA_CORE_VERSION;
1248
- }
1249
1332
  get isEmail() {
1250
1333
  return !!this.email && !this.phone && !this.countryCode && !this.farcasterUsername && !this.telegramUserId;
1251
1334
  }
@@ -1260,9 +1343,10 @@ var ParaCore = class _ParaCore {
1260
1343
  }
1261
1344
  get currentWalletIdsArray() {
1262
1345
  return this.supportedWalletTypes.reduce((acc, { type }) => {
1346
+ var _a;
1263
1347
  return [
1264
1348
  ...acc,
1265
- ...(this.currentWalletIds[type] ?? []).map((id) => {
1349
+ ...((_a = this.currentWalletIds[type]) != null ? _a : []).map((id) => {
1266
1350
  return [id, type];
1267
1351
  })
1268
1352
  ];
@@ -1275,19 +1359,17 @@ var ParaCore = class _ParaCore {
1275
1359
  * A map of pre-generated wallet identifiers that can be claimed in the current instance.
1276
1360
  */
1277
1361
  get pregenIds() {
1278
- return {
1279
- ...Object.values(this.wallets).filter((wallet) => !this.userId || this.isPregenWalletClaimable(wallet)).reduce((acc, wallet) => {
1280
- if ((acc[wallet.pregenIdentifierType] ?? []).includes(wallet.pregenIdentifier)) {
1281
- return acc;
1282
- }
1283
- return {
1284
- ...acc,
1285
- [wallet.pregenIdentifierType]: [
1286
- .../* @__PURE__ */ new Set([...acc[wallet.pregenIdentifierType] ?? [], wallet.pregenIdentifier])
1287
- ]
1288
- };
1289
- }, {})
1290
- };
1362
+ return __spreadValues({}, Object.values(this.wallets).filter((wallet) => !this.userId || this.isPregenWalletClaimable(wallet)).reduce((acc, wallet) => {
1363
+ var _a, _b;
1364
+ if (((_a = acc[wallet.pregenIdentifierType]) != null ? _a : []).includes(wallet.pregenIdentifier)) {
1365
+ return acc;
1366
+ }
1367
+ return __spreadProps(__spreadValues({}, acc), {
1368
+ [wallet.pregenIdentifierType]: [
1369
+ .../* @__PURE__ */ new Set([...(_b = acc[wallet.pregenIdentifierType]) != null ? _b : [], wallet.pregenIdentifier])
1370
+ ]
1371
+ });
1372
+ }, {}));
1291
1373
  }
1292
1374
  /**
1293
1375
  * Whether the instance has multiple wallets connected.
@@ -1295,14 +1377,13 @@ var ParaCore = class _ParaCore {
1295
1377
  get isMultiWallet() {
1296
1378
  return this.currentWalletIdsArray.length > 1;
1297
1379
  }
1298
- #supportedWalletTypes;
1299
- #supportedWalletTypesOpt;
1300
1380
  get supportedWalletTypes() {
1301
- return this.#supportedWalletTypes ?? [];
1381
+ var _a;
1382
+ return (_a = __privateGet(this, _supportedWalletTypes)) != null ? _a : [];
1302
1383
  }
1303
1384
  get isWalletTypeEnabled() {
1304
1385
  return this.supportedWalletTypes.reduce((acc, { type }) => {
1305
- return { ...acc, [type]: true };
1386
+ return __spreadProps(__spreadValues({}, acc), { [type]: true });
1306
1387
  }, {});
1307
1388
  }
1308
1389
  convertBigInt(bigInt) {
@@ -1331,12 +1412,14 @@ var ParaCore = class _ParaCore {
1331
1412
  };
1332
1413
  }
1333
1414
  isPortal(envOverride) {
1415
+ var _a;
1334
1416
  if (typeof window === "undefined") return false;
1335
- return !!window.location?.host && getPortalBaseURL(envOverride ? { env: envOverride } : this.ctx).includes(window.location.host);
1417
+ return !!((_a = window.location) == null ? void 0 : _a.host) && getPortalBaseURL(envOverride ? { env: envOverride } : this.ctx).includes(window.location.host);
1336
1418
  }
1337
1419
  isParaConnect() {
1420
+ var _a;
1338
1421
  if (typeof window === "undefined") return false;
1339
- return !!window.location?.host && getParaConnectBaseUrl(this.ctx).includes(window.location.host);
1422
+ return !!((_a = window.location) == null ? void 0 : _a.host) && getParaConnectBaseUrl(this.ctx).includes(window.location.host);
1340
1423
  }
1341
1424
  requireApiKey() {
1342
1425
  if (!this.ctx.apiKey) {
@@ -1347,19 +1430,20 @@ var ParaCore = class _ParaCore {
1347
1430
  }
1348
1431
  }
1349
1432
  isWalletSupported(wallet) {
1350
- return !this.#supportedWalletTypes || isWalletSupported(this.supportedWalletTypes?.map(({ type }) => type) ?? [], wallet);
1433
+ var _a, _b;
1434
+ return !__privateGet(this, _supportedWalletTypes) || isWalletSupported((_b = (_a = this.supportedWalletTypes) == null ? void 0 : _a.map(({ type }) => type)) != null ? _b : [], wallet);
1351
1435
  }
1352
1436
  isWalletOwned(wallet) {
1353
- return this.isWalletSupported(wallet) && !wallet?.pregenIdentifier && !wallet?.pregenIdentifierType && !!this.userId && wallet?.userId === this.userId;
1437
+ return this.isWalletSupported(wallet) && !(wallet == null ? void 0 : wallet.pregenIdentifier) && !(wallet == null ? void 0 : wallet.pregenIdentifierType) && !!this.userId && (wallet == null ? void 0 : wallet.userId) === this.userId;
1354
1438
  }
1355
1439
  isPregenWalletUnclaimed(wallet) {
1356
- return this.isWalletSupported(wallet) && (!wallet?.userId || wallet?.isPregen && !!wallet?.pregenIdentifier && !!wallet?.pregenIdentifierType);
1440
+ return this.isWalletSupported(wallet) && (!(wallet == null ? void 0 : wallet.userId) || (wallet == null ? void 0 : wallet.isPregen) && !!(wallet == null ? void 0 : wallet.pregenIdentifier) && !!(wallet == null ? void 0 : wallet.pregenIdentifierType));
1357
1441
  }
1358
1442
  isPregenWalletClaimable(wallet) {
1359
- return this.isWalletSupported(wallet) && this.isPregenWalletUnclaimed(wallet) && (!["EMAIL", "PHONE", "TELEGRAM"].includes(wallet?.pregenIdentifierType) || isPregenIdentifierMatch(
1360
- wallet?.pregenIdentifierType === "EMAIL" ? this.email : wallet?.pregenIdentifierType === "TELEGRAM" ? this.telegramUserId : this.getPhoneNumber(),
1361
- wallet?.pregenIdentifier,
1362
- wallet?.pregenIdentifierType
1443
+ return this.isWalletSupported(wallet) && this.isPregenWalletUnclaimed(wallet) && (!["EMAIL", "PHONE", "TELEGRAM"].includes(wallet == null ? void 0 : wallet.pregenIdentifierType) || isPregenIdentifierMatch(
1444
+ (wallet == null ? void 0 : wallet.pregenIdentifierType) === "EMAIL" ? this.email : (wallet == null ? void 0 : wallet.pregenIdentifierType) === "TELEGRAM" ? this.telegramUserId : this.getPhoneNumber(),
1445
+ wallet == null ? void 0 : wallet.pregenIdentifier,
1446
+ wallet == null ? void 0 : wallet.pregenIdentifierType
1363
1447
  ));
1364
1448
  }
1365
1449
  isWalletUsable(walletId, { type: types, scheme: schemes, forbidPregen = false } = {}, throwError = false) {
@@ -1370,15 +1454,18 @@ var ParaCore = class _ParaCore {
1370
1454
  const wallet = this.wallets[walletId];
1371
1455
  const [isUnclaimed, isOwned] = [this.isPregenWalletUnclaimed(wallet), this.isWalletOwned(wallet)];
1372
1456
  if (forbidPregen && isUnclaimed) {
1373
- error = `pre-generated wallet with id ${wallet?.id} cannot be selected`;
1457
+ error = `pre-generated wallet with id ${wallet == null ? void 0 : wallet.id} cannot be selected`;
1374
1458
  } else if (!isOwned && !isUnclaimed) {
1375
- error = `wallet with id ${wallet?.id} is not owned by the current user`;
1459
+ error = `wallet with id ${wallet == null ? void 0 : wallet.id} is not owned by the current user`;
1376
1460
  } else if (!this.isWalletSupported(wallet)) {
1377
- error = `wallet with id ${wallet?.id} and type ${wallet?.type} is not supported, supported types are: ${this.supportedWalletTypes.map(({ type }) => type).join(", ")}`;
1378
- } else if (types && (!getEquivalentTypes(types).includes(wallet?.type) || isOwned && !types.some((type) => this.currentWalletIds?.[type]?.includes(walletId)))) {
1379
- error = `wallet with id ${wallet?.id} and type ${wallet?.type} cannot be selected`;
1380
- } else if (schemes && !schemes.includes(wallet?.scheme)) {
1381
- error = `wallet with id ${wallet?.id} and scheme ${wallet?.scheme} cannot be selected`;
1461
+ error = `wallet with id ${wallet == null ? void 0 : wallet.id} and type ${wallet == null ? void 0 : wallet.type} is not supported, supported types are: ${this.supportedWalletTypes.map(({ type }) => type).join(", ")}`;
1462
+ } else if (types && (!getEquivalentTypes(types).includes(wallet == null ? void 0 : wallet.type) || isOwned && !types.some((type) => {
1463
+ var _a, _b;
1464
+ return (_b = (_a = this.currentWalletIds) == null ? void 0 : _a[type]) == null ? void 0 : _b.includes(walletId);
1465
+ }))) {
1466
+ error = `wallet with id ${wallet == null ? void 0 : wallet.id} and type ${wallet == null ? void 0 : wallet.type} cannot be selected`;
1467
+ } else if (schemes && !schemes.includes(wallet == null ? void 0 : wallet.scheme)) {
1468
+ error = `wallet with id ${wallet == null ? void 0 : wallet.id} and scheme ${wallet == null ? void 0 : wallet.scheme} cannot be selected`;
1382
1469
  }
1383
1470
  }
1384
1471
  if (error) {
@@ -1398,6 +1485,7 @@ var ParaCore = class _ParaCore {
1398
1485
  * @returns the formatted address
1399
1486
  */
1400
1487
  getDisplayAddress(walletId, options = {}) {
1488
+ var _a;
1401
1489
  if (this.externalWallets[walletId]) {
1402
1490
  const wallet2 = this.externalWallets[walletId];
1403
1491
  return options.truncate ? truncateAddress(wallet2.address, wallet2.type, { prefix: this.cosmosPrefix }) : wallet2.address;
@@ -1409,7 +1497,7 @@ var ParaCore = class _ParaCore {
1409
1497
  let str;
1410
1498
  switch (wallet.type) {
1411
1499
  case WalletType2.COSMOS:
1412
- str = getCosmosAddress(wallet.publicKey, this.cosmosPrefix ?? "cosmos");
1500
+ str = getCosmosAddress(wallet.publicKey, (_a = this.cosmosPrefix) != null ? _a : "cosmos");
1413
1501
  break;
1414
1502
  default:
1415
1503
  str = wallet.address;
@@ -1435,89 +1523,87 @@ var ParaCore = class _ParaCore {
1435
1523
  return this.wallets;
1436
1524
  }
1437
1525
  getAddress(walletId) {
1438
- return walletId ? this.wallets[walletId]?.address : Object.values(this.wallets)?.[0]?.address;
1439
- }
1440
- async constructPortalUrl(type, opts = {}) {
1441
- const base = type === "onRamp" ? getPortalBaseURL(this.ctx) : await this.getPortalURL(opts.partnerId);
1442
- let path;
1443
- switch (type) {
1444
- case "createPassword": {
1445
- path = `/web/users/${this.userId}/passwords/${opts.pathId}`;
1446
- break;
1447
- }
1448
- case "createAuth": {
1449
- path = `/web/users/${this.userId}/biometrics/${opts.pathId}`;
1450
- break;
1451
- }
1452
- case "loginPassword": {
1453
- path = "/web/passwords/login";
1454
- break;
1455
- }
1456
- case "loginAuth": {
1457
- path = "/web/biometrics/login";
1458
- break;
1459
- }
1460
- case "txReview": {
1461
- path = `/web/users/${this.userId}/transaction-review/${opts.pathId}`;
1462
- break;
1463
- }
1464
- case "onRamp": {
1465
- path = `/web/users/${this.userId}/on-ramp-transaction/${opts.pathId}`;
1466
- break;
1467
- }
1468
- default: {
1469
- throw new Error(`invalid URL type ${type}`);
1526
+ var _a, _b, _c;
1527
+ return walletId ? (_a = this.wallets[walletId]) == null ? void 0 : _a.address : (_c = (_b = Object.values(this.wallets)) == null ? void 0 : _b[0]) == null ? void 0 : _c.address;
1528
+ }
1529
+ constructPortalUrl(_0) {
1530
+ return __async(this, arguments, function* (type, opts = {}) {
1531
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
1532
+ const base = type === "onRamp" ? getPortalBaseURL(this.ctx) : yield this.getPortalURL(opts.partnerId);
1533
+ let path;
1534
+ switch (type) {
1535
+ case "createPassword": {
1536
+ path = `/web/users/${this.userId}/passwords/${opts.pathId}`;
1537
+ break;
1538
+ }
1539
+ case "createAuth": {
1540
+ path = `/web/users/${this.userId}/biometrics/${opts.pathId}`;
1541
+ break;
1542
+ }
1543
+ case "loginPassword": {
1544
+ path = "/web/passwords/login";
1545
+ break;
1546
+ }
1547
+ case "loginAuth": {
1548
+ path = "/web/biometrics/login";
1549
+ break;
1550
+ }
1551
+ case "txReview": {
1552
+ path = `/web/users/${this.userId}/transaction-review/${opts.pathId}`;
1553
+ break;
1554
+ }
1555
+ case "onRamp": {
1556
+ path = `/web/users/${this.userId}/on-ramp-transaction/${opts.pathId}`;
1557
+ break;
1558
+ }
1559
+ default: {
1560
+ throw new Error(`invalid URL type ${type}`);
1561
+ }
1470
1562
  }
1471
- }
1472
- const [isCreate, isLogin, isOnRamp] = [
1473
- ["createAuth", "createPassword"].includes(type),
1474
- ["loginAuth", "loginPassword"].includes(type),
1475
- type === "onRamp"
1476
- ];
1477
- const partner = opts.partnerId ? (await this.ctx.client.getPartner(opts.partnerId)).data?.partner : void 0;
1478
- const params = {
1479
- apiKey: this.ctx.apiKey,
1480
- partnerId: opts.partnerId,
1481
- portalFont: opts.theme?.font || partner?.font || this.portalTheme?.font,
1482
- portalBorderRadius: opts.theme?.borderRadius || this.portalTheme?.borderRadius,
1483
- portalThemeMode: opts.theme?.mode || partner?.themeMode || this.portalTheme?.mode,
1484
- portalAccentColor: opts.theme?.accentColor || partner?.accentColor || this.portalTheme?.accentColor,
1485
- portalForegroundColor: opts.theme?.foregroundColor || partner?.foregroundColor || this.portalTheme?.foregroundColor,
1486
- portalBackgroundColor: opts.theme?.backgroundColor || partner?.backgroundColor || this.portalBackgroundColor || this.portalTheme?.backgroundColor,
1487
- portalPrimaryButtonColor: this.portalPrimaryButtonColor,
1488
- portalTextColor: this.portalTextColor,
1489
- portalPrimaryButtonTextColor: this.portalPrimaryButtonTextColor,
1490
- isForNewDevice: opts.isForNewDevice ? opts.isForNewDevice.toString() : void 0,
1491
- supportedWalletTypes: this.#supportedWalletTypesOpt ? JSON.stringify(this.#supportedWalletTypesOpt) : void 0,
1492
- ...isCreate || isLogin ? {
1493
- ...opts.authType === "email" ? { email: this.email } : {},
1494
- ...opts.authType === "phone" ? { phone: this.phone, countryCode: this.countryCode } : {},
1495
- ...opts.authType === "farcaster" ? { farcasterUsername: this.farcasterUsername } : {},
1496
- ...opts.authType === "telegram" ? { telegramUserId: this.telegramUserId } : {}
1497
- } : {},
1498
- ...isLogin || isOnRamp ? { sessionId: opts.sessionId } : {},
1499
- ...isLogin ? {
1563
+ const [isCreate, isLogin, isOnRamp] = [
1564
+ ["createAuth", "createPassword"].includes(type),
1565
+ ["loginAuth", "loginPassword"].includes(type),
1566
+ type === "onRamp"
1567
+ ];
1568
+ const partner = opts.partnerId ? (_a = (yield this.ctx.client.getPartner(opts.partnerId)).data) == null ? void 0 : _a.partner : void 0;
1569
+ const params = __spreadValues(__spreadValues(__spreadValues(__spreadValues({
1570
+ apiKey: this.ctx.apiKey,
1571
+ partnerId: opts.partnerId,
1572
+ portalFont: ((_b = opts.theme) == null ? void 0 : _b.font) || (partner == null ? void 0 : partner.font) || ((_c = this.portalTheme) == null ? void 0 : _c.font),
1573
+ portalBorderRadius: ((_d = opts.theme) == null ? void 0 : _d.borderRadius) || ((_e = this.portalTheme) == null ? void 0 : _e.borderRadius),
1574
+ portalThemeMode: ((_f = opts.theme) == null ? void 0 : _f.mode) || (partner == null ? void 0 : partner.themeMode) || ((_g = this.portalTheme) == null ? void 0 : _g.mode),
1575
+ portalAccentColor: ((_h = opts.theme) == null ? void 0 : _h.accentColor) || (partner == null ? void 0 : partner.accentColor) || ((_i = this.portalTheme) == null ? void 0 : _i.accentColor),
1576
+ portalForegroundColor: ((_j = opts.theme) == null ? void 0 : _j.foregroundColor) || (partner == null ? void 0 : partner.foregroundColor) || ((_k = this.portalTheme) == null ? void 0 : _k.foregroundColor),
1577
+ portalBackgroundColor: ((_l = opts.theme) == null ? void 0 : _l.backgroundColor) || (partner == null ? void 0 : partner.backgroundColor) || this.portalBackgroundColor || ((_m = this.portalTheme) == null ? void 0 : _m.backgroundColor),
1578
+ portalPrimaryButtonColor: this.portalPrimaryButtonColor,
1579
+ portalTextColor: this.portalTextColor,
1580
+ portalPrimaryButtonTextColor: this.portalPrimaryButtonTextColor,
1581
+ isForNewDevice: opts.isForNewDevice ? opts.isForNewDevice.toString() : void 0,
1582
+ supportedWalletTypes: __privateGet(this, _supportedWalletTypesOpt) ? JSON.stringify(__privateGet(this, _supportedWalletTypesOpt)) : void 0
1583
+ }, isCreate || isLogin ? __spreadValues(__spreadValues(__spreadValues(__spreadValues({}, opts.authType === "email" ? { email: this.email } : {}), opts.authType === "phone" ? { phone: this.phone, countryCode: this.countryCode } : {}), opts.authType === "farcaster" ? { farcasterUsername: this.farcasterUsername } : {}), opts.authType === "telegram" ? { telegramUserId: this.telegramUserId } : {}) : {}), isLogin || isOnRamp ? { sessionId: opts.sessionId } : {}), isLogin ? {
1500
1584
  encryptionKey: opts.loginEncryptionPublicKey,
1501
1585
  newDeviceSessionLookupId: opts.newDeviceSessionId,
1502
1586
  newDeviceEncryptionKey: opts.newDeviceEncryptionKey,
1503
1587
  pregenIds: JSON.stringify(this.pregenIds),
1504
1588
  displayName: opts.displayName,
1505
1589
  pfpUrl: opts.pfpUrl
1506
- } : {},
1507
- ...opts.params || {}
1508
- };
1509
- return constructUrl({ base, path, params });
1590
+ } : {}), opts.params || {});
1591
+ return constructUrl({ base, path, params });
1592
+ });
1510
1593
  }
1511
- async touchSession(regenerate = false) {
1512
- const res = await this.ctx.client.touchSession(regenerate);
1513
- this.setSupportedWalletTypes(res.data.supportedWalletTypes, res.data.cosmosPrefix);
1514
- return res;
1594
+ touchSession(regenerate = false) {
1595
+ return __async(this, null, function* () {
1596
+ const res = yield this.ctx.client.touchSession(regenerate);
1597
+ this.setSupportedWalletTypes(res.data.supportedWalletTypes, res.data.cosmosPrefix);
1598
+ return res;
1599
+ });
1515
1600
  }
1516
1601
  setSupportedWalletTypes(supportedWalletTypes, cosmosPrefix) {
1517
- if (supportedWalletTypes && !this.#supportedWalletTypes) {
1518
- this.#supportedWalletTypes = supportedWalletTypes;
1602
+ if (supportedWalletTypes && !__privateGet(this, _supportedWalletTypes)) {
1603
+ __privateSet(this, _supportedWalletTypes, supportedWalletTypes);
1519
1604
  Object.keys(this.currentWalletIds).forEach((type) => {
1520
- if (!this.#supportedWalletTypes?.some(({ type: supportedType }) => supportedType === type)) {
1605
+ var _a;
1606
+ if (!((_a = __privateGet(this, _supportedWalletTypes)) == null ? void 0 : _a.some(({ type: supportedType }) => supportedType === type))) {
1521
1607
  delete this.currentWalletIds[type];
1522
1608
  }
1523
1609
  });
@@ -1553,155 +1639,168 @@ var ParaCore = class _ParaCore {
1553
1639
  *
1554
1640
  * Init only needs to be called for storage that is async.
1555
1641
  */
1556
- async init() {
1557
- this.email = await this.localStorageGetItem(LOCAL_STORAGE_EMAIL) || void 0;
1558
- this.countryCode = await this.localStorageGetItem(LOCAL_STORAGE_COUNTRY_CODE) || void 0;
1559
- this.phone = await this.localStorageGetItem(LOCAL_STORAGE_PHONE) || void 0;
1560
- this.userId = await this.localStorageGetItem(LOCAL_STORAGE_USER_ID) || void 0;
1561
- this.telegramUserId = await this.localStorageGetItem(LOCAL_STORAGE_TELEGRAM_USER_ID) || void 0;
1562
- const stringWallets = this.platformUtils.secureStorage ? await this.platformUtils.secureStorage.get(LOCAL_STORAGE_WALLETS) : await this.localStorageGetItem(LOCAL_STORAGE_WALLETS);
1563
- const _wallets = JSON.parse(stringWallets || "{}");
1564
- const stringEd25519Wallets = this.platformUtils.secureStorage ? await this.platformUtils.secureStorage.get(LOCAL_STORAGE_ED25519_WALLETS) : await this.localStorageGetItem(LOCAL_STORAGE_ED25519_WALLETS);
1565
- const _ed25519Wallets = JSON.parse(stringEd25519Wallets || "{}");
1566
- const wallets = {
1567
- ...Object.keys(_wallets).reduce((res, key) => {
1568
- return {
1569
- ...res,
1642
+ init() {
1643
+ return __async(this, null, function* () {
1644
+ var _a;
1645
+ this.email = (yield this.localStorageGetItem(LOCAL_STORAGE_EMAIL)) || void 0;
1646
+ this.countryCode = (yield this.localStorageGetItem(LOCAL_STORAGE_COUNTRY_CODE)) || void 0;
1647
+ this.phone = (yield this.localStorageGetItem(LOCAL_STORAGE_PHONE)) || void 0;
1648
+ this.userId = (yield this.localStorageGetItem(LOCAL_STORAGE_USER_ID)) || void 0;
1649
+ this.telegramUserId = (yield this.localStorageGetItem(LOCAL_STORAGE_TELEGRAM_USER_ID)) || void 0;
1650
+ const stringWallets = this.platformUtils.secureStorage ? yield this.platformUtils.secureStorage.get(LOCAL_STORAGE_WALLETS) : yield this.localStorageGetItem(LOCAL_STORAGE_WALLETS);
1651
+ const _wallets = JSON.parse(stringWallets || "{}");
1652
+ const stringEd25519Wallets = this.platformUtils.secureStorage ? yield this.platformUtils.secureStorage.get(LOCAL_STORAGE_ED25519_WALLETS) : yield this.localStorageGetItem(LOCAL_STORAGE_ED25519_WALLETS);
1653
+ const _ed25519Wallets = JSON.parse(stringEd25519Wallets || "{}");
1654
+ const wallets = __spreadValues(__spreadValues({}, Object.keys(_wallets).reduce((res, key) => {
1655
+ return __spreadProps(__spreadValues({}, res), {
1570
1656
  [key]: migrateWallet(_wallets[key])
1571
- };
1572
- }, {}),
1573
- ...Object.keys(_ed25519Wallets).reduce((res, key) => {
1574
- return {
1575
- ...res,
1576
- ...!res[key] ? { [key]: migrateWallet(_ed25519Wallets[key]) } : {}
1577
- };
1578
- }, {})
1579
- };
1580
- await this.setWallets(wallets);
1581
- const _currentWalletIds = await this.localStorageGetItem(LOCAL_STORAGE_CURRENT_WALLET_IDS) ?? void 0;
1582
- const currentWalletIds = [void 0, null, "undefined", "null"].includes(_currentWalletIds) ? {} : (() => {
1583
- const fromJson = JSON.parse(_currentWalletIds);
1584
- return Array.isArray(fromJson) ? Object.keys(WalletType2).reduce((acc, type) => {
1585
- const wallet = Object.values(this.wallets).find(
1586
- (w) => fromJson.includes(w.id) && WalletSchemeTypeMap[w.scheme][type]
1587
- );
1588
- return {
1589
- ...acc,
1590
- ...wallet && !acc[type] ? { [type]: [wallet.id] } : {}
1591
- };
1592
- }, {}) : fromJson;
1593
- })();
1594
- await this.setCurrentWalletIds(currentWalletIds);
1595
- this.sessionCookie = await this.localStorageGetItem(LOCAL_STORAGE_SESSION_COOKIE) || await this.sessionStorageGetItem(LOCAL_STORAGE_SESSION_COOKIE) || void 0;
1596
- if (Object.values(this.wallets).filter((w) => this.isWalletOwned(w)).length > 0 && this.currentWalletIdsArray.length === 0) {
1597
- this.findWalletId(void 0, { forbidPregen: true });
1598
- }
1599
- const loginEncryptionKey = await this.sessionStorageGetItem(SESSION_STORAGE_LOGIN_ENCRYPTION_KEY_PAIR);
1600
- if (loginEncryptionKey && loginEncryptionKey !== "undefined") {
1601
- this.loginEncryptionKeyPair = this.convertEncryptionKeyPair(JSON.parse(loginEncryptionKey));
1602
- }
1603
- const stringExternalWallets = await this.localStorageGetItem(LOCAL_STORAGE_EXTERNAL_WALLETS);
1604
- const _externalWallets = JSON.parse(stringExternalWallets || "{}");
1605
- await this.setExternalWallets(_externalWallets);
1606
- setupListeners.bind(this)();
1607
- await this.touchSession();
1657
+ });
1658
+ }, {})), Object.keys(_ed25519Wallets).reduce((res, key) => {
1659
+ return __spreadValues(__spreadValues({}, res), !res[key] ? { [key]: migrateWallet(_ed25519Wallets[key]) } : {});
1660
+ }, {}));
1661
+ yield this.setWallets(wallets);
1662
+ const _currentWalletIds = (_a = yield this.localStorageGetItem(LOCAL_STORAGE_CURRENT_WALLET_IDS)) != null ? _a : void 0;
1663
+ const currentWalletIds = [void 0, null, "undefined", "null"].includes(_currentWalletIds) ? {} : (() => {
1664
+ const fromJson = JSON.parse(_currentWalletIds);
1665
+ return Array.isArray(fromJson) ? Object.keys(WalletType2).reduce((acc, type) => {
1666
+ const wallet = Object.values(this.wallets).find(
1667
+ (w) => fromJson.includes(w.id) && WalletSchemeTypeMap[w.scheme][type]
1668
+ );
1669
+ return __spreadValues(__spreadValues({}, acc), wallet && !acc[type] ? { [type]: [wallet.id] } : {});
1670
+ }, {}) : fromJson;
1671
+ })();
1672
+ yield this.setCurrentWalletIds(currentWalletIds);
1673
+ this.sessionCookie = (yield this.localStorageGetItem(LOCAL_STORAGE_SESSION_COOKIE)) || (yield this.sessionStorageGetItem(LOCAL_STORAGE_SESSION_COOKIE)) || void 0;
1674
+ if (Object.values(this.wallets).filter((w) => this.isWalletOwned(w)).length > 0 && this.currentWalletIdsArray.length === 0) {
1675
+ this.findWalletId(void 0, { forbidPregen: true });
1676
+ }
1677
+ const loginEncryptionKey = yield this.sessionStorageGetItem(SESSION_STORAGE_LOGIN_ENCRYPTION_KEY_PAIR);
1678
+ if (loginEncryptionKey && loginEncryptionKey !== "undefined") {
1679
+ this.loginEncryptionKeyPair = this.convertEncryptionKeyPair(JSON.parse(loginEncryptionKey));
1680
+ }
1681
+ const stringExternalWallets = yield this.localStorageGetItem(LOCAL_STORAGE_EXTERNAL_WALLETS);
1682
+ const _externalWallets = JSON.parse(stringExternalWallets || "{}");
1683
+ yield this.setExternalWallets(_externalWallets);
1684
+ setupListeners.bind(this)();
1685
+ yield this.touchSession();
1686
+ });
1608
1687
  }
1609
1688
  /**
1610
1689
  * Sets the email associated with the `ParaCore` instance.
1611
1690
  * @param email - Email to set.
1612
1691
  */
1613
- async setEmail(email) {
1614
- this.email = email;
1615
- await this.localStorageSetItem(LOCAL_STORAGE_EMAIL, email);
1692
+ setEmail(email) {
1693
+ return __async(this, null, function* () {
1694
+ this.email = email;
1695
+ yield this.localStorageSetItem(LOCAL_STORAGE_EMAIL, email);
1696
+ });
1616
1697
  }
1617
1698
  /**
1618
1699
  * Sets the Telegram user ID associated with the `ParaCore` instance.
1619
1700
  * @param telegramUserId - Telegram user ID to set.
1620
1701
  */
1621
- async setTelegramUserId(telegramUserId) {
1622
- this.telegramUserId = telegramUserId;
1623
- await this.localStorageSetItem(LOCAL_STORAGE_TELEGRAM_USER_ID, telegramUserId);
1702
+ setTelegramUserId(telegramUserId) {
1703
+ return __async(this, null, function* () {
1704
+ this.telegramUserId = telegramUserId;
1705
+ yield this.localStorageSetItem(LOCAL_STORAGE_TELEGRAM_USER_ID, telegramUserId);
1706
+ });
1624
1707
  }
1625
1708
  /**
1626
1709
  * Sets the phone number associated with the `ParaCore` instance.
1627
1710
  * @param phone - Phone number to set.
1628
1711
  * @param countryCode - Country Code to set.
1629
1712
  */
1630
- async setPhoneNumber(phone, countryCode) {
1631
- this.phone = phone;
1632
- this.countryCode = countryCode;
1633
- await this.localStorageSetItem(LOCAL_STORAGE_PHONE, phone);
1634
- await this.localStorageSetItem(LOCAL_STORAGE_COUNTRY_CODE, countryCode);
1713
+ setPhoneNumber(phone, countryCode) {
1714
+ return __async(this, null, function* () {
1715
+ this.phone = phone;
1716
+ this.countryCode = countryCode;
1717
+ yield this.localStorageSetItem(LOCAL_STORAGE_PHONE, phone);
1718
+ yield this.localStorageSetItem(LOCAL_STORAGE_COUNTRY_CODE, countryCode);
1719
+ });
1635
1720
  }
1636
1721
  /**
1637
1722
  * Sets the farcaster username associated with the `ParaCore` instance.
1638
1723
  * @param farcasterUsername - Farcaster Username to set.
1639
1724
  */
1640
- async setFarcasterUsername(farcasterUsername) {
1641
- this.farcasterUsername = farcasterUsername;
1642
- await this.localStorageSetItem(LOCAL_STORAGE_FARCASTER_USERNAME, farcasterUsername);
1725
+ setFarcasterUsername(farcasterUsername) {
1726
+ return __async(this, null, function* () {
1727
+ this.farcasterUsername = farcasterUsername;
1728
+ yield this.localStorageSetItem(LOCAL_STORAGE_FARCASTER_USERNAME, farcasterUsername);
1729
+ });
1643
1730
  }
1644
1731
  /**
1645
1732
  * Sets the external wallet address and type associated with the `ParaCore` instance.
1646
1733
  * @param externalAddress - External wallet address to set.
1647
1734
  * @param externalType - Type of external wallet to set.
1648
1735
  */
1649
- async setExternalWallet({ address, type, provider, addressBech32 }) {
1650
- this.externalWallets = {
1651
- [address]: {
1652
- id: address,
1653
- address: addressBech32 ?? address,
1654
- type,
1655
- name: provider,
1656
- isExternal: true,
1657
- signer: ""
1658
- }
1659
- };
1660
- this.setExternalWallets(this.externalWallets);
1661
- dispatchEvent(ParaEvent.EXTERNAL_WALLET_CHANGE_EVENT, null);
1736
+ setExternalWallet(_0) {
1737
+ return __async(this, arguments, function* ({ address, type, provider, addressBech32 }) {
1738
+ this.externalWallets = {
1739
+ [address]: {
1740
+ id: address,
1741
+ address: addressBech32 != null ? addressBech32 : address,
1742
+ type,
1743
+ name: provider,
1744
+ isExternal: true,
1745
+ signer: ""
1746
+ }
1747
+ };
1748
+ this.setExternalWallets(this.externalWallets);
1749
+ dispatchEvent(ParaEvent.EXTERNAL_WALLET_CHANGE_EVENT, null);
1750
+ });
1662
1751
  }
1663
1752
  /**
1664
1753
  * Sets the user id associated with the `ParaCore` instance.
1665
1754
  * @param userId - User id to set.
1666
1755
  */
1667
- async setUserId(userId) {
1668
- this.userId = userId;
1669
- await this.localStorageSetItem(LOCAL_STORAGE_USER_ID, userId);
1756
+ setUserId(userId) {
1757
+ return __async(this, null, function* () {
1758
+ this.userId = userId;
1759
+ yield this.localStorageSetItem(LOCAL_STORAGE_USER_ID, userId);
1760
+ });
1670
1761
  }
1671
1762
  /**
1672
1763
  * Sets the wallets associated with the `ParaCore` instance.
1673
1764
  * @param wallets - Wallets to set.
1674
1765
  */
1675
- async setWallets(wallets) {
1676
- this.wallets = wallets;
1677
- if (this.platformUtils.secureStorage) {
1678
- await this.platformUtils.secureStorage.set(LOCAL_STORAGE_WALLETS, JSON.stringify(wallets));
1679
- return;
1680
- }
1681
- await this.localStorageSetItem(LOCAL_STORAGE_WALLETS, JSON.stringify(wallets));
1766
+ setWallets(wallets) {
1767
+ return __async(this, null, function* () {
1768
+ this.wallets = wallets;
1769
+ if (this.platformUtils.secureStorage) {
1770
+ yield this.platformUtils.secureStorage.set(LOCAL_STORAGE_WALLETS, JSON.stringify(wallets));
1771
+ return;
1772
+ }
1773
+ yield this.localStorageSetItem(LOCAL_STORAGE_WALLETS, JSON.stringify(wallets));
1774
+ });
1682
1775
  }
1683
1776
  /**
1684
1777
  * Sets the external wallets associated with the `ParaCore` instance.
1685
1778
  * @param externalWallets - External wallets to set.
1686
1779
  */
1687
- async setExternalWallets(externalWallets) {
1688
- this.externalWallets = externalWallets;
1689
- await this.localStorageSetItem(LOCAL_STORAGE_EXTERNAL_WALLETS, JSON.stringify(externalWallets));
1780
+ setExternalWallets(externalWallets) {
1781
+ return __async(this, null, function* () {
1782
+ this.externalWallets = externalWallets;
1783
+ yield this.localStorageSetItem(LOCAL_STORAGE_EXTERNAL_WALLETS, JSON.stringify(externalWallets));
1784
+ });
1690
1785
  }
1691
1786
  /**
1692
1787
  * Sets the login encryption key pair associated with the `ParaCore` instance.
1693
1788
  * @param keyPair - Encryption key pair generated from loginEncryptionKey.
1694
1789
  */
1695
- async setLoginEncryptionKeyPair(keyPair) {
1696
- if (!keyPair) {
1697
- keyPair = await getAsymmetricKeyPair(this.ctx);
1698
- }
1699
- this.loginEncryptionKeyPair = keyPair;
1700
- await this.sessionStorageSetItem(SESSION_STORAGE_LOGIN_ENCRYPTION_KEY_PAIR, JSON.stringify(keyPair));
1790
+ setLoginEncryptionKeyPair(keyPair) {
1791
+ return __async(this, null, function* () {
1792
+ if (!keyPair) {
1793
+ keyPair = yield getAsymmetricKeyPair(this.ctx);
1794
+ }
1795
+ this.loginEncryptionKeyPair = keyPair;
1796
+ yield this.sessionStorageSetItem(SESSION_STORAGE_LOGIN_ENCRYPTION_KEY_PAIR, JSON.stringify(keyPair));
1797
+ });
1701
1798
  }
1702
- async deleteLoginEncryptionKeyPair() {
1703
- this.loginEncryptionKeyPair = void 0;
1704
- await this.sessionStorageRemoveItem(SESSION_STORAGE_LOGIN_ENCRYPTION_KEY_PAIR);
1799
+ deleteLoginEncryptionKeyPair() {
1800
+ return __async(this, null, function* () {
1801
+ this.loginEncryptionKeyPair = void 0;
1802
+ yield this.sessionStorageRemoveItem(SESSION_STORAGE_LOGIN_ENCRYPTION_KEY_PAIR);
1803
+ });
1705
1804
  }
1706
1805
  /**
1707
1806
  * Gets the userId associated with the `ParaCore` instance.
@@ -1741,23 +1840,42 @@ var ParaCore = class _ParaCore {
1741
1840
  getFarcasterUsername() {
1742
1841
  return this.farcasterUsername;
1743
1842
  }
1744
- async setCurrentWalletIds(currentWalletIds, {
1745
- needsWallet = false,
1746
- sessionLookupId,
1747
- newDeviceSessionLookupId
1748
- } = {}) {
1749
- this.currentWalletIds = currentWalletIds;
1750
- await this.localStorageSetItem(LOCAL_STORAGE_CURRENT_WALLET_IDS, JSON.stringify(this.currentWalletIds));
1751
- if (sessionLookupId) {
1752
- await this.ctx.client.setCurrentWalletIds(
1753
- this.getUserId(),
1754
- this.currentWalletIds,
1755
- needsWallet,
1756
- sessionLookupId,
1757
- newDeviceSessionLookupId
1758
- );
1759
- }
1760
- dispatchEvent(ParaEvent.WALLETS_CHANGE_EVENT, null);
1843
+ setCurrentWalletIds(_0) {
1844
+ return __async(this, arguments, function* (currentWalletIds, {
1845
+ needsWallet = false,
1846
+ sessionLookupId,
1847
+ newDeviceSessionLookupId
1848
+ } = {}) {
1849
+ this.currentWalletIds = currentWalletIds;
1850
+ yield this.localStorageSetItem(LOCAL_STORAGE_CURRENT_WALLET_IDS, JSON.stringify(this.currentWalletIds));
1851
+ if (sessionLookupId) {
1852
+ yield this.ctx.client.setCurrentWalletIds(
1853
+ this.getUserId(),
1854
+ this.currentWalletIds,
1855
+ needsWallet,
1856
+ sessionLookupId,
1857
+ newDeviceSessionLookupId
1858
+ );
1859
+ }
1860
+ dispatchEvent(ParaEvent.WALLETS_CHANGE_EVENT, null);
1861
+ });
1862
+ }
1863
+ /**
1864
+ * Fetches the most recent OAuth account metadata for the signed-in user.
1865
+ * If applicable, this will include the user's most recent metadata from their Google, Apple, Facebook, X, Discord, Farcaster, or Telegram account, the last time they signed in to your app.
1866
+ * @returns {Promise<AccountMetadata>} the user's account metadata.
1867
+ */
1868
+ getAccountMetadata() {
1869
+ return __async(this, null, function* () {
1870
+ if (!(yield this.isSessionActive()) || !this.userId) {
1871
+ throw new Error("no signed-in user");
1872
+ }
1873
+ const {
1874
+ data: { partnerId }
1875
+ } = yield this.touchSession();
1876
+ const { accountMetadata } = yield this.ctx.client.getAccountMetadata(this.userId, partnerId);
1877
+ return accountMetadata;
1878
+ });
1761
1879
  }
1762
1880
  /**
1763
1881
  * Validates that a wallet ID is present on the instance, usable, and matches the desired filters.
@@ -1811,6 +1929,7 @@ var ParaCore = class _ParaCore {
1811
1929
  return wallet;
1812
1930
  }
1813
1931
  findWallet(idOrAddress, overrideType, filter = {}) {
1932
+ var _b, _c;
1814
1933
  if (!idOrAddress && Object.keys(this.externalWallets).length > 0) {
1815
1934
  return Object.values(this.externalWallets)[0];
1816
1935
  }
@@ -1820,18 +1939,18 @@ var ParaCore = class _ParaCore {
1820
1939
  try {
1821
1940
  const walletId = this.findWalletId(idOrAddress, filter);
1822
1941
  if (walletId && !!this.wallets[walletId]) {
1823
- const { signer: _signer, ...wallet } = this.wallets[walletId];
1824
- const type = overrideType ?? this.currentWalletIdsArray.find(([id]) => id === walletId)?.[1] ?? wallet.type;
1825
- return {
1826
- ...wallet,
1942
+ const _a = this.wallets[walletId], { signer: _signer } = _a, wallet = __objRest(_a, ["signer"]);
1943
+ const type = (_c = overrideType != null ? overrideType : (_b = this.currentWalletIdsArray.find(([id]) => id === walletId)) == null ? void 0 : _b[1]) != null ? _c : wallet.type;
1944
+ return __spreadProps(__spreadValues({}, wallet), {
1827
1945
  type: WalletType2[type]
1828
- };
1946
+ });
1829
1947
  }
1830
1948
  } catch (e) {
1831
1949
  return void 0;
1832
1950
  }
1833
1951
  }
1834
1952
  get availableWallets() {
1953
+ var _a;
1835
1954
  return [
1836
1955
  ...this.currentWalletIdsArray.map(([address, type]) => [address, type, false]).map(([id, type]) => {
1837
1956
  const wallet = this.findWallet(id, type);
@@ -1843,7 +1962,7 @@ var ParaCore = class _ParaCore {
1843
1962
  name: wallet.name
1844
1963
  };
1845
1964
  }).filter((obj) => obj !== null),
1846
- ...Object.values(this.externalWallets ?? {})
1965
+ ...Object.values((_a = this.externalWallets) != null ? _a : {})
1847
1966
  ];
1848
1967
  }
1849
1968
  /**
@@ -1857,61 +1976,78 @@ var ParaCore = class _ParaCore {
1857
1976
  assertIsValidWalletId(walletId, condition = {}) {
1858
1977
  this.isWalletUsable(walletId, condition, true);
1859
1978
  }
1860
- async assertIsValidWalletType(type, walletTypes) {
1861
- if (!this.#supportedWalletTypes) {
1862
- await this.touchSession();
1863
- }
1864
- if (!type || !Object.values(WalletType2).includes(type) || !(walletTypes ?? this.supportedWalletTypes.map(({ type: type2 }) => type2)).includes(type)) {
1865
- throw new Error(`wallet type ${type} is not supported`);
1866
- }
1867
- return type;
1979
+ assertIsValidWalletType(type, walletTypes) {
1980
+ return __async(this, null, function* () {
1981
+ if (!__privateGet(this, _supportedWalletTypes)) {
1982
+ yield this.touchSession();
1983
+ }
1984
+ if (!type || !Object.values(WalletType2).includes(type) || !(walletTypes != null ? walletTypes : this.supportedWalletTypes.map(({ type: type2 }) => type2)).includes(type)) {
1985
+ throw new Error(`wallet type ${type} is not supported`);
1986
+ }
1987
+ return type;
1988
+ });
1868
1989
  }
1869
- async getMissingTypes() {
1870
- if (!this.#supportedWalletTypes) {
1871
- await this.touchSession();
1872
- }
1873
- return this.supportedWalletTypes.filter(
1874
- ({ type: t, optional }) => !optional && Object.values(this.wallets).every((w) => !this.isWalletOwned(w) || !WalletSchemeTypeMap[w.scheme][t])
1875
- ).map(({ type }) => type);
1990
+ getMissingTypes() {
1991
+ return __async(this, null, function* () {
1992
+ if (!__privateGet(this, _supportedWalletTypes)) {
1993
+ yield this.touchSession();
1994
+ }
1995
+ return this.supportedWalletTypes.filter(
1996
+ ({ type: t, optional }) => !optional && Object.values(this.wallets).every((w) => !this.isWalletOwned(w) || !WalletSchemeTypeMap[w.scheme][t])
1997
+ ).map(({ type }) => type);
1998
+ });
1876
1999
  }
1877
- async getTypesToCreate(types) {
1878
- if (!this.#supportedWalletTypes) {
1879
- await this.touchSession();
1880
- }
1881
- return getSchemes(types ?? await this.getMissingTypes()).map((scheme) => {
1882
- switch (scheme) {
1883
- case WalletScheme2.ED25519:
1884
- return WalletType2.SOLANA;
1885
- default:
1886
- return this.supportedWalletTypes.some(({ type, optional }) => type === WalletType2.COSMOS && !optional) ? WalletType2.COSMOS : WalletType2.EVM;
2000
+ getTypesToCreate(types) {
2001
+ return __async(this, null, function* () {
2002
+ if (!__privateGet(this, _supportedWalletTypes)) {
2003
+ yield this.touchSession();
1887
2004
  }
2005
+ return getSchemes(types != null ? types : yield this.getMissingTypes()).map((scheme) => {
2006
+ switch (scheme) {
2007
+ case WalletScheme2.ED25519:
2008
+ return WalletType2.SOLANA;
2009
+ default:
2010
+ return this.supportedWalletTypes.some(({ type, optional }) => type === WalletType2.COSMOS && !optional) ? WalletType2.COSMOS : WalletType2.EVM;
2011
+ }
2012
+ });
1888
2013
  });
1889
2014
  }
1890
- async getPartnerURL(partnerId) {
1891
- const res = await this.ctx.client.getPartner(partnerId);
1892
- return res.data.partner.portalUrl;
2015
+ getPartnerURL(partnerId) {
2016
+ return __async(this, null, function* () {
2017
+ const res = yield this.ctx.client.getPartner(partnerId);
2018
+ return res.data.partner.portalUrl;
2019
+ });
1893
2020
  }
1894
2021
  /**
1895
2022
  * URL of the portal, which can be associated with a partner id
1896
2023
  * @param partnerId: string - id of the partner to get the portal URL for
1897
2024
  * @returns - portal URL
1898
2025
  */
1899
- async getPortalURL(partnerId) {
1900
- return partnerId && await this.getPartnerURL(partnerId) || getPortalBaseURL(this.ctx);
2026
+ getPortalURL(partnerId) {
2027
+ return __async(this, null, function* () {
2028
+ return partnerId && (yield this.getPartnerURL(partnerId)) || getPortalBaseURL(this.ctx);
2029
+ });
1901
2030
  }
1902
- async getWebAuthURLForCreate({
1903
- webAuthId,
1904
- ...options
1905
- }) {
1906
- return this.constructPortalUrl("createAuth", { ...options, pathId: webAuthId });
2031
+ getWebAuthURLForCreate(_a) {
2032
+ return __async(this, null, function* () {
2033
+ var _b = _a, {
2034
+ webAuthId
2035
+ } = _b, options = __objRest(_b, [
2036
+ "webAuthId"
2037
+ ]);
2038
+ return this.constructPortalUrl("createAuth", __spreadProps(__spreadValues({}, options), { pathId: webAuthId }));
2039
+ });
1907
2040
  }
1908
- async getPasswordURLForCreate({
1909
- passwordId,
1910
- ...options
1911
- }) {
1912
- return this.constructPortalUrl("createPassword", {
1913
- ...options,
1914
- pathId: passwordId
2041
+ getPasswordURLForCreate(_c) {
2042
+ return __async(this, null, function* () {
2043
+ var _d = _c, {
2044
+ passwordId
2045
+ } = _d, options = __objRest(_d, [
2046
+ "passwordId"
2047
+ ]);
2048
+ return this.constructPortalUrl("createPassword", __spreadProps(__spreadValues({}, options), {
2049
+ pathId: passwordId
2050
+ }));
1915
2051
  });
1916
2052
  }
1917
2053
  getShortUrl(compressedUrl) {
@@ -1920,35 +2056,42 @@ var ParaCore = class _ParaCore {
1920
2056
  path: `/short/${compressedUrl}`
1921
2057
  });
1922
2058
  }
1923
- async shortenLoginLink(link) {
1924
- const url = await upload(link, this.ctx.client);
1925
- return this.getShortUrl(url);
2059
+ shortenLoginLink(link) {
2060
+ return __async(this, null, function* () {
2061
+ const url = yield upload(link, this.ctx.client);
2062
+ return this.getShortUrl(url);
2063
+ });
1926
2064
  }
1927
2065
  /**
1928
2066
  * Generates a URL for registering a new WebAuth passkey.
1929
2067
  * @param {GetWebAuthUrlForLoginParams} opts the options object
1930
2068
  * @returns - the URL for creating a new passkey
1931
2069
  */
1932
- async getWebAuthURLForLogin(opts) {
1933
- return this.constructPortalUrl("loginAuth", opts);
2070
+ getWebAuthURLForLogin(opts) {
2071
+ return __async(this, null, function* () {
2072
+ return this.constructPortalUrl("loginAuth", opts);
2073
+ });
1934
2074
  }
1935
2075
  /**
1936
2076
  * Generates a URL for registering a new user password.
1937
2077
  * @param {GetWebAuthUrlForLoginParams} opts the options object
1938
2078
  * @returns - the URL for creating a new password
1939
2079
  */
1940
- async getPasswordURLForLogin(opts) {
1941
- return this.constructPortalUrl("loginPassword", opts);
2080
+ getPasswordURLForLogin(opts) {
2081
+ return __async(this, null, function* () {
2082
+ return this.constructPortalUrl("loginPassword", opts);
2083
+ });
1942
2084
  }
1943
2085
  /**
1944
2086
  * Generates a URL for registering a new WebAuth passkey for a phone number.
1945
2087
  * @param {Omit<GetWebAuthUrlForLoginParams, 'authType'>} opts the options object
1946
2088
  * @returns - web auth url
1947
2089
  */
1948
- async getWebAuthURLForLoginForPhone(opts) {
1949
- return this.constructPortalUrl("loginAuth", {
1950
- authType: "phone",
1951
- ...opts
2090
+ getWebAuthURLForLoginForPhone(opts) {
2091
+ return __async(this, null, function* () {
2092
+ return this.constructPortalUrl("loginAuth", __spreadValues({
2093
+ authType: "phone"
2094
+ }, opts));
1952
2095
  });
1953
2096
  }
1954
2097
  /**
@@ -1956,57 +2099,59 @@ var ParaCore = class _ParaCore {
1956
2099
  * @param {string } [walletId] id of the wallet to get the private key for. Will default to the first wallet if not provided.
1957
2100
  * @returns - the private key string.
1958
2101
  */
1959
- async getPrivateKey(walletId) {
1960
- const wallets = Object.values(this.wallets);
1961
- const wallet = walletId ? this.wallets[walletId] : wallets?.[0];
1962
- if (!wallet) {
1963
- throw new Error("wallet not found");
1964
- }
1965
- if (wallet.scheme !== WalletScheme2.DKLS) {
1966
- throw new Error("invalid wallet scheme");
1967
- }
1968
- return await this.platformUtils.getPrivateKey(
1969
- this.ctx,
1970
- this.userId,
1971
- wallet.id,
1972
- wallet.signer,
1973
- this.retrieveSessionCookie()
1974
- );
2102
+ getPrivateKey(walletId) {
2103
+ return __async(this, null, function* () {
2104
+ const wallets = Object.values(this.wallets);
2105
+ const wallet = walletId ? this.wallets[walletId] : wallets == null ? void 0 : wallets[0];
2106
+ if (!wallet) {
2107
+ throw new Error("wallet not found");
2108
+ }
2109
+ if (wallet.scheme !== WalletScheme2.DKLS) {
2110
+ throw new Error("invalid wallet scheme");
2111
+ }
2112
+ return yield this.platformUtils.getPrivateKey(
2113
+ this.ctx,
2114
+ this.userId,
2115
+ wallet.id,
2116
+ wallet.signer,
2117
+ this.retrieveSessionCookie()
2118
+ );
2119
+ });
1975
2120
  }
1976
2121
  /**
1977
2122
  * Fetches the wallets associated with the user.
1978
2123
  * @returns {WalletEntity[]} wallets that were fetched.
1979
2124
  */
1980
- async fetchWallets() {
1981
- const res = await (this.isPortal() || this.isParaConnect() ? this.ctx.client.getAllWallets(this.userId) : this.ctx.client.getWallets(this.userId, true));
1982
- return res.data.wallets.filter(
1983
- (wallet) => !!wallet.address && (this.isParaConnect() || !this.isParaConnect() && this.isWalletSupported(entityToWallet(wallet)))
1984
- );
2125
+ fetchWallets() {
2126
+ return __async(this, null, function* () {
2127
+ const res = yield this.isPortal() || this.isParaConnect() ? this.ctx.client.getAllWallets(this.userId) : this.ctx.client.getWallets(this.userId, true);
2128
+ return res.data.wallets.filter(
2129
+ (wallet) => !!wallet.address && (this.isParaConnect() || !this.isParaConnect() && this.isWalletSupported(entityToWallet(wallet)))
2130
+ );
2131
+ });
1985
2132
  }
1986
- async populateWalletAddresses() {
1987
- const res = await this.ctx.client.getWallets(this.userId, true);
1988
- const wallets = res.data.wallets;
1989
- wallets.forEach((entity) => {
1990
- if (this.wallets[entity.id]) {
1991
- this.wallets[entity.id] = {
1992
- ...entityToWallet(entity),
1993
- ...this.wallets[entity.id]
1994
- };
1995
- }
2133
+ populateWalletAddresses() {
2134
+ return __async(this, null, function* () {
2135
+ const res = yield this.ctx.client.getWallets(this.userId, true);
2136
+ const wallets = res.data.wallets;
2137
+ wallets.forEach((entity) => {
2138
+ if (this.wallets[entity.id]) {
2139
+ this.wallets[entity.id] = __spreadValues(__spreadValues({}, entityToWallet(entity)), this.wallets[entity.id]);
2140
+ }
2141
+ });
2142
+ yield this.setWallets(this.wallets);
1996
2143
  });
1997
- await this.setWallets(this.wallets);
1998
2144
  }
1999
- async populatePregenWalletAddresses() {
2000
- const res = await this.getPregenWallets();
2001
- res.forEach((entity) => {
2002
- if (this.wallets[entity.id]) {
2003
- this.wallets[entity.id] = {
2004
- ...entityToWallet(entity),
2005
- ...this.wallets[entity.id]
2006
- };
2007
- }
2145
+ populatePregenWalletAddresses() {
2146
+ return __async(this, null, function* () {
2147
+ const res = yield this.getPregenWallets();
2148
+ res.forEach((entity) => {
2149
+ if (this.wallets[entity.id]) {
2150
+ this.wallets[entity.id] = __spreadValues(__spreadValues({}, entityToWallet(entity)), this.wallets[entity.id]);
2151
+ }
2152
+ });
2153
+ yield this.setWallets(this.wallets);
2008
2154
  });
2009
- await this.setWallets(this.wallets);
2010
2155
  }
2011
2156
  /**
2012
2157
  * Checks if a user exists for an email address.
@@ -2014,9 +2159,11 @@ var ParaCore = class _ParaCore {
2014
2159
  * @param {string} opts.email the email to check.
2015
2160
  * @returns true if user exists, false otherwise.
2016
2161
  */
2017
- async checkIfUserExists({ email }) {
2018
- const res = await this.ctx.client.checkUserExists({ email });
2019
- return res.data.exists;
2162
+ checkIfUserExists(_0) {
2163
+ return __async(this, arguments, function* ({ email }) {
2164
+ const res = yield this.ctx.client.checkUserExists({ email });
2165
+ return res.data.exists;
2166
+ });
2020
2167
  }
2021
2168
  /**
2022
2169
  * Checks if a user exists for a phone number.
@@ -2025,23 +2172,26 @@ var ParaCore = class _ParaCore {
2025
2172
  * @param {string} opts.countryCode - the country code.
2026
2173
  * @returns true if user exists, false otherwise.
2027
2174
  */
2028
- async checkIfUserExistsByPhone({ phone, countryCode }) {
2029
- const res = await this.ctx.client.checkUserExists({ phone, countryCode });
2030
- return res.data.exists;
2175
+ checkIfUserExistsByPhone(_0) {
2176
+ return __async(this, arguments, function* ({ phone, countryCode }) {
2177
+ const res = yield this.ctx.client.checkUserExists({ phone, countryCode });
2178
+ return res.data.exists;
2179
+ });
2031
2180
  }
2032
2181
  /**
2033
2182
  * Creates a new user.
2034
2183
  * @param {Object} opts the options object
2035
2184
  * @param {string} opts.email the email to use.
2036
2185
  */
2037
- async createUser({ email }) {
2038
- this.requireApiKey();
2039
- await this.setEmail(email);
2040
- const { userId } = await this.ctx.client.createUser({
2041
- email: this.email,
2042
- ...this.getVerificationEmailProps()
2186
+ createUser(_0) {
2187
+ return __async(this, arguments, function* ({ email }) {
2188
+ this.requireApiKey();
2189
+ yield this.setEmail(email);
2190
+ const { userId } = yield this.ctx.client.createUser(__spreadValues({
2191
+ email: this.email
2192
+ }, this.getVerificationEmailProps()));
2193
+ yield this.setUserId(userId);
2043
2194
  });
2044
- await this.setUserId(userId);
2045
2195
  }
2046
2196
  /**
2047
2197
  * Creates a new user with a phone number.
@@ -2049,14 +2199,16 @@ var ParaCore = class _ParaCore {
2049
2199
  * @param {string} opts.phone - the phone number to use for creating the user.
2050
2200
  * @param {string} opts.countryCode - the country code to use for creating the user.
2051
2201
  */
2052
- async createUserByPhone({ phone, countryCode }) {
2053
- this.requireApiKey();
2054
- await this.setPhoneNumber(phone, countryCode);
2055
- const { userId } = await this.ctx.client.createUser({
2056
- phone: this.phone,
2057
- countryCode: this.countryCode
2202
+ createUserByPhone(_0) {
2203
+ return __async(this, arguments, function* ({ phone, countryCode }) {
2204
+ this.requireApiKey();
2205
+ yield this.setPhoneNumber(phone, countryCode);
2206
+ const { userId } = yield this.ctx.client.createUser({
2207
+ phone: this.phone,
2208
+ countryCode: this.countryCode
2209
+ });
2210
+ yield this.setUserId(userId);
2058
2211
  });
2059
- await this.setUserId(userId);
2060
2212
  }
2061
2213
  /**
2062
2214
  * Logs in or creates a new user using an external wallet address.
@@ -2065,17 +2217,19 @@ var ParaCore = class _ParaCore {
2065
2217
  * @param {WalletType} opts.type type of external wallet to use for identification.
2066
2218
  * @param {string} opts.provider the name of the provider for the external wallet.
2067
2219
  */
2068
- async externalWalletLogin(wallet) {
2069
- this.requireApiKey();
2070
- const res = await this.ctx.client.externalWalletLogin({
2071
- externalAddress: wallet.address,
2072
- type: wallet.type,
2073
- externalWalletProvider: wallet.provider,
2074
- shouldTrackUser: wallet.shouldTrackUser
2075
- });
2076
- await this.setExternalWallet(wallet);
2077
- await this.setUserId(res.userId);
2078
- return res;
2220
+ externalWalletLogin(wallet) {
2221
+ return __async(this, null, function* () {
2222
+ this.requireApiKey();
2223
+ const res = yield this.ctx.client.externalWalletLogin({
2224
+ externalAddress: wallet.address,
2225
+ type: wallet.type,
2226
+ externalWalletProvider: wallet.provider,
2227
+ shouldTrackUser: wallet.shouldTrackUser
2228
+ });
2229
+ yield this.setExternalWallet(wallet);
2230
+ yield this.setUserId(res.userId);
2231
+ return res;
2232
+ });
2079
2233
  }
2080
2234
  /**
2081
2235
  * Returns whether or not the user is connected with an external wallet.
@@ -2089,18 +2243,22 @@ var ParaCore = class _ParaCore {
2089
2243
  * @param {string} verificationCode the six-digit code to check
2090
2244
  * @returns {string} the web auth url for creating a new credential
2091
2245
  */
2092
- async verifyEmail({ verificationCode }) {
2093
- await this.ctx.client.verifyEmail(this.userId, { verificationCode });
2094
- return this.getSetUpBiometricsURL();
2095
- }
2096
- async verifyExternalWallet({
2097
- address,
2098
- signedMessage,
2099
- cosmosPublicKeyHex,
2100
- cosmosSigner
2101
- }) {
2102
- await this.ctx.client.verifyExternalWallet(this.userId, { address, signedMessage, cosmosPublicKeyHex, cosmosSigner });
2103
- return this.getSetUpBiometricsURL();
2246
+ verifyEmail(_0) {
2247
+ return __async(this, arguments, function* ({ verificationCode }) {
2248
+ yield this.ctx.client.verifyEmail(this.userId, { verificationCode });
2249
+ return this.getSetUpBiometricsURL();
2250
+ });
2251
+ }
2252
+ verifyExternalWallet(_0) {
2253
+ return __async(this, arguments, function* ({
2254
+ address,
2255
+ signedMessage,
2256
+ cosmosPublicKeyHex,
2257
+ cosmosSigner
2258
+ }) {
2259
+ yield this.ctx.client.verifyExternalWallet(this.userId, { address, signedMessage, cosmosPublicKeyHex, cosmosSigner });
2260
+ return this.getSetUpBiometricsURL();
2261
+ });
2104
2262
  }
2105
2263
  /**
2106
2264
  * Passes the phone code obtained from the user for verification.
@@ -2108,9 +2266,11 @@ var ParaCore = class _ParaCore {
2108
2266
  * @param {string} verificationCode the six-digit code to check
2109
2267
  * @returns {string} the web auth url for creating a new credential
2110
2268
  */
2111
- async verifyPhone({ verificationCode }) {
2112
- await this.ctx.client.verifyPhone(this.userId, { verificationCode });
2113
- return this.getSetUpBiometricsURLForPhone();
2269
+ verifyPhone(_0) {
2270
+ return __async(this, arguments, function* ({ verificationCode }) {
2271
+ yield this.ctx.client.verifyPhone(this.userId, { verificationCode });
2272
+ return this.getSetUpBiometricsURLForPhone();
2273
+ });
2114
2274
  }
2115
2275
  /**
2116
2276
  * Validates the response received from an attempted Telegram login for authenticity, then
@@ -2118,17 +2278,19 @@ var ParaCore = class _ParaCore {
2118
2278
  * @param authResponse - the response JSON object received from the Telegram widget.
2119
2279
  * @returns `{ isValid: boolean; telegramUserId?: string; userId?: string; isNewUser?: boolean; supportedAuthMethods?: AuthMethod[]; biometricHints?: BiometricLocationHint[] }`
2120
2280
  */
2121
- async verifyTelegram(authObject) {
2122
- const res = await this.ctx.client.verifyTelegram(authObject);
2123
- if (res.isValid) {
2124
- await this.setUserId(res.userId);
2125
- await this.setTelegramUserId(res.telegramUserId);
2126
- await this.touchSession(true);
2127
- if (!this.loginEncryptionKeyPair) {
2128
- await this.setLoginEncryptionKeyPair();
2281
+ verifyTelegram(authObject) {
2282
+ return __async(this, null, function* () {
2283
+ const res = yield this.ctx.client.verifyTelegram(authObject);
2284
+ if (res.isValid) {
2285
+ yield this.setUserId(res.userId);
2286
+ yield this.setTelegramUserId(res.telegramUserId);
2287
+ yield this.touchSession(true);
2288
+ if (!this.loginEncryptionKeyPair) {
2289
+ yield this.setLoginEncryptionKeyPair();
2290
+ }
2129
2291
  }
2130
- }
2131
- return res;
2292
+ return res;
2293
+ });
2132
2294
  }
2133
2295
  /**
2134
2296
  * Performs 2FA verification.
@@ -2137,14 +2299,16 @@ var ParaCore = class _ParaCore {
2137
2299
  * @param {string} opts.verificationCode the verification code to received via 2FA.
2138
2300
  * @returns {Object} `{ address, initiatedAt, status, userId, walletId }`
2139
2301
  */
2140
- async verify2FA({ email, verificationCode }) {
2141
- const res = await this.ctx.client.verify2FA(email, verificationCode);
2142
- return {
2143
- initiatedAt: res.data.initiatedAt,
2144
- status: res.data.status,
2145
- userId: res.data.userId,
2146
- wallets: res.data.wallets
2147
- };
2302
+ verify2FA(_0) {
2303
+ return __async(this, arguments, function* ({ email, verificationCode }) {
2304
+ const res = yield this.ctx.client.verify2FA(email, verificationCode);
2305
+ return {
2306
+ initiatedAt: res.data.initiatedAt,
2307
+ status: res.data.status,
2308
+ userId: res.data.userId,
2309
+ wallets: res.data.wallets
2310
+ };
2311
+ });
2148
2312
  }
2149
2313
  /**
2150
2314
  * Performs 2FA verification.
@@ -2154,65 +2318,76 @@ var ParaCore = class _ParaCore {
2154
2318
  * @param {string} opts.verificationCode - verification code to received via 2FA.
2155
2319
  * @returns {Object} `{ address, initiatedAt, status, userId, walletId }`
2156
2320
  */
2157
- async verify2FAForPhone({
2158
- phone,
2159
- countryCode,
2160
- verificationCode
2161
- }) {
2162
- const res = await this.ctx.client.verify2FAForPhone(phone, countryCode, verificationCode);
2163
- return {
2164
- initiatedAt: res.data.initiatedAt,
2165
- status: res.data.status,
2166
- userId: res.data.userId,
2167
- wallets: res.data.wallets
2168
- };
2321
+ verify2FAForPhone(_0) {
2322
+ return __async(this, arguments, function* ({
2323
+ phone,
2324
+ countryCode,
2325
+ verificationCode
2326
+ }) {
2327
+ const res = yield this.ctx.client.verify2FAForPhone(phone, countryCode, verificationCode);
2328
+ return {
2329
+ initiatedAt: res.data.initiatedAt,
2330
+ status: res.data.status,
2331
+ userId: res.data.userId,
2332
+ wallets: res.data.wallets
2333
+ };
2334
+ });
2169
2335
  }
2170
2336
  /**
2171
2337
  * Sets up two-factor authentication for the current user.
2172
2338
  * @returns {string} uri - uri to use for setting up 2FA
2173
2339
  * */
2174
- async setup2FA() {
2175
- const res = await this.ctx.client.setup2FA(this.userId);
2176
- return {
2177
- uri: res.data.uri
2178
- };
2340
+ setup2FA() {
2341
+ return __async(this, null, function* () {
2342
+ const res = yield this.ctx.client.setup2FA(this.userId);
2343
+ return {
2344
+ uri: res.data.uri
2345
+ };
2346
+ });
2179
2347
  }
2180
2348
  /**
2181
2349
  * Enables 2FA.
2182
2350
  * @param {Object} opts the options object
2183
2351
  * @param {string} opts.verificationCode - the verification code received via 2FA.
2184
2352
  */
2185
- async enable2FA({ verificationCode }) {
2186
- await this.ctx.client.enable2FA(this.userId, verificationCode);
2353
+ enable2FA(_0) {
2354
+ return __async(this, arguments, function* ({ verificationCode }) {
2355
+ yield this.ctx.client.enable2FA(this.userId, verificationCode);
2356
+ });
2187
2357
  }
2188
2358
  /**
2189
2359
  * Determines if 2FA has been set up.
2190
2360
  * @returns {Object} `{ isSetup: boolean }` - true if 2FA is setup, false otherwise
2191
2361
  */
2192
- async check2FAStatus() {
2193
- if (!this.userId) {
2194
- return { isSetup: false };
2195
- }
2196
- const res = await this.ctx.client.check2FAStatus(this.userId);
2197
- return {
2198
- isSetup: res.data.isSetup
2199
- };
2362
+ check2FAStatus() {
2363
+ return __async(this, null, function* () {
2364
+ if (!this.userId) {
2365
+ return { isSetup: false };
2366
+ }
2367
+ const res = yield this.ctx.client.check2FAStatus(this.userId);
2368
+ return {
2369
+ isSetup: res.data.isSetup
2370
+ };
2371
+ });
2200
2372
  }
2201
2373
  /**
2202
2374
  * Resend a verification email for the current user.
2203
2375
  */
2204
- async resendVerificationCode() {
2205
- await this.ctx.client.resendVerificationCode({
2206
- userId: this.userId,
2207
- ...this.getVerificationEmailProps()
2376
+ resendVerificationCode() {
2377
+ return __async(this, null, function* () {
2378
+ yield this.ctx.client.resendVerificationCode(__spreadValues({
2379
+ userId: this.userId
2380
+ }, this.getVerificationEmailProps()));
2208
2381
  });
2209
2382
  }
2210
2383
  /**
2211
2384
  * Resend a verification SMS for the current user.
2212
2385
  */
2213
- async resendVerificationCodeByPhone() {
2214
- await this.ctx.client.resendVerificationCodeByPhone({
2215
- userId: this.userId
2386
+ resendVerificationCodeByPhone() {
2387
+ return __async(this, null, function* () {
2388
+ yield this.ctx.client.resendVerificationCodeByPhone({
2389
+ userId: this.userId
2390
+ });
2216
2391
  });
2217
2392
  }
2218
2393
  /**
@@ -2222,19 +2397,21 @@ var ParaCore = class _ParaCore {
2222
2397
  * @param {boolean} opts.isForNewDevice whether the passkey is for a new device of an existing user
2223
2398
  * @returns {string} the URL
2224
2399
  */
2225
- async getSetUpBiometricsURL({
2226
- authType = "email",
2227
- isForNewDevice = false
2228
- } = {}) {
2229
- const res = await this.ctx.client.addSessionPublicKey(this.userId, {
2230
- status: PublicKeyStatus.PENDING,
2231
- type: PublicKeyType.WEB
2232
- });
2233
- return this.getWebAuthURLForCreate({
2234
- authType,
2235
- isForNewDevice,
2236
- webAuthId: res.data.id,
2237
- partnerId: res.data.partnerId
2400
+ getSetUpBiometricsURL() {
2401
+ return __async(this, arguments, function* ({
2402
+ authType = "email",
2403
+ isForNewDevice = false
2404
+ } = {}) {
2405
+ const res = yield this.ctx.client.addSessionPublicKey(this.userId, {
2406
+ status: PublicKeyStatus.PENDING,
2407
+ type: PublicKeyType.WEB
2408
+ });
2409
+ return this.getWebAuthURLForCreate({
2410
+ authType,
2411
+ isForNewDevice,
2412
+ webAuthId: res.data.id,
2413
+ partnerId: res.data.partnerId
2414
+ });
2238
2415
  });
2239
2416
  }
2240
2417
  /**
@@ -2243,18 +2420,20 @@ var ParaCore = class _ParaCore {
2243
2420
  * @param {boolean} opts.isForNewDevice whether the passkey is for a new device of an existing user
2244
2421
  * @returns {string} the URL
2245
2422
  */
2246
- async getSetUpBiometricsURLForPhone({
2247
- isForNewDevice = false
2248
- } = {}) {
2249
- const res = await this.ctx.client.addSessionPublicKey(this.userId, {
2250
- status: PublicKeyStatus.PENDING,
2251
- type: PublicKeyType.WEB
2252
- });
2253
- return this.getWebAuthURLForCreate({
2254
- authType: "phone",
2255
- isForNewDevice,
2256
- webAuthId: res.data.id,
2257
- partnerId: res.data.partnerId
2423
+ getSetUpBiometricsURLForPhone() {
2424
+ return __async(this, arguments, function* ({
2425
+ isForNewDevice = false
2426
+ } = {}) {
2427
+ const res = yield this.ctx.client.addSessionPublicKey(this.userId, {
2428
+ status: PublicKeyStatus.PENDING,
2429
+ type: PublicKeyType.WEB
2430
+ });
2431
+ return this.getWebAuthURLForCreate({
2432
+ authType: "phone",
2433
+ isForNewDevice,
2434
+ webAuthId: res.data.id,
2435
+ partnerId: res.data.partnerId
2436
+ });
2258
2437
  });
2259
2438
  }
2260
2439
  /**
@@ -2265,95 +2444,107 @@ var ParaCore = class _ParaCore {
2265
2444
  * @param {Theme} [opts.theme] the portal theme to use in place of the partner's default
2266
2445
  * @returns {string} the URL
2267
2446
  */
2268
- async getSetupPasswordURL({
2269
- authType = "email",
2270
- isForNewDevice = false,
2271
- theme
2272
- } = {}) {
2273
- const res = await this.ctx.client.addSessionPasswordPublicKey(this.userId, {
2274
- status: PasswordStatus.PENDING
2275
- });
2276
- return this.getPasswordURLForCreate({
2277
- authType,
2278
- isForNewDevice,
2279
- passwordId: res.data.id,
2280
- partnerId: res.data.partnerId,
2447
+ getSetupPasswordURL() {
2448
+ return __async(this, arguments, function* ({
2449
+ authType = "email",
2450
+ isForNewDevice = false,
2281
2451
  theme
2452
+ } = {}) {
2453
+ const res = yield this.ctx.client.addSessionPasswordPublicKey(this.userId, {
2454
+ status: PasswordStatus.PENDING
2455
+ });
2456
+ return this.getPasswordURLForCreate({
2457
+ authType,
2458
+ isForNewDevice,
2459
+ passwordId: res.data.id,
2460
+ partnerId: res.data.partnerId,
2461
+ theme
2462
+ });
2282
2463
  });
2283
2464
  }
2284
2465
  /**
2285
2466
  * Checks if the current session is active.
2286
2467
  * @returns `true` if active, `false` otherwise
2287
2468
  */
2288
- async isSessionActive() {
2289
- if (this.isUsingExternalWallet()) {
2290
- return true;
2291
- }
2292
- const res = await this.touchSession();
2293
- return !!res.data.isAuthenticated;
2469
+ isSessionActive() {
2470
+ return __async(this, null, function* () {
2471
+ if (this.isUsingExternalWallet()) {
2472
+ return true;
2473
+ }
2474
+ const res = yield this.touchSession();
2475
+ return !!res.data.isAuthenticated;
2476
+ });
2294
2477
  }
2295
2478
  /**
2296
2479
  * Checks if a session is active and a wallet exists.
2297
2480
  * @returns `true` if active, `false` otherwise
2298
2481
  **/
2299
- async isFullyLoggedIn() {
2300
- if (this.isUsingExternalWallet()) {
2301
- return true;
2302
- }
2303
- const isSessionActive = await this.isSessionActive();
2304
- return isSessionActive && this.currentWalletIdsArray.length > 0 && this.currentWalletIdsArray.reduce((acc, [id]) => acc && !!this.wallets[id], true);
2482
+ isFullyLoggedIn() {
2483
+ return __async(this, null, function* () {
2484
+ if (this.isUsingExternalWallet()) {
2485
+ return true;
2486
+ }
2487
+ const isSessionActive = yield this.isSessionActive();
2488
+ return isSessionActive && this.currentWalletIdsArray.length > 0 && this.currentWalletIdsArray.reduce((acc, [id]) => acc && !!this.wallets[id], true);
2489
+ });
2305
2490
  }
2306
- async supportedAuthMethods(auth) {
2307
- const { supportedAuthMethods } = await this.ctx.client.getSupportedAuthMethods(auth);
2308
- const authMethods = /* @__PURE__ */ new Set();
2309
- for (const type of supportedAuthMethods) {
2310
- switch (type) {
2311
- case "PASSWORD":
2312
- authMethods.add(AuthMethod.PASSWORD);
2313
- break;
2314
- case "BIOMETRIC":
2315
- authMethods.add(AuthMethod.PASSKEY);
2316
- break;
2491
+ supportedAuthMethods(auth) {
2492
+ return __async(this, null, function* () {
2493
+ const { supportedAuthMethods } = yield this.ctx.client.getSupportedAuthMethods(auth);
2494
+ const authMethods = /* @__PURE__ */ new Set();
2495
+ for (const type of supportedAuthMethods) {
2496
+ switch (type) {
2497
+ case "PASSWORD":
2498
+ authMethods.add(AuthMethod.PASSWORD);
2499
+ break;
2500
+ case "BIOMETRIC":
2501
+ authMethods.add(AuthMethod.PASSKEY);
2502
+ break;
2503
+ }
2317
2504
  }
2318
- }
2319
- return authMethods;
2505
+ return authMethods;
2506
+ });
2320
2507
  }
2321
2508
  /**
2322
2509
  * Get hints associated with the users stored biometrics.
2323
2510
  * @returns Array containing useragents and AAGuids for stored biometrics
2324
2511
  */
2325
- async getUserBiometricLocationHints() {
2326
- if (!this.email && !this.phone && !this.farcasterUsername && !this.telegramUserId) {
2327
- throw new Error("one of email, phone or farcaster username are required to get biometric location hints");
2328
- }
2329
- return await this.ctx.client.getBiometricLocationHints({
2330
- email: this.email,
2331
- phone: this.phone,
2332
- countryCode: this.countryCode,
2333
- farcasterUsername: this.farcasterUsername,
2334
- telegramUserId: this.telegramUserId
2512
+ getUserBiometricLocationHints() {
2513
+ return __async(this, null, function* () {
2514
+ if (!this.email && !this.phone && !this.farcasterUsername && !this.telegramUserId) {
2515
+ throw new Error("one of email, phone or farcaster username are required to get biometric location hints");
2516
+ }
2517
+ return yield this.ctx.client.getBiometricLocationHints({
2518
+ email: this.email,
2519
+ phone: this.phone,
2520
+ countryCode: this.countryCode,
2521
+ farcasterUsername: this.farcasterUsername,
2522
+ telegramUserId: this.telegramUserId
2523
+ });
2335
2524
  });
2336
2525
  }
2337
- async setAuth(auth) {
2338
- const authInfo = extractAuthInfo(auth);
2339
- if (!authInfo) {
2340
- return void 0;
2341
- }
2342
- switch (authInfo.authType) {
2343
- case "email":
2344
- await this.setEmail(authInfo.identifier);
2345
- break;
2346
- case "phone":
2347
- await this.setPhoneNumber(authInfo.auth.phone, authInfo.auth.countryCode);
2348
- break;
2349
- case "farcaster":
2350
- await this.setFarcasterUsername(authInfo.identifier);
2351
- break;
2352
- case "telegram":
2353
- await this.setTelegramUserId(authInfo.identifier);
2354
- break;
2355
- }
2356
- return authInfo;
2526
+ setAuth(auth) {
2527
+ return __async(this, null, function* () {
2528
+ const authInfo = extractAuthInfo(auth);
2529
+ if (!authInfo) {
2530
+ return void 0;
2531
+ }
2532
+ switch (authInfo.authType) {
2533
+ case "email":
2534
+ yield this.setEmail(authInfo.identifier);
2535
+ break;
2536
+ case "phone":
2537
+ yield this.setPhoneNumber(authInfo.auth.phone, authInfo.auth.countryCode);
2538
+ break;
2539
+ case "farcaster":
2540
+ yield this.setFarcasterUsername(authInfo.identifier);
2541
+ break;
2542
+ case "telegram":
2543
+ yield this.setTelegramUserId(authInfo.identifier);
2544
+ break;
2545
+ }
2546
+ return authInfo;
2547
+ });
2357
2548
  }
2358
2549
  /**
2359
2550
  * Initiates a login.
@@ -2362,41 +2553,46 @@ var ParaCore = class _ParaCore {
2362
2553
  * @param {boolean} opts.useShortURL - whether to shorten the link
2363
2554
  * @returns - the WebAuth URL for logging in
2364
2555
  **/
2365
- async initiateUserLogin({ useShortUrl = false, ...auth }) {
2366
- const authInfo = await this.setAuth(auth);
2367
- if (!authInfo) {
2368
- return;
2369
- }
2370
- const res = await this.touchSession(true);
2371
- if (!this.loginEncryptionKeyPair) {
2372
- await this.setLoginEncryptionKeyPair();
2373
- }
2374
- const webAuthLoginURL = await this.getWebAuthURLForLogin({
2375
- authType: authInfo.authType,
2376
- sessionId: res.data.sessionId,
2377
- partnerId: res.data.partnerId,
2378
- loginEncryptionPublicKey: getPublicKeyHex(this.loginEncryptionKeyPair)
2379
- });
2380
- if (!useShortUrl) {
2381
- return webAuthLoginURL;
2382
- }
2383
- return this.shortenLoginLink(webAuthLoginURL);
2556
+ initiateUserLogin(_e) {
2557
+ return __async(this, null, function* () {
2558
+ var _f = _e, { useShortUrl = false } = _f, auth = __objRest(_f, ["useShortUrl"]);
2559
+ const authInfo = yield this.setAuth(auth);
2560
+ if (!authInfo) {
2561
+ return;
2562
+ }
2563
+ const res = yield this.touchSession(true);
2564
+ if (!this.loginEncryptionKeyPair) {
2565
+ yield this.setLoginEncryptionKeyPair();
2566
+ }
2567
+ const webAuthLoginURL = yield this.getWebAuthURLForLogin({
2568
+ authType: authInfo.authType,
2569
+ sessionId: res.data.sessionId,
2570
+ partnerId: res.data.partnerId,
2571
+ loginEncryptionPublicKey: getPublicKeyHex(this.loginEncryptionKeyPair)
2572
+ });
2573
+ if (!useShortUrl) {
2574
+ return webAuthLoginURL;
2575
+ }
2576
+ return this.shortenLoginLink(webAuthLoginURL);
2577
+ });
2384
2578
  }
2385
2579
  /**
2386
2580
  * Initiates a login.
2387
2581
  * @param email - the email to login with
2388
2582
  * @returns - a set of supported auth methods for the user
2389
2583
  **/
2390
- async initiateUserLoginV2(auth) {
2391
- const authInfo = await this.setAuth(auth);
2392
- if (!authInfo) {
2393
- return;
2394
- }
2395
- await this.touchSession(true);
2396
- if (!this.loginEncryptionKeyPair) {
2397
- await this.setLoginEncryptionKeyPair();
2398
- }
2399
- return await this.supportedAuthMethods(authInfo.auth);
2584
+ initiateUserLoginV2(auth) {
2585
+ return __async(this, null, function* () {
2586
+ const authInfo = yield this.setAuth(auth);
2587
+ if (!authInfo) {
2588
+ return;
2589
+ }
2590
+ yield this.touchSession(true);
2591
+ if (!this.loginEncryptionKeyPair) {
2592
+ yield this.setLoginEncryptionKeyPair();
2593
+ }
2594
+ return yield this.supportedAuthMethods(authInfo.auth);
2595
+ });
2400
2596
  }
2401
2597
  /**
2402
2598
  * Initiates a login.
@@ -2406,112 +2602,124 @@ var ParaCore = class _ParaCore {
2406
2602
  * @param opts.useShortURL - whether to shorten the link
2407
2603
  * @returns - the WebAuth URL for logging in
2408
2604
  **/
2409
- async initiateUserLoginForPhone({
2410
- useShortUrl = false,
2411
- ...auth
2412
- }) {
2413
- await this.setAuth(auth);
2414
- const res = await this.touchSession(true);
2415
- if (!this.loginEncryptionKeyPair) {
2416
- await this.setLoginEncryptionKeyPair();
2417
- }
2418
- const webAuthLoginURL = await this.getWebAuthURLForLoginForPhone({
2419
- sessionId: res.data.sessionId,
2420
- loginEncryptionPublicKey: getPublicKeyHex(this.loginEncryptionKeyPair),
2421
- partnerId: res.data.partnerId
2605
+ initiateUserLoginForPhone(_g) {
2606
+ return __async(this, null, function* () {
2607
+ var _h = _g, {
2608
+ useShortUrl = false
2609
+ } = _h, auth = __objRest(_h, [
2610
+ "useShortUrl"
2611
+ ]);
2612
+ yield this.setAuth(auth);
2613
+ const res = yield this.touchSession(true);
2614
+ if (!this.loginEncryptionKeyPair) {
2615
+ yield this.setLoginEncryptionKeyPair();
2616
+ }
2617
+ const webAuthLoginURL = yield this.getWebAuthURLForLoginForPhone({
2618
+ sessionId: res.data.sessionId,
2619
+ loginEncryptionPublicKey: getPublicKeyHex(this.loginEncryptionKeyPair),
2620
+ partnerId: res.data.partnerId
2621
+ });
2622
+ if (!useShortUrl) {
2623
+ return webAuthLoginURL;
2624
+ }
2625
+ return this.shortenLoginLink(webAuthLoginURL);
2422
2626
  });
2423
- if (!useShortUrl) {
2424
- return webAuthLoginURL;
2425
- }
2426
- return this.shortenLoginLink(webAuthLoginURL);
2427
2627
  }
2428
2628
  /**
2429
2629
  * Waits for the session to be active.
2430
2630
  **/
2431
- async waitForAccountCreation({ popupWindow } = {}) {
2432
- await this.touchSession();
2433
- this.externalWallets = {};
2434
- this.isAwaitingAccountCreation = true;
2435
- while (this.isAwaitingAccountCreation) {
2436
- try {
2437
- await new Promise((resolve) => setTimeout(resolve, POLLING_INTERVAL_MS));
2438
- if (await this.isSessionActive()) {
2439
- this.isAwaitingAccountCreation = false;
2440
- dispatchEvent(ParaEvent.ACCOUNT_CREATION_EVENT, true);
2441
- return true;
2442
- } else {
2443
- if (popupWindow?.closed) {
2631
+ waitForAccountCreation() {
2632
+ return __async(this, arguments, function* ({ popupWindow } = {}) {
2633
+ yield this.touchSession();
2634
+ this.externalWallets = {};
2635
+ this.isAwaitingAccountCreation = true;
2636
+ while (this.isAwaitingAccountCreation) {
2637
+ try {
2638
+ yield new Promise((resolve) => setTimeout(resolve, POLLING_INTERVAL_MS));
2639
+ if (yield this.isSessionActive()) {
2444
2640
  this.isAwaitingAccountCreation = false;
2445
- return false;
2641
+ dispatchEvent(ParaEvent.ACCOUNT_CREATION_EVENT, true);
2642
+ return true;
2643
+ } else {
2644
+ if (popupWindow == null ? void 0 : popupWindow.closed) {
2645
+ this.isAwaitingAccountCreation = false;
2646
+ return false;
2647
+ }
2446
2648
  }
2649
+ } catch (err) {
2650
+ console.error(err);
2447
2651
  }
2448
- } catch (err) {
2449
- console.error(err);
2450
2652
  }
2451
- }
2452
- return false;
2653
+ return false;
2654
+ });
2453
2655
  }
2454
- async waitForPasskeyAndCreateWallet({
2455
- popupWindow
2456
- } = {}) {
2457
- await this.waitForAccountCreation({ popupWindow });
2458
- const pregenWallets = await this.getPregenWallets();
2459
- let recoverySecret, walletIds = {};
2460
- if (pregenWallets.length > 0) {
2461
- recoverySecret = await this.claimPregenWallets();
2462
- walletIds = this.supportedWalletTypes.reduce((acc, { type }) => {
2463
- return {
2464
- ...acc,
2465
- [type]: [pregenWallets.find((w) => !!WalletSchemeTypeMap[w.scheme][type])?.id]
2466
- };
2467
- }, {});
2468
- }
2469
- const created = await this.createWalletPerType();
2470
- recoverySecret = recoverySecret ?? created.recoverySecret;
2471
- walletIds = { ...walletIds, ...created.walletIds };
2472
- const resp = { walletIds, recoverySecret };
2473
- dispatchEvent(ParaEvent.ACCOUNT_SETUP_EVENT, resp);
2474
- return resp;
2656
+ waitForPasskeyAndCreateWallet() {
2657
+ return __async(this, arguments, function* ({
2658
+ popupWindow
2659
+ } = {}) {
2660
+ yield this.waitForAccountCreation({ popupWindow });
2661
+ const pregenWallets = yield this.getPregenWallets();
2662
+ let recoverySecret, walletIds = {};
2663
+ if (pregenWallets.length > 0) {
2664
+ recoverySecret = yield this.claimPregenWallets();
2665
+ walletIds = this.supportedWalletTypes.reduce((acc, { type }) => {
2666
+ var _a;
2667
+ return __spreadProps(__spreadValues({}, acc), {
2668
+ [type]: [(_a = pregenWallets.find((w) => !!WalletSchemeTypeMap[w.scheme][type])) == null ? void 0 : _a.id]
2669
+ });
2670
+ }, {});
2671
+ }
2672
+ const created = yield this.createWalletPerType();
2673
+ recoverySecret = recoverySecret != null ? recoverySecret : created.recoverySecret;
2674
+ walletIds = __spreadValues(__spreadValues({}, walletIds), created.walletIds);
2675
+ const resp = { walletIds, recoverySecret };
2676
+ dispatchEvent(ParaEvent.ACCOUNT_SETUP_EVENT, resp);
2677
+ return resp;
2678
+ });
2475
2679
  }
2476
2680
  /**
2477
2681
  * Initiates a Farcaster login attempt and return the URI for the user to connect.
2478
2682
  * You can create a QR code with this URI that works with Farcaster's mobile app.
2479
2683
  * @return {string} the Farcaster connect URI
2480
2684
  */
2481
- async getFarcasterConnectURL() {
2482
- await this.logout();
2483
- await this.touchSession(true);
2484
- const {
2485
- data: { connect_uri }
2486
- } = await this.ctx.client.initializeFarcasterLogin();
2487
- return connect_uri;
2685
+ getFarcasterConnectURL() {
2686
+ return __async(this, null, function* () {
2687
+ yield this.logout();
2688
+ yield this.touchSession(true);
2689
+ const {
2690
+ data: { connect_uri }
2691
+ } = yield this.ctx.client.initializeFarcasterLogin();
2692
+ return connect_uri;
2693
+ });
2488
2694
  }
2489
2695
  /**
2490
2696
  * Awaits the response from a user's attempt to log in with Farcaster.
2491
2697
  * If successful, this returns the user's Farcaster username and profile picture and indicates whether the user already exists.
2492
2698
  * @return {Object} `{userExists: boolean; username: string; pfpUrl?: string | null }` - the user's information and whether the user already exists.
2493
2699
  */
2494
- async waitForFarcasterStatus() {
2495
- this.isAwaitingFarcaster = true;
2496
- while (this.isAwaitingFarcaster) {
2497
- try {
2498
- await new Promise((resolve) => setTimeout(resolve, POLLING_INTERVAL_MS));
2499
- const res = await this.ctx.client.getFarcasterAuthStatus();
2500
- if (res.data.state === "completed") {
2501
- const { userId, userExists, username, pfpUrl } = res.data;
2502
- await this.setUserId(userId);
2503
- await this.setFarcasterUsername(username);
2504
- return {
2505
- userExists,
2506
- username,
2507
- pfpUrl
2508
- };
2700
+ waitForFarcasterStatus() {
2701
+ return __async(this, null, function* () {
2702
+ this.isAwaitingFarcaster = true;
2703
+ while (this.isAwaitingFarcaster) {
2704
+ try {
2705
+ yield new Promise((resolve) => setTimeout(resolve, POLLING_INTERVAL_MS));
2706
+ const res = yield this.ctx.client.getFarcasterAuthStatus();
2707
+ if (res.data.state === "completed") {
2708
+ const { userId, userExists, username, pfpUrl } = res.data;
2709
+ yield this.setUserId(userId);
2710
+ yield this.setFarcasterUsername(username);
2711
+ return {
2712
+ userExists,
2713
+ username,
2714
+ pfpUrl
2715
+ };
2716
+ }
2717
+ } catch (err) {
2718
+ console.error(err);
2719
+ this.isAwaitingFarcaster = false;
2509
2720
  }
2510
- } catch (err) {
2511
- console.error(err);
2512
- this.isAwaitingFarcaster = false;
2513
2721
  }
2514
- }
2722
+ });
2515
2723
  }
2516
2724
  /**
2517
2725
  * Generates a URL for the user to log in with OAuth using a desire method.
@@ -2521,17 +2729,19 @@ var ParaCore = class _ParaCore {
2521
2729
  * @param {string} [opts.deeplinkUrl] the deeplink to redirect to after the OAuth flow. This is for mobile only.
2522
2730
  * @returns {string} the URL for the user to log in with OAuth.
2523
2731
  */
2524
- async getOAuthURL({ method, deeplinkUrl }) {
2525
- await this.logout();
2526
- const res = await this.touchSession(true);
2527
- return constructUrl({
2528
- base: method === OAuthMethod.TELEGRAM ? getPortalBaseURL(this.ctx, true) : getBaseOAuthUrl(this.ctx.env),
2529
- path: `/auth/${method.toLowerCase()}`,
2530
- params: {
2531
- apiKey: this.ctx.apiKey,
2532
- sessionLookupId: res.data.sessionLookupId,
2533
- deeplinkUrl
2534
- }
2732
+ getOAuthURL(_0) {
2733
+ return __async(this, arguments, function* ({ method, deeplinkUrl }) {
2734
+ yield this.logout();
2735
+ const res = yield this.touchSession(true);
2736
+ return constructUrl({
2737
+ base: method === OAuthMethod.TELEGRAM ? getPortalBaseURL(this.ctx, true) : getBaseOAuthUrl(this.ctx.env),
2738
+ path: `/auth/${method.toLowerCase()}`,
2739
+ params: {
2740
+ apiKey: this.ctx.apiKey,
2741
+ sessionLookupId: res.data.sessionLookupId,
2742
+ deeplinkUrl
2743
+ }
2744
+ });
2535
2745
  });
2536
2746
  }
2537
2747
  /**
@@ -2542,36 +2752,38 @@ var ParaCore = class _ParaCore {
2542
2752
  * @param {Window} [opts.popupWindow] the popup window being used for login.
2543
2753
  * @return {Object} `{ email?: string; isError?: boolean; userExists: boolean; }` the result data
2544
2754
  */
2545
- async waitForOAuth({ popupWindow } = {}) {
2546
- this.isAwaitingOAuth = true;
2547
- while (this.isAwaitingOAuth) {
2548
- try {
2549
- if (popupWindow?.closed) {
2550
- return { isError: true, userExists: false };
2551
- }
2552
- await new Promise((resolve) => setTimeout(resolve, POLLING_INTERVAL_MS));
2553
- if (this.isAwaitingOAuth) {
2554
- const res = await this.touchSession();
2555
- if (res.data.userId) {
2556
- const { userId, email } = res.data;
2557
- if (!this.loginEncryptionKeyPair) {
2558
- await this.setLoginEncryptionKeyPair();
2755
+ waitForOAuth() {
2756
+ return __async(this, arguments, function* ({ popupWindow } = {}) {
2757
+ this.isAwaitingOAuth = true;
2758
+ while (this.isAwaitingOAuth) {
2759
+ try {
2760
+ if (popupWindow == null ? void 0 : popupWindow.closed) {
2761
+ return { isError: true, userExists: false };
2762
+ }
2763
+ yield new Promise((resolve) => setTimeout(resolve, POLLING_INTERVAL_MS));
2764
+ if (this.isAwaitingOAuth) {
2765
+ const res = yield this.touchSession();
2766
+ if (res.data.userId) {
2767
+ const { userId, email } = res.data;
2768
+ if (!this.loginEncryptionKeyPair) {
2769
+ yield this.setLoginEncryptionKeyPair();
2770
+ }
2771
+ yield this.setUserId(userId);
2772
+ yield this.setEmail(email);
2773
+ const userExists = yield this.checkIfUserExists({ email });
2774
+ this.isAwaitingOAuth = false;
2775
+ return {
2776
+ userExists,
2777
+ email
2778
+ };
2559
2779
  }
2560
- await this.setUserId(userId);
2561
- await this.setEmail(email);
2562
- const userExists = await this.checkIfUserExists({ email });
2563
- this.isAwaitingOAuth = false;
2564
- return {
2565
- userExists,
2566
- email
2567
- };
2568
2780
  }
2781
+ } catch (err) {
2782
+ console.error(err);
2569
2783
  }
2570
- } catch (err) {
2571
- console.error(err);
2572
2784
  }
2573
- }
2574
- return { userExists: false };
2785
+ return { userExists: false };
2786
+ });
2575
2787
  }
2576
2788
  /**
2577
2789
  * Waits for the session to be active and sets up the user.
@@ -2581,56 +2793,59 @@ var ParaCore = class _ParaCore {
2581
2793
  * @param {boolean} [opts.skipSessionRefresh] whether to skip refreshing the session.
2582
2794
  * @returns {Object} `{ isComplete: boolean; isError: boolean; needsWallet: boolean; partnerId: string; }` the result data
2583
2795
  **/
2584
- async waitForLoginAndSetup({
2585
- popupWindow,
2586
- skipSessionRefresh = false
2587
- } = {}) {
2588
- this.externalWallets = {};
2589
- this.isAwaitingLogin = true;
2590
- while (this.isAwaitingLogin) {
2591
- try {
2592
- await new Promise((resolve) => setTimeout(resolve, POLLING_INTERVAL_MS));
2593
- if (!await this.isSessionActive()) {
2594
- if (popupWindow?.closed) {
2595
- const resp2 = { isComplete: false, isError: true };
2596
- dispatchEvent(ParaEvent.LOGIN_EVENT, resp2, "failed to setup user");
2597
- return resp2;
2598
- }
2599
- continue;
2600
- }
2601
- const postLoginData = await this.userSetupAfterLogin();
2602
- const needsWallet = postLoginData.data.needsWallet ?? false;
2603
- if (!needsWallet) {
2604
- if (this.currentWalletIdsArray.length === 0) {
2605
- if (popupWindow?.closed) {
2796
+ waitForLoginAndSetup() {
2797
+ return __async(this, arguments, function* ({
2798
+ popupWindow,
2799
+ skipSessionRefresh = false
2800
+ } = {}) {
2801
+ var _a;
2802
+ this.externalWallets = {};
2803
+ this.isAwaitingLogin = true;
2804
+ while (this.isAwaitingLogin) {
2805
+ try {
2806
+ yield new Promise((resolve) => setTimeout(resolve, POLLING_INTERVAL_MS));
2807
+ if (!(yield this.isSessionActive())) {
2808
+ if (popupWindow == null ? void 0 : popupWindow.closed) {
2606
2809
  const resp2 = { isComplete: false, isError: true };
2607
2810
  dispatchEvent(ParaEvent.LOGIN_EVENT, resp2, "failed to setup user");
2608
2811
  return resp2;
2609
- } else {
2610
- continue;
2611
2812
  }
2813
+ continue;
2612
2814
  }
2815
+ const postLoginData = yield this.userSetupAfterLogin();
2816
+ const needsWallet = (_a = postLoginData.data.needsWallet) != null ? _a : false;
2817
+ if (!needsWallet) {
2818
+ if (this.currentWalletIdsArray.length === 0) {
2819
+ if (popupWindow == null ? void 0 : popupWindow.closed) {
2820
+ const resp2 = { isComplete: false, isError: true };
2821
+ dispatchEvent(ParaEvent.LOGIN_EVENT, resp2, "failed to setup user");
2822
+ return resp2;
2823
+ } else {
2824
+ continue;
2825
+ }
2826
+ }
2827
+ }
2828
+ const fetchedWallets = yield this.fetchWallets();
2829
+ const tempSharesRes = yield this.getTransmissionKeyShares();
2830
+ if (tempSharesRes.data.temporaryShares.length === fetchedWallets.length) {
2831
+ yield this.setupAfterLogin({ temporaryShares: tempSharesRes.data.temporaryShares, skipSessionRefresh });
2832
+ yield this.claimPregenWallets();
2833
+ const resp2 = {
2834
+ isComplete: true,
2835
+ needsWallet: needsWallet || Object.values(this.wallets).length === 0,
2836
+ partnerId: postLoginData.data.partnerId
2837
+ };
2838
+ dispatchEvent(ParaEvent.LOGIN_EVENT, resp2);
2839
+ return resp2;
2840
+ }
2841
+ } catch (err) {
2842
+ console.error(err);
2613
2843
  }
2614
- const fetchedWallets = await this.fetchWallets();
2615
- const tempSharesRes = await this.getTransmissionKeyShares();
2616
- if (tempSharesRes.data.temporaryShares.length === fetchedWallets.length) {
2617
- await this.setupAfterLogin({ temporaryShares: tempSharesRes.data.temporaryShares, skipSessionRefresh });
2618
- await this.claimPregenWallets();
2619
- const resp2 = {
2620
- isComplete: true,
2621
- needsWallet: needsWallet || Object.values(this.wallets).length === 0,
2622
- partnerId: postLoginData.data.partnerId
2623
- };
2624
- dispatchEvent(ParaEvent.LOGIN_EVENT, resp2);
2625
- return resp2;
2626
- }
2627
- } catch (err) {
2628
- console.error(err);
2629
2844
  }
2630
- }
2631
- const resp = { isComplete: false };
2632
- dispatchEvent(ParaEvent.LOGIN_EVENT, resp, "exitted login without setting up user");
2633
- return resp;
2845
+ const resp = { isComplete: false };
2846
+ dispatchEvent(ParaEvent.LOGIN_EVENT, resp, "exitted login without setting up user");
2847
+ return resp;
2848
+ });
2634
2849
  }
2635
2850
  /**
2636
2851
  * Updates the session with the user management server, possibly
@@ -2640,32 +2855,36 @@ var ParaCore = class _ParaCore {
2640
2855
  * @param {boolean} [shouldOpenPopup] - if `true`, the running device will open a popup to reauthenticate the user.
2641
2856
  * @returns a URL for the user to reauthenticate.
2642
2857
  **/
2643
- async refreshSession({ shouldOpenPopup = false } = {}) {
2644
- const res = await this.touchSession(true);
2645
- if (!this.loginEncryptionKeyPair) {
2646
- await this.setLoginEncryptionKeyPair();
2647
- }
2648
- const link = await this.getWebAuthURLForLogin({
2649
- sessionId: res.data.sessionId,
2650
- loginEncryptionPublicKey: getPublicKeyHex(this.loginEncryptionKeyPair)
2858
+ refreshSession() {
2859
+ return __async(this, arguments, function* ({ shouldOpenPopup = false } = {}) {
2860
+ const res = yield this.touchSession(true);
2861
+ if (!this.loginEncryptionKeyPair) {
2862
+ yield this.setLoginEncryptionKeyPair();
2863
+ }
2864
+ const link = yield this.getWebAuthURLForLogin({
2865
+ sessionId: res.data.sessionId,
2866
+ loginEncryptionPublicKey: getPublicKeyHex(this.loginEncryptionKeyPair)
2867
+ });
2868
+ if (shouldOpenPopup) {
2869
+ this.platformUtils.openPopup(link);
2870
+ }
2871
+ return link;
2651
2872
  });
2652
- if (shouldOpenPopup) {
2653
- this.platformUtils.openPopup(link);
2654
- }
2655
- return link;
2656
2873
  }
2657
2874
  /**
2658
2875
  * Call this method after login to ensure that the user ID is set
2659
2876
  * internally.
2660
2877
  **/
2661
- async userSetupAfterLogin() {
2662
- const res = await this.touchSession();
2663
- await this.setUserId(res.data.userId);
2664
- if (res.data.currentWalletIds && res.data.currentWalletIds !== this.currentWalletIds)
2665
- await this.setCurrentWalletIds(res.data.currentWalletIds, {
2666
- sessionLookupId: this.isPortal() ? res.data.sessionLookupId : void 0
2667
- });
2668
- return res;
2878
+ userSetupAfterLogin() {
2879
+ return __async(this, null, function* () {
2880
+ const res = yield this.touchSession();
2881
+ yield this.setUserId(res.data.userId);
2882
+ if (res.data.currentWalletIds && res.data.currentWalletIds !== this.currentWalletIds)
2883
+ yield this.setCurrentWalletIds(res.data.currentWalletIds, {
2884
+ sessionLookupId: this.isPortal() ? res.data.sessionLookupId : void 0
2885
+ });
2886
+ return res;
2887
+ });
2669
2888
  }
2670
2889
  /**
2671
2890
  * Get transmission shares associated with session.
@@ -2673,10 +2892,12 @@ var ParaCore = class _ParaCore {
2673
2892
  * @param {boolean} opts.isForNewDevice - true if this device is registering.
2674
2893
  * @returns - transmission keyshares.
2675
2894
  **/
2676
- async getTransmissionKeyShares({ isForNewDevice = false } = {}) {
2677
- const res = await this.touchSession();
2678
- const sessionLookupId = isForNewDevice ? `${res.data.sessionLookupId}-new-device` : res.data.sessionLookupId;
2679
- return this.ctx.client.getTransmissionKeyshares(this.userId, sessionLookupId);
2895
+ getTransmissionKeyShares() {
2896
+ return __async(this, arguments, function* ({ isForNewDevice = false } = {}) {
2897
+ const res = yield this.touchSession();
2898
+ const sessionLookupId = isForNewDevice ? `${res.data.sessionLookupId}-new-device` : res.data.sessionLookupId;
2899
+ return this.ctx.client.getTransmissionKeyshares(this.userId, sessionLookupId);
2900
+ });
2680
2901
  }
2681
2902
  /**
2682
2903
  * Call this method after login to perform setup.
@@ -2684,23 +2905,25 @@ var ParaCore = class _ParaCore {
2684
2905
  * @param {any[]} opts.temporaryShares optional temporary shares to use for decryption.
2685
2906
  * @param {boolean} [opts.skipSessionRefresh] - whether or not to skip refreshing the session.
2686
2907
  **/
2687
- async setupAfterLogin({
2688
- temporaryShares,
2689
- skipSessionRefresh = false
2690
- } = {}) {
2691
- if (!temporaryShares) {
2692
- temporaryShares = (await this.getTransmissionKeyShares()).data.temporaryShares;
2693
- }
2694
- temporaryShares.forEach((share) => {
2695
- const signer = decryptWithPrivateKey(this.loginEncryptionKeyPair.privateKey, share.encryptedShare, share.encryptedKey);
2696
- this.wallets[share.walletId] = {
2697
- id: share.walletId,
2698
- signer
2699
- };
2908
+ setupAfterLogin() {
2909
+ return __async(this, arguments, function* ({
2910
+ temporaryShares,
2911
+ skipSessionRefresh = false
2912
+ } = {}) {
2913
+ if (!temporaryShares) {
2914
+ temporaryShares = (yield this.getTransmissionKeyShares()).data.temporaryShares;
2915
+ }
2916
+ temporaryShares.forEach((share) => {
2917
+ const signer = decryptWithPrivateKey(this.loginEncryptionKeyPair.privateKey, share.encryptedShare, share.encryptedKey);
2918
+ this.wallets[share.walletId] = {
2919
+ id: share.walletId,
2920
+ signer
2921
+ };
2922
+ });
2923
+ yield this.deleteLoginEncryptionKeyPair();
2924
+ yield this.populateWalletAddresses();
2925
+ yield this.touchSession(!skipSessionRefresh);
2700
2926
  });
2701
- await this.deleteLoginEncryptionKeyPair();
2702
- await this.populateWalletAddresses();
2703
- await this.touchSession(!skipSessionRefresh);
2704
2927
  }
2705
2928
  /**
2706
2929
  * Distributes a new wallet recovery share.
@@ -2711,51 +2934,55 @@ var ParaCore = class _ParaCore {
2711
2934
  * @param {boolean} opts.forceRefreshRecovery whether or not to force recovery secret regeneration. Used when regenerating recovery shares.
2712
2935
  * @returns {string} the recovery share.
2713
2936
  **/
2714
- async distributeNewWalletShare({
2715
- walletId,
2716
- userShare,
2717
- skipBiometricShareCreation = false,
2718
- forceRefresh = false
2719
- }) {
2720
- let userSigner = userShare;
2721
- if (!userSigner) {
2722
- userSigner = this.wallets[walletId].signer;
2723
- }
2724
- const recoveryShare = skipBiometricShareCreation ? await sendRecoveryForShare({
2725
- ctx: this.ctx,
2726
- userId: this.userId,
2937
+ distributeNewWalletShare(_0) {
2938
+ return __async(this, arguments, function* ({
2727
2939
  walletId,
2728
- userSigner,
2729
- emailProps: this.getBackupKitEmailProps(),
2730
- forceRefresh
2731
- }) : await distributeNewShare({
2732
- ctx: this.ctx,
2733
- userId: this.userId,
2734
- walletId,
2735
- userShare: userSigner,
2736
- emailProps: this.getBackupKitEmailProps()
2940
+ userShare,
2941
+ skipBiometricShareCreation = false,
2942
+ forceRefresh = false
2943
+ }) {
2944
+ let userSigner = userShare;
2945
+ if (!userSigner) {
2946
+ userSigner = this.wallets[walletId].signer;
2947
+ }
2948
+ const recoveryShare = skipBiometricShareCreation ? yield sendRecoveryForShare({
2949
+ ctx: this.ctx,
2950
+ userId: this.userId,
2951
+ walletId,
2952
+ userSigner,
2953
+ emailProps: this.getBackupKitEmailProps(),
2954
+ forceRefresh
2955
+ }) : yield distributeNewShare({
2956
+ ctx: this.ctx,
2957
+ userId: this.userId,
2958
+ walletId,
2959
+ userShare: userSigner,
2960
+ emailProps: this.getBackupKitEmailProps()
2961
+ });
2962
+ return recoveryShare;
2737
2963
  });
2738
- return recoveryShare;
2739
2964
  }
2740
- async waitForWalletAddress(walletId) {
2741
- let maxPolls = 0;
2742
- while (true) {
2743
- try {
2744
- if (maxPolls === 10) {
2745
- break;
2746
- }
2747
- ++maxPolls;
2748
- const res = await this.ctx.client.getWallets(this.userId);
2749
- const wallet = res.data.wallets.find((w) => w.id === walletId);
2750
- if (wallet && wallet.address) {
2751
- return;
2965
+ waitForWalletAddress(walletId) {
2966
+ return __async(this, null, function* () {
2967
+ let maxPolls = 0;
2968
+ while (true) {
2969
+ try {
2970
+ if (maxPolls === 10) {
2971
+ break;
2972
+ }
2973
+ ++maxPolls;
2974
+ const res = yield this.ctx.client.getWallets(this.userId);
2975
+ const wallet = res.data.wallets.find((w) => w.id === walletId);
2976
+ if (wallet && wallet.address) {
2977
+ return;
2978
+ }
2979
+ yield new Promise((resolve) => setTimeout(resolve, SHORT_POLLING_INTERVAL_MS));
2980
+ } catch (err) {
2981
+ console.error(err);
2752
2982
  }
2753
- await new Promise((resolve) => setTimeout(resolve, SHORT_POLLING_INTERVAL_MS));
2754
- } catch (err) {
2755
- console.error(err);
2756
2983
  }
2757
- }
2758
- throw new Error("timed out waiting for wallet address");
2984
+ throw new Error("timed out waiting for wallet address");
2985
+ });
2759
2986
  }
2760
2987
  /**
2761
2988
  * Waits for a pregen wallet address to be created.
@@ -2765,25 +2992,27 @@ var ParaCore = class _ParaCore {
2765
2992
  * @param pregenIdentifierType - the identifier type of the user the pregen wallet is associated with.
2766
2993
  * @returns - recovery share.
2767
2994
  **/
2768
- async waitForPregenWalletAddress(walletId) {
2769
- let maxPolls = 0;
2770
- while (true) {
2771
- try {
2772
- if (maxPolls === 10) {
2773
- break;
2774
- }
2775
- ++maxPolls;
2776
- const res = await this.getPregenWallets();
2777
- const wallet = res.find((w) => w.id === walletId);
2778
- if (wallet && wallet.address) {
2779
- return;
2995
+ waitForPregenWalletAddress(walletId) {
2996
+ return __async(this, null, function* () {
2997
+ let maxPolls = 0;
2998
+ while (true) {
2999
+ try {
3000
+ if (maxPolls === 10) {
3001
+ break;
3002
+ }
3003
+ ++maxPolls;
3004
+ const res = yield this.getPregenWallets();
3005
+ const wallet = res.find((w) => w.id === walletId);
3006
+ if (wallet && wallet.address) {
3007
+ return;
3008
+ }
3009
+ yield new Promise((resolve) => setTimeout(resolve, SHORT_POLLING_INTERVAL_MS));
3010
+ } catch (err) {
3011
+ console.error(err);
2780
3012
  }
2781
- await new Promise((resolve) => setTimeout(resolve, SHORT_POLLING_INTERVAL_MS));
2782
- } catch (err) {
2783
- console.error(err);
2784
3013
  }
2785
- }
2786
- throw new Error("timed out waiting for wallet address");
3014
+ throw new Error("timed out waiting for wallet address");
3015
+ });
2787
3016
  }
2788
3017
  /**
2789
3018
  * Creates several new wallets with the desired types. If no types are provided, this method
@@ -2796,24 +3025,26 @@ var ParaCore = class _ParaCore {
2796
3025
  * @param {WalletType[]} [opts.types] the types of wallets to create.
2797
3026
  * @returns {Object} the wallets created, their ids, and the recovery secret.
2798
3027
  **/
2799
- async createWalletPerType({
2800
- skipDistribute = false,
2801
- types
2802
- } = {}) {
2803
- const wallets = [];
2804
- const walletIds = {};
2805
- let recoverySecret;
2806
- for (const type of await this.getTypesToCreate(types)) {
2807
- const [wallet, recoveryShare] = await this.createWallet({ type, skipDistribute });
2808
- wallets.push(wallet);
2809
- getEquivalentTypes(type).filter((t) => !!this.isWalletTypeEnabled[t]).forEach((t) => {
2810
- walletIds[t] = [wallet.id];
2811
- });
2812
- if (recoveryShare) {
2813
- recoverySecret = recoveryShare;
3028
+ createWalletPerType() {
3029
+ return __async(this, arguments, function* ({
3030
+ skipDistribute = false,
3031
+ types
3032
+ } = {}) {
3033
+ const wallets = [];
3034
+ const walletIds = {};
3035
+ let recoverySecret;
3036
+ for (const type of yield this.getTypesToCreate(types)) {
3037
+ const [wallet, recoveryShare] = yield this.createWallet({ type, skipDistribute });
3038
+ wallets.push(wallet);
3039
+ getEquivalentTypes(type).filter((t) => !!this.isWalletTypeEnabled[t]).forEach((t) => {
3040
+ walletIds[t] = [wallet.id];
3041
+ });
3042
+ if (recoveryShare) {
3043
+ recoverySecret = recoveryShare;
3044
+ }
2814
3045
  }
2815
- }
2816
- return { wallets, walletIds, recoverySecret };
3046
+ return { wallets, walletIds, recoverySecret };
3047
+ });
2817
3048
  }
2818
3049
  /**
2819
3050
  * Refresh the current user share for a wallet.
@@ -2827,35 +3058,37 @@ var ParaCore = class _ParaCore {
2827
3058
  * @param {boolean} [opts.redistributeBackupEncryptedShares] whether or not to redistribute backup encrypted shares.
2828
3059
  * @returns {Object} the new user share and recovery secret.
2829
3060
  **/
2830
- async refreshShare({
2831
- walletId,
2832
- share,
2833
- oldPartnerId,
2834
- newPartnerId,
2835
- keyShareProtocolId,
2836
- redistributeBackupEncryptedShares
2837
- }) {
2838
- const { signer, protocolId } = await this.platformUtils.refresh(
2839
- this.ctx,
2840
- this.retrieveSessionCookie(),
2841
- this.userId,
3061
+ refreshShare(_0) {
3062
+ return __async(this, arguments, function* ({
2842
3063
  walletId,
2843
3064
  share,
2844
3065
  oldPartnerId,
2845
3066
  newPartnerId,
2846
- keyShareProtocolId
2847
- );
2848
- const recoverySecret = await distributeNewShare({
2849
- ctx: this.ctx,
2850
- userId: this.userId,
2851
- walletId,
2852
- userShare: signer,
2853
- ignoreRedistributingBackupEncryptedShare: !redistributeBackupEncryptedShares,
2854
- emailProps: this.getBackupKitEmailProps(),
2855
- partnerId: newPartnerId,
2856
- protocolId
3067
+ keyShareProtocolId,
3068
+ redistributeBackupEncryptedShares
3069
+ }) {
3070
+ const { signer, protocolId } = yield this.platformUtils.refresh(
3071
+ this.ctx,
3072
+ this.retrieveSessionCookie(),
3073
+ this.userId,
3074
+ walletId,
3075
+ share,
3076
+ oldPartnerId,
3077
+ newPartnerId,
3078
+ keyShareProtocolId
3079
+ );
3080
+ const recoverySecret = yield distributeNewShare({
3081
+ ctx: this.ctx,
3082
+ userId: this.userId,
3083
+ walletId,
3084
+ userShare: signer,
3085
+ ignoreRedistributingBackupEncryptedShare: !redistributeBackupEncryptedShares,
3086
+ emailProps: this.getBackupKitEmailProps(),
3087
+ partnerId: newPartnerId,
3088
+ protocolId
3089
+ });
3090
+ return { signer, recoverySecret, protocolId };
2857
3091
  });
2858
- return { signer, recoverySecret, protocolId };
2859
3092
  }
2860
3093
  /**
2861
3094
  * Creates a new wallet.
@@ -2864,71 +3097,73 @@ var ParaCore = class _ParaCore {
2864
3097
  * @param {boolean} opts.skipDistribute - if true, recovery share will not be distributed.
2865
3098
  * @returns {[Wallet, string | null]} `[wallet, recoveryShare]` - the wallet object and the new recovery share.
2866
3099
  **/
2867
- async createWallet({
2868
- type: _type,
2869
- skipDistribute = false
2870
- } = {}) {
2871
- this.requireApiKey();
2872
- const walletType = await this.assertIsValidWalletType(
2873
- _type ?? this.supportedWalletTypes.find(({ optional }) => !optional)?.type
2874
- );
2875
- let signer;
2876
- let wallet;
2877
- let keygenRes;
2878
- switch (walletType) {
2879
- case WalletType2.SOLANA: {
2880
- keygenRes = await this.platformUtils.ed25519Keygen(
2881
- this.ctx,
2882
- this.userId,
2883
- this.retrieveSessionCookie(),
2884
- this.getBackupKitEmailProps()
2885
- );
2886
- break;
3100
+ createWallet() {
3101
+ return __async(this, arguments, function* ({
3102
+ type: _type,
3103
+ skipDistribute = false
3104
+ } = {}) {
3105
+ var _a, _b;
3106
+ this.requireApiKey();
3107
+ const walletType = yield this.assertIsValidWalletType(
3108
+ _type != null ? _type : (_a = this.supportedWalletTypes.find(({ optional }) => !optional)) == null ? void 0 : _a.type
3109
+ );
3110
+ let signer;
3111
+ let wallet;
3112
+ let keygenRes;
3113
+ switch (walletType) {
3114
+ case WalletType2.SOLANA: {
3115
+ keygenRes = yield this.platformUtils.ed25519Keygen(
3116
+ this.ctx,
3117
+ this.userId,
3118
+ this.retrieveSessionCookie(),
3119
+ this.getBackupKitEmailProps()
3120
+ );
3121
+ break;
3122
+ }
3123
+ default: {
3124
+ keygenRes = yield this.platformUtils.keygen(
3125
+ this.ctx,
3126
+ this.userId,
3127
+ walletType,
3128
+ null,
3129
+ this.retrieveSessionCookie(),
3130
+ this.getBackupKitEmailProps()
3131
+ );
3132
+ break;
3133
+ }
2887
3134
  }
2888
- default: {
2889
- keygenRes = await this.platformUtils.keygen(
2890
- this.ctx,
2891
- this.userId,
2892
- walletType,
2893
- null,
2894
- this.retrieveSessionCookie(),
2895
- this.getBackupKitEmailProps()
2896
- );
2897
- break;
3135
+ const walletId = keygenRes.walletId;
3136
+ signer = keygenRes.signer;
3137
+ this.wallets[walletId] = {
3138
+ id: walletId,
3139
+ signer,
3140
+ scheme: walletType === WalletType2.SOLANA ? WalletScheme2.ED25519 : WalletScheme2.DKLS,
3141
+ type: walletType
3142
+ };
3143
+ wallet = this.wallets[walletId];
3144
+ yield this.waitForWalletAddress(wallet.id);
3145
+ yield this.populateWalletAddresses();
3146
+ let recoveryShare = null;
3147
+ if (!skipDistribute) {
3148
+ recoveryShare = yield distributeNewShare({
3149
+ ctx: this.ctx,
3150
+ userId: this.userId,
3151
+ walletId: wallet.id,
3152
+ userShare: signer,
3153
+ emailProps: this.getBackupKitEmailProps()
3154
+ });
2898
3155
  }
2899
- }
2900
- const walletId = keygenRes.walletId;
2901
- signer = keygenRes.signer;
2902
- this.wallets[walletId] = {
2903
- id: walletId,
2904
- signer,
2905
- scheme: walletType === WalletType2.SOLANA ? WalletScheme2.ED25519 : WalletScheme2.DKLS,
2906
- type: walletType
2907
- };
2908
- wallet = this.wallets[walletId];
2909
- await this.waitForWalletAddress(wallet.id);
2910
- await this.populateWalletAddresses();
2911
- let recoveryShare = null;
2912
- if (!skipDistribute) {
2913
- recoveryShare = await distributeNewShare({
2914
- ctx: this.ctx,
2915
- userId: this.userId,
2916
- walletId: wallet.id,
2917
- userShare: signer,
2918
- emailProps: this.getBackupKitEmailProps()
3156
+ yield this.setCurrentWalletIds(__spreadProps(__spreadValues({}, this.currentWalletIds), {
3157
+ [walletType]: [...(_b = this.currentWalletIds[walletType]) != null ? _b : [], walletId]
3158
+ }));
3159
+ const walletNoSigner = __spreadValues({}, wallet);
3160
+ delete walletNoSigner.signer;
3161
+ dispatchEvent(ParaEvent.WALLET_CREATED, {
3162
+ wallet: walletNoSigner,
3163
+ recoverySecret: recoveryShare
2919
3164
  });
2920
- }
2921
- await this.setCurrentWalletIds({
2922
- ...this.currentWalletIds,
2923
- [walletType]: [...this.currentWalletIds[walletType] ?? [], walletId]
2924
- });
2925
- const walletNoSigner = { ...wallet };
2926
- delete walletNoSigner.signer;
2927
- dispatchEvent(ParaEvent.WALLET_CREATED, {
2928
- wallet: walletNoSigner,
2929
- recoverySecret: recoveryShare
3165
+ return [wallet, recoveryShare];
2930
3166
  });
2931
- return [wallet, recoveryShare];
2932
3167
  }
2933
3168
  /**
2934
3169
  * Creates a new pregenerated wallet.
@@ -2939,51 +3174,54 @@ var ParaCore = class _ParaCore {
2939
3174
  * @param {WalletType} [opts.type] the type of wallet to create. Defaults to the first non-optional type in the instance's `supportedWalletTypes` array.
2940
3175
  * @returns {Wallet} the created wallet.
2941
3176
  **/
2942
- async createPregenWallet(opts) {
2943
- const {
2944
- type: _type = this.supportedWalletTypes.find(({ optional }) => !optional)?.type,
2945
- pregenIdentifier,
2946
- pregenIdentifierType = "EMAIL"
2947
- } = opts;
2948
- this.requireApiKey();
2949
- const walletType = await this.assertIsValidWalletType(
2950
- _type ?? this.supportedWalletTypes.find(({ optional }) => !optional)?.type
2951
- );
2952
- let keygenRes;
2953
- switch (walletType) {
2954
- case WalletType2.SOLANA:
2955
- keygenRes = await this.platformUtils.ed25519PreKeygen(
2956
- this.ctx,
2957
- pregenIdentifier,
2958
- pregenIdentifierType,
2959
- this.retrieveSessionCookie()
2960
- );
2961
- break;
2962
- default:
2963
- keygenRes = await this.platformUtils.preKeygen(
2964
- this.ctx,
2965
- void 0,
2966
- pregenIdentifier,
2967
- pregenIdentifierType,
2968
- walletType,
2969
- null,
2970
- this.retrieveSessionCookie()
2971
- );
2972
- break;
2973
- }
2974
- const { signer, walletId } = keygenRes;
2975
- this.wallets[walletId] = {
2976
- id: walletId,
2977
- signer,
2978
- scheme: walletType === WalletType2.SOLANA ? WalletScheme2.ED25519 : WalletScheme2.DKLS,
2979
- type: walletType,
2980
- isPregen: true,
2981
- pregenIdentifier,
2982
- pregenIdentifierType
2983
- };
2984
- await this.waitForPregenWalletAddress(walletId);
2985
- await this.populatePregenWalletAddresses();
2986
- return this.wallets[walletId];
3177
+ createPregenWallet(opts) {
3178
+ return __async(this, null, function* () {
3179
+ var _a, _b;
3180
+ const {
3181
+ type: _type = (_a = this.supportedWalletTypes.find(({ optional }) => !optional)) == null ? void 0 : _a.type,
3182
+ pregenIdentifier,
3183
+ pregenIdentifierType = "EMAIL"
3184
+ } = opts;
3185
+ this.requireApiKey();
3186
+ const walletType = yield this.assertIsValidWalletType(
3187
+ _type != null ? _type : (_b = this.supportedWalletTypes.find(({ optional }) => !optional)) == null ? void 0 : _b.type
3188
+ );
3189
+ let keygenRes;
3190
+ switch (walletType) {
3191
+ case WalletType2.SOLANA:
3192
+ keygenRes = yield this.platformUtils.ed25519PreKeygen(
3193
+ this.ctx,
3194
+ pregenIdentifier,
3195
+ pregenIdentifierType,
3196
+ this.retrieveSessionCookie()
3197
+ );
3198
+ break;
3199
+ default:
3200
+ keygenRes = yield this.platformUtils.preKeygen(
3201
+ this.ctx,
3202
+ void 0,
3203
+ pregenIdentifier,
3204
+ pregenIdentifierType,
3205
+ walletType,
3206
+ null,
3207
+ this.retrieveSessionCookie()
3208
+ );
3209
+ break;
3210
+ }
3211
+ const { signer, walletId } = keygenRes;
3212
+ this.wallets[walletId] = {
3213
+ id: walletId,
3214
+ signer,
3215
+ scheme: walletType === WalletType2.SOLANA ? WalletScheme2.ED25519 : WalletScheme2.DKLS,
3216
+ type: walletType,
3217
+ isPregen: true,
3218
+ pregenIdentifier,
3219
+ pregenIdentifierType
3220
+ };
3221
+ yield this.waitForPregenWalletAddress(walletId);
3222
+ yield this.populatePregenWalletAddresses();
3223
+ return this.wallets[walletId];
3224
+ });
2987
3225
  }
2988
3226
  /**
2989
3227
  * Creates new pregenerated wallets for each desired type.
@@ -2995,17 +3233,19 @@ var ParaCore = class _ParaCore {
2995
3233
  * @param {WalletType[]} [opts.types] the wallet types to create. Defaults to any types the instance supports that are not already present.
2996
3234
  * @returns {Wallet[]} an array containing the created wallets.
2997
3235
  **/
2998
- async createPregenWalletPerType({
2999
- types,
3000
- pregenIdentifier,
3001
- pregenIdentifierType = "EMAIL"
3002
- }) {
3003
- const wallets = [];
3004
- for (const type of await this.getTypesToCreate(types)) {
3005
- const wallet = await this.createPregenWallet({ type, pregenIdentifier, pregenIdentifierType });
3006
- wallets.push(wallet);
3007
- }
3008
- return wallets;
3236
+ createPregenWalletPerType(_0) {
3237
+ return __async(this, arguments, function* ({
3238
+ types,
3239
+ pregenIdentifier,
3240
+ pregenIdentifierType = "EMAIL"
3241
+ }) {
3242
+ const wallets = [];
3243
+ for (const type of yield this.getTypesToCreate(types)) {
3244
+ const wallet = yield this.createPregenWallet({ type, pregenIdentifier, pregenIdentifierType });
3245
+ wallets.push(wallet);
3246
+ }
3247
+ return wallets;
3248
+ });
3009
3249
  }
3010
3250
  /**
3011
3251
  * Claims a pregenerated wallet.
@@ -3015,63 +3255,71 @@ var ParaCore = class _ParaCore {
3015
3255
  * @param {TPregenIdentifierType} opts.pregenIdentifierType type of the identifier of the user claiming the wallet
3016
3256
  * @returns {[Wallet, string | null]} `[wallet, recoveryShare]` - the wallet object and the new recovery share.
3017
3257
  **/
3018
- async claimPregenWallets({
3019
- pregenIdentifier,
3020
- pregenIdentifierType = !!pregenIdentifier ? "EMAIL" : void 0
3021
- } = {}) {
3022
- this.requireApiKey();
3023
- const pregenWallets = pregenIdentifier && pregenIdentifierType ? await this.getPregenWallets({ pregenIdentifier, pregenIdentifierType }) : await this.getPregenWallets();
3024
- if (pregenWallets.length === 0) {
3025
- return void 0;
3026
- }
3027
- let newRecoverySecret;
3028
- const { walletIds } = await this.ctx.client.claimPregenWallets({
3029
- userId: this.userId,
3030
- walletIds: pregenWallets.map((w) => w.id)
3031
- });
3032
- for (const walletId of walletIds) {
3033
- const wallet = this.wallets[walletId];
3034
- let refreshedShare;
3035
- if (wallet.scheme === WalletScheme2.ED25519) {
3036
- const distributeRes = await distributeNewShare({
3037
- ctx: this.ctx,
3258
+ claimPregenWallets() {
3259
+ return __async(this, arguments, function* ({
3260
+ pregenIdentifier,
3261
+ pregenIdentifierType = !!pregenIdentifier ? "EMAIL" : void 0
3262
+ } = {}) {
3263
+ var _a;
3264
+ this.requireApiKey();
3265
+ const pregenWallets = pregenIdentifier && pregenIdentifierType ? yield this.getPregenWallets({ pregenIdentifier, pregenIdentifierType }) : yield this.getPregenWallets();
3266
+ if (pregenWallets.length === 0) {
3267
+ return void 0;
3268
+ }
3269
+ const missingWallets = pregenWallets.filter((wallet) => !this.wallets[wallet.id]);
3270
+ if (missingWallets.length > 0) {
3271
+ throw new Error(
3272
+ `Cannot claim pregen wallets because wallet data is missing. Please call setUserShare first to load the wallet data for the following wallet IDs: ${missingWallets.map((w) => w.id).join(", ")}`
3273
+ );
3274
+ }
3275
+ let newRecoverySecret;
3276
+ const { walletIds } = yield this.ctx.client.claimPregenWallets({
3277
+ userId: this.userId,
3278
+ walletIds: pregenWallets.map((w) => w.id)
3279
+ });
3280
+ for (const walletId of walletIds) {
3281
+ const wallet = this.wallets[walletId];
3282
+ let refreshedShare;
3283
+ if (wallet.scheme === WalletScheme2.ED25519) {
3284
+ const distributeRes = yield distributeNewShare({
3285
+ ctx: this.ctx,
3286
+ userId: this.userId,
3287
+ walletId: wallet.id,
3288
+ userShare: this.wallets[wallet.id].signer,
3289
+ emailProps: this.getBackupKitEmailProps(),
3290
+ partnerId: wallet.partnerId
3291
+ });
3292
+ if (distributeRes.length > 0) {
3293
+ newRecoverySecret = distributeRes;
3294
+ }
3295
+ } else {
3296
+ refreshedShare = yield this.refreshShare({
3297
+ walletId: wallet.id,
3298
+ share: this.wallets[wallet.id].signer,
3299
+ oldPartnerId: wallet.partnerId,
3300
+ newPartnerId: wallet.partnerId,
3301
+ redistributeBackupEncryptedShares: true
3302
+ });
3303
+ if (refreshedShare.recoverySecret) {
3304
+ newRecoverySecret = refreshedShare.recoverySecret;
3305
+ }
3306
+ }
3307
+ this.wallets[wallet.id] = __spreadProps(__spreadValues({}, this.wallets[wallet.id]), {
3308
+ signer: (_a = refreshedShare == null ? void 0 : refreshedShare.signer) != null ? _a : wallet.signer,
3038
3309
  userId: this.userId,
3039
- walletId: wallet.id,
3040
- userShare: this.wallets[wallet.id].signer,
3041
- emailProps: this.getBackupKitEmailProps(),
3042
- partnerId: wallet.partnerId
3310
+ pregenIdentifier: void 0,
3311
+ pregenIdentifierType: void 0
3043
3312
  });
3044
- if (distributeRes.length > 0) {
3045
- newRecoverySecret = distributeRes;
3046
- }
3047
- } else {
3048
- refreshedShare = await this.refreshShare({
3049
- walletId: wallet.id,
3050
- share: this.wallets[wallet.id].signer,
3051
- oldPartnerId: wallet.partnerId,
3052
- newPartnerId: wallet.partnerId,
3053
- redistributeBackupEncryptedShares: true
3313
+ const walletNoSigner = __spreadValues({}, this.wallets[wallet.id]);
3314
+ delete walletNoSigner.signer;
3315
+ dispatchEvent(ParaEvent.PREGEN_WALLET_CLAIMED, {
3316
+ wallet: walletNoSigner,
3317
+ recoverySecret: newRecoverySecret
3054
3318
  });
3055
- if (refreshedShare.recoverySecret) {
3056
- newRecoverySecret = refreshedShare.recoverySecret;
3057
- }
3058
3319
  }
3059
- this.wallets[wallet.id] = {
3060
- ...this.wallets[wallet.id],
3061
- signer: refreshedShare?.signer ?? wallet.signer,
3062
- userId: this.userId,
3063
- pregenIdentifier: void 0,
3064
- pregenIdentifierType: void 0
3065
- };
3066
- const walletNoSigner = { ...this.wallets[wallet.id] };
3067
- delete walletNoSigner.signer;
3068
- dispatchEvent(ParaEvent.PREGEN_WALLET_CLAIMED, {
3069
- wallet: walletNoSigner,
3070
- recoverySecret: newRecoverySecret
3071
- });
3072
- }
3073
- await this.setWallets(this.wallets);
3074
- return newRecoverySecret;
3320
+ yield this.setWallets(this.wallets);
3321
+ return newRecoverySecret;
3322
+ });
3075
3323
  }
3076
3324
  /**
3077
3325
  * Updates the identifier for a pregen wallet.
@@ -3080,24 +3328,25 @@ var ParaCore = class _ParaCore {
3080
3328
  * @param {string} opts.newPregenIdentifier the new identtifier
3081
3329
  * @param {TPregenIdentifierType} opts.newPregenIdentifierType: the new identifier type
3082
3330
  **/
3083
- async updatePregenWalletIdentifier({
3084
- walletId,
3085
- newPregenIdentifier,
3086
- newPregenIdentifierType
3087
- }) {
3088
- this.requireApiKey();
3089
- await this.ctx.client.updatePregenWallet(walletId, {
3090
- pregenIdentifier: newPregenIdentifier,
3091
- pregenIdentifierType: newPregenIdentifierType
3092
- });
3093
- if (!!this.wallets[walletId]) {
3094
- this.wallets[walletId] = {
3095
- ...this.wallets[walletId],
3331
+ updatePregenWalletIdentifier(_0) {
3332
+ return __async(this, arguments, function* ({
3333
+ walletId,
3334
+ newPregenIdentifier,
3335
+ newPregenIdentifierType
3336
+ }) {
3337
+ this.requireApiKey();
3338
+ yield this.ctx.client.updatePregenWallet(walletId, {
3096
3339
  pregenIdentifier: newPregenIdentifier,
3097
3340
  pregenIdentifierType: newPregenIdentifierType
3098
- };
3099
- await this.setWallets(this.wallets);
3100
- }
3341
+ });
3342
+ if (!!this.wallets[walletId]) {
3343
+ this.wallets[walletId] = __spreadProps(__spreadValues({}, this.wallets[walletId]), {
3344
+ pregenIdentifier: newPregenIdentifier,
3345
+ pregenIdentifierType: newPregenIdentifierType
3346
+ });
3347
+ yield this.setWallets(this.wallets);
3348
+ }
3349
+ });
3101
3350
  }
3102
3351
  /**
3103
3352
  * Checks if a pregen Wallet exists for the given identifier with the current partner.
@@ -3106,17 +3355,19 @@ var ParaCore = class _ParaCore {
3106
3355
  * @param {TPregenIdentifierType} opts.pregenIdentifierType type of the string of the identifier of the user claiming the wallet
3107
3356
  * @returns {boolean} whether the pregen wallet exists
3108
3357
  **/
3109
- async hasPregenWallet({
3110
- pregenIdentifier,
3111
- pregenIdentifierType
3112
- }) {
3113
- this.requireApiKey();
3114
- const res = await this.getPregenWallets({ pregenIdentifier, pregenIdentifierType });
3115
- const wallet = res.find((w) => w.pregenIdentifier === pregenIdentifier && w.pregenIdentifierType === pregenIdentifierType);
3116
- if (!wallet) {
3117
- return false;
3118
- }
3119
- return true;
3358
+ hasPregenWallet(_0) {
3359
+ return __async(this, arguments, function* ({
3360
+ pregenIdentifier,
3361
+ pregenIdentifierType
3362
+ }) {
3363
+ this.requireApiKey();
3364
+ const res = yield this.getPregenWallets({ pregenIdentifier, pregenIdentifierType });
3365
+ const wallet = res.find((w) => w.pregenIdentifier === pregenIdentifier && w.pregenIdentifierType === pregenIdentifierType);
3366
+ if (!wallet) {
3367
+ return false;
3368
+ }
3369
+ return true;
3370
+ });
3120
3371
  }
3121
3372
  /**
3122
3373
  * Get pregen wallets for the given identifier.
@@ -3125,17 +3376,19 @@ var ParaCore = class _ParaCore {
3125
3376
  * @param {TPregenIdentifierType} opts.pregenIdentifierType - type of the identifier of the user claiming the wallet
3126
3377
  * @returns {Promise<WalletEntity[]>} the array of found wallets
3127
3378
  **/
3128
- async getPregenWallets({
3129
- pregenIdentifier,
3130
- pregenIdentifierType = !!pregenIdentifier ? "EMAIL" : void 0
3131
- } = {}) {
3132
- this.requireApiKey();
3133
- const res = await this.ctx.client.getPregenWallets(
3134
- pregenIdentifier && pregenIdentifierType ? { [pregenIdentifierType]: [pregenIdentifier] } : this.pregenIds,
3135
- this.isPortal(),
3136
- this.userId
3137
- );
3138
- return res.wallets.filter((w) => this.isWalletSupported(entityToWallet(w)));
3379
+ getPregenWallets() {
3380
+ return __async(this, arguments, function* ({
3381
+ pregenIdentifier,
3382
+ pregenIdentifierType = !!pregenIdentifier ? "EMAIL" : void 0
3383
+ } = {}) {
3384
+ this.requireApiKey();
3385
+ const res = yield this.ctx.client.getPregenWallets(
3386
+ pregenIdentifier && pregenIdentifierType ? { [pregenIdentifierType]: [pregenIdentifier] } : this.pregenIds,
3387
+ this.isPortal(),
3388
+ this.userId
3389
+ );
3390
+ return res.wallets.filter((w) => this.isWalletSupported(entityToWallet(w)));
3391
+ });
3139
3392
  }
3140
3393
  encodeWalletBase64(wallet) {
3141
3394
  const walletJson = JSON.stringify(wallet);
@@ -3156,45 +3409,54 @@ var ParaCore = class _ParaCore {
3156
3409
  * Sets the current wallets from a Base 64 string.
3157
3410
  * @param {string} base64Wallet the encoded wallet string
3158
3411
  **/
3159
- async setUserShare(base64Wallets) {
3160
- if (!base64Wallets) {
3161
- return;
3162
- }
3163
- const base64WalletsSplit = base64Wallets.split("-");
3164
- for (const base64Wallet of base64WalletsSplit) {
3165
- const walletJson = Buffer.from(base64Wallet, "base64").toString();
3166
- const wallet = migrateWallet(JSON.parse(walletJson));
3167
- this.wallets[wallet.id] = wallet;
3168
- await this.setWallets(this.wallets);
3169
- }
3170
- }
3171
- async getTransactionReviewUrl(transactionId, timeoutMs) {
3172
- const res = await this.touchSession();
3173
- return this.constructPortalUrl("txReview", {
3174
- partnerId: res.data.partnerId,
3175
- pathId: transactionId,
3176
- params: {
3177
- email: this.email,
3178
- timeoutMs: timeoutMs?.toString()
3412
+ setUserShare(base64Wallets) {
3413
+ return __async(this, null, function* () {
3414
+ if (!base64Wallets) {
3415
+ return;
3416
+ }
3417
+ const base64WalletsSplit = base64Wallets.split("-");
3418
+ for (const base64Wallet of base64WalletsSplit) {
3419
+ const walletJson = Buffer.from(base64Wallet, "base64").toString();
3420
+ const wallet = migrateWallet(JSON.parse(walletJson));
3421
+ this.wallets[wallet.id] = wallet;
3422
+ yield this.setWallets(this.wallets);
3179
3423
  }
3180
3424
  });
3181
3425
  }
3182
- async getOnRampTransactionUrl({
3183
- purchaseId,
3184
- providerKey,
3185
- ...walletParams
3186
- }) {
3187
- const res = await this.touchSession();
3188
- const [key, identifier] = extractWalletRef(walletParams);
3189
- return this.constructPortalUrl("onRamp", {
3190
- partnerId: res.data.partnerId,
3191
- pathId: purchaseId,
3192
- sessionId: res.data.sessionId,
3193
- params: {
3194
- [key]: identifier,
3195
- providerKey,
3196
- currentWalletIds: JSON.stringify(this.currentWalletIds)
3197
- }
3426
+ getTransactionReviewUrl(transactionId, timeoutMs) {
3427
+ return __async(this, null, function* () {
3428
+ const res = yield this.touchSession();
3429
+ return this.constructPortalUrl("txReview", {
3430
+ partnerId: res.data.partnerId,
3431
+ pathId: transactionId,
3432
+ params: {
3433
+ email: this.email,
3434
+ timeoutMs: timeoutMs == null ? void 0 : timeoutMs.toString()
3435
+ }
3436
+ });
3437
+ });
3438
+ }
3439
+ getOnRampTransactionUrl(_i) {
3440
+ return __async(this, null, function* () {
3441
+ var _j = _i, {
3442
+ purchaseId,
3443
+ providerKey
3444
+ } = _j, walletParams = __objRest(_j, [
3445
+ "purchaseId",
3446
+ "providerKey"
3447
+ ]);
3448
+ const res = yield this.touchSession();
3449
+ const [key, identifier] = extractWalletRef(walletParams);
3450
+ return this.constructPortalUrl("onRamp", {
3451
+ partnerId: res.data.partnerId,
3452
+ pathId: purchaseId,
3453
+ sessionId: res.data.sessionId,
3454
+ params: {
3455
+ [key]: identifier,
3456
+ providerKey,
3457
+ currentWalletIds: JSON.stringify(this.currentWalletIds)
3458
+ }
3459
+ });
3198
3460
  });
3199
3461
  }
3200
3462
  /**
@@ -3208,91 +3470,95 @@ var ParaCore = class _ParaCore {
3208
3470
  * @param {number} [opts.timeout] optional timeout in milliseconds. If not present, defaults to 30 seconds.
3209
3471
  * @param {string} [opts.cosmosSignDocBase64] the Cosmos `SignDoc` in base64, if applicable
3210
3472
  **/
3211
- async signMessage({
3212
- walletId,
3213
- messageBase64,
3214
- timeoutMs = 3e4,
3215
- cosmosSignDocBase64
3216
- }) {
3217
- this.assertIsValidWalletId(walletId);
3218
- const wallet = this.wallets[walletId];
3219
- let signerId = this.userId;
3220
- if (wallet.partnerId && !wallet.userId) {
3221
- signerId = wallet.partnerId;
3222
- }
3223
- let signRes = await this.signMessageInner({ wallet, signerId, messageBase64, cosmosSignDocBase64 });
3224
- let timeStart = Date.now();
3225
- if (signRes.pendingTransactionId) {
3226
- this.platformUtils.openPopup(
3227
- await this.getTransactionReviewUrl(signRes.pendingTransactionId, timeoutMs),
3228
- { type: cosmosSignDocBase64 ? "SIGN_TRANSACTION_REVIEW" /* SIGN_TRANSACTION_REVIEW */ : "SIGN_MESSAGE_REVIEW" /* SIGN_MESSAGE_REVIEW */ }
3229
- );
3230
- } else {
3231
- dispatchEvent(ParaEvent.SIGN_MESSAGE_EVENT, signRes);
3232
- return signRes;
3233
- }
3234
- await new Promise((resolve) => setTimeout(resolve, POLLING_INTERVAL_MS));
3235
- while (true) {
3236
- if (Date.now() - timeStart > timeoutMs) {
3237
- break;
3238
- }
3239
- try {
3240
- await this.ctx.client.getPendingTransaction(this.userId, signRes.pendingTransactionId);
3241
- } catch (err) {
3242
- const error = new TransactionReviewDenied();
3243
- dispatchEvent(ParaEvent.SIGN_MESSAGE_EVENT, signRes, error.message);
3244
- throw error;
3473
+ signMessage(_0) {
3474
+ return __async(this, arguments, function* ({
3475
+ walletId,
3476
+ messageBase64,
3477
+ timeoutMs = 3e4,
3478
+ cosmosSignDocBase64
3479
+ }) {
3480
+ this.assertIsValidWalletId(walletId);
3481
+ const wallet = this.wallets[walletId];
3482
+ let signerId = this.userId;
3483
+ if (wallet.partnerId && !wallet.userId) {
3484
+ signerId = wallet.partnerId;
3245
3485
  }
3246
- signRes = await this.signMessageInner({ wallet, signerId, messageBase64, cosmosSignDocBase64 });
3486
+ let signRes = yield this.signMessageInner({ wallet, signerId, messageBase64, cosmosSignDocBase64 });
3487
+ let timeStart = Date.now();
3247
3488
  if (signRes.pendingTransactionId) {
3248
- await new Promise((resolve) => setTimeout(resolve, POLLING_INTERVAL_MS));
3489
+ this.platformUtils.openPopup(
3490
+ yield this.getTransactionReviewUrl(signRes.pendingTransactionId, timeoutMs),
3491
+ { type: cosmosSignDocBase64 ? "SIGN_TRANSACTION_REVIEW" /* SIGN_TRANSACTION_REVIEW */ : "SIGN_MESSAGE_REVIEW" /* SIGN_MESSAGE_REVIEW */ }
3492
+ );
3249
3493
  } else {
3250
- break;
3494
+ dispatchEvent(ParaEvent.SIGN_MESSAGE_EVENT, signRes);
3495
+ return signRes;
3251
3496
  }
3252
- }
3253
- if (signRes.pendingTransactionId) {
3254
- const error = new TransactionReviewTimeout(
3255
- await this.getTransactionReviewUrl(signRes.pendingTransactionId),
3256
- signRes.pendingTransactionId
3257
- );
3258
- dispatchEvent(ParaEvent.SIGN_MESSAGE_EVENT, signRes, error.message);
3259
- throw error;
3260
- }
3261
- dispatchEvent(ParaEvent.SIGN_MESSAGE_EVENT, signRes);
3262
- return signRes;
3263
- }
3264
- async signMessageInner({
3265
- wallet,
3266
- signerId,
3267
- messageBase64,
3268
- cosmosSignDocBase64
3269
- }) {
3270
- let signRes;
3271
- switch (wallet.scheme) {
3272
- case WalletScheme2.ED25519:
3273
- signRes = await this.platformUtils.ed25519Sign(
3274
- this.ctx,
3275
- signerId,
3276
- wallet.id,
3277
- wallet.signer,
3278
- messageBase64,
3279
- this.retrieveSessionCookie()
3280
- );
3281
- break;
3282
- default:
3283
- signRes = await this.platformUtils.signMessage(
3284
- this.ctx,
3285
- signerId,
3286
- wallet.id,
3287
- wallet.signer,
3288
- messageBase64,
3289
- this.retrieveSessionCookie(),
3290
- wallet.scheme === WalletScheme2.DKLS,
3291
- cosmosSignDocBase64
3497
+ yield new Promise((resolve) => setTimeout(resolve, POLLING_INTERVAL_MS));
3498
+ while (true) {
3499
+ if (Date.now() - timeStart > timeoutMs) {
3500
+ break;
3501
+ }
3502
+ try {
3503
+ yield this.ctx.client.getPendingTransaction(this.userId, signRes.pendingTransactionId);
3504
+ } catch (err) {
3505
+ const error = new TransactionReviewDenied();
3506
+ dispatchEvent(ParaEvent.SIGN_MESSAGE_EVENT, signRes, error.message);
3507
+ throw error;
3508
+ }
3509
+ signRes = yield this.signMessageInner({ wallet, signerId, messageBase64, cosmosSignDocBase64 });
3510
+ if (signRes.pendingTransactionId) {
3511
+ yield new Promise((resolve) => setTimeout(resolve, POLLING_INTERVAL_MS));
3512
+ } else {
3513
+ break;
3514
+ }
3515
+ }
3516
+ if (signRes.pendingTransactionId) {
3517
+ const error = new TransactionReviewTimeout(
3518
+ yield this.getTransactionReviewUrl(signRes.pendingTransactionId),
3519
+ signRes.pendingTransactionId
3292
3520
  );
3293
- break;
3294
- }
3295
- return signRes;
3521
+ dispatchEvent(ParaEvent.SIGN_MESSAGE_EVENT, signRes, error.message);
3522
+ throw error;
3523
+ }
3524
+ dispatchEvent(ParaEvent.SIGN_MESSAGE_EVENT, signRes);
3525
+ return signRes;
3526
+ });
3527
+ }
3528
+ signMessageInner(_0) {
3529
+ return __async(this, arguments, function* ({
3530
+ wallet,
3531
+ signerId,
3532
+ messageBase64,
3533
+ cosmosSignDocBase64
3534
+ }) {
3535
+ let signRes;
3536
+ switch (wallet.scheme) {
3537
+ case WalletScheme2.ED25519:
3538
+ signRes = yield this.platformUtils.ed25519Sign(
3539
+ this.ctx,
3540
+ signerId,
3541
+ wallet.id,
3542
+ wallet.signer,
3543
+ messageBase64,
3544
+ this.retrieveSessionCookie()
3545
+ );
3546
+ break;
3547
+ default:
3548
+ signRes = yield this.platformUtils.signMessage(
3549
+ this.ctx,
3550
+ signerId,
3551
+ wallet.id,
3552
+ wallet.signer,
3553
+ messageBase64,
3554
+ this.retrieveSessionCookie(),
3555
+ wallet.scheme === WalletScheme2.DKLS,
3556
+ cosmosSignDocBase64
3557
+ );
3558
+ break;
3559
+ }
3560
+ return signRes;
3561
+ });
3296
3562
  }
3297
3563
  /**
3298
3564
  * Signs a transaction.
@@ -3302,51 +3568,20 @@ var ParaCore = class _ParaCore {
3302
3568
  * @param {string} [opts.chainId] the EVM chain id of the chain the transaction is being sent on, if applicable
3303
3569
  * @param {number} [opts.timeoutMs] the amount of time to wait for the user to sign the transaction, in milliseconds
3304
3570
  **/
3305
- async signTransaction({
3306
- walletId,
3307
- rlpEncodedTxBase64,
3308
- chainId,
3309
- timeoutMs = 3e4
3310
- }) {
3311
- this.assertIsValidWalletId(walletId);
3312
- const wallet = this.wallets[walletId];
3313
- let signerId = this.userId;
3314
- if (wallet.partnerId && !wallet.userId) {
3315
- signerId = wallet.partnerId;
3316
- }
3317
- let signRes = await this.platformUtils.signTransaction(
3318
- this.ctx,
3319
- signerId,
3571
+ signTransaction(_0) {
3572
+ return __async(this, arguments, function* ({
3320
3573
  walletId,
3321
- this.wallets[walletId].signer,
3322
3574
  rlpEncodedTxBase64,
3323
3575
  chainId,
3324
- this.retrieveSessionCookie(),
3325
- wallet.scheme === WalletScheme2.DKLS
3326
- );
3327
- let timeStart = Date.now();
3328
- if (signRes.pendingTransactionId) {
3329
- this.platformUtils.openPopup(
3330
- await this.getTransactionReviewUrl(signRes.pendingTransactionId, timeoutMs),
3331
- { type: "SIGN_TRANSACTION_REVIEW" /* SIGN_TRANSACTION_REVIEW */ }
3332
- );
3333
- } else {
3334
- dispatchEvent(ParaEvent.SIGN_TRANSACTION_EVENT, signRes);
3335
- return signRes;
3336
- }
3337
- await new Promise((resolve) => setTimeout(resolve, POLLING_INTERVAL_MS));
3338
- while (true) {
3339
- if (Date.now() - timeStart > timeoutMs) {
3340
- break;
3341
- }
3342
- try {
3343
- await this.ctx.client.getPendingTransaction(this.userId, signRes.pendingTransactionId);
3344
- } catch (err) {
3345
- const error = new TransactionReviewDenied();
3346
- dispatchEvent(ParaEvent.SIGN_TRANSACTION_EVENT, signRes, error.message);
3347
- throw error;
3576
+ timeoutMs = 3e4
3577
+ }) {
3578
+ this.assertIsValidWalletId(walletId);
3579
+ const wallet = this.wallets[walletId];
3580
+ let signerId = this.userId;
3581
+ if (wallet.partnerId && !wallet.userId) {
3582
+ signerId = wallet.partnerId;
3348
3583
  }
3349
- signRes = await this.platformUtils.signTransaction(
3584
+ let signRes = yield this.platformUtils.signTransaction(
3350
3585
  this.ctx,
3351
3586
  signerId,
3352
3587
  walletId,
@@ -3356,22 +3591,55 @@ var ParaCore = class _ParaCore {
3356
3591
  this.retrieveSessionCookie(),
3357
3592
  wallet.scheme === WalletScheme2.DKLS
3358
3593
  );
3594
+ let timeStart = Date.now();
3359
3595
  if (signRes.pendingTransactionId) {
3360
- await new Promise((resolve) => setTimeout(resolve, POLLING_INTERVAL_MS));
3596
+ this.platformUtils.openPopup(
3597
+ yield this.getTransactionReviewUrl(signRes.pendingTransactionId, timeoutMs),
3598
+ { type: "SIGN_TRANSACTION_REVIEW" /* SIGN_TRANSACTION_REVIEW */ }
3599
+ );
3361
3600
  } else {
3362
- break;
3601
+ dispatchEvent(ParaEvent.SIGN_TRANSACTION_EVENT, signRes);
3602
+ return signRes;
3363
3603
  }
3364
- }
3365
- if (signRes.pendingTransactionId) {
3366
- const error = new TransactionReviewTimeout(
3367
- await this.getTransactionReviewUrl(signRes.pendingTransactionId),
3368
- signRes.pendingTransactionId
3369
- );
3370
- dispatchEvent(ParaEvent.SIGN_TRANSACTION_EVENT, signRes, error.message);
3371
- throw error;
3372
- }
3373
- dispatchEvent(ParaEvent.SIGN_TRANSACTION_EVENT, signRes);
3374
- return signRes;
3604
+ yield new Promise((resolve) => setTimeout(resolve, POLLING_INTERVAL_MS));
3605
+ while (true) {
3606
+ if (Date.now() - timeStart > timeoutMs) {
3607
+ break;
3608
+ }
3609
+ try {
3610
+ yield this.ctx.client.getPendingTransaction(this.userId, signRes.pendingTransactionId);
3611
+ } catch (err) {
3612
+ const error = new TransactionReviewDenied();
3613
+ dispatchEvent(ParaEvent.SIGN_TRANSACTION_EVENT, signRes, error.message);
3614
+ throw error;
3615
+ }
3616
+ signRes = yield this.platformUtils.signTransaction(
3617
+ this.ctx,
3618
+ signerId,
3619
+ walletId,
3620
+ this.wallets[walletId].signer,
3621
+ rlpEncodedTxBase64,
3622
+ chainId,
3623
+ this.retrieveSessionCookie(),
3624
+ wallet.scheme === WalletScheme2.DKLS
3625
+ );
3626
+ if (signRes.pendingTransactionId) {
3627
+ yield new Promise((resolve) => setTimeout(resolve, POLLING_INTERVAL_MS));
3628
+ } else {
3629
+ break;
3630
+ }
3631
+ }
3632
+ if (signRes.pendingTransactionId) {
3633
+ const error = new TransactionReviewTimeout(
3634
+ yield this.getTransactionReviewUrl(signRes.pendingTransactionId),
3635
+ signRes.pendingTransactionId
3636
+ );
3637
+ dispatchEvent(ParaEvent.SIGN_TRANSACTION_EVENT, signRes, error.message);
3638
+ throw error;
3639
+ }
3640
+ dispatchEvent(ParaEvent.SIGN_TRANSACTION_EVENT, signRes);
3641
+ return signRes;
3642
+ });
3375
3643
  }
3376
3644
  /**
3377
3645
  * @deprecated
@@ -3380,34 +3648,36 @@ var ParaCore = class _ParaCore {
3380
3648
  * @param rlpEncodedTxBase64 - rlp encoded tx as base64 string
3381
3649
  * @param chainId - chain id of the chain the transaction is being sent on.
3382
3650
  **/
3383
- async sendTransaction({
3384
- walletId,
3385
- rlpEncodedTxBase64,
3386
- chainId
3387
- }) {
3388
- this.assertIsValidWalletId(walletId);
3389
- const wallet = this.wallets[walletId];
3390
- const signRes = await this.platformUtils.sendTransaction(
3391
- this.ctx,
3392
- this.userId,
3651
+ sendTransaction(_0) {
3652
+ return __async(this, arguments, function* ({
3393
3653
  walletId,
3394
- this.wallets[walletId].signer,
3395
3654
  rlpEncodedTxBase64,
3396
- chainId,
3397
- this.retrieveSessionCookie(),
3398
- wallet.scheme === WalletScheme2.DKLS
3399
- );
3400
- if (signRes.pendingTransactionId) {
3401
- this.platformUtils.openPopup(
3402
- await this.getTransactionReviewUrl(signRes.pendingTransactionId),
3403
- { type: "SIGN_TRANSACTION_REVIEW" /* SIGN_TRANSACTION_REVIEW */ }
3404
- );
3405
- const error = new TransactionReviewError(
3406
- await this.getTransactionReviewUrl(signRes.pendingTransactionId)
3655
+ chainId
3656
+ }) {
3657
+ this.assertIsValidWalletId(walletId);
3658
+ const wallet = this.wallets[walletId];
3659
+ const signRes = yield this.platformUtils.sendTransaction(
3660
+ this.ctx,
3661
+ this.userId,
3662
+ walletId,
3663
+ this.wallets[walletId].signer,
3664
+ rlpEncodedTxBase64,
3665
+ chainId,
3666
+ this.retrieveSessionCookie(),
3667
+ wallet.scheme === WalletScheme2.DKLS
3407
3668
  );
3408
- throw error;
3409
- }
3410
- return signRes;
3669
+ if (signRes.pendingTransactionId) {
3670
+ this.platformUtils.openPopup(
3671
+ yield this.getTransactionReviewUrl(signRes.pendingTransactionId),
3672
+ { type: "SIGN_TRANSACTION_REVIEW" /* SIGN_TRANSACTION_REVIEW */ }
3673
+ );
3674
+ const error = new TransactionReviewError(
3675
+ yield this.getTransactionReviewUrl(signRes.pendingTransactionId)
3676
+ );
3677
+ throw error;
3678
+ }
3679
+ return signRes;
3680
+ });
3411
3681
  }
3412
3682
  isProviderModalDisabled() {
3413
3683
  return !!this.disableProviderModal;
@@ -3420,36 +3690,38 @@ var ParaCore = class _ParaCore {
3420
3690
  * @param {string} opts.walletId the wallet ID to use for the transaction, where funds will be sent or withdrawn.
3421
3691
  * @param {string} opts.externalWalletAddress the external wallet address to send funds to or withdraw funds from, if using an external wallet.
3422
3692
  **/
3423
- async initiateOnRampTransaction(options) {
3424
- const { params, shouldOpenPopup, ...walletParams } = options;
3425
- const onRampPurchase = await this.ctx.client.createOnRampPurchase({
3426
- userId: this.userId,
3427
- params: {
3428
- ...params,
3429
- address: walletParams.externalWalletAddress ?? this.getDisplayAddress(walletParams.walletId, { addressType: params.walletType })
3430
- },
3431
- ...walletParams
3432
- });
3433
- const portalUrl = await this.getOnRampTransactionUrl({
3434
- purchaseId: onRampPurchase.id,
3435
- providerKey: onRampPurchase.providerKey,
3436
- ...walletParams
3693
+ initiateOnRampTransaction(options) {
3694
+ return __async(this, null, function* () {
3695
+ var _b;
3696
+ const _a = options, { params, shouldOpenPopup } = _a, walletParams = __objRest(_a, ["params", "shouldOpenPopup"]);
3697
+ const onRampPurchase = yield this.ctx.client.createOnRampPurchase(__spreadValues({
3698
+ userId: this.userId,
3699
+ params: __spreadProps(__spreadValues({}, params), {
3700
+ address: (_b = walletParams.externalWalletAddress) != null ? _b : this.getDisplayAddress(walletParams.walletId, { addressType: params.walletType })
3701
+ })
3702
+ }, walletParams));
3703
+ const portalUrl = yield this.getOnRampTransactionUrl(__spreadValues({
3704
+ purchaseId: onRampPurchase.id,
3705
+ providerKey: onRampPurchase.providerKey
3706
+ }, walletParams));
3707
+ if (shouldOpenPopup) {
3708
+ this.platformUtils.openPopup(portalUrl, { type: "ON_RAMP_TRANSACTION" /* ON_RAMP_TRANSACTION */ });
3709
+ }
3710
+ return { onRampPurchase, portalUrl };
3437
3711
  });
3438
- if (shouldOpenPopup) {
3439
- this.platformUtils.openPopup(portalUrl, { type: "ON_RAMP_TRANSACTION" /* ON_RAMP_TRANSACTION */ });
3440
- }
3441
- return { onRampPurchase, portalUrl };
3442
3712
  }
3443
3713
  /**
3444
3714
  * Returns `true` if session was successfully kept alive, `false` otherwise.
3445
3715
  **/
3446
- async keepSessionAlive() {
3447
- try {
3448
- await this.ctx.client.keepSessionAlive(this.userId);
3449
- return true;
3450
- } catch (err) {
3451
- return false;
3452
- }
3716
+ keepSessionAlive() {
3717
+ return __async(this, null, function* () {
3718
+ try {
3719
+ yield this.ctx.client.keepSessionAlive(this.userId);
3720
+ return true;
3721
+ } catch (err) {
3722
+ return false;
3723
+ }
3724
+ });
3453
3725
  }
3454
3726
  /**
3455
3727
  * Serialize the current session for import by another Para instance.
@@ -3474,34 +3746,37 @@ var ParaCore = class _ParaCore {
3474
3746
  * Imports a session serialized by another Para instance.
3475
3747
  * @param {string} serializedInstanceBase64 the serialized session
3476
3748
  */
3477
- async importSession(serializedInstanceBase64) {
3478
- const serializedInstance = Buffer.from(serializedInstanceBase64, "base64").toString("utf8");
3479
- const sessionInfo = JSON.parse(serializedInstance);
3480
- await this.setEmail(sessionInfo.email);
3481
- await this.setTelegramUserId(sessionInfo.telegramUserId);
3482
- await this.setFarcasterUsername(sessionInfo.farcasterUsername);
3483
- await this.setUserId(sessionInfo.userId);
3484
- await this.setWallets(sessionInfo.wallets);
3485
- await this.setExternalWallets(sessionInfo.externalWallets || {});
3486
- for (const walletId of Object.keys(this.wallets)) {
3487
- if (!this.wallets[walletId].userId) {
3488
- this.wallets[walletId].userId = this.userId;
3749
+ importSession(serializedInstanceBase64) {
3750
+ return __async(this, null, function* () {
3751
+ var _a;
3752
+ const serializedInstance = Buffer.from(serializedInstanceBase64, "base64").toString("utf8");
3753
+ const sessionInfo = JSON.parse(serializedInstance);
3754
+ yield this.setEmail(sessionInfo.email);
3755
+ yield this.setTelegramUserId(sessionInfo.telegramUserId);
3756
+ yield this.setFarcasterUsername(sessionInfo.farcasterUsername);
3757
+ yield this.setUserId(sessionInfo.userId);
3758
+ yield this.setWallets(sessionInfo.wallets);
3759
+ yield this.setExternalWallets(sessionInfo.externalWallets || {});
3760
+ for (const walletId of Object.keys(this.wallets)) {
3761
+ if (!this.wallets[walletId].userId) {
3762
+ this.wallets[walletId].userId = this.userId;
3763
+ }
3489
3764
  }
3490
- }
3491
- if (Object.keys(sessionInfo.currentWalletIds).length !== 0) {
3492
- await this.setCurrentWalletIds(sessionInfo.currentWalletIds);
3493
- } else {
3494
- const currentWalletIds = {};
3495
- for (const walletId of Object.keys(sessionInfo.wallets)) {
3496
- currentWalletIds[sessionInfo.wallets[walletId].type] = [
3497
- ...currentWalletIds[sessionInfo.wallets[walletId].type] ?? [],
3498
- walletId
3499
- ];
3765
+ if (Object.keys(sessionInfo.currentWalletIds).length !== 0) {
3766
+ yield this.setCurrentWalletIds(sessionInfo.currentWalletIds);
3767
+ } else {
3768
+ const currentWalletIds = {};
3769
+ for (const walletId of Object.keys(sessionInfo.wallets)) {
3770
+ currentWalletIds[sessionInfo.wallets[walletId].type] = [
3771
+ ...(_a = currentWalletIds[sessionInfo.wallets[walletId].type]) != null ? _a : [],
3772
+ walletId
3773
+ ];
3774
+ }
3775
+ yield this.setCurrentWalletIds(currentWalletIds);
3500
3776
  }
3501
- await this.setCurrentWalletIds(currentWalletIds);
3502
- }
3503
- this.persistSessionCookie(sessionInfo.sessionCookie);
3504
- await this.setPhoneNumber(sessionInfo.phone, sessionInfo.countryCode);
3777
+ this.persistSessionCookie(sessionInfo.sessionCookie);
3778
+ yield this.setPhoneNumber(sessionInfo.phone, sessionInfo.countryCode);
3779
+ });
3505
3780
  }
3506
3781
  exitAccountCreation() {
3507
3782
  this.isAwaitingAccountCreation = false;
@@ -3525,48 +3800,54 @@ var ParaCore = class _ParaCore {
3525
3800
  * Retrieves a token to verify the current session.
3526
3801
  * @returns {Promise<string>} the ID
3527
3802
  **/
3528
- async getVerificationToken() {
3529
- const { data } = await this.touchSession();
3530
- return data.sessionLookupId;
3803
+ getVerificationToken() {
3804
+ return __async(this, null, function* () {
3805
+ const { data } = yield this.touchSession();
3806
+ return data.sessionLookupId;
3807
+ });
3531
3808
  }
3532
3809
  /**
3533
3810
  * Logs the user out.
3534
3811
  * @param {Object} opts the options object.
3535
3812
  * @param {boolean} opts.clearPregenWallets if `true`, will remove all pregen wallets from storage
3536
3813
  **/
3537
- async logout({ clearPregenWallets = false } = {}) {
3538
- await this.ctx.client.logout();
3539
- await this.clearStorage();
3540
- if (!clearPregenWallets) {
3541
- Object.entries(this.wallets).forEach(([id, wallet]) => {
3542
- if (!wallet.pregenIdentifier) {
3543
- delete this.wallets[id];
3544
- }
3545
- });
3546
- await this.setWallets(this.wallets);
3547
- } else {
3548
- this.wallets = {};
3549
- }
3550
- this.currentWalletIds = {};
3551
- this.externalWallets = {};
3552
- this.loginEncryptionKeyPair = void 0;
3553
- this.email = void 0;
3554
- this.telegramUserId = void 0;
3555
- this.phone = void 0;
3556
- this.countryCode = void 0;
3557
- this.userId = void 0;
3558
- this.sessionCookie = void 0;
3559
- dispatchEvent(ParaEvent.LOGOUT_EVENT, null);
3560
- }
3561
- async getSupportedCreateAuthMethods() {
3562
- const res = await this.touchSession();
3563
- const partnerId = res.data.partnerId;
3564
- const partnerRes = await this.ctx.client.getPartner(partnerId);
3565
- let supportedAuthMethods = /* @__PURE__ */ new Set();
3566
- for (const authMethod of partnerRes.data.partner.supportedAuthMethods) {
3567
- supportedAuthMethods.add(AuthMethod[authMethod]);
3568
- }
3569
- return supportedAuthMethods;
3814
+ logout() {
3815
+ return __async(this, arguments, function* ({ clearPregenWallets = false } = {}) {
3816
+ yield this.ctx.client.logout();
3817
+ yield this.clearStorage();
3818
+ if (!clearPregenWallets) {
3819
+ Object.entries(this.wallets).forEach(([id, wallet]) => {
3820
+ if (!wallet.pregenIdentifier) {
3821
+ delete this.wallets[id];
3822
+ }
3823
+ });
3824
+ yield this.setWallets(this.wallets);
3825
+ } else {
3826
+ this.wallets = {};
3827
+ }
3828
+ this.currentWalletIds = {};
3829
+ this.externalWallets = {};
3830
+ this.loginEncryptionKeyPair = void 0;
3831
+ this.email = void 0;
3832
+ this.telegramUserId = void 0;
3833
+ this.phone = void 0;
3834
+ this.countryCode = void 0;
3835
+ this.userId = void 0;
3836
+ this.sessionCookie = void 0;
3837
+ dispatchEvent(ParaEvent.LOGOUT_EVENT, null);
3838
+ });
3839
+ }
3840
+ getSupportedCreateAuthMethods() {
3841
+ return __async(this, null, function* () {
3842
+ const res = yield this.touchSession();
3843
+ const partnerId = res.data.partnerId;
3844
+ const partnerRes = yield this.ctx.client.getPartner(partnerId);
3845
+ let supportedAuthMethods = /* @__PURE__ */ new Set();
3846
+ for (const authMethod of partnerRes.data.partner.supportedAuthMethods) {
3847
+ supportedAuthMethods.add(AuthMethod[authMethod]);
3848
+ }
3849
+ return supportedAuthMethods;
3850
+ });
3570
3851
  }
3571
3852
  /**
3572
3853
  * Converts to a string, removing sensitive data when logging this class.
@@ -3575,12 +3856,10 @@ var ParaCore = class _ParaCore {
3575
3856
  **/
3576
3857
  toString() {
3577
3858
  const redactedWallets = Object.keys(this.wallets).reduce(
3578
- (acc, walletId) => ({
3579
- ...acc,
3580
- [walletId]: {
3581
- ...this.wallets[walletId],
3859
+ (acc, walletId) => __spreadProps(__spreadValues({}, acc), {
3860
+ [walletId]: __spreadProps(__spreadValues({}, this.wallets[walletId]), {
3582
3861
  signer: this.wallets[walletId].signer ? "[REDACTED]" : void 0
3583
- }
3862
+ })
3584
3863
  }),
3585
3864
  {}
3586
3865
  );
@@ -3611,6 +3890,10 @@ var ParaCore = class _ParaCore {
3611
3890
  return `Para ${JSON.stringify(obj, null, 2)}`;
3612
3891
  }
3613
3892
  };
3893
+ _supportedWalletTypes = new WeakMap();
3894
+ _supportedWalletTypesOpt = new WeakMap();
3895
+ _ParaCore.version = PARA_CORE_VERSION;
3896
+ var ParaCore = _ParaCore;
3614
3897
 
3615
3898
  // src/index.ts
3616
3899
  import {