@getpara/core-sdk 1.4.5-dev.0 → 1.5.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,65 +1,8 @@
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
- };
35
2
  var __export = (target, all) => {
36
3
  for (var name in all)
37
4
  __defProp(target, name, { get: all[name], enumerable: true });
38
5
  };
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
- };
63
6
 
64
7
  // src/ParaCore.ts
65
8
  import { Buffer as NodeBuffer } from "buffer";
@@ -83,7 +26,7 @@ import forge from "node-forge";
83
26
  // src/utils/events.ts
84
27
  function dispatchEvent(type, data, error) {
85
28
  typeof window !== "undefined" && !!window.dispatchEvent && window.dispatchEvent(
86
- new CustomEvent(type, { detail: __spreadValues({ data }, error && { error: new Error(error) }) })
29
+ new CustomEvent(type, { detail: { data, ...error && { error: new Error(error) } } })
87
30
  );
88
31
  }
89
32
 
@@ -150,8 +93,7 @@ function truncateAddress(str, addressType, { prefix = addressType === "COSMOS" ?
150
93
  return `${str.slice(0, headLength)}...${str.slice(-4)}`;
151
94
  }
152
95
  function stringToPhoneNumber(str) {
153
- var _a;
154
- return (_a = parsePhoneNumberFromString(str)) == null ? void 0 : _a.formatInternational().replace(/[^\d+]/g, "");
96
+ return parsePhoneNumberFromString(str)?.formatInternational().replace(/[^\d+]/g, "");
155
97
  }
156
98
  function normalizePhoneNumber(countryCode, number) {
157
99
  return stringToPhoneNumber(`${countryCode[0] !== "+" ? "+" : ""}${countryCode}${number}`);
@@ -194,17 +136,15 @@ function getOnRampAssets(data, {
194
136
  }
195
137
 
196
138
  // src/utils/polling.ts
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));
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;
205
144
  }
206
- return false;
207
- });
145
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
146
+ }
147
+ return false;
208
148
  }
209
149
 
210
150
  // src/types/config.ts
@@ -378,10 +318,7 @@ function isPregenIdentifierMatch(a, b, type) {
378
318
  }
379
319
  }
380
320
  function isWalletSupported(types, wallet) {
381
- return types.some((walletType) => {
382
- var _a;
383
- return !!((_a = WalletSchemeTypeMap[wallet == null ? void 0 : wallet.scheme]) == null ? void 0 : _a[walletType]);
384
- });
321
+ return types.some((walletType) => !!WalletSchemeTypeMap[wallet?.scheme]?.[walletType]);
385
322
  }
386
323
  function getSchemes(types) {
387
324
  return Object.keys(WalletSchemeTypeMap).filter((scheme) => {
@@ -404,11 +341,12 @@ function getEquivalentTypes(types) {
404
341
  return getWalletTypes(getSchemes((Array.isArray(types) ? types : [types]).map((t) => WalletType[t])));
405
342
  }
406
343
  function entityToWallet(w) {
407
- return __spreadProps(__spreadValues({}, w), {
344
+ return {
345
+ ...w,
408
346
  scheme: w.scheme,
409
347
  type: w.type,
410
348
  pregenIdentifierType: w.pregenIdentifierType
411
- });
349
+ };
412
350
  }
413
351
  function migrateWallet(obj) {
414
352
  if (["USER", "PREGEN"].includes(obj.type)) {
@@ -450,87 +388,79 @@ function decodePrivateKeyPemHex(privateKeyPemHex) {
450
388
  const pem = Buffer.from(privateKeyPemHex, "hex").toString("utf-8");
451
389
  return forge.pki.privateKeyFromPem(pem);
452
390
  }
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
- });
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");
474
410
  }
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
- });
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;
496
430
  }
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
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);
510
437
  };
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
- });
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
+ );
527
459
  }
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
- });
460
+ async function getPublicKeyFromSignature(ctx, userHandle) {
461
+ const encodedUserHandle = base64url.encode(userHandle);
462
+ const keyPair = await getAsymmetricKeyPair(ctx, encodedUserHandle);
463
+ return getPublicKeyHex(keyPair);
534
464
  }
535
465
  function symmetricKeyEncryptMessage(message) {
536
466
  const key = forge.random.getBytesSync(16);
@@ -558,57 +488,49 @@ function decryptWithPrivateKey(privateKey, encryptedMessageHex, encryptedKeyHex)
558
488
  const key = privateKey.decrypt(encryptedKey, RSA_ENCRYPTION_SCHEME);
559
489
  return decipherEncryptedMessageHex(key, encryptedMessageHex);
560
490
  }
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
- });
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);
589
498
  }
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) => ({
499
+ async function getDerivedPrivateKeyAndDecrypt(ctx, seedValue, encryptedShares) {
500
+ return Promise.all(
501
+ encryptedShares.map(async (share) => ({
605
502
  walletId: share.walletId,
606
503
  walletScheme: share.walletScheme,
607
504
  partnerId: share.partnerId,
608
- signer: decryptWithPrivateKey(privateKey, share.encryptedShare, share.encryptedKey),
505
+ signer: await decryptWithDerivedPrivateKey(ctx, {
506
+ seedValue,
507
+ encryptedMessageHex: share.encryptedShare,
508
+ encryptedKeyHex: share.encryptedKey
509
+ }),
609
510
  protocolId: share.protocolId
610
- }));
611
- });
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
+ }));
612
534
  }
613
535
  function encryptWithDerivedPublicKey(publicKeyHex, message) {
614
536
  const { key, encryptedMessageHex } = symmetricKeyEncryptMessage(message);
@@ -627,55 +549,49 @@ function hashPasswordWithSalt(password) {
627
549
  function generateSalt(length = 16) {
628
550
  return forge.util.bytesToHex(forge.random.getBytesSync(length));
629
551
  }
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
- });
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
+ );
644
564
  }
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
- });
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");
657
575
  }
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
- });
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;
679
595
  }
680
596
 
681
597
  // src/external/userManagementClient.ts
@@ -837,126 +753,125 @@ var KeyContainer = class _KeyContainer {
837
753
  };
838
754
 
839
755
  // src/shares/recovery.ts
840
- function sendRecoveryForShare(_0) {
841
- return __async(this, arguments, function* ({
842
- ctx,
843
- userId,
844
- walletId,
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({
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(
898
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) => ({
899
809
  walletId,
900
- useDKLS: ctx.useDKLS
901
- }, emailProps));
902
- return recoveryPrivateKeyContainer ? JSON.stringify(recoveryPrivateKeyContainer) : "";
810
+ ...share
811
+ })),
812
+ ...ignoreRedistributingBackupEncryptedShare ? [] : userBackupKeyShareOptsArr
813
+ ]);
814
+ await ctx.client.distributeParaShare({
815
+ userId,
816
+ walletId,
817
+ useDKLS: ctx.useDKLS,
818
+ ...emailProps
903
819
  });
820
+ return recoveryPrivateKeyContainer ? JSON.stringify(recoveryPrivateKeyContainer) : "";
904
821
  }
905
822
 
906
823
  // src/shares/shareDistribution.ts
907
- function distributeNewShare(_0) {
908
- return __async(this, arguments, function* ({
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({
909
868
  ctx,
910
869
  userId,
911
870
  walletId,
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
- });
871
+ otherEncryptedShares: allEncryptedShares,
872
+ userSigner: userShare,
873
+ ignoreRedistributingBackupEncryptedShare,
874
+ emailProps
960
875
  });
961
876
  }
962
877
 
@@ -965,36 +880,32 @@ import { Encrypt as ECIESEncrypt2, Decrypt as ECIESDecrypt2 } from "@celo/utils/
965
880
  import { Buffer as Buffer2 } from "buffer";
966
881
  import * as eutil2 from "ethereumjs-util";
967
882
  import { randomBytes } from "crypto";
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
- }
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;
980
893
  }
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
- });
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);
988
901
  }
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
- });
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;
998
909
  }
999
910
 
1000
911
  // src/errors.ts
@@ -1021,7 +932,7 @@ var TransactionReviewTimeout = class extends Error {
1021
932
  };
1022
933
 
1023
934
  // src/constants.ts
1024
- var PARA_CORE_VERSION = '1.4.4';
935
+ var PARA_CORE_VERSION = '1.5.0';
1025
936
  var PREFIX = "@CAPSULE/";
1026
937
  var LOCAL_STORAGE_EMAIL = `${PREFIX}e-mail`;
1027
938
  var LOCAL_STORAGE_PHONE = `${PREFIX}phone`;
@@ -1033,7 +944,6 @@ var LOCAL_STORAGE_ED25519_WALLETS = `${PREFIX}ed25519Wallets`;
1033
944
  var LOCAL_STORAGE_WALLETS = `${PREFIX}wallets`;
1034
945
  var LOCAL_STORAGE_EXTERNAL_WALLETS = `${PREFIX}externalWallets`;
1035
946
  var LOCAL_STORAGE_CURRENT_WALLET_IDS = `${PREFIX}currentWalletIds`;
1036
- var LOCAL_STORAGE_CURRENT_EXTERNAL_WALLET_ADDRESSES = `${PREFIX}currentExternalWalletAddresses`;
1037
947
  var LOCAL_STORAGE_SESSION_COOKIE = `${PREFIX}sessionCookie`;
1038
948
  var SESSION_STORAGE_LOGIN_ENCRYPTION_KEY_PAIR = `${PREFIX}loginEncryptionKeyPair`;
1039
949
  var POLLING_INTERVAL_MS = 2e3;
@@ -1044,9 +954,6 @@ function storageListener(e) {
1044
954
  if (!e.url.includes(window.location.origin)) {
1045
955
  return;
1046
956
  }
1047
- if (e.key === LOCAL_STORAGE_CURRENT_EXTERNAL_WALLET_ADDRESSES) {
1048
- this.updateCurrentExternalWalletAddressesFromStorage();
1049
- }
1050
957
  if (e.key === LOCAL_STORAGE_EXTERNAL_WALLETS) {
1051
958
  this.updateExternalWalletsFromStorage();
1052
959
  }
@@ -1096,8 +1003,7 @@ if (typeof global !== "undefined") {
1096
1003
  self.global = self.global || self;
1097
1004
  }
1098
1005
  var { pki, jsbn } = forge3;
1099
- var _supportedWalletTypes, _supportedWalletTypesOpt;
1100
- var _ParaCore = class _ParaCore {
1006
+ var ParaCore = class _ParaCore {
1101
1007
  /**
1102
1008
  * Constructs a new `ParaCore` instance.
1103
1009
  * @param env - `Environment` to use.
@@ -1114,8 +1020,8 @@ var _ParaCore = class _ParaCore {
1114
1020
  * 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.
1115
1021
  */
1116
1022
  this.currentWalletIds = {};
1117
- __privateAdd(this, _supportedWalletTypes);
1118
- __privateAdd(this, _supportedWalletTypesOpt);
1023
+ this.#supportedWalletTypes = void 0;
1024
+ this.#supportedWalletTypesOpt = void 0;
1119
1025
  this.localStorageGetItem = (key) => {
1120
1026
  return this.platformUtils.localStorage.get(key);
1121
1027
  };
@@ -1138,14 +1044,14 @@ var _ParaCore = class _ParaCore {
1138
1044
  * Remove all local storage and prefixed session storage.
1139
1045
  * @param {'local' | 'session' | 'secure' | 'all'} type - Type of storage to clear. Defaults to 'all'.
1140
1046
  */
1141
- this.clearStorage = (type = "all") => __async(this, null, function* () {
1047
+ this.clearStorage = async (type = "all") => {
1142
1048
  const isAll = type === "all";
1143
1049
  (isAll || type === "local") && this.platformUtils.localStorage.clear(PREFIX);
1144
1050
  (isAll || type === "session") && this.platformUtils.sessionStorage.clear(PREFIX);
1145
1051
  if ((isAll || type === "secure") && this.platformUtils.secureStorage) {
1146
1052
  this.platformUtils.secureStorage.clear(PREFIX);
1147
1053
  }
1148
- });
1054
+ };
1149
1055
  this.initializeFromStorage = () => {
1150
1056
  this.updateEmailFromStorage();
1151
1057
  this.updateCountryCodeFromStorage();
@@ -1157,7 +1063,6 @@ var _ParaCore = class _ParaCore {
1157
1063
  this.updateSessionCookieFromStorage();
1158
1064
  this.updateLoginEncryptionKeyPairFromStorage();
1159
1065
  this.updateExternalWalletsFromStorage();
1160
- this.updateCurrentExternalWalletAddressesFromStorage();
1161
1066
  };
1162
1067
  this.updateTelegramUserIdFromStorage = () => {
1163
1068
  this.telegramUserId = this.localStorageGetItem(LOCAL_STORAGE_TELEGRAM_USER_ID) || void 0;
@@ -1174,16 +1079,18 @@ var _ParaCore = class _ParaCore {
1174
1079
  this.updateEmailFromStorage = () => {
1175
1080
  this.email = this.localStorageGetItem(LOCAL_STORAGE_EMAIL) || void 0;
1176
1081
  };
1177
- this.updateWalletsFromStorage = () => __async(this, null, function* () {
1178
- var _a;
1179
- const _currentWalletIds = (_a = this.localStorageGetItem(LOCAL_STORAGE_CURRENT_WALLET_IDS)) != null ? _a : void 0;
1082
+ this.updateWalletsFromStorage = async () => {
1083
+ const _currentWalletIds = this.localStorageGetItem(LOCAL_STORAGE_CURRENT_WALLET_IDS) ?? void 0;
1180
1084
  const currentWalletIds = [void 0, null, "undefined"].includes(_currentWalletIds) ? {} : (() => {
1181
1085
  const fromJson = JSON.parse(_currentWalletIds);
1182
1086
  return Array.isArray(fromJson) ? Object.keys(WalletType2).reduce((acc, type) => {
1183
1087
  const wallet = Object.values(this.wallets).find(
1184
1088
  (w) => fromJson.includes(w.id) && WalletSchemeTypeMap[w.scheme][type]
1185
1089
  );
1186
- return __spreadValues(__spreadValues({}, acc), wallet && !acc[type] ? { [type]: [wallet.id] } : {});
1090
+ return {
1091
+ ...acc,
1092
+ ...wallet && !acc[type] ? { [type]: [wallet.id] } : {}
1093
+ };
1187
1094
  }, {}) : fromJson;
1188
1095
  })();
1189
1096
  this.setCurrentWalletIds(currentWalletIds);
@@ -1191,25 +1098,34 @@ var _ParaCore = class _ParaCore {
1191
1098
  const _wallets = JSON.parse(stringWallets || "{}");
1192
1099
  const stringEd25519Wallets = this.platformUtils.secureStorage ? this.platformUtils.secureStorage.get(LOCAL_STORAGE_ED25519_WALLETS) : this.localStorageGetItem(LOCAL_STORAGE_ED25519_WALLETS);
1193
1100
  const _ed25519Wallets = JSON.parse(stringEd25519Wallets || "{}");
1194
- const wallets = __spreadValues(__spreadValues({}, Object.keys(_wallets).reduce((res, key) => {
1195
- return __spreadProps(__spreadValues({}, res), {
1196
- [key]: migrateWallet(_wallets[key])
1197
- });
1198
- }, {})), Object.keys(_ed25519Wallets).reduce((res, key) => {
1199
- return __spreadValues(__spreadValues({}, res), !res[key] ? { [key]: migrateWallet(_ed25519Wallets[key]) } : {});
1200
- }, {}));
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
+ };
1201
1115
  this.setWallets(wallets);
1202
- });
1116
+ };
1203
1117
  this.updateWalletIdsFromStorage = () => {
1204
- var _a;
1205
- const _currentWalletIds = (_a = this.localStorageGetItem(LOCAL_STORAGE_CURRENT_WALLET_IDS)) != null ? _a : void 0;
1118
+ const _currentWalletIds = this.localStorageGetItem(LOCAL_STORAGE_CURRENT_WALLET_IDS) ?? void 0;
1206
1119
  const currentWalletIds = [void 0, null, "undefined"].includes(_currentWalletIds) ? {} : (() => {
1207
1120
  const fromJson = JSON.parse(_currentWalletIds);
1208
1121
  return Array.isArray(fromJson) ? Object.keys(WalletType2).reduce((acc, type) => {
1209
1122
  const wallet = Object.values(this.wallets).find(
1210
1123
  (w) => fromJson.includes(w.id) && WalletSchemeTypeMap[w.scheme][type]
1211
1124
  );
1212
- return __spreadValues(__spreadValues({}, acc), wallet && !acc[type] ? { [type]: [wallet.id] } : {});
1125
+ return {
1126
+ ...acc,
1127
+ ...wallet && !acc[type] ? { [type]: [wallet.id] } : {}
1128
+ };
1213
1129
  }, {}) : fromJson;
1214
1130
  })();
1215
1131
  this.setCurrentWalletIds(currentWalletIds);
@@ -1231,10 +1147,6 @@ var _ParaCore = class _ParaCore {
1231
1147
  const _externalWallets = JSON.parse(stringExternalWallets || "{}");
1232
1148
  this.setExternalWallets(_externalWallets);
1233
1149
  };
1234
- this.updateCurrentExternalWalletAddressesFromStorage = () => {
1235
- const _currentExternalWalletAddresses = this.localStorageGetItem(LOCAL_STORAGE_CURRENT_EXTERNAL_WALLET_ADDRESSES) || void 0;
1236
- this.currentExternalWalletAddresses = _currentExternalWalletAddresses ? JSON.parse(_currentExternalWalletAddresses) : void 0;
1237
- };
1238
1150
  /**
1239
1151
  * Creates several new wallets with the desired types. If no types are provided, this method
1240
1152
  * will create one for each of the non-optional types specified in the instance's `supportedWalletTypes`
@@ -1302,7 +1214,7 @@ var _ParaCore = class _ParaCore {
1302
1214
  this.ctx.mpcComputationClient = initClient2(opts.offloadMPCComputationURL, opts.disableWorkers);
1303
1215
  }
1304
1216
  try {
1305
- __privateSet(this, _supportedWalletTypes, opts.supportedWalletTypes ? (() => {
1217
+ this.#supportedWalletTypes = opts.supportedWalletTypes ? (() => {
1306
1218
  if (Object.values(opts.supportedWalletTypes).every(
1307
1219
  (config) => !!config && typeof config === "object" && config.optional
1308
1220
  )) {
@@ -1311,20 +1223,19 @@ var _ParaCore = class _ParaCore {
1311
1223
  if (!Object.keys(opts.supportedWalletTypes).every((type) => Object.values(WalletType2).includes(type))) {
1312
1224
  throw new Error("unsupported wallet type");
1313
1225
  }
1314
- __privateSet(this, _supportedWalletTypesOpt, opts.supportedWalletTypes);
1226
+ this.#supportedWalletTypesOpt = opts.supportedWalletTypes;
1315
1227
  return Object.entries(opts.supportedWalletTypes).reduce((acc, [key, value]) => {
1316
- var _a;
1317
1228
  if (!value) {
1318
1229
  return acc;
1319
1230
  }
1320
1231
  if (key === WalletType2.COSMOS && typeof value === "object" && !!value.prefix) {
1321
1232
  this.cosmosPrefix = value.prefix;
1322
1233
  }
1323
- return [...acc, { type: key, optional: value === true ? false : (_a = value.optional) != null ? _a : false }];
1234
+ return [...acc, { type: key, optional: value === true ? false : value.optional ?? false }];
1324
1235
  }, []);
1325
- })() : void 0);
1236
+ })() : void 0;
1326
1237
  } catch (e) {
1327
- __privateSet(this, _supportedWalletTypes, void 0);
1238
+ this.#supportedWalletTypes = void 0;
1328
1239
  }
1329
1240
  if (!this.platformUtils.isSyncStorage || opts.useStorageOverrides) {
1330
1241
  return;
@@ -1332,6 +1243,9 @@ var _ParaCore = class _ParaCore {
1332
1243
  this.initializeFromStorage();
1333
1244
  setupListeners.bind(this)();
1334
1245
  }
1246
+ static {
1247
+ this.version = PARA_CORE_VERSION;
1248
+ }
1335
1249
  get isEmail() {
1336
1250
  return !!this.email && !this.phone && !this.countryCode && !this.farcasterUsername && !this.telegramUserId;
1337
1251
  }
@@ -1346,10 +1260,9 @@ var _ParaCore = class _ParaCore {
1346
1260
  }
1347
1261
  get currentWalletIdsArray() {
1348
1262
  return this.supportedWalletTypes.reduce((acc, { type }) => {
1349
- var _a;
1350
1263
  return [
1351
1264
  ...acc,
1352
- ...((_a = this.currentWalletIds[type]) != null ? _a : []).map((id) => {
1265
+ ...(this.currentWalletIds[type] ?? []).map((id) => {
1353
1266
  return [id, type];
1354
1267
  })
1355
1268
  ];
@@ -1362,17 +1275,19 @@ var _ParaCore = class _ParaCore {
1362
1275
  * A map of pre-generated wallet identifiers that can be claimed in the current instance.
1363
1276
  */
1364
1277
  get pregenIds() {
1365
- return __spreadValues({}, Object.values(this.wallets).filter((wallet) => !this.userId || this.isPregenWalletClaimable(wallet)).reduce((acc, wallet) => {
1366
- var _a, _b;
1367
- if (((_a = acc[wallet.pregenIdentifierType]) != null ? _a : []).includes(wallet.pregenIdentifier)) {
1368
- return acc;
1369
- }
1370
- return __spreadProps(__spreadValues({}, acc), {
1371
- [wallet.pregenIdentifierType]: [
1372
- .../* @__PURE__ */ new Set([...(_b = acc[wallet.pregenIdentifierType]) != null ? _b : [], wallet.pregenIdentifier])
1373
- ]
1374
- });
1375
- }, {}));
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
+ };
1376
1291
  }
1377
1292
  /**
1378
1293
  * Whether the instance has multiple wallets connected.
@@ -1380,13 +1295,14 @@ var _ParaCore = class _ParaCore {
1380
1295
  get isMultiWallet() {
1381
1296
  return this.currentWalletIdsArray.length > 1;
1382
1297
  }
1298
+ #supportedWalletTypes;
1299
+ #supportedWalletTypesOpt;
1383
1300
  get supportedWalletTypes() {
1384
- var _a;
1385
- return (_a = __privateGet(this, _supportedWalletTypes)) != null ? _a : [];
1301
+ return this.#supportedWalletTypes ?? [];
1386
1302
  }
1387
1303
  get isWalletTypeEnabled() {
1388
1304
  return this.supportedWalletTypes.reduce((acc, { type }) => {
1389
- return __spreadProps(__spreadValues({}, acc), { [type]: true });
1305
+ return { ...acc, [type]: true };
1390
1306
  }, {});
1391
1307
  }
1392
1308
  convertBigInt(bigInt) {
@@ -1415,14 +1331,12 @@ var _ParaCore = class _ParaCore {
1415
1331
  };
1416
1332
  }
1417
1333
  isPortal(envOverride) {
1418
- var _a;
1419
1334
  if (typeof window === "undefined") return false;
1420
- return !!((_a = window.location) == null ? void 0 : _a.host) && getPortalBaseURL(envOverride ? { env: envOverride } : this.ctx).includes(window.location.host);
1335
+ return !!window.location?.host && getPortalBaseURL(envOverride ? { env: envOverride } : this.ctx).includes(window.location.host);
1421
1336
  }
1422
1337
  isParaConnect() {
1423
- var _a;
1424
1338
  if (typeof window === "undefined") return false;
1425
- return !!((_a = window.location) == null ? void 0 : _a.host) && getParaConnectBaseUrl(this.ctx).includes(window.location.host);
1339
+ return !!window.location?.host && getParaConnectBaseUrl(this.ctx).includes(window.location.host);
1426
1340
  }
1427
1341
  requireApiKey() {
1428
1342
  if (!this.ctx.apiKey) {
@@ -1433,20 +1347,19 @@ var _ParaCore = class _ParaCore {
1433
1347
  }
1434
1348
  }
1435
1349
  isWalletSupported(wallet) {
1436
- var _a, _b;
1437
- return !__privateGet(this, _supportedWalletTypes) || isWalletSupported((_b = (_a = this.supportedWalletTypes) == null ? void 0 : _a.map(({ type }) => type)) != null ? _b : [], wallet);
1350
+ return !this.#supportedWalletTypes || isWalletSupported(this.supportedWalletTypes?.map(({ type }) => type) ?? [], wallet);
1438
1351
  }
1439
1352
  isWalletOwned(wallet) {
1440
- 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;
1353
+ return this.isWalletSupported(wallet) && !wallet?.pregenIdentifier && !wallet?.pregenIdentifierType && !!this.userId && wallet?.userId === this.userId;
1441
1354
  }
1442
1355
  isPregenWalletUnclaimed(wallet) {
1443
- 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));
1356
+ return this.isWalletSupported(wallet) && (!wallet?.userId || wallet?.isPregen && !!wallet?.pregenIdentifier && !!wallet?.pregenIdentifierType);
1444
1357
  }
1445
1358
  isPregenWalletClaimable(wallet) {
1446
- return this.isWalletSupported(wallet) && this.isPregenWalletUnclaimed(wallet) && (!["EMAIL", "PHONE", "TELEGRAM"].includes(wallet == null ? void 0 : wallet.pregenIdentifierType) || isPregenIdentifierMatch(
1447
- (wallet == null ? void 0 : wallet.pregenIdentifierType) === "EMAIL" ? this.email : (wallet == null ? void 0 : wallet.pregenIdentifierType) === "TELEGRAM" ? this.telegramUserId : this.getPhoneNumber(),
1448
- wallet == null ? void 0 : wallet.pregenIdentifier,
1449
- wallet == null ? void 0 : wallet.pregenIdentifierType
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
1450
1363
  ));
1451
1364
  }
1452
1365
  isWalletUsable(walletId, { type: types, scheme: schemes, forbidPregen = false } = {}, throwError = false) {
@@ -1457,18 +1370,15 @@ var _ParaCore = class _ParaCore {
1457
1370
  const wallet = this.wallets[walletId];
1458
1371
  const [isUnclaimed, isOwned] = [this.isPregenWalletUnclaimed(wallet), this.isWalletOwned(wallet)];
1459
1372
  if (forbidPregen && isUnclaimed) {
1460
- error = `pre-generated wallet with id ${wallet == null ? void 0 : wallet.id} cannot be selected`;
1373
+ error = `pre-generated wallet with id ${wallet?.id} cannot be selected`;
1461
1374
  } else if (!isOwned && !isUnclaimed) {
1462
- error = `wallet with id ${wallet == null ? void 0 : wallet.id} is not owned by the current user`;
1375
+ error = `wallet with id ${wallet?.id} is not owned by the current user`;
1463
1376
  } else if (!this.isWalletSupported(wallet)) {
1464
- 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(", ")}`;
1465
- } else if (types && (!getEquivalentTypes(types).includes(wallet == null ? void 0 : wallet.type) || isOwned && !types.some((type) => {
1466
- var _a, _b;
1467
- return (_b = (_a = this.currentWalletIds) == null ? void 0 : _a[type]) == null ? void 0 : _b.includes(walletId);
1468
- }))) {
1469
- error = `wallet with id ${wallet == null ? void 0 : wallet.id} and type ${wallet == null ? void 0 : wallet.type} cannot be selected`;
1470
- } else if (schemes && !schemes.includes(wallet == null ? void 0 : wallet.scheme)) {
1471
- error = `wallet with id ${wallet == null ? void 0 : wallet.id} and scheme ${wallet == null ? void 0 : wallet.scheme} cannot be selected`;
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`;
1472
1382
  }
1473
1383
  }
1474
1384
  if (error) {
@@ -1488,7 +1398,6 @@ var _ParaCore = class _ParaCore {
1488
1398
  * @returns the formatted address
1489
1399
  */
1490
1400
  getDisplayAddress(walletId, options = {}) {
1491
- var _a;
1492
1401
  if (this.externalWallets[walletId]) {
1493
1402
  const wallet2 = this.externalWallets[walletId];
1494
1403
  return options.truncate ? truncateAddress(wallet2.address, wallet2.type, { prefix: this.cosmosPrefix }) : wallet2.address;
@@ -1500,7 +1409,7 @@ var _ParaCore = class _ParaCore {
1500
1409
  let str;
1501
1410
  switch (wallet.type) {
1502
1411
  case WalletType2.COSMOS:
1503
- str = getCosmosAddress(wallet.publicKey, (_a = this.cosmosPrefix) != null ? _a : "cosmos");
1412
+ str = getCosmosAddress(wallet.publicKey, this.cosmosPrefix ?? "cosmos");
1504
1413
  break;
1505
1414
  default:
1506
1415
  str = wallet.address;
@@ -1526,87 +1435,89 @@ var _ParaCore = class _ParaCore {
1526
1435
  return this.wallets;
1527
1436
  }
1528
1437
  getAddress(walletId) {
1529
- var _a, _b, _c;
1530
- 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;
1531
- }
1532
- constructPortalUrl(_0) {
1533
- return __async(this, arguments, function* (type, opts = {}) {
1534
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
1535
- const base = type === "onRamp" ? getPortalBaseURL(this.ctx) : yield this.getPortalURL(opts.partnerId);
1536
- let path;
1537
- switch (type) {
1538
- case "createPassword": {
1539
- path = `/web/users/${this.userId}/passwords/${opts.pathId}`;
1540
- break;
1541
- }
1542
- case "createAuth": {
1543
- path = `/web/users/${this.userId}/biometrics/${opts.pathId}`;
1544
- break;
1545
- }
1546
- case "loginPassword": {
1547
- path = "/web/passwords/login";
1548
- break;
1549
- }
1550
- case "loginAuth": {
1551
- path = "/web/biometrics/login";
1552
- break;
1553
- }
1554
- case "txReview": {
1555
- path = `/web/users/${this.userId}/transaction-review/${opts.pathId}`;
1556
- break;
1557
- }
1558
- case "onRamp": {
1559
- path = `/web/users/${this.userId}/on-ramp-transaction/${opts.pathId}`;
1560
- break;
1561
- }
1562
- default: {
1563
- throw new Error(`invalid URL type ${type}`);
1564
- }
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;
1565
1447
  }
1566
- const [isCreate, isLogin, isOnRamp] = [
1567
- ["createAuth", "createPassword"].includes(type),
1568
- ["loginAuth", "loginPassword"].includes(type),
1569
- type === "onRamp"
1570
- ];
1571
- const partner = opts.partnerId ? (_a = (yield this.ctx.client.getPartner(opts.partnerId)).data) == null ? void 0 : _a.partner : void 0;
1572
- const params = __spreadValues(__spreadValues(__spreadValues(__spreadValues({
1573
- apiKey: this.ctx.apiKey,
1574
- partnerId: opts.partnerId,
1575
- portalFont: ((_b = opts.theme) == null ? void 0 : _b.font) || (partner == null ? void 0 : partner.font) || ((_c = this.portalTheme) == null ? void 0 : _c.font),
1576
- portalBorderRadius: ((_d = opts.theme) == null ? void 0 : _d.borderRadius) || ((_e = this.portalTheme) == null ? void 0 : _e.borderRadius),
1577
- portalThemeMode: ((_f = opts.theme) == null ? void 0 : _f.mode) || (partner == null ? void 0 : partner.themeMode) || ((_g = this.portalTheme) == null ? void 0 : _g.mode),
1578
- portalAccentColor: ((_h = opts.theme) == null ? void 0 : _h.accentColor) || (partner == null ? void 0 : partner.accentColor) || ((_i = this.portalTheme) == null ? void 0 : _i.accentColor),
1579
- portalForegroundColor: ((_j = opts.theme) == null ? void 0 : _j.foregroundColor) || (partner == null ? void 0 : partner.foregroundColor) || ((_k = this.portalTheme) == null ? void 0 : _k.foregroundColor),
1580
- 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),
1581
- portalPrimaryButtonColor: this.portalPrimaryButtonColor,
1582
- portalTextColor: this.portalTextColor,
1583
- portalPrimaryButtonTextColor: this.portalPrimaryButtonTextColor,
1584
- isForNewDevice: opts.isForNewDevice ? opts.isForNewDevice.toString() : void 0,
1585
- supportedWalletTypes: __privateGet(this, _supportedWalletTypesOpt) ? JSON.stringify(__privateGet(this, _supportedWalletTypesOpt)) : void 0
1586
- }, 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 ? {
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}`);
1470
+ }
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 ? {
1587
1500
  encryptionKey: opts.loginEncryptionPublicKey,
1588
1501
  newDeviceSessionLookupId: opts.newDeviceSessionId,
1589
1502
  newDeviceEncryptionKey: opts.newDeviceEncryptionKey,
1590
1503
  pregenIds: JSON.stringify(this.pregenIds),
1591
1504
  displayName: opts.displayName,
1592
1505
  pfpUrl: opts.pfpUrl
1593
- } : {}), opts.params || {});
1594
- return constructUrl({ base, path, params });
1595
- });
1506
+ } : {},
1507
+ ...opts.params || {}
1508
+ };
1509
+ return constructUrl({ base, path, params });
1596
1510
  }
1597
- touchSession(regenerate = false) {
1598
- return __async(this, null, function* () {
1599
- const res = yield this.ctx.client.touchSession(regenerate);
1600
- this.setSupportedWalletTypes(res.data.supportedWalletTypes, res.data.cosmosPrefix);
1601
- return res;
1602
- });
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;
1603
1515
  }
1604
1516
  setSupportedWalletTypes(supportedWalletTypes, cosmosPrefix) {
1605
- if (supportedWalletTypes && !__privateGet(this, _supportedWalletTypes)) {
1606
- __privateSet(this, _supportedWalletTypes, supportedWalletTypes);
1517
+ if (supportedWalletTypes && !this.#supportedWalletTypes) {
1518
+ this.#supportedWalletTypes = supportedWalletTypes;
1607
1519
  Object.keys(this.currentWalletIds).forEach((type) => {
1608
- var _a;
1609
- if (!((_a = __privateGet(this, _supportedWalletTypes)) == null ? void 0 : _a.some(({ type: supportedType }) => supportedType === type))) {
1520
+ if (!this.#supportedWalletTypes?.some(({ type: supportedType }) => supportedType === type)) {
1610
1521
  delete this.currentWalletIds[type];
1611
1522
  }
1612
1523
  });
@@ -1642,181 +1553,155 @@ var _ParaCore = class _ParaCore {
1642
1553
  *
1643
1554
  * Init only needs to be called for storage that is async.
1644
1555
  */
1645
- init() {
1646
- return __async(this, null, function* () {
1647
- var _a;
1648
- this.email = (yield this.localStorageGetItem(LOCAL_STORAGE_EMAIL)) || void 0;
1649
- this.countryCode = (yield this.localStorageGetItem(LOCAL_STORAGE_COUNTRY_CODE)) || void 0;
1650
- this.phone = (yield this.localStorageGetItem(LOCAL_STORAGE_PHONE)) || void 0;
1651
- this.userId = (yield this.localStorageGetItem(LOCAL_STORAGE_USER_ID)) || void 0;
1652
- this.telegramUserId = (yield this.localStorageGetItem(LOCAL_STORAGE_TELEGRAM_USER_ID)) || void 0;
1653
- const stringWallets = this.platformUtils.secureStorage ? yield this.platformUtils.secureStorage.get(LOCAL_STORAGE_WALLETS) : yield this.localStorageGetItem(LOCAL_STORAGE_WALLETS);
1654
- const _wallets = JSON.parse(stringWallets || "{}");
1655
- const stringEd25519Wallets = this.platformUtils.secureStorage ? yield this.platformUtils.secureStorage.get(LOCAL_STORAGE_ED25519_WALLETS) : yield this.localStorageGetItem(LOCAL_STORAGE_ED25519_WALLETS);
1656
- const _ed25519Wallets = JSON.parse(stringEd25519Wallets || "{}");
1657
- const wallets = __spreadValues(__spreadValues({}, Object.keys(_wallets).reduce((res, key) => {
1658
- return __spreadProps(__spreadValues({}, res), {
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,
1659
1570
  [key]: migrateWallet(_wallets[key])
1660
- });
1661
- }, {})), Object.keys(_ed25519Wallets).reduce((res, key) => {
1662
- return __spreadValues(__spreadValues({}, res), !res[key] ? { [key]: migrateWallet(_ed25519Wallets[key]) } : {});
1663
- }, {}));
1664
- yield this.setWallets(wallets);
1665
- const _currentWalletIds = (_a = yield this.localStorageGetItem(LOCAL_STORAGE_CURRENT_WALLET_IDS)) != null ? _a : void 0;
1666
- const currentWalletIds = [void 0, null, "undefined", "null"].includes(_currentWalletIds) ? {} : (() => {
1667
- const fromJson = JSON.parse(_currentWalletIds);
1668
- return Array.isArray(fromJson) ? Object.keys(WalletType2).reduce((acc, type) => {
1669
- const wallet = Object.values(this.wallets).find(
1670
- (w) => fromJson.includes(w.id) && WalletSchemeTypeMap[w.scheme][type]
1671
- );
1672
- return __spreadValues(__spreadValues({}, acc), wallet && !acc[type] ? { [type]: [wallet.id] } : {});
1673
- }, {}) : fromJson;
1674
- })();
1675
- yield this.setCurrentWalletIds(currentWalletIds);
1676
- this.sessionCookie = (yield this.localStorageGetItem(LOCAL_STORAGE_SESSION_COOKIE)) || (yield this.sessionStorageGetItem(LOCAL_STORAGE_SESSION_COOKIE)) || void 0;
1677
- if (Object.values(this.wallets).filter((w) => this.isWalletOwned(w)).length > 0 && this.currentWalletIdsArray.length === 0) {
1678
- this.findWalletId(void 0, { forbidPregen: true });
1679
- }
1680
- const loginEncryptionKey = yield this.sessionStorageGetItem(SESSION_STORAGE_LOGIN_ENCRYPTION_KEY_PAIR);
1681
- if (loginEncryptionKey && loginEncryptionKey !== "undefined") {
1682
- this.loginEncryptionKeyPair = this.convertEncryptionKeyPair(JSON.parse(loginEncryptionKey));
1683
- }
1684
- const stringExternalWallets = yield this.localStorageGetItem(LOCAL_STORAGE_EXTERNAL_WALLETS);
1685
- const _externalWallets = JSON.parse(stringExternalWallets || "{}");
1686
- yield this.setExternalWallets(_externalWallets);
1687
- const _currentExternalWalletAddresses = (yield this.localStorageGetItem(LOCAL_STORAGE_CURRENT_EXTERNAL_WALLET_ADDRESSES)) || void 0;
1688
- this.currentExternalWalletAddresses = _currentExternalWalletAddresses ? JSON.parse(_currentExternalWalletAddresses) : void 0;
1689
- setupListeners.bind(this)();
1690
- yield this.touchSession();
1691
- });
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();
1692
1608
  }
1693
1609
  /**
1694
1610
  * Sets the email associated with the `ParaCore` instance.
1695
1611
  * @param email - Email to set.
1696
1612
  */
1697
- setEmail(email) {
1698
- return __async(this, null, function* () {
1699
- this.email = email;
1700
- yield this.localStorageSetItem(LOCAL_STORAGE_EMAIL, email);
1701
- });
1613
+ async setEmail(email) {
1614
+ this.email = email;
1615
+ await this.localStorageSetItem(LOCAL_STORAGE_EMAIL, email);
1702
1616
  }
1703
1617
  /**
1704
1618
  * Sets the Telegram user ID associated with the `ParaCore` instance.
1705
1619
  * @param telegramUserId - Telegram user ID to set.
1706
1620
  */
1707
- setTelegramUserId(telegramUserId) {
1708
- return __async(this, null, function* () {
1709
- this.telegramUserId = telegramUserId;
1710
- yield this.localStorageSetItem(LOCAL_STORAGE_TELEGRAM_USER_ID, telegramUserId);
1711
- });
1621
+ async setTelegramUserId(telegramUserId) {
1622
+ this.telegramUserId = telegramUserId;
1623
+ await this.localStorageSetItem(LOCAL_STORAGE_TELEGRAM_USER_ID, telegramUserId);
1712
1624
  }
1713
1625
  /**
1714
1626
  * Sets the phone number associated with the `ParaCore` instance.
1715
1627
  * @param phone - Phone number to set.
1716
1628
  * @param countryCode - Country Code to set.
1717
1629
  */
1718
- setPhoneNumber(phone, countryCode) {
1719
- return __async(this, null, function* () {
1720
- this.phone = phone;
1721
- this.countryCode = countryCode;
1722
- yield this.localStorageSetItem(LOCAL_STORAGE_PHONE, phone);
1723
- yield this.localStorageSetItem(LOCAL_STORAGE_COUNTRY_CODE, countryCode);
1724
- });
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);
1725
1635
  }
1726
1636
  /**
1727
1637
  * Sets the farcaster username associated with the `ParaCore` instance.
1728
1638
  * @param farcasterUsername - Farcaster Username to set.
1729
1639
  */
1730
- setFarcasterUsername(farcasterUsername) {
1731
- return __async(this, null, function* () {
1732
- this.farcasterUsername = farcasterUsername;
1733
- yield this.localStorageSetItem(LOCAL_STORAGE_FARCASTER_USERNAME, farcasterUsername);
1734
- });
1640
+ async setFarcasterUsername(farcasterUsername) {
1641
+ this.farcasterUsername = farcasterUsername;
1642
+ await this.localStorageSetItem(LOCAL_STORAGE_FARCASTER_USERNAME, farcasterUsername);
1735
1643
  }
1736
1644
  /**
1737
1645
  * Sets the external wallet address and type associated with the `ParaCore` instance.
1738
1646
  * @param externalAddress - External wallet address to set.
1739
1647
  * @param externalType - Type of external wallet to set.
1740
1648
  */
1741
- setExternalWallet(_0) {
1742
- return __async(this, arguments, function* ({ address, type, provider, addressBech32 }) {
1743
- this.externalWallets = {
1744
- [address]: {
1745
- id: address,
1746
- address: addressBech32 != null ? addressBech32 : address,
1747
- type,
1748
- name: provider,
1749
- isExternal: true,
1750
- signer: ""
1751
- }
1752
- };
1753
- this.currentExternalWalletAddresses = [address];
1754
- this.setCurrentExternalWalletAddresses(this.currentExternalWalletAddresses);
1755
- this.setExternalWallets(this.externalWallets);
1756
- dispatchEvent(ParaEvent.EXTERNAL_WALLET_CHANGE_EVENT, null);
1757
- });
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);
1758
1662
  }
1759
1663
  /**
1760
1664
  * Sets the user id associated with the `ParaCore` instance.
1761
1665
  * @param userId - User id to set.
1762
1666
  */
1763
- setUserId(userId) {
1764
- return __async(this, null, function* () {
1765
- this.userId = userId;
1766
- yield this.localStorageSetItem(LOCAL_STORAGE_USER_ID, userId);
1767
- });
1667
+ async setUserId(userId) {
1668
+ this.userId = userId;
1669
+ await this.localStorageSetItem(LOCAL_STORAGE_USER_ID, userId);
1768
1670
  }
1769
1671
  /**
1770
1672
  * Sets the wallets associated with the `ParaCore` instance.
1771
1673
  * @param wallets - Wallets to set.
1772
1674
  */
1773
- setWallets(wallets) {
1774
- return __async(this, null, function* () {
1775
- this.wallets = wallets;
1776
- if (this.platformUtils.secureStorage) {
1777
- yield this.platformUtils.secureStorage.set(LOCAL_STORAGE_WALLETS, JSON.stringify(wallets));
1778
- return;
1779
- }
1780
- yield this.localStorageSetItem(LOCAL_STORAGE_WALLETS, JSON.stringify(wallets));
1781
- });
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));
1782
1682
  }
1783
1683
  /**
1784
1684
  * Sets the external wallets associated with the `ParaCore` instance.
1785
1685
  * @param externalWallets - External wallets to set.
1786
1686
  */
1787
- setExternalWallets(externalWallets) {
1788
- return __async(this, null, function* () {
1789
- this.externalWallets = externalWallets;
1790
- yield this.localStorageSetItem(LOCAL_STORAGE_EXTERNAL_WALLETS, JSON.stringify(externalWallets));
1791
- });
1792
- }
1793
- setCurrentExternalWalletAddresses(currentExternalWalletAddresses) {
1794
- return __async(this, null, function* () {
1795
- this.currentExternalWalletAddresses = currentExternalWalletAddresses;
1796
- yield this.localStorageSetItem(
1797
- LOCAL_STORAGE_CURRENT_EXTERNAL_WALLET_ADDRESSES,
1798
- JSON.stringify(currentExternalWalletAddresses)
1799
- );
1800
- });
1687
+ async setExternalWallets(externalWallets) {
1688
+ this.externalWallets = externalWallets;
1689
+ await this.localStorageSetItem(LOCAL_STORAGE_EXTERNAL_WALLETS, JSON.stringify(externalWallets));
1801
1690
  }
1802
1691
  /**
1803
1692
  * Sets the login encryption key pair associated with the `ParaCore` instance.
1804
1693
  * @param keyPair - Encryption key pair generated from loginEncryptionKey.
1805
1694
  */
1806
- setLoginEncryptionKeyPair(keyPair) {
1807
- return __async(this, null, function* () {
1808
- if (!keyPair) {
1809
- keyPair = yield getAsymmetricKeyPair(this.ctx);
1810
- }
1811
- this.loginEncryptionKeyPair = keyPair;
1812
- yield this.sessionStorageSetItem(SESSION_STORAGE_LOGIN_ENCRYPTION_KEY_PAIR, JSON.stringify(keyPair));
1813
- });
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));
1814
1701
  }
1815
- deleteLoginEncryptionKeyPair() {
1816
- return __async(this, null, function* () {
1817
- this.loginEncryptionKeyPair = void 0;
1818
- yield this.sessionStorageRemoveItem(SESSION_STORAGE_LOGIN_ENCRYPTION_KEY_PAIR);
1819
- });
1702
+ async deleteLoginEncryptionKeyPair() {
1703
+ this.loginEncryptionKeyPair = void 0;
1704
+ await this.sessionStorageRemoveItem(SESSION_STORAGE_LOGIN_ENCRYPTION_KEY_PAIR);
1820
1705
  }
1821
1706
  /**
1822
1707
  * Gets the userId associated with the `ParaCore` instance.
@@ -1856,25 +1741,23 @@ var _ParaCore = class _ParaCore {
1856
1741
  getFarcasterUsername() {
1857
1742
  return this.farcasterUsername;
1858
1743
  }
1859
- setCurrentWalletIds(_0) {
1860
- return __async(this, arguments, function* (currentWalletIds, {
1861
- needsWallet = false,
1862
- sessionLookupId,
1863
- newDeviceSessionLookupId
1864
- } = {}) {
1865
- this.currentWalletIds = currentWalletIds;
1866
- yield this.localStorageSetItem(LOCAL_STORAGE_CURRENT_WALLET_IDS, JSON.stringify(this.currentWalletIds));
1867
- if (sessionLookupId) {
1868
- yield this.ctx.client.setCurrentWalletIds(
1869
- this.getUserId(),
1870
- this.currentWalletIds,
1871
- needsWallet,
1872
- sessionLookupId,
1873
- newDeviceSessionLookupId
1874
- );
1875
- }
1876
- dispatchEvent(ParaEvent.WALLETS_CHANGE_EVENT, null);
1877
- });
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);
1878
1761
  }
1879
1762
  /**
1880
1763
  * Validates that a wallet ID is present on the instance, usable, and matches the desired filters.
@@ -1928,7 +1811,6 @@ var _ParaCore = class _ParaCore {
1928
1811
  return wallet;
1929
1812
  }
1930
1813
  findWallet(idOrAddress, overrideType, filter = {}) {
1931
- var _b, _c;
1932
1814
  if (!idOrAddress && Object.keys(this.externalWallets).length > 0) {
1933
1815
  return Object.values(this.externalWallets)[0];
1934
1816
  }
@@ -1938,18 +1820,18 @@ var _ParaCore = class _ParaCore {
1938
1820
  try {
1939
1821
  const walletId = this.findWalletId(idOrAddress, filter);
1940
1822
  if (walletId && !!this.wallets[walletId]) {
1941
- const _a = this.wallets[walletId], { signer: _signer } = _a, wallet = __objRest(_a, ["signer"]);
1942
- const type = (_c = overrideType != null ? overrideType : (_b = this.currentWalletIdsArray.find(([id]) => id === walletId)) == null ? void 0 : _b[1]) != null ? _c : wallet.type;
1943
- return __spreadProps(__spreadValues({}, wallet), {
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,
1944
1827
  type: WalletType2[type]
1945
- });
1828
+ };
1946
1829
  }
1947
1830
  } catch (e) {
1948
1831
  return void 0;
1949
1832
  }
1950
1833
  }
1951
1834
  get availableWallets() {
1952
- var _a;
1953
1835
  return [
1954
1836
  ...this.currentWalletIdsArray.map(([address, type]) => [address, type, false]).map(([id, type]) => {
1955
1837
  const wallet = this.findWallet(id, type);
@@ -1961,7 +1843,7 @@ var _ParaCore = class _ParaCore {
1961
1843
  name: wallet.name
1962
1844
  };
1963
1845
  }).filter((obj) => obj !== null),
1964
- ...Object.values((_a = this.externalWallets) != null ? _a : {})
1846
+ ...Object.values(this.externalWallets ?? {})
1965
1847
  ];
1966
1848
  }
1967
1849
  /**
@@ -1975,78 +1857,61 @@ var _ParaCore = class _ParaCore {
1975
1857
  assertIsValidWalletId(walletId, condition = {}) {
1976
1858
  this.isWalletUsable(walletId, condition, true);
1977
1859
  }
1978
- assertIsValidWalletType(type, walletTypes) {
1979
- return __async(this, null, function* () {
1980
- if (!__privateGet(this, _supportedWalletTypes)) {
1981
- yield this.touchSession();
1982
- }
1983
- if (!type || !Object.values(WalletType2).includes(type) || !(walletTypes != null ? walletTypes : this.supportedWalletTypes.map(({ type: type2 }) => type2)).includes(type)) {
1984
- throw new Error(`wallet type ${type} is not supported`);
1985
- }
1986
- return type;
1987
- });
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;
1988
1868
  }
1989
- getMissingTypes() {
1990
- return __async(this, null, function* () {
1991
- if (!__privateGet(this, _supportedWalletTypes)) {
1992
- yield this.touchSession();
1993
- }
1994
- return this.supportedWalletTypes.filter(
1995
- ({ type: t, optional }) => !optional && Object.values(this.wallets).every((w) => !this.isWalletOwned(w) || !WalletSchemeTypeMap[w.scheme][t])
1996
- ).map(({ type }) => type);
1997
- });
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);
1998
1876
  }
1999
- getTypesToCreate(types) {
2000
- return __async(this, null, function* () {
2001
- if (!__privateGet(this, _supportedWalletTypes)) {
2002
- yield this.touchSession();
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;
2003
1887
  }
2004
- return getSchemes(types != null ? types : yield this.getMissingTypes()).map((scheme) => {
2005
- switch (scheme) {
2006
- case WalletScheme2.ED25519:
2007
- return WalletType2.SOLANA;
2008
- default:
2009
- return this.supportedWalletTypes.some(({ type, optional }) => type === WalletType2.COSMOS && !optional) ? WalletType2.COSMOS : WalletType2.EVM;
2010
- }
2011
- });
2012
1888
  });
2013
1889
  }
2014
- getPartnerURL(partnerId) {
2015
- return __async(this, null, function* () {
2016
- const res = yield this.ctx.client.getPartner(partnerId);
2017
- return res.data.partner.portalUrl;
2018
- });
1890
+ async getPartnerURL(partnerId) {
1891
+ const res = await this.ctx.client.getPartner(partnerId);
1892
+ return res.data.partner.portalUrl;
2019
1893
  }
2020
1894
  /**
2021
1895
  * URL of the portal, which can be associated with a partner id
2022
1896
  * @param partnerId: string - id of the partner to get the portal URL for
2023
1897
  * @returns - portal URL
2024
1898
  */
2025
- getPortalURL(partnerId) {
2026
- return __async(this, null, function* () {
2027
- return partnerId && (yield this.getPartnerURL(partnerId)) || getPortalBaseURL(this.ctx);
2028
- });
1899
+ async getPortalURL(partnerId) {
1900
+ return partnerId && await this.getPartnerURL(partnerId) || getPortalBaseURL(this.ctx);
2029
1901
  }
2030
- getWebAuthURLForCreate(_a) {
2031
- return __async(this, null, function* () {
2032
- var _b = _a, {
2033
- webAuthId
2034
- } = _b, options = __objRest(_b, [
2035
- "webAuthId"
2036
- ]);
2037
- return this.constructPortalUrl("createAuth", __spreadProps(__spreadValues({}, options), { pathId: webAuthId }));
2038
- });
1902
+ async getWebAuthURLForCreate({
1903
+ webAuthId,
1904
+ ...options
1905
+ }) {
1906
+ return this.constructPortalUrl("createAuth", { ...options, pathId: webAuthId });
2039
1907
  }
2040
- getPasswordURLForCreate(_c) {
2041
- return __async(this, null, function* () {
2042
- var _d = _c, {
2043
- passwordId
2044
- } = _d, options = __objRest(_d, [
2045
- "passwordId"
2046
- ]);
2047
- return this.constructPortalUrl("createPassword", __spreadProps(__spreadValues({}, options), {
2048
- pathId: passwordId
2049
- }));
1908
+ async getPasswordURLForCreate({
1909
+ passwordId,
1910
+ ...options
1911
+ }) {
1912
+ return this.constructPortalUrl("createPassword", {
1913
+ ...options,
1914
+ pathId: passwordId
2050
1915
  });
2051
1916
  }
2052
1917
  getShortUrl(compressedUrl) {
@@ -2055,42 +1920,35 @@ var _ParaCore = class _ParaCore {
2055
1920
  path: `/short/${compressedUrl}`
2056
1921
  });
2057
1922
  }
2058
- shortenLoginLink(link) {
2059
- return __async(this, null, function* () {
2060
- const url = yield upload(link, this.ctx.client);
2061
- return this.getShortUrl(url);
2062
- });
1923
+ async shortenLoginLink(link) {
1924
+ const url = await upload(link, this.ctx.client);
1925
+ return this.getShortUrl(url);
2063
1926
  }
2064
1927
  /**
2065
1928
  * Generates a URL for registering a new WebAuth passkey.
2066
1929
  * @param {GetWebAuthUrlForLoginParams} opts the options object
2067
1930
  * @returns - the URL for creating a new passkey
2068
1931
  */
2069
- getWebAuthURLForLogin(opts) {
2070
- return __async(this, null, function* () {
2071
- return this.constructPortalUrl("loginAuth", opts);
2072
- });
1932
+ async getWebAuthURLForLogin(opts) {
1933
+ return this.constructPortalUrl("loginAuth", opts);
2073
1934
  }
2074
1935
  /**
2075
1936
  * Generates a URL for registering a new user password.
2076
1937
  * @param {GetWebAuthUrlForLoginParams} opts the options object
2077
1938
  * @returns - the URL for creating a new password
2078
1939
  */
2079
- getPasswordURLForLogin(opts) {
2080
- return __async(this, null, function* () {
2081
- return this.constructPortalUrl("loginPassword", opts);
2082
- });
1940
+ async getPasswordURLForLogin(opts) {
1941
+ return this.constructPortalUrl("loginPassword", opts);
2083
1942
  }
2084
1943
  /**
2085
1944
  * Generates a URL for registering a new WebAuth passkey for a phone number.
2086
1945
  * @param {Omit<GetWebAuthUrlForLoginParams, 'authType'>} opts the options object
2087
1946
  * @returns - web auth url
2088
1947
  */
2089
- getWebAuthURLForLoginForPhone(opts) {
2090
- return __async(this, null, function* () {
2091
- return this.constructPortalUrl("loginAuth", __spreadValues({
2092
- authType: "phone"
2093
- }, opts));
1948
+ async getWebAuthURLForLoginForPhone(opts) {
1949
+ return this.constructPortalUrl("loginAuth", {
1950
+ authType: "phone",
1951
+ ...opts
2094
1952
  });
2095
1953
  }
2096
1954
  /**
@@ -2098,59 +1956,57 @@ var _ParaCore = class _ParaCore {
2098
1956
  * @param {string } [walletId] id of the wallet to get the private key for. Will default to the first wallet if not provided.
2099
1957
  * @returns - the private key string.
2100
1958
  */
2101
- getPrivateKey(walletId) {
2102
- return __async(this, null, function* () {
2103
- const wallets = Object.values(this.wallets);
2104
- const wallet = walletId ? this.wallets[walletId] : wallets == null ? void 0 : wallets[0];
2105
- if (!wallet) {
2106
- throw new Error("wallet not found");
2107
- }
2108
- if (wallet.scheme !== WalletScheme2.DKLS) {
2109
- throw new Error("invalid wallet scheme");
2110
- }
2111
- return yield this.platformUtils.getPrivateKey(
2112
- this.ctx,
2113
- this.userId,
2114
- wallet.id,
2115
- wallet.signer,
2116
- this.retrieveSessionCookie()
2117
- );
2118
- });
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
+ );
2119
1975
  }
2120
1976
  /**
2121
1977
  * Fetches the wallets associated with the user.
2122
1978
  * @returns {WalletEntity[]} wallets that were fetched.
2123
1979
  */
2124
- fetchWallets() {
2125
- return __async(this, null, function* () {
2126
- const res = yield this.isPortal() || this.isParaConnect() ? this.ctx.client.getAllWallets(this.userId) : this.ctx.client.getWallets(this.userId, true);
2127
- return res.data.wallets.filter(
2128
- (wallet) => !!wallet.address && (this.isParaConnect() || !this.isParaConnect() && this.isWalletSupported(entityToWallet(wallet)))
2129
- );
2130
- });
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
+ );
2131
1985
  }
2132
- populateWalletAddresses() {
2133
- return __async(this, null, function* () {
2134
- const res = yield this.ctx.client.getWallets(this.userId, true);
2135
- const wallets = res.data.wallets;
2136
- wallets.forEach((entity) => {
2137
- if (this.wallets[entity.id]) {
2138
- this.wallets[entity.id] = __spreadValues(__spreadValues({}, entityToWallet(entity)), this.wallets[entity.id]);
2139
- }
2140
- });
2141
- yield this.setWallets(this.wallets);
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
+ }
2142
1996
  });
1997
+ await this.setWallets(this.wallets);
2143
1998
  }
2144
- populatePregenWalletAddresses() {
2145
- return __async(this, null, function* () {
2146
- const res = yield this.getPregenWallets();
2147
- res.forEach((entity) => {
2148
- if (this.wallets[entity.id]) {
2149
- this.wallets[entity.id] = __spreadValues(__spreadValues({}, entityToWallet(entity)), this.wallets[entity.id]);
2150
- }
2151
- });
2152
- yield this.setWallets(this.wallets);
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
+ }
2153
2008
  });
2009
+ await this.setWallets(this.wallets);
2154
2010
  }
2155
2011
  /**
2156
2012
  * Checks if a user exists for an email address.
@@ -2158,11 +2014,9 @@ var _ParaCore = class _ParaCore {
2158
2014
  * @param {string} opts.email the email to check.
2159
2015
  * @returns true if user exists, false otherwise.
2160
2016
  */
2161
- checkIfUserExists(_0) {
2162
- return __async(this, arguments, function* ({ email }) {
2163
- const res = yield this.ctx.client.checkUserExists({ email });
2164
- return res.data.exists;
2165
- });
2017
+ async checkIfUserExists({ email }) {
2018
+ const res = await this.ctx.client.checkUserExists({ email });
2019
+ return res.data.exists;
2166
2020
  }
2167
2021
  /**
2168
2022
  * Checks if a user exists for a phone number.
@@ -2171,26 +2025,23 @@ var _ParaCore = class _ParaCore {
2171
2025
  * @param {string} opts.countryCode - the country code.
2172
2026
  * @returns true if user exists, false otherwise.
2173
2027
  */
2174
- checkIfUserExistsByPhone(_0) {
2175
- return __async(this, arguments, function* ({ phone, countryCode }) {
2176
- const res = yield this.ctx.client.checkUserExists({ phone, countryCode });
2177
- return res.data.exists;
2178
- });
2028
+ async checkIfUserExistsByPhone({ phone, countryCode }) {
2029
+ const res = await this.ctx.client.checkUserExists({ phone, countryCode });
2030
+ return res.data.exists;
2179
2031
  }
2180
2032
  /**
2181
2033
  * Creates a new user.
2182
2034
  * @param {Object} opts the options object
2183
2035
  * @param {string} opts.email the email to use.
2184
2036
  */
2185
- createUser(_0) {
2186
- return __async(this, arguments, function* ({ email }) {
2187
- this.requireApiKey();
2188
- yield this.setEmail(email);
2189
- const { userId } = yield this.ctx.client.createUser(__spreadValues({
2190
- email: this.email
2191
- }, this.getVerificationEmailProps()));
2192
- yield this.setUserId(userId);
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()
2193
2043
  });
2044
+ await this.setUserId(userId);
2194
2045
  }
2195
2046
  /**
2196
2047
  * Creates a new user with a phone number.
@@ -2198,16 +2049,14 @@ var _ParaCore = class _ParaCore {
2198
2049
  * @param {string} opts.phone - the phone number to use for creating the user.
2199
2050
  * @param {string} opts.countryCode - the country code to use for creating the user.
2200
2051
  */
2201
- createUserByPhone(_0) {
2202
- return __async(this, arguments, function* ({ phone, countryCode }) {
2203
- this.requireApiKey();
2204
- yield this.setPhoneNumber(phone, countryCode);
2205
- const { userId } = yield this.ctx.client.createUser({
2206
- phone: this.phone,
2207
- countryCode: this.countryCode
2208
- });
2209
- yield this.setUserId(userId);
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
2210
2058
  });
2059
+ await this.setUserId(userId);
2211
2060
  }
2212
2061
  /**
2213
2062
  * Logs in or creates a new user using an external wallet address.
@@ -2216,19 +2065,17 @@ var _ParaCore = class _ParaCore {
2216
2065
  * @param {WalletType} opts.type type of external wallet to use for identification.
2217
2066
  * @param {string} opts.provider the name of the provider for the external wallet.
2218
2067
  */
2219
- externalWalletLogin(wallet) {
2220
- return __async(this, null, function* () {
2221
- this.requireApiKey();
2222
- const res = yield this.ctx.client.externalWalletLogin({
2223
- externalAddress: wallet.address,
2224
- type: wallet.type,
2225
- externalWalletProvider: wallet.provider,
2226
- shouldTrackUser: wallet.shouldTrackUser
2227
- });
2228
- yield this.setExternalWallet(wallet);
2229
- yield this.setUserId(res.userId);
2230
- return res;
2231
- });
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;
2232
2079
  }
2233
2080
  /**
2234
2081
  * Returns whether or not the user is connected with an external wallet.
@@ -2242,22 +2089,18 @@ var _ParaCore = class _ParaCore {
2242
2089
  * @param {string} verificationCode the six-digit code to check
2243
2090
  * @returns {string} the web auth url for creating a new credential
2244
2091
  */
2245
- verifyEmail(_0) {
2246
- return __async(this, arguments, function* ({ verificationCode }) {
2247
- yield this.ctx.client.verifyEmail(this.userId, { verificationCode });
2248
- return this.getSetUpBiometricsURL();
2249
- });
2250
- }
2251
- verifyExternalWallet(_0) {
2252
- return __async(this, arguments, function* ({
2253
- address,
2254
- signedMessage,
2255
- cosmosPublicKeyHex,
2256
- cosmosSigner
2257
- }) {
2258
- yield this.ctx.client.verifyExternalWallet(this.userId, { address, signedMessage, cosmosPublicKeyHex, cosmosSigner });
2259
- return this.getSetUpBiometricsURL();
2260
- });
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();
2261
2104
  }
2262
2105
  /**
2263
2106
  * Passes the phone code obtained from the user for verification.
@@ -2265,11 +2108,9 @@ var _ParaCore = class _ParaCore {
2265
2108
  * @param {string} verificationCode the six-digit code to check
2266
2109
  * @returns {string} the web auth url for creating a new credential
2267
2110
  */
2268
- verifyPhone(_0) {
2269
- return __async(this, arguments, function* ({ verificationCode }) {
2270
- yield this.ctx.client.verifyPhone(this.userId, { verificationCode });
2271
- return this.getSetUpBiometricsURLForPhone();
2272
- });
2111
+ async verifyPhone({ verificationCode }) {
2112
+ await this.ctx.client.verifyPhone(this.userId, { verificationCode });
2113
+ return this.getSetUpBiometricsURLForPhone();
2273
2114
  }
2274
2115
  /**
2275
2116
  * Validates the response received from an attempted Telegram login for authenticity, then
@@ -2277,19 +2118,17 @@ var _ParaCore = class _ParaCore {
2277
2118
  * @param authResponse - the response JSON object received from the Telegram widget.
2278
2119
  * @returns `{ isValid: boolean; telegramUserId?: string; userId?: string; isNewUser?: boolean; supportedAuthMethods?: AuthMethod[]; biometricHints?: BiometricLocationHint[] }`
2279
2120
  */
2280
- verifyTelegram(authObject) {
2281
- return __async(this, null, function* () {
2282
- const res = yield this.ctx.client.verifyTelegram(authObject);
2283
- if (res.isValid) {
2284
- yield this.setUserId(res.userId);
2285
- yield this.setTelegramUserId(res.telegramUserId);
2286
- yield this.touchSession(true);
2287
- if (!this.loginEncryptionKeyPair) {
2288
- yield this.setLoginEncryptionKeyPair();
2289
- }
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();
2290
2129
  }
2291
- return res;
2292
- });
2130
+ }
2131
+ return res;
2293
2132
  }
2294
2133
  /**
2295
2134
  * Performs 2FA verification.
@@ -2298,16 +2137,14 @@ var _ParaCore = class _ParaCore {
2298
2137
  * @param {string} opts.verificationCode the verification code to received via 2FA.
2299
2138
  * @returns {Object} `{ address, initiatedAt, status, userId, walletId }`
2300
2139
  */
2301
- verify2FA(_0) {
2302
- return __async(this, arguments, function* ({ email, verificationCode }) {
2303
- const res = yield this.ctx.client.verify2FA(email, verificationCode);
2304
- return {
2305
- initiatedAt: res.data.initiatedAt,
2306
- status: res.data.status,
2307
- userId: res.data.userId,
2308
- wallets: res.data.wallets
2309
- };
2310
- });
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
+ };
2311
2148
  }
2312
2149
  /**
2313
2150
  * Performs 2FA verification.
@@ -2317,76 +2154,65 @@ var _ParaCore = class _ParaCore {
2317
2154
  * @param {string} opts.verificationCode - verification code to received via 2FA.
2318
2155
  * @returns {Object} `{ address, initiatedAt, status, userId, walletId }`
2319
2156
  */
2320
- verify2FAForPhone(_0) {
2321
- return __async(this, arguments, function* ({
2322
- phone,
2323
- countryCode,
2324
- verificationCode
2325
- }) {
2326
- const res = yield this.ctx.client.verify2FAForPhone(phone, countryCode, verificationCode);
2327
- return {
2328
- initiatedAt: res.data.initiatedAt,
2329
- status: res.data.status,
2330
- userId: res.data.userId,
2331
- wallets: res.data.wallets
2332
- };
2333
- });
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
+ };
2334
2169
  }
2335
2170
  /**
2336
2171
  * Sets up two-factor authentication for the current user.
2337
2172
  * @returns {string} uri - uri to use for setting up 2FA
2338
2173
  * */
2339
- setup2FA() {
2340
- return __async(this, null, function* () {
2341
- const res = yield this.ctx.client.setup2FA(this.userId);
2342
- return {
2343
- uri: res.data.uri
2344
- };
2345
- });
2174
+ async setup2FA() {
2175
+ const res = await this.ctx.client.setup2FA(this.userId);
2176
+ return {
2177
+ uri: res.data.uri
2178
+ };
2346
2179
  }
2347
2180
  /**
2348
2181
  * Enables 2FA.
2349
2182
  * @param {Object} opts the options object
2350
2183
  * @param {string} opts.verificationCode - the verification code received via 2FA.
2351
2184
  */
2352
- enable2FA(_0) {
2353
- return __async(this, arguments, function* ({ verificationCode }) {
2354
- yield this.ctx.client.enable2FA(this.userId, verificationCode);
2355
- });
2185
+ async enable2FA({ verificationCode }) {
2186
+ await this.ctx.client.enable2FA(this.userId, verificationCode);
2356
2187
  }
2357
2188
  /**
2358
2189
  * Determines if 2FA has been set up.
2359
2190
  * @returns {Object} `{ isSetup: boolean }` - true if 2FA is setup, false otherwise
2360
2191
  */
2361
- check2FAStatus() {
2362
- return __async(this, null, function* () {
2363
- if (!this.userId) {
2364
- return { isSetup: false };
2365
- }
2366
- const res = yield this.ctx.client.check2FAStatus(this.userId);
2367
- return {
2368
- isSetup: res.data.isSetup
2369
- };
2370
- });
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
+ };
2371
2200
  }
2372
2201
  /**
2373
2202
  * Resend a verification email for the current user.
2374
2203
  */
2375
- resendVerificationCode() {
2376
- return __async(this, null, function* () {
2377
- yield this.ctx.client.resendVerificationCode(__spreadValues({
2378
- userId: this.userId
2379
- }, this.getVerificationEmailProps()));
2204
+ async resendVerificationCode() {
2205
+ await this.ctx.client.resendVerificationCode({
2206
+ userId: this.userId,
2207
+ ...this.getVerificationEmailProps()
2380
2208
  });
2381
2209
  }
2382
2210
  /**
2383
2211
  * Resend a verification SMS for the current user.
2384
2212
  */
2385
- resendVerificationCodeByPhone() {
2386
- return __async(this, null, function* () {
2387
- yield this.ctx.client.resendVerificationCodeByPhone({
2388
- userId: this.userId
2389
- });
2213
+ async resendVerificationCodeByPhone() {
2214
+ await this.ctx.client.resendVerificationCodeByPhone({
2215
+ userId: this.userId
2390
2216
  });
2391
2217
  }
2392
2218
  /**
@@ -2396,21 +2222,19 @@ var _ParaCore = class _ParaCore {
2396
2222
  * @param {boolean} opts.isForNewDevice whether the passkey is for a new device of an existing user
2397
2223
  * @returns {string} the URL
2398
2224
  */
2399
- getSetUpBiometricsURL() {
2400
- return __async(this, arguments, function* ({
2401
- authType = "email",
2402
- isForNewDevice = false
2403
- } = {}) {
2404
- const res = yield this.ctx.client.addSessionPublicKey(this.userId, {
2405
- status: PublicKeyStatus.PENDING,
2406
- type: PublicKeyType.WEB
2407
- });
2408
- return this.getWebAuthURLForCreate({
2409
- authType,
2410
- isForNewDevice,
2411
- webAuthId: res.data.id,
2412
- partnerId: res.data.partnerId
2413
- });
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
2414
2238
  });
2415
2239
  }
2416
2240
  /**
@@ -2419,20 +2243,18 @@ var _ParaCore = class _ParaCore {
2419
2243
  * @param {boolean} opts.isForNewDevice whether the passkey is for a new device of an existing user
2420
2244
  * @returns {string} the URL
2421
2245
  */
2422
- getSetUpBiometricsURLForPhone() {
2423
- return __async(this, arguments, function* ({
2424
- isForNewDevice = false
2425
- } = {}) {
2426
- const res = yield this.ctx.client.addSessionPublicKey(this.userId, {
2427
- status: PublicKeyStatus.PENDING,
2428
- type: PublicKeyType.WEB
2429
- });
2430
- return this.getWebAuthURLForCreate({
2431
- authType: "phone",
2432
- isForNewDevice,
2433
- webAuthId: res.data.id,
2434
- partnerId: res.data.partnerId
2435
- });
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
2436
2258
  });
2437
2259
  }
2438
2260
  /**
@@ -2443,107 +2265,95 @@ var _ParaCore = class _ParaCore {
2443
2265
  * @param {Theme} [opts.theme] the portal theme to use in place of the partner's default
2444
2266
  * @returns {string} the URL
2445
2267
  */
2446
- getSetupPasswordURL() {
2447
- return __async(this, arguments, function* ({
2448
- authType = "email",
2449
- isForNewDevice = false,
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,
2450
2281
  theme
2451
- } = {}) {
2452
- const res = yield this.ctx.client.addSessionPasswordPublicKey(this.userId, {
2453
- status: PasswordStatus.PENDING
2454
- });
2455
- return this.getPasswordURLForCreate({
2456
- authType,
2457
- isForNewDevice,
2458
- passwordId: res.data.id,
2459
- partnerId: res.data.partnerId,
2460
- theme
2461
- });
2462
2282
  });
2463
2283
  }
2464
2284
  /**
2465
2285
  * Checks if the current session is active.
2466
2286
  * @returns `true` if active, `false` otherwise
2467
2287
  */
2468
- isSessionActive() {
2469
- return __async(this, null, function* () {
2470
- if (this.isUsingExternalWallet()) {
2471
- return true;
2472
- }
2473
- const res = yield this.touchSession();
2474
- return !!res.data.isAuthenticated;
2475
- });
2288
+ async isSessionActive() {
2289
+ if (this.isUsingExternalWallet()) {
2290
+ return true;
2291
+ }
2292
+ const res = await this.touchSession();
2293
+ return !!res.data.isAuthenticated;
2476
2294
  }
2477
2295
  /**
2478
2296
  * Checks if a session is active and a wallet exists.
2479
2297
  * @returns `true` if active, `false` otherwise
2480
2298
  **/
2481
- isFullyLoggedIn() {
2482
- return __async(this, null, function* () {
2483
- if (this.isUsingExternalWallet()) {
2484
- return true;
2485
- }
2486
- const isSessionActive = yield this.isSessionActive();
2487
- return isSessionActive && this.currentWalletIdsArray.length > 0 && this.currentWalletIdsArray.reduce((acc, [id]) => acc && !!this.wallets[id], true);
2488
- });
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);
2489
2305
  }
2490
- supportedAuthMethods(auth) {
2491
- return __async(this, null, function* () {
2492
- const { supportedAuthMethods } = yield this.ctx.client.getSupportedAuthMethods(auth);
2493
- const authMethods = /* @__PURE__ */ new Set();
2494
- for (const type of supportedAuthMethods) {
2495
- switch (type) {
2496
- case "PASSWORD":
2497
- authMethods.add(AuthMethod.PASSWORD);
2498
- break;
2499
- case "BIOMETRIC":
2500
- authMethods.add(AuthMethod.PASSKEY);
2501
- break;
2502
- }
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;
2503
2317
  }
2504
- return authMethods;
2505
- });
2318
+ }
2319
+ return authMethods;
2506
2320
  }
2507
2321
  /**
2508
2322
  * Get hints associated with the users stored biometrics.
2509
2323
  * @returns Array containing useragents and AAGuids for stored biometrics
2510
2324
  */
2511
- getUserBiometricLocationHints() {
2512
- return __async(this, null, function* () {
2513
- if (!this.email && !this.phone && !this.farcasterUsername && !this.telegramUserId) {
2514
- throw new Error("one of email, phone or farcaster username are required to get biometric location hints");
2515
- }
2516
- return yield this.ctx.client.getBiometricLocationHints({
2517
- email: this.email,
2518
- phone: this.phone,
2519
- countryCode: this.countryCode,
2520
- farcasterUsername: this.farcasterUsername,
2521
- telegramUserId: this.telegramUserId
2522
- });
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
2523
2335
  });
2524
2336
  }
2525
- setAuth(auth) {
2526
- return __async(this, null, function* () {
2527
- const authInfo = extractAuthInfo(auth);
2528
- if (!authInfo) {
2529
- return void 0;
2530
- }
2531
- switch (authInfo.authType) {
2532
- case "email":
2533
- yield this.setEmail(authInfo.identifier);
2534
- break;
2535
- case "phone":
2536
- yield this.setPhoneNumber(authInfo.auth.phone, authInfo.auth.countryCode);
2537
- break;
2538
- case "farcaster":
2539
- yield this.setFarcasterUsername(authInfo.identifier);
2540
- break;
2541
- case "telegram":
2542
- yield this.setTelegramUserId(authInfo.identifier);
2543
- break;
2544
- }
2545
- return authInfo;
2546
- });
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;
2547
2357
  }
2548
2358
  /**
2549
2359
  * Initiates a login.
@@ -2552,46 +2362,41 @@ var _ParaCore = class _ParaCore {
2552
2362
  * @param {boolean} opts.useShortURL - whether to shorten the link
2553
2363
  * @returns - the WebAuth URL for logging in
2554
2364
  **/
2555
- initiateUserLogin(_e) {
2556
- return __async(this, null, function* () {
2557
- var _f = _e, { useShortUrl = false } = _f, auth = __objRest(_f, ["useShortUrl"]);
2558
- const authInfo = yield this.setAuth(auth);
2559
- if (!authInfo) {
2560
- return;
2561
- }
2562
- const res = yield this.touchSession(true);
2563
- if (!this.loginEncryptionKeyPair) {
2564
- yield this.setLoginEncryptionKeyPair();
2565
- }
2566
- const webAuthLoginURL = yield this.getWebAuthURLForLogin({
2567
- authType: authInfo.authType,
2568
- sessionId: res.data.sessionId,
2569
- partnerId: res.data.partnerId,
2570
- loginEncryptionPublicKey: getPublicKeyHex(this.loginEncryptionKeyPair)
2571
- });
2572
- if (!useShortUrl) {
2573
- return webAuthLoginURL;
2574
- }
2575
- return this.shortenLoginLink(webAuthLoginURL);
2576
- });
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);
2577
2384
  }
2578
2385
  /**
2579
2386
  * Initiates a login.
2580
2387
  * @param email - the email to login with
2581
2388
  * @returns - a set of supported auth methods for the user
2582
2389
  **/
2583
- initiateUserLoginV2(auth) {
2584
- return __async(this, null, function* () {
2585
- const authInfo = yield this.setAuth(auth);
2586
- if (!authInfo) {
2587
- return;
2588
- }
2589
- yield this.touchSession(true);
2590
- if (!this.loginEncryptionKeyPair) {
2591
- yield this.setLoginEncryptionKeyPair();
2592
- }
2593
- return yield this.supportedAuthMethods(authInfo.auth);
2594
- });
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);
2595
2400
  }
2596
2401
  /**
2597
2402
  * Initiates a login.
@@ -2601,125 +2406,112 @@ var _ParaCore = class _ParaCore {
2601
2406
  * @param opts.useShortURL - whether to shorten the link
2602
2407
  * @returns - the WebAuth URL for logging in
2603
2408
  **/
2604
- initiateUserLoginForPhone(_g) {
2605
- return __async(this, null, function* () {
2606
- var _h = _g, {
2607
- useShortUrl = false
2608
- } = _h, auth = __objRest(_h, [
2609
- "useShortUrl"
2610
- ]);
2611
- yield this.setAuth(auth);
2612
- const res = yield this.touchSession(true);
2613
- if (!this.loginEncryptionKeyPair) {
2614
- yield this.setLoginEncryptionKeyPair();
2615
- }
2616
- const webAuthLoginURL = yield this.getWebAuthURLForLoginForPhone({
2617
- sessionId: res.data.sessionId,
2618
- loginEncryptionPublicKey: getPublicKeyHex(this.loginEncryptionKeyPair),
2619
- partnerId: res.data.partnerId
2620
- });
2621
- if (!useShortUrl) {
2622
- return webAuthLoginURL;
2623
- }
2624
- return this.shortenLoginLink(webAuthLoginURL);
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
2625
2422
  });
2423
+ if (!useShortUrl) {
2424
+ return webAuthLoginURL;
2425
+ }
2426
+ return this.shortenLoginLink(webAuthLoginURL);
2626
2427
  }
2627
2428
  /**
2628
2429
  * Waits for the session to be active.
2629
2430
  **/
2630
- waitForAccountCreation() {
2631
- return __async(this, arguments, function* ({ popupWindow } = {}) {
2632
- yield this.touchSession();
2633
- this.currentExternalWalletAddresses = void 0;
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()) {
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) {
2640
2444
  this.isAwaitingAccountCreation = 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
- }
2445
+ return false;
2648
2446
  }
2649
- } catch (err) {
2650
- console.error(err);
2651
2447
  }
2448
+ } catch (err) {
2449
+ console.error(err);
2652
2450
  }
2653
- return false;
2654
- });
2451
+ }
2452
+ return false;
2655
2453
  }
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
- });
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;
2679
2475
  }
2680
2476
  /**
2681
2477
  * Initiates a Farcaster login attempt and return the URI for the user to connect.
2682
2478
  * You can create a QR code with this URI that works with Farcaster's mobile app.
2683
2479
  * @return {string} the Farcaster connect URI
2684
2480
  */
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
- });
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;
2694
2488
  }
2695
2489
  /**
2696
2490
  * Awaits the response from a user's attempt to log in with Farcaster.
2697
2491
  * If successful, this returns the user's Farcaster username and profile picture and indicates whether the user already exists.
2698
2492
  * @return {Object} `{userExists: boolean; username: string; pfpUrl?: string | null }` - the user's information and whether the user already exists.
2699
2493
  */
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;
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
+ };
2720
2509
  }
2510
+ } catch (err) {
2511
+ console.error(err);
2512
+ this.isAwaitingFarcaster = false;
2721
2513
  }
2722
- });
2514
+ }
2723
2515
  }
2724
2516
  /**
2725
2517
  * Generates a URL for the user to log in with OAuth using a desire method.
@@ -2729,19 +2521,17 @@ var _ParaCore = class _ParaCore {
2729
2521
  * @param {string} [opts.deeplinkUrl] the deeplink to redirect to after the OAuth flow. This is for mobile only.
2730
2522
  * @returns {string} the URL for the user to log in with OAuth.
2731
2523
  */
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
- });
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
+ }
2745
2535
  });
2746
2536
  }
2747
2537
  /**
@@ -2752,38 +2542,36 @@ var _ParaCore = class _ParaCore {
2752
2542
  * @param {Window} [opts.popupWindow] the popup window being used for login.
2753
2543
  * @return {Object} `{ email?: string; isError?: boolean; userExists: boolean; }` the result data
2754
2544
  */
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
- };
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();
2779
2559
  }
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
+ };
2780
2568
  }
2781
- } catch (err) {
2782
- console.error(err);
2783
2569
  }
2570
+ } catch (err) {
2571
+ console.error(err);
2784
2572
  }
2785
- return { userExists: false };
2786
- });
2573
+ }
2574
+ return { userExists: false };
2787
2575
  }
2788
2576
  /**
2789
2577
  * Waits for the session to be active and sets up the user.
@@ -2793,60 +2581,56 @@ var _ParaCore = class _ParaCore {
2793
2581
  * @param {boolean} [opts.skipSessionRefresh] whether to skip refreshing the session.
2794
2582
  * @returns {Object} `{ isComplete: boolean; isError: boolean; needsWallet: boolean; partnerId: string; }` the result data
2795
2583
  **/
2796
- waitForLoginAndSetup() {
2797
- return __async(this, arguments, function* ({
2798
- popupWindow,
2799
- skipSessionRefresh = false
2800
- } = {}) {
2801
- var _a;
2802
- this.currentExternalWalletAddresses = void 0;
2803
- this.externalWallets = {};
2804
- this.isAwaitingLogin = true;
2805
- while (this.isAwaitingLogin) {
2806
- try {
2807
- yield new Promise((resolve) => setTimeout(resolve, POLLING_INTERVAL_MS));
2808
- if (!(yield this.isSessionActive())) {
2809
- if (popupWindow == null ? void 0 : popupWindow.closed) {
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) {
2810
2606
  const resp2 = { isComplete: false, isError: true };
2811
2607
  dispatchEvent(ParaEvent.LOGIN_EVENT, resp2, "failed to setup user");
2812
2608
  return resp2;
2609
+ } else {
2610
+ continue;
2813
2611
  }
2814
- continue;
2815
- }
2816
- const postLoginData = yield this.userSetupAfterLogin();
2817
- const needsWallet = (_a = postLoginData.data.needsWallet) != null ? _a : false;
2818
- if (!needsWallet) {
2819
- if (this.currentWalletIdsArray.length === 0) {
2820
- if (popupWindow == null ? void 0 : popupWindow.closed) {
2821
- const resp2 = { isComplete: false, isError: true };
2822
- dispatchEvent(ParaEvent.LOGIN_EVENT, resp2, "failed to setup user");
2823
- return resp2;
2824
- } else {
2825
- continue;
2826
- }
2827
- }
2828
- }
2829
- const fetchedWallets = yield this.fetchWallets();
2830
- const tempSharesRes = yield this.getTransmissionKeyShares();
2831
- if (tempSharesRes.data.temporaryShares.length === fetchedWallets.length) {
2832
- yield this.setupAfterLogin({ temporaryShares: tempSharesRes.data.temporaryShares, skipSessionRefresh });
2833
- yield this.claimPregenWallets();
2834
- const resp2 = {
2835
- isComplete: true,
2836
- needsWallet: needsWallet || Object.values(this.wallets).length === 0,
2837
- partnerId: postLoginData.data.partnerId
2838
- };
2839
- dispatchEvent(ParaEvent.LOGIN_EVENT, resp2);
2840
- return resp2;
2841
2612
  }
2842
- } catch (err) {
2843
- console.error(err);
2844
2613
  }
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);
2845
2629
  }
2846
- const resp = { isComplete: false };
2847
- dispatchEvent(ParaEvent.LOGIN_EVENT, resp, "exitted login without setting up user");
2848
- return resp;
2849
- });
2630
+ }
2631
+ const resp = { isComplete: false };
2632
+ dispatchEvent(ParaEvent.LOGIN_EVENT, resp, "exitted login without setting up user");
2633
+ return resp;
2850
2634
  }
2851
2635
  /**
2852
2636
  * Updates the session with the user management server, possibly
@@ -2856,36 +2640,32 @@ var _ParaCore = class _ParaCore {
2856
2640
  * @param {boolean} [shouldOpenPopup] - if `true`, the running device will open a popup to reauthenticate the user.
2857
2641
  * @returns a URL for the user to reauthenticate.
2858
2642
  **/
2859
- refreshSession() {
2860
- return __async(this, arguments, function* ({ shouldOpenPopup = false } = {}) {
2861
- const res = yield this.touchSession(true);
2862
- if (!this.loginEncryptionKeyPair) {
2863
- yield this.setLoginEncryptionKeyPair();
2864
- }
2865
- const link = yield this.getWebAuthURLForLogin({
2866
- sessionId: res.data.sessionId,
2867
- loginEncryptionPublicKey: getPublicKeyHex(this.loginEncryptionKeyPair)
2868
- });
2869
- if (shouldOpenPopup) {
2870
- this.platformUtils.openPopup(link);
2871
- }
2872
- return link;
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)
2873
2651
  });
2652
+ if (shouldOpenPopup) {
2653
+ this.platformUtils.openPopup(link);
2654
+ }
2655
+ return link;
2874
2656
  }
2875
2657
  /**
2876
2658
  * Call this method after login to ensure that the user ID is set
2877
2659
  * internally.
2878
2660
  **/
2879
- userSetupAfterLogin() {
2880
- return __async(this, null, function* () {
2881
- const res = yield this.touchSession();
2882
- yield this.setUserId(res.data.userId);
2883
- if (res.data.currentWalletIds && res.data.currentWalletIds !== this.currentWalletIds)
2884
- yield this.setCurrentWalletIds(res.data.currentWalletIds, {
2885
- sessionLookupId: this.isPortal() ? res.data.sessionLookupId : void 0
2886
- });
2887
- return res;
2888
- });
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;
2889
2669
  }
2890
2670
  /**
2891
2671
  * Get transmission shares associated with session.
@@ -2893,12 +2673,10 @@ var _ParaCore = class _ParaCore {
2893
2673
  * @param {boolean} opts.isForNewDevice - true if this device is registering.
2894
2674
  * @returns - transmission keyshares.
2895
2675
  **/
2896
- getTransmissionKeyShares() {
2897
- return __async(this, arguments, function* ({ isForNewDevice = false } = {}) {
2898
- const res = yield this.touchSession();
2899
- const sessionLookupId = isForNewDevice ? `${res.data.sessionLookupId}-new-device` : res.data.sessionLookupId;
2900
- return this.ctx.client.getTransmissionKeyshares(this.userId, sessionLookupId);
2901
- });
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);
2902
2680
  }
2903
2681
  /**
2904
2682
  * Call this method after login to perform setup.
@@ -2906,25 +2684,23 @@ var _ParaCore = class _ParaCore {
2906
2684
  * @param {any[]} opts.temporaryShares optional temporary shares to use for decryption.
2907
2685
  * @param {boolean} [opts.skipSessionRefresh] - whether or not to skip refreshing the session.
2908
2686
  **/
2909
- setupAfterLogin() {
2910
- return __async(this, arguments, function* ({
2911
- temporaryShares,
2912
- skipSessionRefresh = false
2913
- } = {}) {
2914
- if (!temporaryShares) {
2915
- temporaryShares = (yield this.getTransmissionKeyShares()).data.temporaryShares;
2916
- }
2917
- temporaryShares.forEach((share) => {
2918
- const signer = decryptWithPrivateKey(this.loginEncryptionKeyPair.privateKey, share.encryptedShare, share.encryptedKey);
2919
- this.wallets[share.walletId] = {
2920
- id: share.walletId,
2921
- signer
2922
- };
2923
- });
2924
- yield this.deleteLoginEncryptionKeyPair();
2925
- yield this.populateWalletAddresses();
2926
- yield this.touchSession(!skipSessionRefresh);
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
+ };
2927
2700
  });
2701
+ await this.deleteLoginEncryptionKeyPair();
2702
+ await this.populateWalletAddresses();
2703
+ await this.touchSession(!skipSessionRefresh);
2928
2704
  }
2929
2705
  /**
2930
2706
  * Distributes a new wallet recovery share.
@@ -2935,55 +2711,51 @@ var _ParaCore = class _ParaCore {
2935
2711
  * @param {boolean} opts.forceRefreshRecovery whether or not to force recovery secret regeneration. Used when regenerating recovery shares.
2936
2712
  * @returns {string} the recovery share.
2937
2713
  **/
2938
- distributeNewWalletShare(_0) {
2939
- return __async(this, arguments, function* ({
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,
2940
2727
  walletId,
2941
- userShare,
2942
- skipBiometricShareCreation = false,
2943
- forceRefresh = false
2944
- }) {
2945
- let userSigner = userShare;
2946
- if (!userSigner) {
2947
- userSigner = this.wallets[walletId].signer;
2948
- }
2949
- const recoveryShare = skipBiometricShareCreation ? yield sendRecoveryForShare({
2950
- ctx: this.ctx,
2951
- userId: this.userId,
2952
- walletId,
2953
- userSigner,
2954
- emailProps: this.getBackupKitEmailProps(),
2955
- forceRefresh
2956
- }) : yield distributeNewShare({
2957
- ctx: this.ctx,
2958
- userId: this.userId,
2959
- walletId,
2960
- userShare: userSigner,
2961
- emailProps: this.getBackupKitEmailProps()
2962
- });
2963
- return recoveryShare;
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()
2964
2737
  });
2738
+ return recoveryShare;
2965
2739
  }
2966
- waitForWalletAddress(walletId) {
2967
- return __async(this, null, function* () {
2968
- let maxPolls = 0;
2969
- while (true) {
2970
- try {
2971
- if (maxPolls === 10) {
2972
- break;
2973
- }
2974
- ++maxPolls;
2975
- const res = yield this.ctx.client.getWallets(this.userId);
2976
- const wallet = res.data.wallets.find((w) => w.id === walletId);
2977
- if (wallet && wallet.address) {
2978
- return;
2979
- }
2980
- yield new Promise((resolve) => setTimeout(resolve, SHORT_POLLING_INTERVAL_MS));
2981
- } catch (err) {
2982
- console.error(err);
2740
+ async waitForWalletAddress(walletId) {
2741
+ let maxPolls = 0;
2742
+ while (true) {
2743
+ try {
2744
+ if (maxPolls === 10) {
2745
+ break;
2983
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;
2752
+ }
2753
+ await new Promise((resolve) => setTimeout(resolve, SHORT_POLLING_INTERVAL_MS));
2754
+ } catch (err) {
2755
+ console.error(err);
2984
2756
  }
2985
- throw new Error("timed out waiting for wallet address");
2986
- });
2757
+ }
2758
+ throw new Error("timed out waiting for wallet address");
2987
2759
  }
2988
2760
  /**
2989
2761
  * Waits for a pregen wallet address to be created.
@@ -2993,27 +2765,25 @@ var _ParaCore = class _ParaCore {
2993
2765
  * @param pregenIdentifierType - the identifier type of the user the pregen wallet is associated with.
2994
2766
  * @returns - recovery share.
2995
2767
  **/
2996
- waitForPregenWalletAddress(walletId) {
2997
- return __async(this, null, function* () {
2998
- let maxPolls = 0;
2999
- while (true) {
3000
- try {
3001
- if (maxPolls === 10) {
3002
- break;
3003
- }
3004
- ++maxPolls;
3005
- const res = yield this.getPregenWallets();
3006
- const wallet = res.find((w) => w.id === walletId);
3007
- if (wallet && wallet.address) {
3008
- return;
3009
- }
3010
- yield new Promise((resolve) => setTimeout(resolve, SHORT_POLLING_INTERVAL_MS));
3011
- } catch (err) {
3012
- console.error(err);
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;
3013
2780
  }
2781
+ await new Promise((resolve) => setTimeout(resolve, SHORT_POLLING_INTERVAL_MS));
2782
+ } catch (err) {
2783
+ console.error(err);
3014
2784
  }
3015
- throw new Error("timed out waiting for wallet address");
3016
- });
2785
+ }
2786
+ throw new Error("timed out waiting for wallet address");
3017
2787
  }
3018
2788
  /**
3019
2789
  * Creates several new wallets with the desired types. If no types are provided, this method
@@ -3026,26 +2796,24 @@ var _ParaCore = class _ParaCore {
3026
2796
  * @param {WalletType[]} [opts.types] the types of wallets to create.
3027
2797
  * @returns {Object} the wallets created, their ids, and the recovery secret.
3028
2798
  **/
3029
- createWalletPerType() {
3030
- return __async(this, arguments, function* ({
3031
- skipDistribute = false,
3032
- types
3033
- } = {}) {
3034
- const wallets = [];
3035
- const walletIds = {};
3036
- let recoverySecret;
3037
- for (const type of yield this.getTypesToCreate(types)) {
3038
- const [wallet, recoveryShare] = yield this.createWallet({ type, skipDistribute });
3039
- wallets.push(wallet);
3040
- getEquivalentTypes(type).filter((t) => !!this.isWalletTypeEnabled[t]).forEach((t) => {
3041
- walletIds[t] = [wallet.id];
3042
- });
3043
- if (recoveryShare) {
3044
- recoverySecret = recoveryShare;
3045
- }
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;
3046
2814
  }
3047
- return { wallets, walletIds, recoverySecret };
3048
- });
2815
+ }
2816
+ return { wallets, walletIds, recoverySecret };
3049
2817
  }
3050
2818
  /**
3051
2819
  * Refresh the current user share for a wallet.
@@ -3059,37 +2827,35 @@ var _ParaCore = class _ParaCore {
3059
2827
  * @param {boolean} [opts.redistributeBackupEncryptedShares] whether or not to redistribute backup encrypted shares.
3060
2828
  * @returns {Object} the new user share and recovery secret.
3061
2829
  **/
3062
- refreshShare(_0) {
3063
- return __async(this, arguments, function* ({
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,
3064
2842
  walletId,
3065
2843
  share,
3066
2844
  oldPartnerId,
3067
2845
  newPartnerId,
3068
- keyShareProtocolId,
3069
- redistributeBackupEncryptedShares
3070
- }) {
3071
- const { signer, protocolId } = yield this.platformUtils.refresh(
3072
- this.ctx,
3073
- this.retrieveSessionCookie(),
3074
- this.userId,
3075
- walletId,
3076
- share,
3077
- oldPartnerId,
3078
- newPartnerId,
3079
- keyShareProtocolId
3080
- );
3081
- const recoverySecret = yield distributeNewShare({
3082
- ctx: this.ctx,
3083
- userId: this.userId,
3084
- walletId,
3085
- userShare: signer,
3086
- ignoreRedistributingBackupEncryptedShare: !redistributeBackupEncryptedShares,
3087
- emailProps: this.getBackupKitEmailProps(),
3088
- partnerId: newPartnerId,
3089
- protocolId
3090
- });
3091
- return { signer, recoverySecret, protocolId };
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
3092
2857
  });
2858
+ return { signer, recoverySecret, protocolId };
3093
2859
  }
3094
2860
  /**
3095
2861
  * Creates a new wallet.
@@ -3098,73 +2864,71 @@ var _ParaCore = class _ParaCore {
3098
2864
  * @param {boolean} opts.skipDistribute - if true, recovery share will not be distributed.
3099
2865
  * @returns {[Wallet, string | null]} `[wallet, recoveryShare]` - the wallet object and the new recovery share.
3100
2866
  **/
3101
- createWallet() {
3102
- return __async(this, arguments, function* ({
3103
- type: _type,
3104
- skipDistribute = false
3105
- } = {}) {
3106
- var _a, _b;
3107
- this.requireApiKey();
3108
- const walletType = yield this.assertIsValidWalletType(
3109
- _type != null ? _type : (_a = this.supportedWalletTypes.find(({ optional }) => !optional)) == null ? void 0 : _a.type
3110
- );
3111
- let signer;
3112
- let wallet;
3113
- let keygenRes;
3114
- switch (walletType) {
3115
- case WalletType2.SOLANA: {
3116
- keygenRes = yield this.platformUtils.ed25519Keygen(
3117
- this.ctx,
3118
- this.userId,
3119
- this.retrieveSessionCookie(),
3120
- this.getBackupKitEmailProps()
3121
- );
3122
- break;
3123
- }
3124
- default: {
3125
- keygenRes = yield this.platformUtils.keygen(
3126
- this.ctx,
3127
- this.userId,
3128
- walletType,
3129
- null,
3130
- this.retrieveSessionCookie(),
3131
- this.getBackupKitEmailProps()
3132
- );
3133
- break;
3134
- }
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;
3135
2887
  }
3136
- const walletId = keygenRes.walletId;
3137
- signer = keygenRes.signer;
3138
- this.wallets[walletId] = {
3139
- id: walletId,
3140
- signer,
3141
- scheme: walletType === WalletType2.SOLANA ? WalletScheme2.ED25519 : WalletScheme2.DKLS,
3142
- type: walletType
3143
- };
3144
- wallet = this.wallets[walletId];
3145
- yield this.waitForWalletAddress(wallet.id);
3146
- yield this.populateWalletAddresses();
3147
- let recoveryShare = null;
3148
- if (!skipDistribute) {
3149
- recoveryShare = yield distributeNewShare({
3150
- ctx: this.ctx,
3151
- userId: this.userId,
3152
- walletId: wallet.id,
3153
- userShare: signer,
3154
- emailProps: this.getBackupKitEmailProps()
3155
- });
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;
3156
2898
  }
3157
- yield this.setCurrentWalletIds(__spreadProps(__spreadValues({}, this.currentWalletIds), {
3158
- [walletType]: [...(_b = this.currentWalletIds[walletType]) != null ? _b : [], walletId]
3159
- }));
3160
- const walletNoSigner = __spreadValues({}, wallet);
3161
- delete walletNoSigner.signer;
3162
- dispatchEvent(ParaEvent.WALLET_CREATED, {
3163
- wallet: walletNoSigner,
3164
- recoverySecret: recoveryShare
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()
3165
2919
  });
3166
- return [wallet, recoveryShare];
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
3167
2930
  });
2931
+ return [wallet, recoveryShare];
3168
2932
  }
3169
2933
  /**
3170
2934
  * Creates a new pregenerated wallet.
@@ -3175,54 +2939,51 @@ var _ParaCore = class _ParaCore {
3175
2939
  * @param {WalletType} [opts.type] the type of wallet to create. Defaults to the first non-optional type in the instance's `supportedWalletTypes` array.
3176
2940
  * @returns {Wallet} the created wallet.
3177
2941
  **/
3178
- createPregenWallet(opts) {
3179
- return __async(this, null, function* () {
3180
- var _a, _b;
3181
- const {
3182
- type: _type = (_a = this.supportedWalletTypes.find(({ optional }) => !optional)) == null ? void 0 : _a.type,
3183
- pregenIdentifier,
3184
- pregenIdentifierType = "EMAIL"
3185
- } = opts;
3186
- this.requireApiKey();
3187
- const walletType = yield this.assertIsValidWalletType(
3188
- _type != null ? _type : (_b = this.supportedWalletTypes.find(({ optional }) => !optional)) == null ? void 0 : _b.type
3189
- );
3190
- let keygenRes;
3191
- switch (walletType) {
3192
- case WalletType2.SOLANA:
3193
- keygenRes = yield this.platformUtils.ed25519PreKeygen(
3194
- this.ctx,
3195
- pregenIdentifier,
3196
- pregenIdentifierType,
3197
- this.retrieveSessionCookie()
3198
- );
3199
- break;
3200
- default:
3201
- keygenRes = yield this.platformUtils.preKeygen(
3202
- this.ctx,
3203
- void 0,
3204
- pregenIdentifier,
3205
- pregenIdentifierType,
3206
- walletType,
3207
- null,
3208
- this.retrieveSessionCookie()
3209
- );
3210
- break;
3211
- }
3212
- const { signer, walletId } = keygenRes;
3213
- this.wallets[walletId] = {
3214
- id: walletId,
3215
- signer,
3216
- scheme: walletType === WalletType2.SOLANA ? WalletScheme2.ED25519 : WalletScheme2.DKLS,
3217
- type: walletType,
3218
- isPregen: true,
3219
- pregenIdentifier,
3220
- pregenIdentifierType
3221
- };
3222
- yield this.waitForPregenWalletAddress(walletId);
3223
- yield this.populatePregenWalletAddresses();
3224
- return this.wallets[walletId];
3225
- });
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];
3226
2987
  }
3227
2988
  /**
3228
2989
  * Creates new pregenerated wallets for each desired type.
@@ -3234,19 +2995,17 @@ var _ParaCore = class _ParaCore {
3234
2995
  * @param {WalletType[]} [opts.types] the wallet types to create. Defaults to any types the instance supports that are not already present.
3235
2996
  * @returns {Wallet[]} an array containing the created wallets.
3236
2997
  **/
3237
- createPregenWalletPerType(_0) {
3238
- return __async(this, arguments, function* ({
3239
- types,
3240
- pregenIdentifier,
3241
- pregenIdentifierType = "EMAIL"
3242
- }) {
3243
- const wallets = [];
3244
- for (const type of yield this.getTypesToCreate(types)) {
3245
- const wallet = yield this.createPregenWallet({ type, pregenIdentifier, pregenIdentifierType });
3246
- wallets.push(wallet);
3247
- }
3248
- return wallets;
3249
- });
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;
3250
3009
  }
3251
3010
  /**
3252
3011
  * Claims a pregenerated wallet.
@@ -3256,65 +3015,63 @@ var _ParaCore = class _ParaCore {
3256
3015
  * @param {TPregenIdentifierType} opts.pregenIdentifierType type of the identifier of the user claiming the wallet
3257
3016
  * @returns {[Wallet, string | null]} `[wallet, recoveryShare]` - the wallet object and the new recovery share.
3258
3017
  **/
3259
- claimPregenWallets() {
3260
- return __async(this, arguments, function* ({
3261
- pregenIdentifier,
3262
- pregenIdentifierType = !!pregenIdentifier ? "EMAIL" : void 0
3263
- } = {}) {
3264
- var _a;
3265
- this.requireApiKey();
3266
- const pregenWallets = pregenIdentifier && pregenIdentifierType ? yield this.getPregenWallets({ pregenIdentifier, pregenIdentifierType }) : yield this.getPregenWallets();
3267
- if (pregenWallets.length === 0) {
3268
- return void 0;
3269
- }
3270
- let newRecoverySecret;
3271
- const { walletIds } = yield this.ctx.client.claimPregenWallets({
3272
- userId: this.userId,
3273
- walletIds: pregenWallets.map((w) => w.id)
3274
- });
3275
- for (const walletId of walletIds) {
3276
- const wallet = this.wallets[walletId];
3277
- let refreshedShare;
3278
- if (wallet.scheme === WalletScheme2.ED25519) {
3279
- const distributeRes = yield distributeNewShare({
3280
- ctx: this.ctx,
3281
- userId: this.userId,
3282
- walletId: wallet.id,
3283
- userShare: this.wallets[wallet.id].signer,
3284
- emailProps: this.getBackupKitEmailProps(),
3285
- partnerId: wallet.partnerId
3286
- });
3287
- if (distributeRes.length > 0) {
3288
- newRecoverySecret = distributeRes;
3289
- }
3290
- } else {
3291
- refreshedShare = yield this.refreshShare({
3292
- walletId: wallet.id,
3293
- share: this.wallets[wallet.id].signer,
3294
- oldPartnerId: wallet.partnerId,
3295
- newPartnerId: wallet.partnerId,
3296
- redistributeBackupEncryptedShares: true
3297
- });
3298
- if (refreshedShare.recoverySecret) {
3299
- newRecoverySecret = refreshedShare.recoverySecret;
3300
- }
3301
- }
3302
- this.wallets[wallet.id] = __spreadProps(__spreadValues({}, this.wallets[wallet.id]), {
3303
- signer: (_a = refreshedShare == null ? void 0 : refreshedShare.signer) != null ? _a : wallet.signer,
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,
3304
3038
  userId: this.userId,
3305
- pregenIdentifier: void 0,
3306
- pregenIdentifierType: void 0
3039
+ walletId: wallet.id,
3040
+ userShare: this.wallets[wallet.id].signer,
3041
+ emailProps: this.getBackupKitEmailProps(),
3042
+ partnerId: wallet.partnerId
3307
3043
  });
3308
- const walletNoSigner = __spreadValues({}, this.wallets[wallet.id]);
3309
- delete walletNoSigner.signer;
3310
- dispatchEvent(ParaEvent.PREGEN_WALLET_CLAIMED, {
3311
- wallet: walletNoSigner,
3312
- recoverySecret: newRecoverySecret
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
3054
  });
3055
+ if (refreshedShare.recoverySecret) {
3056
+ newRecoverySecret = refreshedShare.recoverySecret;
3057
+ }
3314
3058
  }
3315
- yield this.setWallets(this.wallets);
3316
- return newRecoverySecret;
3317
- });
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;
3318
3075
  }
3319
3076
  /**
3320
3077
  * Updates the identifier for a pregen wallet.
@@ -3323,25 +3080,24 @@ var _ParaCore = class _ParaCore {
3323
3080
  * @param {string} opts.newPregenIdentifier the new identtifier
3324
3081
  * @param {TPregenIdentifierType} opts.newPregenIdentifierType: the new identifier type
3325
3082
  **/
3326
- updatePregenWalletIdentifier(_0) {
3327
- return __async(this, arguments, function* ({
3328
- walletId,
3329
- newPregenIdentifier,
3330
- newPregenIdentifierType
3331
- }) {
3332
- this.requireApiKey();
3333
- yield this.ctx.client.updatePregenWallet(walletId, {
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],
3334
3096
  pregenIdentifier: newPregenIdentifier,
3335
3097
  pregenIdentifierType: newPregenIdentifierType
3336
- });
3337
- if (!!this.wallets[walletId]) {
3338
- this.wallets[walletId] = __spreadProps(__spreadValues({}, this.wallets[walletId]), {
3339
- pregenIdentifier: newPregenIdentifier,
3340
- pregenIdentifierType: newPregenIdentifierType
3341
- });
3342
- yield this.setWallets(this.wallets);
3343
- }
3344
- });
3098
+ };
3099
+ await this.setWallets(this.wallets);
3100
+ }
3345
3101
  }
3346
3102
  /**
3347
3103
  * Checks if a pregen Wallet exists for the given identifier with the current partner.
@@ -3350,19 +3106,17 @@ var _ParaCore = class _ParaCore {
3350
3106
  * @param {TPregenIdentifierType} opts.pregenIdentifierType type of the string of the identifier of the user claiming the wallet
3351
3107
  * @returns {boolean} whether the pregen wallet exists
3352
3108
  **/
3353
- hasPregenWallet(_0) {
3354
- return __async(this, arguments, function* ({
3355
- pregenIdentifier,
3356
- pregenIdentifierType
3357
- }) {
3358
- this.requireApiKey();
3359
- const res = yield this.getPregenWallets({ pregenIdentifier, pregenIdentifierType });
3360
- const wallet = res.find((w) => w.pregenIdentifier === pregenIdentifier && w.pregenIdentifierType === pregenIdentifierType);
3361
- if (!wallet) {
3362
- return false;
3363
- }
3364
- return true;
3365
- });
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;
3366
3120
  }
3367
3121
  /**
3368
3122
  * Get pregen wallets for the given identifier.
@@ -3371,19 +3125,17 @@ var _ParaCore = class _ParaCore {
3371
3125
  * @param {TPregenIdentifierType} opts.pregenIdentifierType - type of the identifier of the user claiming the wallet
3372
3126
  * @returns {Promise<WalletEntity[]>} the array of found wallets
3373
3127
  **/
3374
- getPregenWallets() {
3375
- return __async(this, arguments, function* ({
3376
- pregenIdentifier,
3377
- pregenIdentifierType = !!pregenIdentifier ? "EMAIL" : void 0
3378
- } = {}) {
3379
- this.requireApiKey();
3380
- const res = yield this.ctx.client.getPregenWallets(
3381
- pregenIdentifier && pregenIdentifierType ? { [pregenIdentifierType]: [pregenIdentifier] } : this.pregenIds,
3382
- this.isPortal(),
3383
- this.userId
3384
- );
3385
- return res.wallets.filter((w) => this.isWalletSupported(entityToWallet(w)));
3386
- });
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)));
3387
3139
  }
3388
3140
  encodeWalletBase64(wallet) {
3389
3141
  const walletJson = JSON.stringify(wallet);
@@ -3404,54 +3156,45 @@ var _ParaCore = class _ParaCore {
3404
3156
  * Sets the current wallets from a Base 64 string.
3405
3157
  * @param {string} base64Wallet the encoded wallet string
3406
3158
  **/
3407
- setUserShare(base64Wallets) {
3408
- return __async(this, null, function* () {
3409
- if (!base64Wallets) {
3410
- return;
3411
- }
3412
- const base64WalletsSplit = base64Wallets.split("-");
3413
- for (const base64Wallet of base64WalletsSplit) {
3414
- const walletJson = Buffer.from(base64Wallet, "base64").toString();
3415
- const wallet = migrateWallet(JSON.parse(walletJson));
3416
- this.wallets[wallet.id] = wallet;
3417
- yield this.setWallets(this.wallets);
3418
- }
3419
- });
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
+ }
3420
3170
  }
3421
- getTransactionReviewUrl(transactionId, timeoutMs) {
3422
- return __async(this, null, function* () {
3423
- const res = yield this.touchSession();
3424
- return this.constructPortalUrl("txReview", {
3425
- partnerId: res.data.partnerId,
3426
- pathId: transactionId,
3427
- params: {
3428
- email: this.email,
3429
- timeoutMs: timeoutMs == null ? void 0 : timeoutMs.toString()
3430
- }
3431
- });
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()
3179
+ }
3432
3180
  });
3433
3181
  }
3434
- getOnRampTransactionUrl(_i) {
3435
- return __async(this, null, function* () {
3436
- var _j = _i, {
3437
- purchaseId,
3438
- providerKey
3439
- } = _j, walletParams = __objRest(_j, [
3440
- "purchaseId",
3441
- "providerKey"
3442
- ]);
3443
- const res = yield this.touchSession();
3444
- const [key, identifier] = extractWalletRef(walletParams);
3445
- return this.constructPortalUrl("onRamp", {
3446
- partnerId: res.data.partnerId,
3447
- pathId: purchaseId,
3448
- sessionId: res.data.sessionId,
3449
- params: {
3450
- [key]: identifier,
3451
- providerKey,
3452
- currentWalletIds: JSON.stringify(this.currentWalletIds)
3453
- }
3454
- });
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
+ }
3455
3198
  });
3456
3199
  }
3457
3200
  /**
@@ -3465,95 +3208,91 @@ var _ParaCore = class _ParaCore {
3465
3208
  * @param {number} [opts.timeout] optional timeout in milliseconds. If not present, defaults to 30 seconds.
3466
3209
  * @param {string} [opts.cosmosSignDocBase64] the Cosmos `SignDoc` in base64, if applicable
3467
3210
  **/
3468
- signMessage(_0) {
3469
- return __async(this, arguments, function* ({
3470
- walletId,
3471
- messageBase64,
3472
- timeoutMs = 3e4,
3473
- cosmosSignDocBase64
3474
- }) {
3475
- this.assertIsValidWalletId(walletId);
3476
- const wallet = this.wallets[walletId];
3477
- let signerId = this.userId;
3478
- if (wallet.partnerId && !wallet.userId) {
3479
- signerId = wallet.partnerId;
3480
- }
3481
- let signRes = yield this.signMessageInner({ wallet, signerId, messageBase64, cosmosSignDocBase64 });
3482
- let timeStart = Date.now();
3483
- if (signRes.pendingTransactionId) {
3484
- this.platformUtils.openPopup(
3485
- yield this.getTransactionReviewUrl(signRes.pendingTransactionId, timeoutMs),
3486
- { type: cosmosSignDocBase64 ? "SIGN_TRANSACTION_REVIEW" /* SIGN_TRANSACTION_REVIEW */ : "SIGN_MESSAGE_REVIEW" /* SIGN_MESSAGE_REVIEW */ }
3487
- );
3488
- } else {
3489
- dispatchEvent(ParaEvent.SIGN_MESSAGE_EVENT, signRes);
3490
- return signRes;
3491
- }
3492
- yield new Promise((resolve) => setTimeout(resolve, POLLING_INTERVAL_MS));
3493
- while (true) {
3494
- if (Date.now() - timeStart > timeoutMs) {
3495
- break;
3496
- }
3497
- try {
3498
- yield this.ctx.client.getPendingTransaction(this.userId, signRes.pendingTransactionId);
3499
- } catch (err) {
3500
- const error = new TransactionReviewDenied();
3501
- dispatchEvent(ParaEvent.SIGN_MESSAGE_EVENT, signRes, error.message);
3502
- throw error;
3503
- }
3504
- signRes = yield this.signMessageInner({ wallet, signerId, messageBase64, cosmosSignDocBase64 });
3505
- if (signRes.pendingTransactionId) {
3506
- yield new Promise((resolve) => setTimeout(resolve, POLLING_INTERVAL_MS));
3507
- } else {
3508
- break;
3509
- }
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;
3510
3238
  }
3511
- if (signRes.pendingTransactionId) {
3512
- const error = new TransactionReviewTimeout(
3513
- yield this.getTransactionReviewUrl(signRes.pendingTransactionId),
3514
- signRes.pendingTransactionId
3515
- );
3239
+ try {
3240
+ await this.ctx.client.getPendingTransaction(this.userId, signRes.pendingTransactionId);
3241
+ } catch (err) {
3242
+ const error = new TransactionReviewDenied();
3516
3243
  dispatchEvent(ParaEvent.SIGN_MESSAGE_EVENT, signRes, error.message);
3517
3244
  throw error;
3518
3245
  }
3519
- dispatchEvent(ParaEvent.SIGN_MESSAGE_EVENT, signRes);
3520
- return signRes;
3521
- });
3522
- }
3523
- signMessageInner(_0) {
3524
- return __async(this, arguments, function* ({
3525
- wallet,
3526
- signerId,
3527
- messageBase64,
3528
- cosmosSignDocBase64
3529
- }) {
3530
- let signRes;
3531
- switch (wallet.scheme) {
3532
- case WalletScheme2.ED25519:
3533
- signRes = yield this.platformUtils.ed25519Sign(
3534
- this.ctx,
3535
- signerId,
3536
- wallet.id,
3537
- wallet.signer,
3538
- messageBase64,
3539
- this.retrieveSessionCookie()
3540
- );
3541
- break;
3542
- default:
3543
- signRes = yield this.platformUtils.signMessage(
3544
- this.ctx,
3545
- signerId,
3546
- wallet.id,
3547
- wallet.signer,
3548
- messageBase64,
3549
- this.retrieveSessionCookie(),
3550
- wallet.scheme === WalletScheme2.DKLS,
3551
- cosmosSignDocBase64
3552
- );
3553
- break;
3246
+ signRes = await this.signMessageInner({ wallet, signerId, messageBase64, cosmosSignDocBase64 });
3247
+ if (signRes.pendingTransactionId) {
3248
+ await new Promise((resolve) => setTimeout(resolve, POLLING_INTERVAL_MS));
3249
+ } else {
3250
+ break;
3554
3251
  }
3555
- return signRes;
3556
- });
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
3292
+ );
3293
+ break;
3294
+ }
3295
+ return signRes;
3557
3296
  }
3558
3297
  /**
3559
3298
  * Signs a transaction.
@@ -3563,20 +3302,51 @@ var _ParaCore = class _ParaCore {
3563
3302
  * @param {string} [opts.chainId] the EVM chain id of the chain the transaction is being sent on, if applicable
3564
3303
  * @param {number} [opts.timeoutMs] the amount of time to wait for the user to sign the transaction, in milliseconds
3565
3304
  **/
3566
- signTransaction(_0) {
3567
- return __async(this, arguments, function* ({
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,
3568
3320
  walletId,
3321
+ this.wallets[walletId].signer,
3569
3322
  rlpEncodedTxBase64,
3570
3323
  chainId,
3571
- timeoutMs = 3e4
3572
- }) {
3573
- this.assertIsValidWalletId(walletId);
3574
- const wallet = this.wallets[walletId];
3575
- let signerId = this.userId;
3576
- if (wallet.partnerId && !wallet.userId) {
3577
- signerId = wallet.partnerId;
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;
3578
3348
  }
3579
- let signRes = yield this.platformUtils.signTransaction(
3349
+ signRes = await this.platformUtils.signTransaction(
3580
3350
  this.ctx,
3581
3351
  signerId,
3582
3352
  walletId,
@@ -3586,55 +3356,22 @@ var _ParaCore = class _ParaCore {
3586
3356
  this.retrieveSessionCookie(),
3587
3357
  wallet.scheme === WalletScheme2.DKLS
3588
3358
  );
3589
- let timeStart = Date.now();
3590
3359
  if (signRes.pendingTransactionId) {
3591
- this.platformUtils.openPopup(
3592
- yield this.getTransactionReviewUrl(signRes.pendingTransactionId, timeoutMs),
3593
- { type: "SIGN_TRANSACTION_REVIEW" /* SIGN_TRANSACTION_REVIEW */ }
3594
- );
3360
+ await new Promise((resolve) => setTimeout(resolve, POLLING_INTERVAL_MS));
3595
3361
  } else {
3596
- dispatchEvent(ParaEvent.SIGN_TRANSACTION_EVENT, signRes);
3597
- return signRes;
3598
- }
3599
- yield new Promise((resolve) => setTimeout(resolve, POLLING_INTERVAL_MS));
3600
- while (true) {
3601
- if (Date.now() - timeStart > timeoutMs) {
3602
- break;
3603
- }
3604
- try {
3605
- yield this.ctx.client.getPendingTransaction(this.userId, signRes.pendingTransactionId);
3606
- } catch (err) {
3607
- const error = new TransactionReviewDenied();
3608
- dispatchEvent(ParaEvent.SIGN_TRANSACTION_EVENT, signRes, error.message);
3609
- throw error;
3610
- }
3611
- signRes = yield this.platformUtils.signTransaction(
3612
- this.ctx,
3613
- signerId,
3614
- walletId,
3615
- this.wallets[walletId].signer,
3616
- rlpEncodedTxBase64,
3617
- chainId,
3618
- this.retrieveSessionCookie(),
3619
- wallet.scheme === WalletScheme2.DKLS
3620
- );
3621
- if (signRes.pendingTransactionId) {
3622
- yield new Promise((resolve) => setTimeout(resolve, POLLING_INTERVAL_MS));
3623
- } else {
3624
- break;
3625
- }
3626
- }
3627
- if (signRes.pendingTransactionId) {
3628
- const error = new TransactionReviewTimeout(
3629
- yield this.getTransactionReviewUrl(signRes.pendingTransactionId),
3630
- signRes.pendingTransactionId
3631
- );
3632
- dispatchEvent(ParaEvent.SIGN_TRANSACTION_EVENT, signRes, error.message);
3633
- throw error;
3362
+ break;
3634
3363
  }
3635
- dispatchEvent(ParaEvent.SIGN_TRANSACTION_EVENT, signRes);
3636
- return signRes;
3637
- });
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;
3638
3375
  }
3639
3376
  /**
3640
3377
  * @deprecated
@@ -3643,36 +3380,34 @@ var _ParaCore = class _ParaCore {
3643
3380
  * @param rlpEncodedTxBase64 - rlp encoded tx as base64 string
3644
3381
  * @param chainId - chain id of the chain the transaction is being sent on.
3645
3382
  **/
3646
- sendTransaction(_0) {
3647
- return __async(this, arguments, function* ({
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,
3648
3393
  walletId,
3394
+ this.wallets[walletId].signer,
3649
3395
  rlpEncodedTxBase64,
3650
- chainId
3651
- }) {
3652
- this.assertIsValidWalletId(walletId);
3653
- const wallet = this.wallets[walletId];
3654
- const signRes = yield this.platformUtils.sendTransaction(
3655
- this.ctx,
3656
- this.userId,
3657
- walletId,
3658
- this.wallets[walletId].signer,
3659
- rlpEncodedTxBase64,
3660
- chainId,
3661
- this.retrieveSessionCookie(),
3662
- wallet.scheme === WalletScheme2.DKLS
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 */ }
3663
3404
  );
3664
- if (signRes.pendingTransactionId) {
3665
- this.platformUtils.openPopup(
3666
- yield this.getTransactionReviewUrl(signRes.pendingTransactionId),
3667
- { type: "SIGN_TRANSACTION_REVIEW" /* SIGN_TRANSACTION_REVIEW */ }
3668
- );
3669
- const error = new TransactionReviewError(
3670
- yield this.getTransactionReviewUrl(signRes.pendingTransactionId)
3671
- );
3672
- throw error;
3673
- }
3674
- return signRes;
3675
- });
3405
+ const error = new TransactionReviewError(
3406
+ await this.getTransactionReviewUrl(signRes.pendingTransactionId)
3407
+ );
3408
+ throw error;
3409
+ }
3410
+ return signRes;
3676
3411
  }
3677
3412
  isProviderModalDisabled() {
3678
3413
  return !!this.disableProviderModal;
@@ -3685,38 +3420,36 @@ var _ParaCore = class _ParaCore {
3685
3420
  * @param {string} opts.walletId the wallet ID to use for the transaction, where funds will be sent or withdrawn.
3686
3421
  * @param {string} opts.externalWalletAddress the external wallet address to send funds to or withdraw funds from, if using an external wallet.
3687
3422
  **/
3688
- initiateOnRampTransaction(options) {
3689
- return __async(this, null, function* () {
3690
- var _b;
3691
- const _a = options, { params, shouldOpenPopup } = _a, walletParams = __objRest(_a, ["params", "shouldOpenPopup"]);
3692
- const onRampPurchase = yield this.ctx.client.createOnRampPurchase(__spreadValues({
3693
- userId: this.userId,
3694
- params: __spreadProps(__spreadValues({}, params), {
3695
- address: (_b = walletParams.externalWalletAddress) != null ? _b : this.getDisplayAddress(walletParams.walletId, { addressType: params.walletType })
3696
- })
3697
- }, walletParams));
3698
- const portalUrl = yield this.getOnRampTransactionUrl(__spreadValues({
3699
- purchaseId: onRampPurchase.id,
3700
- providerKey: onRampPurchase.providerKey
3701
- }, walletParams));
3702
- if (shouldOpenPopup) {
3703
- this.platformUtils.openPopup(portalUrl, { type: "ON_RAMP_TRANSACTION" /* ON_RAMP_TRANSACTION */ });
3704
- }
3705
- return { onRampPurchase, portalUrl };
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
3706
3437
  });
3438
+ if (shouldOpenPopup) {
3439
+ this.platformUtils.openPopup(portalUrl, { type: "ON_RAMP_TRANSACTION" /* ON_RAMP_TRANSACTION */ });
3440
+ }
3441
+ return { onRampPurchase, portalUrl };
3707
3442
  }
3708
3443
  /**
3709
3444
  * Returns `true` if session was successfully kept alive, `false` otherwise.
3710
3445
  **/
3711
- keepSessionAlive() {
3712
- return __async(this, null, function* () {
3713
- try {
3714
- yield this.ctx.client.keepSessionAlive(this.userId);
3715
- return true;
3716
- } catch (err) {
3717
- return false;
3718
- }
3719
- });
3446
+ async keepSessionAlive() {
3447
+ try {
3448
+ await this.ctx.client.keepSessionAlive(this.userId);
3449
+ return true;
3450
+ } catch (err) {
3451
+ return false;
3452
+ }
3720
3453
  }
3721
3454
  /**
3722
3455
  * Serialize the current session for import by another Para instance.
@@ -3741,37 +3474,34 @@ var _ParaCore = class _ParaCore {
3741
3474
  * Imports a session serialized by another Para instance.
3742
3475
  * @param {string} serializedInstanceBase64 the serialized session
3743
3476
  */
3744
- importSession(serializedInstanceBase64) {
3745
- return __async(this, null, function* () {
3746
- var _a;
3747
- const serializedInstance = Buffer.from(serializedInstanceBase64, "base64").toString("utf8");
3748
- const sessionInfo = JSON.parse(serializedInstance);
3749
- yield this.setEmail(sessionInfo.email);
3750
- yield this.setTelegramUserId(sessionInfo.telegramUserId);
3751
- yield this.setFarcasterUsername(sessionInfo.farcasterUsername);
3752
- yield this.setUserId(sessionInfo.userId);
3753
- yield this.setWallets(sessionInfo.wallets);
3754
- yield this.setExternalWallets(sessionInfo.externalWallets || {});
3755
- for (const walletId of Object.keys(this.wallets)) {
3756
- if (!this.wallets[walletId].userId) {
3757
- this.wallets[walletId].userId = this.userId;
3758
- }
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;
3759
3489
  }
3760
- if (Object.keys(sessionInfo.currentWalletIds).length !== 0) {
3761
- yield this.setCurrentWalletIds(sessionInfo.currentWalletIds);
3762
- } else {
3763
- const currentWalletIds = {};
3764
- for (const walletId of Object.keys(sessionInfo.wallets)) {
3765
- currentWalletIds[sessionInfo.wallets[walletId].type] = [
3766
- ...(_a = currentWalletIds[sessionInfo.wallets[walletId].type]) != null ? _a : [],
3767
- walletId
3768
- ];
3769
- }
3770
- yield this.setCurrentWalletIds(currentWalletIds);
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
+ ];
3771
3500
  }
3772
- this.persistSessionCookie(sessionInfo.sessionCookie);
3773
- yield this.setPhoneNumber(sessionInfo.phone, sessionInfo.countryCode);
3774
- });
3501
+ await this.setCurrentWalletIds(currentWalletIds);
3502
+ }
3503
+ this.persistSessionCookie(sessionInfo.sessionCookie);
3504
+ await this.setPhoneNumber(sessionInfo.phone, sessionInfo.countryCode);
3775
3505
  }
3776
3506
  exitAccountCreation() {
3777
3507
  this.isAwaitingAccountCreation = false;
@@ -3795,55 +3525,48 @@ var _ParaCore = class _ParaCore {
3795
3525
  * Retrieves a token to verify the current session.
3796
3526
  * @returns {Promise<string>} the ID
3797
3527
  **/
3798
- getVerificationToken() {
3799
- return __async(this, null, function* () {
3800
- const { data } = yield this.touchSession();
3801
- return data.sessionLookupId;
3802
- });
3528
+ async getVerificationToken() {
3529
+ const { data } = await this.touchSession();
3530
+ return data.sessionLookupId;
3803
3531
  }
3804
3532
  /**
3805
3533
  * Logs the user out.
3806
3534
  * @param {Object} opts the options object.
3807
3535
  * @param {boolean} opts.clearPregenWallets if `true`, will remove all pregen wallets from storage
3808
3536
  **/
3809
- logout() {
3810
- return __async(this, arguments, function* ({ clearPregenWallets = false } = {}) {
3811
- yield this.ctx.client.logout();
3812
- yield this.clearStorage();
3813
- if (!clearPregenWallets) {
3814
- Object.entries(this.wallets).forEach(([id, wallet]) => {
3815
- if (!wallet.pregenIdentifier) {
3816
- delete this.wallets[id];
3817
- }
3818
- });
3819
- yield this.setWallets(this.wallets);
3820
- } else {
3821
- this.wallets = {};
3822
- }
3823
- this.currentWalletIds = {};
3824
- this.currentExternalWalletAddresses = void 0;
3825
- this.externalWallets = {};
3826
- this.loginEncryptionKeyPair = void 0;
3827
- this.email = void 0;
3828
- this.telegramUserId = void 0;
3829
- this.phone = void 0;
3830
- this.countryCode = void 0;
3831
- this.userId = void 0;
3832
- this.sessionCookie = void 0;
3833
- dispatchEvent(ParaEvent.LOGOUT_EVENT, null);
3834
- });
3835
- }
3836
- getSupportedCreateAuthMethods() {
3837
- return __async(this, null, function* () {
3838
- const res = yield this.touchSession();
3839
- const partnerId = res.data.partnerId;
3840
- const partnerRes = yield this.ctx.client.getPartner(partnerId);
3841
- let supportedAuthMethods = /* @__PURE__ */ new Set();
3842
- for (const authMethod of partnerRes.data.partner.supportedAuthMethods) {
3843
- supportedAuthMethods.add(AuthMethod[authMethod]);
3844
- }
3845
- return supportedAuthMethods;
3846
- });
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;
3847
3570
  }
3848
3571
  /**
3849
3572
  * Converts to a string, removing sensitive data when logging this class.
@@ -3852,10 +3575,12 @@ var _ParaCore = class _ParaCore {
3852
3575
  **/
3853
3576
  toString() {
3854
3577
  const redactedWallets = Object.keys(this.wallets).reduce(
3855
- (acc, walletId) => __spreadProps(__spreadValues({}, acc), {
3856
- [walletId]: __spreadProps(__spreadValues({}, this.wallets[walletId]), {
3578
+ (acc, walletId) => ({
3579
+ ...acc,
3580
+ [walletId]: {
3581
+ ...this.wallets[walletId],
3857
3582
  signer: this.wallets[walletId].signer ? "[REDACTED]" : void 0
3858
- })
3583
+ }
3859
3584
  }),
3860
3585
  {}
3861
3586
  );
@@ -3886,10 +3611,6 @@ var _ParaCore = class _ParaCore {
3886
3611
  return `Para ${JSON.stringify(obj, null, 2)}`;
3887
3612
  }
3888
3613
  };
3889
- _supportedWalletTypes = new WeakMap();
3890
- _supportedWalletTypesOpt = new WeakMap();
3891
- _ParaCore.version = PARA_CORE_VERSION;
3892
- var ParaCore = _ParaCore;
3893
3614
 
3894
3615
  // src/index.ts
3895
3616
  import {