@getpara/core-sdk 1.7.1 → 2.0.0-alpha.3

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/cjs/index.js CHANGED
@@ -61,6 +61,7 @@ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot
61
61
  var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
62
62
  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);
63
63
  var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
64
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
64
65
  var __async = (__this, __arguments, generator) => {
65
66
  return new Promise((resolve, reject) => {
66
67
  var fulfilled = (value) => {
@@ -98,6 +99,7 @@ __export(src_exports, {
98
99
  OnRampProvider: () => import_user_management_client6.OnRampProvider,
99
100
  OnRampPurchaseStatus: () => import_user_management_client6.OnRampPurchaseStatus,
100
101
  OnRampPurchaseType: () => import_user_management_client6.OnRampPurchaseType,
102
+ PARA_CORE_METHODS: () => PARA_CORE_METHODS,
101
103
  PREGEN_IDENTIFIER_TYPES: () => import_user_management_client6.PREGEN_IDENTIFIER_TYPES,
102
104
  ParaEvent: () => ParaEvent,
103
105
  PopupType: () => PopupType,
@@ -109,6 +111,7 @@ __export(src_exports, {
109
111
  TransactionReviewTimeout: () => TransactionReviewTimeout,
110
112
  WalletScheme: () => import_user_management_client6.WalletScheme,
111
113
  WalletType: () => import_user_management_client6.WalletType,
114
+ constructUrl: () => constructUrl,
112
115
  decimalToHex: () => decimalToHex,
113
116
  decryptPrivateKey: () => decryptPrivateKey,
114
117
  decryptPrivateKeyAndDecryptShare: () => decryptPrivateKeyAndDecryptShare,
@@ -116,12 +119,14 @@ __export(src_exports, {
116
119
  decryptWithKeyPair: () => decryptWithKeyPair,
117
120
  decryptWithPrivateKey: () => decryptWithPrivateKey,
118
121
  default: () => src_default,
122
+ displayPhoneNumber: () => displayPhoneNumber,
119
123
  distributeNewShare: () => distributeNewShare,
120
124
  encodePrivateKeyToPemHex: () => encodePrivateKeyToPemHex,
121
125
  encryptPrivateKey: () => encryptPrivateKey,
122
126
  encryptPrivateKeyWithPassword: () => encryptPrivateKeyWithPassword,
123
127
  encryptWithDerivedPublicKey: () => encryptWithDerivedPublicKey,
124
128
  entityToWallet: () => entityToWallet,
129
+ formatPhoneNumber: () => formatPhoneNumber,
125
130
  getAsymmetricKeyPair: () => getAsymmetricKeyPair,
126
131
  getBaseMPCNetworkUrl: () => getBaseMPCNetworkUrl,
127
132
  getBaseOAuthUrl: () => getBaseOAuthUrl,
@@ -143,10 +148,9 @@ __export(src_exports, {
143
148
  initClient: () => initClient,
144
149
  isWalletSupported: () => isWalletSupported,
145
150
  mpcComputationClient: () => mpcComputationClient_exports,
146
- normalizePhoneNumber: () => normalizePhoneNumber,
147
151
  paraVersion: () => paraVersion,
148
152
  publicKeyFromHex: () => publicKeyFromHex,
149
- stringToPhoneNumber: () => stringToPhoneNumber,
153
+ shortenUrl: () => shortenUrl,
150
154
  toAssetInfoArray: () => toAssetInfoArray,
151
155
  transmissionUtilsRetrieve: () => retrieve,
152
156
  truncateAddress: () => truncateAddress,
@@ -163,6 +167,23 @@ var import_node_forge2 = __toESM(require("node-forge"));
163
167
  var import_base64url = __toESM(require("base64url"));
164
168
  var import_node_forge = __toESM(require("node-forge"));
165
169
 
170
+ // src/utils/autobind.ts
171
+ function autoBind(instance) {
172
+ let proto = instance;
173
+ while (proto && proto !== Object.prototype) {
174
+ for (const key of Object.getOwnPropertyNames(proto)) {
175
+ const value = instance[key];
176
+ if (typeof value === "function" && key !== "constructor") {
177
+ try {
178
+ instance[key] = value.bind(instance);
179
+ } catch (e) {
180
+ }
181
+ }
182
+ }
183
+ proto = Object.getPrototypeOf(proto);
184
+ }
185
+ }
186
+
166
187
  // src/utils/events.ts
167
188
  function dispatchEvent(type, data, error) {
168
189
  typeof window !== "undefined" && !!window.dispatchEvent && window.dispatchEvent(
@@ -175,7 +196,6 @@ var import_encoding = require("@cosmjs/encoding");
175
196
  var import_sha256 = require("@noble/hashes/sha256");
176
197
  var import_ripemd160 = require("@noble/hashes/ripemd160");
177
198
  var import_elliptic = __toESM(require("elliptic"));
178
- var import_libphonenumber_js = __toESM(require("libphonenumber-js"));
179
199
  var secp256k1 = new import_elliptic.default.ec("secp256k1");
180
200
  function hexStringToBase64(hexString) {
181
201
  if (hexString.substring(0, 2) === "0x") {
@@ -232,12 +252,72 @@ function truncateAddress(str, addressType, { prefix = addressType === "COSMOS" ?
232
252
  const headLength = (addressType === "COSMOS" ? prefix.length : addressType === "SOLANA" ? 0 : 2) + 4;
233
253
  return `${str.slice(0, headLength)}...${str.slice(-4)}`;
234
254
  }
235
- function stringToPhoneNumber(str) {
236
- var _a;
237
- return (_a = (0, import_libphonenumber_js.default)(str)) == null ? void 0 : _a.formatInternational().replace(/[^\d+]/g, "");
255
+
256
+ // src/utils/json.ts
257
+ function jsonParse(data, validate) {
258
+ try {
259
+ const res = JSON.parse(data);
260
+ if (validate && !validate(res)) {
261
+ return void 0;
262
+ }
263
+ return res;
264
+ } catch (e) {
265
+ return void 0;
266
+ }
267
+ }
268
+
269
+ // src/constants.ts
270
+ var PARA_CORE_VERSION = '2.0.0-alpha.0';
271
+ var PREFIX = "@CAPSULE/";
272
+ var LOCAL_STORAGE_AUTH_INFO = `${PREFIX}authInfo`;
273
+ var LOCAL_STORAGE_EMAIL = `${PREFIX}e-mail`;
274
+ var LOCAL_STORAGE_PHONE = `${PREFIX}phone`;
275
+ var LOCAL_STORAGE_COUNTRY_CODE = `${PREFIX}countryCode`;
276
+ var LOCAL_STORAGE_FARCASTER_USERNAME = `${PREFIX}farcasterUsername`;
277
+ var LOCAL_STORAGE_TELEGRAM_USER_ID = `${PREFIX}telegramUserId`;
278
+ var LOCAL_STORAGE_USER_ID = `${PREFIX}userId`;
279
+ var LOCAL_STORAGE_ED25519_WALLETS = `${PREFIX}ed25519Wallets`;
280
+ var LOCAL_STORAGE_WALLETS = `${PREFIX}wallets`;
281
+ var LOCAL_STORAGE_EXTERNAL_WALLETS = `${PREFIX}externalWallets`;
282
+ var LOCAL_STORAGE_CURRENT_WALLET_IDS = `${PREFIX}currentWalletIds`;
283
+ var LOCAL_STORAGE_SESSION_COOKIE = `${PREFIX}sessionCookie`;
284
+ var SESSION_STORAGE_LOGIN_ENCRYPTION_KEY_PAIR = `${PREFIX}loginEncryptionKeyPair`;
285
+ var POLLING_INTERVAL_MS = 2e3;
286
+ var SHORT_POLLING_INTERVAL_MS = 1e3;
287
+ var POLLING_TIMEOUT_MS = 3e5;
288
+
289
+ // src/utils/listeners.ts
290
+ function storageListener(e) {
291
+ if (!e.url.includes(window.location.origin)) {
292
+ return;
293
+ }
294
+ if (e.key === LOCAL_STORAGE_EXTERNAL_WALLETS) {
295
+ this.updateExternalWalletsFromStorage();
296
+ }
297
+ if (e.key === SESSION_STORAGE_LOGIN_ENCRYPTION_KEY_PAIR) {
298
+ this.updateLoginEncryptionKeyPairFromStorage();
299
+ }
300
+ if (e.key === LOCAL_STORAGE_SESSION_COOKIE) {
301
+ this.updateSessionCookieFromStorage();
302
+ }
303
+ if (e.key === LOCAL_STORAGE_CURRENT_WALLET_IDS) {
304
+ this.updateWalletIdsFromStorage();
305
+ }
306
+ if (e.key === LOCAL_STORAGE_WALLETS || e.key === LOCAL_STORAGE_ED25519_WALLETS) {
307
+ this.updateWalletsFromStorage();
308
+ }
309
+ if (e.key === LOCAL_STORAGE_AUTH_INFO) {
310
+ this.updateAuthInfoFromStorage();
311
+ }
312
+ if (e.key === LOCAL_STORAGE_USER_ID) {
313
+ this.updateUserIdFromStorage();
314
+ }
238
315
  }
239
- function normalizePhoneNumber(countryCode, number) {
240
- return stringToPhoneNumber(`${countryCode[0] !== "+" ? "+" : ""}${countryCode}${number}`);
316
+ function setupListeners() {
317
+ if (typeof window !== "undefined" && window.addEventListener && window.location) {
318
+ window.removeEventListener("storage", storageListener.bind(this));
319
+ window.addEventListener("storage", storageListener.bind(this));
320
+ }
241
321
  }
242
322
 
243
323
  // src/utils/onRamps.ts
@@ -276,6 +356,31 @@ function getOnRampAssets(data, {
276
356
  ];
277
357
  }
278
358
 
359
+ // src/utils/phone.ts
360
+ var import_libphonenumber_js = __toESM(require("libphonenumber-js"));
361
+ function formatPhoneNumber(phone, countryCode, { forDisplay = false } = {}) {
362
+ phone = phone.toString();
363
+ countryCode = countryCode == null ? void 0 : countryCode.toString();
364
+ let sanitizedNumber, parsedNumber;
365
+ if (!!countryCode) {
366
+ sanitizedNumber = phone.replace(/\D/g, "");
367
+ if (/^\+\d+$/.test(countryCode)) {
368
+ countryCode = countryCode.slice(1);
369
+ }
370
+ parsedNumber = (0, import_libphonenumber_js.default)(sanitizedNumber, { defaultCallingCode: countryCode });
371
+ } else {
372
+ sanitizedNumber = `+${phone.replace(/\D/g, "")}`;
373
+ parsedNumber = (0, import_libphonenumber_js.default)(sanitizedNumber);
374
+ }
375
+ if (parsedNumber == null ? void 0 : parsedNumber.isValid()) {
376
+ return forDisplay ? parsedNumber.formatInternational() : parsedNumber.formatInternational().replace(/[^\d+]/g, "");
377
+ }
378
+ return null;
379
+ }
380
+ function displayPhoneNumber(phone, countryCode) {
381
+ return formatPhoneNumber(phone, countryCode, { forDisplay: true });
382
+ }
383
+
279
384
  // src/utils/polling.ts
280
385
  function waitUntilTrue(condition, timeoutMs, intervalMs) {
281
386
  return __async(this, null, function* () {
@@ -290,6 +395,48 @@ function waitUntilTrue(condition, timeoutMs, intervalMs) {
290
395
  });
291
396
  }
292
397
 
398
+ // src/utils/types.ts
399
+ function isServerAuthState(obj) {
400
+ return "stage" in obj && Object.keys(obj).length > 0;
401
+ }
402
+
403
+ // src/transmission/transmissionUtils.ts
404
+ var import_ecies = require("@celo/utils/lib/ecies.js");
405
+ var import_buffer = require("buffer");
406
+ var eutil = __toESM(require("ethereumjs-util"));
407
+ var import_crypto = require("crypto");
408
+ function upload(message, userManagementClient) {
409
+ return __async(this, null, function* () {
410
+ let secret;
411
+ let publicKeyUint8Array;
412
+ while (true) {
413
+ try {
414
+ secret = (0, import_crypto.randomBytes)(32).toString("hex");
415
+ publicKeyUint8Array = eutil.privateToPublic(import_buffer.Buffer.from(secret, "hex"));
416
+ break;
417
+ } catch (e) {
418
+ continue;
419
+ }
420
+ }
421
+ const pubkey = import_buffer.Buffer.from(publicKeyUint8Array);
422
+ const data = (0, import_ecies.Encrypt)(pubkey, import_buffer.Buffer.from(message, "ucs2")).toString("base64");
423
+ const {
424
+ data: { id }
425
+ } = yield userManagementClient.tempTrasmissionInit(data);
426
+ return encodeURIComponent(id + "|" + secret);
427
+ });
428
+ }
429
+ function retrieve(uriEncodedMessage, userManagementClient) {
430
+ return __async(this, null, function* () {
431
+ const [id, secret] = decodeURIComponent(uriEncodedMessage).split("|");
432
+ const response = yield userManagementClient.tempTrasmission(id);
433
+ const data = response.data.message;
434
+ const buf = import_buffer.Buffer.from(data, "base64");
435
+ const res = import_buffer.Buffer.from((0, import_ecies.Decrypt)(import_buffer.Buffer.from(secret, "hex"), buf).buffer).toString("ucs2");
436
+ return res;
437
+ });
438
+ }
439
+
293
440
  // src/types/config.ts
294
441
  var Environment = /* @__PURE__ */ ((Environment2) => {
295
442
  Environment2["DEV"] = "DEV";
@@ -307,6 +454,49 @@ var EnabledFlow = /* @__PURE__ */ ((EnabledFlow2) => {
307
454
  return EnabledFlow2;
308
455
  })(EnabledFlow || {});
309
456
 
457
+ // src/types/coreApi.ts
458
+ var PARA_CORE_METHODS = [
459
+ "signUpOrLogIn",
460
+ "verifyNewAccount",
461
+ "waitForLogin",
462
+ "waitForSignup",
463
+ "waitForWalletCreation",
464
+ "verifyOAuth",
465
+ "verifyFarcaster",
466
+ "verifyTelegram",
467
+ "resendVerificationCode",
468
+ "loginExternalWallet",
469
+ "verifyExternalWallet",
470
+ "setup2fa",
471
+ "enable2fa",
472
+ "verify2fa",
473
+ "logout",
474
+ "clearStorage",
475
+ "isSessionActive",
476
+ "isFullyLoggedIn",
477
+ "refreshSession",
478
+ "keepSessionAlive",
479
+ "exportSession",
480
+ "importSession",
481
+ "getVerificationToken",
482
+ "fetchWallets",
483
+ "createWallet",
484
+ "createWalletPerType",
485
+ "getPregenWallets",
486
+ "hasPregenWallet",
487
+ "updatePregenWalletIdentifier",
488
+ "createPregenWallet",
489
+ "createPregenWalletPerType",
490
+ "claimPregenWallets",
491
+ "distributeNewWalletShare",
492
+ "getUserShare",
493
+ "setUserShare",
494
+ "refreshShare",
495
+ "signMessage",
496
+ "signTransaction",
497
+ "initiateOnRampTransaction"
498
+ ];
499
+
310
500
  // src/types/wallet.ts
311
501
  var PregenIdentifierType = /* @__PURE__ */ ((PregenIdentifierType2) => {
312
502
  PregenIdentifierType2["EMAIL"] = "EMAIL";
@@ -335,13 +525,13 @@ var PopupType = /* @__PURE__ */ ((PopupType2) => {
335
525
  })(PopupType || {});
336
526
 
337
527
  // src/types/recovery.ts
338
- var RecoveryStatus = /* @__PURE__ */ ((RecoveryStatus3) => {
339
- RecoveryStatus3["INITIATED"] = "INITIATED";
340
- RecoveryStatus3["READY"] = "READY";
341
- RecoveryStatus3["EXPIRED"] = "EXPIRED";
342
- RecoveryStatus3["FINISHED"] = "FINISHED";
343
- RecoveryStatus3["CANCELLED"] = "CANCELLED";
344
- return RecoveryStatus3;
528
+ var RecoveryStatus = /* @__PURE__ */ ((RecoveryStatus2) => {
529
+ RecoveryStatus2["INITIATED"] = "INITIATED";
530
+ RecoveryStatus2["READY"] = "READY";
531
+ RecoveryStatus2["EXPIRED"] = "EXPIRED";
532
+ RecoveryStatus2["FINISHED"] = "FINISHED";
533
+ RecoveryStatus2["CANCELLED"] = "CANCELLED";
534
+ return RecoveryStatus2;
345
535
  })(RecoveryStatus || {});
346
536
 
347
537
  // src/types/events.ts
@@ -429,6 +619,15 @@ function constructUrl({
429
619
  });
430
620
  return url.toString();
431
621
  }
622
+ function shortenUrl(ctx, url) {
623
+ return __async(this, null, function* () {
624
+ const compressedUrl = yield upload(url, ctx.client);
625
+ return constructUrl({
626
+ base: getPortalBaseURL(ctx),
627
+ path: `/short/${compressedUrl}`
628
+ });
629
+ });
630
+ }
432
631
 
433
632
  // src/utils/wallet.ts
434
633
  var import_user_management_client = require("@getpara/user-management-client");
@@ -453,7 +652,7 @@ function isPregenIdentifierMatch(a, b, type) {
453
652
  case "EMAIL":
454
653
  return a.toLowerCase() === b.toLowerCase();
455
654
  case "PHONE":
456
- return stringToPhoneNumber(a) === stringToPhoneNumber(b);
655
+ return formatPhoneNumber(a) === formatPhoneNumber(b);
457
656
  case "CUSTOM_ID":
458
657
  return a === b;
459
658
  default:
@@ -503,6 +702,9 @@ function migrateWallet(obj) {
503
702
  }
504
703
  return obj;
505
704
  }
705
+ function supportedWalletTypesEq(a, b) {
706
+ return a.length === b.length && a.every(({ type, optional }, index) => b[index].type === type && b[index].optional === optional);
707
+ }
506
708
 
507
709
  // src/cryptography/utils.ts
508
710
  var rsa = import_node_forge.default.pki.rsa;
@@ -817,7 +1019,7 @@ function initClient({
817
1019
  }) {
818
1020
  return new import_user_management_client2.default({
819
1021
  userManagementHost: getBaseUrl(env),
820
- version: ["DEV" /* DEV */, "SANDBOX" /* SANDBOX */].includes(env) ? "dev" : version,
1022
+ version: ["DEV" /* DEV */, "SANDBOX" /* SANDBOX */].includes(env) ? "dev-v2" : version,
821
1023
  apiKey,
822
1024
  partnerId,
823
1025
  opts: { useFetchAdapter },
@@ -865,8 +1067,8 @@ var import_user_management_client4 = require("@getpara/user-management-client");
865
1067
  var import_user_management_client3 = require("@getpara/user-management-client");
866
1068
 
867
1069
  // src/shares/KeyContainer.ts
868
- var import_ecies = require("@celo/utils/lib/ecies.js");
869
- var eutil = __toESM(require("ethereumjs-util"));
1070
+ var import_ecies2 = require("@celo/utils/lib/ecies.js");
1071
+ var eutil2 = __toESM(require("ethereumjs-util"));
870
1072
  var forge2 = __toESM(require("node-forge"));
871
1073
  var KeyContainer = class _KeyContainer {
872
1074
  constructor(walletId, keyshare, address) {
@@ -886,7 +1088,7 @@ var KeyContainer = class _KeyContainer {
886
1088
  }
887
1089
  }
888
1090
  getPublicEncryptionKey() {
889
- return Buffer.from(eutil.privateToPublic(Buffer.from(this.backupDecryptionKey, "hex")));
1091
+ return Buffer.from(eutil2.privateToPublic(Buffer.from(this.backupDecryptionKey, "hex")));
890
1092
  }
891
1093
  getPublicEncryptionKeyHex() {
892
1094
  return this.getPublicEncryptionKey().toString("hex");
@@ -894,7 +1096,7 @@ var KeyContainer = class _KeyContainer {
894
1096
  encryptForSelf(backup) {
895
1097
  try {
896
1098
  const pubkey = this.getPublicEncryptionKey();
897
- const data = (0, import_ecies.Encrypt)(pubkey, Buffer.from(backup, "ucs2")).toString("base64");
1099
+ const data = (0, import_ecies2.Encrypt)(pubkey, Buffer.from(backup, "ucs2")).toString("base64");
898
1100
  return data;
899
1101
  } catch (error) {
900
1102
  throw Error("Error encrypting backup");
@@ -902,7 +1104,7 @@ var KeyContainer = class _KeyContainer {
902
1104
  }
903
1105
  static encryptWithPublicKey(publicKey, backup) {
904
1106
  try {
905
- const data = (0, import_ecies.Encrypt)(publicKey, Buffer.from(backup, "ucs2")).toString("base64");
1107
+ const data = (0, import_ecies2.Encrypt)(publicKey, Buffer.from(backup, "ucs2")).toString("base64");
906
1108
  return data;
907
1109
  } catch (error) {
908
1110
  throw Error("Error encrypting backup");
@@ -911,7 +1113,7 @@ var KeyContainer = class _KeyContainer {
911
1113
  decrypt(encryptedBackup) {
912
1114
  try {
913
1115
  const buf = Buffer.from(encryptedBackup, "base64");
914
- const data = (0, import_ecies.Decrypt)(Buffer.from(this.backupDecryptionKey, "hex"), buf);
1116
+ const data = (0, import_ecies2.Decrypt)(Buffer.from(this.backupDecryptionKey, "hex"), buf);
915
1117
  return Buffer.from(data.buffer).toString("ucs2");
916
1118
  } catch (error) {
917
1119
  throw Error("Error decrypting backup");
@@ -1043,43 +1245,6 @@ function distributeNewShare(_0) {
1043
1245
  });
1044
1246
  }
1045
1247
 
1046
- // src/transmission/transmissionUtils.ts
1047
- var import_ecies2 = require("@celo/utils/lib/ecies.js");
1048
- var import_buffer = require("buffer");
1049
- var eutil2 = __toESM(require("ethereumjs-util"));
1050
- var import_crypto = require("crypto");
1051
- function upload(message, userManagementClient) {
1052
- return __async(this, null, function* () {
1053
- let secret;
1054
- let publicKeyUint8Array;
1055
- while (true) {
1056
- try {
1057
- secret = (0, import_crypto.randomBytes)(32).toString("hex");
1058
- publicKeyUint8Array = eutil2.privateToPublic(import_buffer.Buffer.from(secret, "hex"));
1059
- break;
1060
- } catch (e) {
1061
- continue;
1062
- }
1063
- }
1064
- const pubkey = import_buffer.Buffer.from(publicKeyUint8Array);
1065
- const data = (0, import_ecies2.Encrypt)(pubkey, import_buffer.Buffer.from(message, "ucs2")).toString("base64");
1066
- const {
1067
- data: { id }
1068
- } = yield userManagementClient.tempTrasmissionInit(data);
1069
- return encodeURIComponent(id + "|" + secret);
1070
- });
1071
- }
1072
- function retrieve(uriEncodedMessage, userManagementClient) {
1073
- return __async(this, null, function* () {
1074
- const [id, secret] = decodeURIComponent(uriEncodedMessage).split("|");
1075
- const response = yield userManagementClient.tempTrasmission(id);
1076
- const data = response.data.message;
1077
- const buf = import_buffer.Buffer.from(data, "base64");
1078
- const res = import_buffer.Buffer.from((0, import_ecies2.Decrypt)(import_buffer.Buffer.from(secret, "hex"), buf).buffer).toString("ucs2");
1079
- return res;
1080
- });
1081
- }
1082
-
1083
1248
  // src/errors.ts
1084
1249
  var TransactionReviewError = class extends Error {
1085
1250
  constructor(transactionReviewUrl) {
@@ -1103,68 +1268,6 @@ var TransactionReviewTimeout = class extends Error {
1103
1268
  }
1104
1269
  };
1105
1270
 
1106
- // src/constants.ts
1107
- var PARA_CORE_VERSION = '1.7.1';
1108
- var PREFIX = "@CAPSULE/";
1109
- var LOCAL_STORAGE_EMAIL = `${PREFIX}e-mail`;
1110
- var LOCAL_STORAGE_PHONE = `${PREFIX}phone`;
1111
- var LOCAL_STORAGE_COUNTRY_CODE = `${PREFIX}countryCode`;
1112
- var LOCAL_STORAGE_FARCASTER_USERNAME = `${PREFIX}farcasterUsername`;
1113
- var LOCAL_STORAGE_TELEGRAM_USER_ID = `${PREFIX}telegramUserId`;
1114
- var LOCAL_STORAGE_EXTERNAL_WALLET_USER_ID = `${PREFIX}externalWalletUserId`;
1115
- var LOCAL_STORAGE_USER_ID = `${PREFIX}userId`;
1116
- var LOCAL_STORAGE_ED25519_WALLETS = `${PREFIX}ed25519Wallets`;
1117
- var LOCAL_STORAGE_WALLETS = `${PREFIX}wallets`;
1118
- var LOCAL_STORAGE_EXTERNAL_WALLETS = `${PREFIX}externalWallets`;
1119
- var LOCAL_STORAGE_CURRENT_WALLET_IDS = `${PREFIX}currentWalletIds`;
1120
- var LOCAL_STORAGE_SESSION_COOKIE = `${PREFIX}sessionCookie`;
1121
- var SESSION_STORAGE_LOGIN_ENCRYPTION_KEY_PAIR = `${PREFIX}loginEncryptionKeyPair`;
1122
- var POLLING_INTERVAL_MS = 2e3;
1123
- var SHORT_POLLING_INTERVAL_MS = 1e3;
1124
-
1125
- // src/utils/listeners.ts
1126
- function storageListener(e) {
1127
- if (!e.url.includes(window.location.origin)) {
1128
- return;
1129
- }
1130
- if (e.key === LOCAL_STORAGE_EXTERNAL_WALLETS) {
1131
- this.updateExternalWalletsFromStorage();
1132
- }
1133
- if (e.key === SESSION_STORAGE_LOGIN_ENCRYPTION_KEY_PAIR) {
1134
- this.updateLoginEncryptionKeyPairFromStorage();
1135
- }
1136
- if (e.key === LOCAL_STORAGE_SESSION_COOKIE) {
1137
- this.updateSessionCookieFromStorage();
1138
- }
1139
- if (e.key === LOCAL_STORAGE_CURRENT_WALLET_IDS) {
1140
- this.updateWalletIdsFromStorage();
1141
- }
1142
- if (e.key === LOCAL_STORAGE_WALLETS || e.key === LOCAL_STORAGE_ED25519_WALLETS) {
1143
- this.updateWalletsFromStorage();
1144
- }
1145
- if (e.key === LOCAL_STORAGE_EMAIL) {
1146
- this.updateEmailFromStorage();
1147
- }
1148
- if (e.key === LOCAL_STORAGE_COUNTRY_CODE) {
1149
- this.updateCountryCodeFromStorage();
1150
- }
1151
- if (e.key === LOCAL_STORAGE_PHONE) {
1152
- this.updatePhoneFromStorage();
1153
- }
1154
- if (e.key === LOCAL_STORAGE_USER_ID) {
1155
- this.updateUserIdFromStorage();
1156
- }
1157
- if (e.key === LOCAL_STORAGE_TELEGRAM_USER_ID) {
1158
- this.updateTelegramUserIdFromStorage();
1159
- }
1160
- }
1161
- function setupListeners() {
1162
- if (typeof window !== "undefined" && window.addEventListener && window.location) {
1163
- window.removeEventListener("storage", storageListener.bind(this));
1164
- window.addEventListener("storage", storageListener.bind(this));
1165
- }
1166
- }
1167
-
1168
1271
  // src/ParaCore.ts
1169
1272
  if (typeof global !== "undefined") {
1170
1273
  global.Buffer = global.Buffer || import_buffer2.Buffer;
@@ -1176,7 +1279,7 @@ if (typeof global !== "undefined") {
1176
1279
  self.global = self.global || self;
1177
1280
  }
1178
1281
  var { pki, jsbn } = import_node_forge2.default;
1179
- var _supportedWalletTypes, _supportedWalletTypesOpt;
1282
+ var _authInfo, _partner, _ParaCore_instances, assertPartner_fn, toAuthInfo_fn, setAuthInfo_fn, getPartner_fn, prepareAuthState_fn, prepareLogin_fn, prepareLoginState_fn, prepareSignUpState_fn;
1180
1283
  var _ParaCore = class _ParaCore {
1181
1284
  /**
1182
1285
  * Constructs a new `ParaCore` instance.
@@ -1186,6 +1289,10 @@ var _ParaCore = class _ParaCore {
1186
1289
  * @returns - A new ParaCore instance.
1187
1290
  */
1188
1291
  constructor(env, apiKey, opts) {
1292
+ __privateAdd(this, _ParaCore_instances);
1293
+ __privateAdd(this, _authInfo);
1294
+ this.isNativePasskey = false;
1295
+ __privateAdd(this, _partner);
1189
1296
  this.isAwaitingAccountCreation = false;
1190
1297
  this.isAwaitingLogin = false;
1191
1298
  this.isAwaitingFarcaster = false;
@@ -1194,14 +1301,19 @@ var _ParaCore = class _ParaCore {
1194
1301
  * 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.
1195
1302
  */
1196
1303
  this.currentWalletIds = {};
1197
- __privateAdd(this, _supportedWalletTypes);
1198
- __privateAdd(this, _supportedWalletTypesOpt);
1304
+ /**
1305
+ * Wallets associated with the `ParaCore` instance.
1306
+ */
1307
+ this.externalWallets = {};
1199
1308
  this.localStorageGetItem = (key) => {
1200
1309
  return this.platformUtils.localStorage.get(key);
1201
1310
  };
1202
1311
  this.localStorageSetItem = (key, value) => {
1203
1312
  return this.platformUtils.localStorage.set(key, value);
1204
1313
  };
1314
+ this.localStorageRemoveItem = (key) => {
1315
+ return this.platformUtils.localStorage.removeItem(key);
1316
+ };
1205
1317
  this.sessionStorageGetItem = (key) => {
1206
1318
  return this.platformUtils.sessionStorage.get(key);
1207
1319
  };
@@ -1227,32 +1339,35 @@ var _ParaCore = class _ParaCore {
1227
1339
  }
1228
1340
  });
1229
1341
  this.initializeFromStorage = () => {
1230
- this.updateEmailFromStorage();
1231
- this.updateCountryCodeFromStorage();
1232
- this.updatePhoneFromStorage();
1342
+ this.updateExternalWalletsFromStorage();
1343
+ this.updateAuthInfoFromStorage();
1233
1344
  this.updateUserIdFromStorage();
1234
- this.updateTelegramUserIdFromStorage();
1235
1345
  this.updateWalletsFromStorage();
1236
1346
  this.updateWalletIdsFromStorage();
1237
1347
  this.updateSessionCookieFromStorage();
1238
1348
  this.updateLoginEncryptionKeyPairFromStorage();
1239
- this.updateExternalWalletsFromStorage();
1240
1349
  };
1241
- this.updateTelegramUserIdFromStorage = () => {
1242
- this.telegramUserId = this.localStorageGetItem(LOCAL_STORAGE_TELEGRAM_USER_ID) || void 0;
1350
+ this.updateAuthInfoFromStorage = () => {
1351
+ var _a;
1352
+ const storageAuthInfo = this.localStorageGetItem(LOCAL_STORAGE_AUTH_INFO) || void 0;
1353
+ let authInfo = jsonParse(storageAuthInfo);
1354
+ if (!authInfo) {
1355
+ const authParams = {
1356
+ email: this.localStorageGetItem(LOCAL_STORAGE_EMAIL) || void 0,
1357
+ phone: this.localStorageGetItem(LOCAL_STORAGE_PHONE) || void 0,
1358
+ countryCode: this.localStorageGetItem(LOCAL_STORAGE_COUNTRY_CODE) || void 0,
1359
+ farcasterUsername: this.localStorageGetItem(LOCAL_STORAGE_FARCASTER_USERNAME) || void 0,
1360
+ telegramUserId: this.localStorageGetItem(LOCAL_STORAGE_TELEGRAM_USER_ID) || void 0,
1361
+ // Using id here since we store the bech32 address for cosmos in the address field of the wallet
1362
+ externalWalletAddress: ((_a = this.externalWalletWithParaAuth) == null ? void 0 : _a.id) || void 0
1363
+ };
1364
+ authInfo = __privateMethod(this, _ParaCore_instances, toAuthInfo_fn).call(this, authParams);
1365
+ }
1366
+ __privateSet(this, _authInfo, authInfo);
1243
1367
  };
1244
1368
  this.updateUserIdFromStorage = () => {
1245
1369
  this.userId = this.localStorageGetItem(LOCAL_STORAGE_USER_ID) || void 0;
1246
1370
  };
1247
- this.updatePhoneFromStorage = () => {
1248
- this.phone = this.localStorageGetItem(LOCAL_STORAGE_PHONE) || void 0;
1249
- };
1250
- this.updateCountryCodeFromStorage = () => {
1251
- this.countryCode = this.localStorageGetItem(LOCAL_STORAGE_COUNTRY_CODE) || void 0;
1252
- };
1253
- this.updateEmailFromStorage = () => {
1254
- this.email = this.localStorageGetItem(LOCAL_STORAGE_EMAIL) || void 0;
1255
- };
1256
1371
  this.updateWalletsFromStorage = () => __async(this, null, function* () {
1257
1372
  var _a;
1258
1373
  const _currentWalletIds = (_a = this.localStorageGetItem(LOCAL_STORAGE_CURRENT_WALLET_IDS)) != null ? _a : void 0;
@@ -1282,7 +1397,7 @@ var _ParaCore = class _ParaCore {
1282
1397
  this.updateWalletIdsFromStorage = () => {
1283
1398
  var _a;
1284
1399
  const _currentWalletIds = (_a = this.localStorageGetItem(LOCAL_STORAGE_CURRENT_WALLET_IDS)) != null ? _a : void 0;
1285
- const currentWalletIds = [void 0, null, "undefined"].includes(_currentWalletIds) ? {} : (() => {
1400
+ const currentWalletIds = [void 0, null, "undefined", "null"].includes(_currentWalletIds) ? {} : (() => {
1286
1401
  const fromJson = JSON.parse(_currentWalletIds);
1287
1402
  return Array.isArray(fromJson) ? Object.keys(import_user_management_client5.WalletType).reduce((acc, type) => {
1288
1403
  const wallet = Object.values(this.wallets).find(
@@ -1319,6 +1434,9 @@ var _ParaCore = class _ParaCore {
1319
1434
  * @deprecated alias for `createWalletPerType`
1320
1435
  **/
1321
1436
  this.createWalletPerMissingType = this.createWalletPerType;
1437
+ if (!apiKey) {
1438
+ throw new Error("A Para API key is required.");
1439
+ }
1322
1440
  if (!opts) opts = {};
1323
1441
  let isE2E = false;
1324
1442
  if (env === "E2E") {
@@ -1376,86 +1494,101 @@ var _ParaCore = class _ParaCore {
1376
1494
  useDKLS: opts.useDKLSForCreation || !opts.offloadMPCComputationURL,
1377
1495
  disableWebSockets: !!opts.disableWebSockets,
1378
1496
  wasmOverride: opts.wasmOverride,
1379
- cosmosPrefix: this.cosmosPrefix,
1380
1497
  isE2E
1381
1498
  };
1382
1499
  if (opts.offloadMPCComputationURL) {
1383
1500
  this.ctx.mpcComputationClient = initClient2(opts.offloadMPCComputationURL, opts.disableWorkers);
1384
1501
  }
1385
- try {
1386
- __privateSet(this, _supportedWalletTypes, opts.supportedWalletTypes ? (() => {
1387
- if (Object.values(opts.supportedWalletTypes).every(
1388
- (config) => !!config && typeof config === "object" && config.optional
1389
- )) {
1390
- throw new Error("at least one wallet type must be non-optional");
1391
- }
1392
- if (!Object.keys(opts.supportedWalletTypes).every((type) => Object.values(import_user_management_client5.WalletType).includes(type))) {
1393
- throw new Error("unsupported wallet type");
1394
- }
1395
- __privateSet(this, _supportedWalletTypesOpt, opts.supportedWalletTypes);
1396
- return Object.entries(opts.supportedWalletTypes).reduce((acc, [key, value]) => {
1397
- var _a;
1398
- if (!value) {
1399
- return acc;
1400
- }
1401
- if (key === import_user_management_client5.WalletType.COSMOS && typeof value === "object" && !!value.prefix) {
1402
- this.cosmosPrefix = value.prefix;
1403
- }
1404
- return [...acc, { type: key, optional: value === true ? false : (_a = value.optional) != null ? _a : false }];
1405
- }, []);
1406
- })() : void 0);
1407
- } catch (e) {
1408
- __privateSet(this, _supportedWalletTypes, void 0);
1409
- }
1410
1502
  if (!this.platformUtils.isSyncStorage || opts.useStorageOverrides) {
1411
1503
  return;
1412
1504
  }
1413
1505
  this.initializeFromStorage();
1414
1506
  setupListeners.bind(this)();
1507
+ autoBind(this);
1415
1508
  }
1416
- get isEmail() {
1417
- return !!this.email && !this.phone && !this.countryCode && !this.farcasterUsername && !this.telegramUserId && !this.externalWalletWithParaAuth;
1509
+ get authInfo() {
1510
+ return __privateGet(this, _authInfo);
1418
1511
  }
1419
- get isPhone() {
1420
- return !!this.phone && !!this.countryCode && !this.email && !this.farcasterUsername && !this.telegramUserId && !this.externalWalletWithParaAuth;
1512
+ get email() {
1513
+ var _a;
1514
+ return (0, import_user_management_client5.isEmail)((_a = __privateGet(this, _authInfo)) == null ? void 0 : _a.auth) ? __privateGet(this, _authInfo).auth.email : void 0;
1421
1515
  }
1422
- get isFarcaster() {
1423
- return !!this.farcasterUsername && !this.email && !this.phone && !this.countryCode && !this.telegramUserId && !this.externalWalletWithParaAuth;
1516
+ get phone() {
1517
+ var _a;
1518
+ return (0, import_user_management_client5.isPhone)((_a = __privateGet(this, _authInfo)) == null ? void 0 : _a.auth) ? __privateGet(this, _authInfo).auth.phone : void 0;
1424
1519
  }
1425
- get isTelegram() {
1426
- return !!this.telegramUserId && !this.email && !this.phone && !this.countryCode && !this.farcasterUsername && !this.externalWalletWithParaAuth;
1520
+ get farcasterUsername() {
1521
+ var _a;
1522
+ return (0, import_user_management_client5.isFarcaster)((_a = __privateGet(this, _authInfo)) == null ? void 0 : _a.auth) ? __privateGet(this, _authInfo).auth.farcasterUsername : void 0;
1523
+ }
1524
+ get telegramUserId() {
1525
+ var _a;
1526
+ return (0, import_user_management_client5.isTelegram)((_a = __privateGet(this, _authInfo)) == null ? void 0 : _a.auth) ? __privateGet(this, _authInfo).auth.telegramUserId : void 0;
1427
1527
  }
1428
1528
  get externalWalletWithParaAuth() {
1429
1529
  const externalWallets = Object.values(this.externalWallets);
1430
1530
  return externalWallets.find((w) => w.isExternalWithParaAuth);
1431
1531
  }
1432
- get isExternalWalletAuth() {
1433
- return !!this.externalWalletWithParaAuth && !this.email && !this.phone && !this.countryCode && !this.farcasterUsername && !this.telegramUserId;
1532
+ get externalWalletConnectionType() {
1533
+ if (this.isExternalWalletAuth) {
1534
+ return "AUTHENTICATED";
1535
+ } else if (!!Object.keys(this.externalWallets).length) {
1536
+ return "CONNECTION_ONLY";
1537
+ }
1538
+ return "NONE";
1434
1539
  }
1435
- get currentWalletIdsArray() {
1436
- return this.supportedWalletTypes.reduce((acc, { type }) => {
1437
- var _a;
1438
- return [
1439
- ...acc,
1440
- ...((_a = this.currentWalletIds[type]) != null ? _a : []).map((id) => {
1441
- return [id, type];
1442
- })
1443
- ];
1444
- }, []);
1540
+ get isEmail() {
1541
+ var _a;
1542
+ return (0, import_user_management_client5.isEmail)((_a = this.authInfo) == null ? void 0 : _a.auth);
1445
1543
  }
1446
- get currentWalletIdsUnique() {
1447
- return [...new Set(Object.values(this.currentWalletIds).flat())];
1544
+ get isPhone() {
1545
+ var _a;
1546
+ return (0, import_user_management_client5.isPhone)((_a = this.authInfo) == null ? void 0 : _a.auth);
1448
1547
  }
1449
- /**
1450
- * A map of pre-generated wallet identifiers that can be claimed in the current instance.
1451
- */
1452
- get pregenIds() {
1453
- return __spreadValues({}, Object.values(this.wallets).filter((wallet) => !this.userId || this.isPregenWalletClaimable(wallet)).reduce((acc, wallet) => {
1454
- var _a, _b;
1455
- if (((_a = acc[wallet.pregenIdentifierType]) != null ? _a : []).includes(wallet.pregenIdentifier)) {
1456
- return acc;
1457
- }
1458
- return __spreadProps(__spreadValues({}, acc), {
1548
+ get isFarcaster() {
1549
+ var _a;
1550
+ return (0, import_user_management_client5.isFarcaster)((_a = this.authInfo) == null ? void 0 : _a.auth);
1551
+ }
1552
+ get isTelegram() {
1553
+ var _a;
1554
+ return (0, import_user_management_client5.isTelegram)((_a = this.authInfo) == null ? void 0 : _a.auth);
1555
+ }
1556
+ get isExternalWalletAuth() {
1557
+ var _a;
1558
+ return (0, import_user_management_client5.isExternalWallet)((_a = __privateGet(this, _authInfo)) == null ? void 0 : _a.auth);
1559
+ }
1560
+ get partnerId() {
1561
+ var _a;
1562
+ return (_a = __privateGet(this, _partner)) == null ? void 0 : _a.id;
1563
+ }
1564
+ get currentWalletIdsArray() {
1565
+ var _a, _b;
1566
+ return ((_b = (_a = __privateGet(this, _partner)) == null ? void 0 : _a.supportedWalletTypes) != null ? _b : Object.keys(this.currentWalletIds).map((type) => ({ type }))).reduce(
1567
+ (acc, { type }) => {
1568
+ var _a2;
1569
+ return [
1570
+ ...acc,
1571
+ ...((_a2 = this.currentWalletIds[type]) != null ? _a2 : []).map((id) => {
1572
+ return [id, type];
1573
+ })
1574
+ ];
1575
+ },
1576
+ []
1577
+ );
1578
+ }
1579
+ get currentWalletIdsUnique() {
1580
+ return [...new Set(Object.values(this.currentWalletIds).flat())];
1581
+ }
1582
+ /**
1583
+ * A map of pre-generated wallet identifiers that can be claimed in the current instance.
1584
+ */
1585
+ get pregenIds() {
1586
+ return __spreadValues({}, Object.values(this.wallets).filter((wallet) => !this.userId || this.isPregenWalletClaimable(wallet)).reduce((acc, wallet) => {
1587
+ var _a, _b;
1588
+ if (((_a = acc[wallet.pregenIdentifierType]) != null ? _a : []).includes(wallet.pregenIdentifier)) {
1589
+ return acc;
1590
+ }
1591
+ return __spreadProps(__spreadValues({}, acc), {
1459
1592
  [wallet.pregenIdentifierType]: [
1460
1593
  .../* @__PURE__ */ new Set([...(_b = acc[wallet.pregenIdentifierType]) != null ? _b : [], wallet.pregenIdentifier])
1461
1594
  ]
@@ -1469,11 +1602,16 @@ var _ParaCore = class _ParaCore {
1469
1602
  return this.currentWalletIdsArray.length > 1;
1470
1603
  }
1471
1604
  get supportedWalletTypes() {
1605
+ var _a, _b;
1606
+ return (_b = (_a = __privateGet(this, _partner)) == null ? void 0 : _a.supportedWalletTypes) != null ? _b : [];
1607
+ }
1608
+ get cosmosPrefix() {
1472
1609
  var _a;
1473
- return (_a = __privateGet(this, _supportedWalletTypes)) != null ? _a : [];
1610
+ return (_a = __privateGet(this, _partner)) == null ? void 0 : _a.cosmosPrefix;
1474
1611
  }
1475
1612
  get isWalletTypeEnabled() {
1476
- return this.supportedWalletTypes.reduce((acc, { type }) => {
1613
+ var _a;
1614
+ return (((_a = __privateGet(this, _partner)) == null ? void 0 : _a.supportedWalletTypes) || []).reduce((acc, { type }) => {
1477
1615
  return __spreadProps(__spreadValues({}, acc), { [type]: true });
1478
1616
  }, {});
1479
1617
  }
@@ -1522,7 +1660,7 @@ var _ParaCore = class _ParaCore {
1522
1660
  }
1523
1661
  isWalletSupported(wallet) {
1524
1662
  var _a, _b;
1525
- return !__privateGet(this, _supportedWalletTypes) || isWalletSupported((_b = (_a = this.supportedWalletTypes) == null ? void 0 : _a.map(({ type }) => type)) != null ? _b : [], wallet);
1663
+ return !((_a = __privateGet(this, _partner)) == null ? void 0 : _a.supportedWalletTypes) || isWalletSupported((_b = __privateGet(this, _partner).supportedWalletTypes.map(({ type }) => type)) != null ? _b : [], wallet);
1526
1664
  }
1527
1665
  isWalletOwned(wallet) {
1528
1666
  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;
@@ -1538,7 +1676,7 @@ var _ParaCore = class _ParaCore {
1538
1676
  ));
1539
1677
  }
1540
1678
  isWalletUsable(walletId, { type: types, scheme: schemes, forbidPregen = false } = {}, throwError = false) {
1541
- var _a;
1679
+ var _a, _b;
1542
1680
  let error;
1543
1681
  if ((_a = this.externalWallets) == null ? void 0 : _a[walletId]) {
1544
1682
  return true;
@@ -1553,10 +1691,10 @@ var _ParaCore = class _ParaCore {
1553
1691
  } else if (!isOwned && !isUnclaimed) {
1554
1692
  error = `wallet with id ${wallet == null ? void 0 : wallet.id} is not owned by the current user`;
1555
1693
  } else if (!this.isWalletSupported(wallet)) {
1556
- 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(", ")}`;
1694
+ error = `wallet with id ${wallet.id} and type ${wallet.type} is not supported, supported types are: ${(((_b = __privateGet(this, _partner)) == null ? void 0 : _b.supportedWalletTypes) || []).map(({ type }) => type).join(", ")}`;
1557
1695
  } else if (types && (!getEquivalentTypes(types).includes(wallet == null ? void 0 : wallet.type) || isOwned && !types.some((type) => {
1558
- var _a2, _b;
1559
- return (_b = (_a2 = this.currentWalletIds) == null ? void 0 : _a2[type]) == null ? void 0 : _b.includes(walletId);
1696
+ var _a2, _b2;
1697
+ return (_b2 = (_a2 = this.currentWalletIds) == null ? void 0 : _a2[type]) == null ? void 0 : _b2.includes(walletId);
1560
1698
  }))) {
1561
1699
  error = `wallet with id ${wallet == null ? void 0 : wallet.id} and type ${wallet == null ? void 0 : wallet.type} cannot be selected`;
1562
1700
  } else if (schemes && !schemes.includes(wallet == null ? void 0 : wallet.scheme)) {
@@ -1580,10 +1718,10 @@ var _ParaCore = class _ParaCore {
1580
1718
  * @returns the formatted address
1581
1719
  */
1582
1720
  getDisplayAddress(walletId, options = {}) {
1583
- var _a;
1721
+ var _a, _b, _c, _d;
1584
1722
  if (this.externalWallets[walletId]) {
1585
1723
  const wallet2 = this.externalWallets[walletId];
1586
- return options.truncate ? truncateAddress(wallet2.address, wallet2.type, { prefix: this.cosmosPrefix }) : wallet2.address;
1724
+ return options.truncate ? truncateAddress(wallet2.address, wallet2.type, { prefix: (_a = __privateGet(this, _partner)) == null ? void 0 : _a.cosmosPrefix }) : wallet2.address;
1587
1725
  }
1588
1726
  const wallet = this.findWallet(walletId, options.addressType);
1589
1727
  if (!wallet) {
@@ -1592,13 +1730,13 @@ var _ParaCore = class _ParaCore {
1592
1730
  let str;
1593
1731
  switch (wallet.type) {
1594
1732
  case import_user_management_client5.WalletType.COSMOS:
1595
- str = getCosmosAddress(wallet.publicKey, (_a = this.cosmosPrefix) != null ? _a : "cosmos");
1733
+ str = getCosmosAddress(wallet.publicKey, (_c = (_b = __privateGet(this, _partner)) == null ? void 0 : _b.cosmosPrefix) != null ? _c : "cosmos");
1596
1734
  break;
1597
1735
  default:
1598
1736
  str = wallet.address;
1599
1737
  break;
1600
1738
  }
1601
- return options.truncate ? truncateAddress(str, wallet.type, { prefix: this.cosmosPrefix }) : str;
1739
+ return options.truncate ? truncateAddress(str, wallet.type, { prefix: (_d = __privateGet(this, _partner)) == null ? void 0 : _d.cosmosPrefix }) : str;
1602
1740
  }
1603
1741
  /**
1604
1742
  * Returns a unique hash for a wallet suitable for use as an identicon seed.
@@ -1623,8 +1761,25 @@ var _ParaCore = class _ParaCore {
1623
1761
  }
1624
1762
  constructPortalUrl(_0) {
1625
1763
  return __async(this, arguments, function* (type, opts = {}) {
1626
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
1627
- const base = type === "onRamp" ? getPortalBaseURL(this.ctx) : yield this.getPortalURL(opts.partnerId);
1764
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
1765
+ const [isCreate, isLogin, isOnRamp] = [
1766
+ ["createAuth", "createPassword"].includes(type),
1767
+ ["loginAuth", "loginPassword"].includes(type),
1768
+ type === "onRamp"
1769
+ ];
1770
+ let auth;
1771
+ if (isCreate || isLogin) {
1772
+ auth = this.assertIsAuthSet().auth;
1773
+ }
1774
+ let sessionId = opts.sessionId;
1775
+ if ((isLogin || isOnRamp) && !sessionId) {
1776
+ const session = yield this.touchSession(true);
1777
+ sessionId = session.sessionId;
1778
+ }
1779
+ if (!this.loginEncryptionKeyPair) {
1780
+ yield this.setLoginEncryptionKeyPair();
1781
+ }
1782
+ const base = type === "onRamp" ? getPortalBaseURL(this.ctx) : yield this.getPortalURL();
1628
1783
  let path;
1629
1784
  switch (type) {
1630
1785
  case "createPassword": {
@@ -1655,61 +1810,50 @@ var _ParaCore = class _ParaCore {
1655
1810
  throw new Error(`invalid URL type ${type}`);
1656
1811
  }
1657
1812
  }
1658
- const [isCreate, isLogin, isOnRamp] = [
1659
- ["createAuth", "createPassword"].includes(type),
1660
- ["loginAuth", "loginPassword"].includes(type),
1661
- type === "onRamp"
1662
- ];
1663
- const partner = opts.partnerId ? (_a = (yield this.ctx.client.getPartner(opts.partnerId)).data) == null ? void 0 : _a.partner : void 0;
1813
+ const partner = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
1814
+ const thisDevice = (_a = opts.thisDevice) != null ? _a : {
1815
+ encryptionKey: getPublicKeyHex(this.loginEncryptionKeyPair),
1816
+ sessionId
1817
+ };
1664
1818
  const params = __spreadValues(__spreadValues(__spreadValues(__spreadValues({
1665
1819
  apiKey: this.ctx.apiKey,
1666
- partnerId: opts.partnerId,
1667
- portalFont: ((_b = opts.theme) == null ? void 0 : _b.font) || (partner == null ? void 0 : partner.font) || ((_c = this.portalTheme) == null ? void 0 : _c.font),
1668
- portalBorderRadius: ((_d = opts.theme) == null ? void 0 : _d.borderRadius) || ((_e = this.portalTheme) == null ? void 0 : _e.borderRadius),
1669
- portalThemeMode: ((_f = opts.theme) == null ? void 0 : _f.mode) || (partner == null ? void 0 : partner.themeMode) || ((_g = this.portalTheme) == null ? void 0 : _g.mode),
1670
- portalAccentColor: ((_h = opts.theme) == null ? void 0 : _h.accentColor) || (partner == null ? void 0 : partner.accentColor) || ((_i = this.portalTheme) == null ? void 0 : _i.accentColor),
1671
- portalForegroundColor: ((_j = opts.theme) == null ? void 0 : _j.foregroundColor) || (partner == null ? void 0 : partner.foregroundColor) || ((_k = this.portalTheme) == null ? void 0 : _k.foregroundColor),
1672
- 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),
1820
+ partnerId: partner.id,
1821
+ portalFont: ((_b = opts.portalTheme) == null ? void 0 : _b.font) || (partner == null ? void 0 : partner.font) || ((_c = this.portalTheme) == null ? void 0 : _c.font),
1822
+ portalBorderRadius: ((_d = opts.portalTheme) == null ? void 0 : _d.borderRadius) || ((_e = this.portalTheme) == null ? void 0 : _e.borderRadius),
1823
+ portalThemeMode: ((_f = opts.portalTheme) == null ? void 0 : _f.mode) || (partner == null ? void 0 : partner.themeMode) || ((_g = this.portalTheme) == null ? void 0 : _g.mode),
1824
+ portalAccentColor: ((_h = opts.portalTheme) == null ? void 0 : _h.accentColor) || (partner == null ? void 0 : partner.accentColor) || ((_i = this.portalTheme) == null ? void 0 : _i.accentColor),
1825
+ portalForegroundColor: ((_j = opts.portalTheme) == null ? void 0 : _j.foregroundColor) || (partner == null ? void 0 : partner.foregroundColor) || ((_k = this.portalTheme) == null ? void 0 : _k.foregroundColor),
1826
+ portalBackgroundColor: ((_l = opts.portalTheme) == null ? void 0 : _l.backgroundColor) || (partner == null ? void 0 : partner.backgroundColor) || this.portalBackgroundColor || ((_m = this.portalTheme) == null ? void 0 : _m.backgroundColor),
1673
1827
  portalPrimaryButtonColor: this.portalPrimaryButtonColor,
1674
1828
  portalTextColor: this.portalTextColor,
1675
1829
  portalPrimaryButtonTextColor: this.portalPrimaryButtonTextColor,
1676
- isForNewDevice: opts.isForNewDevice ? opts.isForNewDevice.toString() : void 0,
1677
- supportedWalletTypes: __privateGet(this, _supportedWalletTypesOpt) ? JSON.stringify(__privateGet(this, _supportedWalletTypesOpt)) : void 0
1678
- }, isCreate || isLogin ? __spreadValues(__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 } : {}), opts.authType === "externalWallet" ? {
1679
- // Using id here since we store the bech32 address for cosmos in the address field of the wallet
1680
- externalWalletAddress: (_n = this.externalWalletWithParaAuth) == null ? void 0 : _n.id
1681
- } : {}) : {}), isLogin || isOnRamp ? { sessionId: opts.sessionId } : {}), isLogin ? {
1682
- encryptionKey: opts.loginEncryptionPublicKey,
1683
- newDeviceSessionLookupId: opts.newDeviceSessionId,
1684
- newDeviceEncryptionKey: opts.newDeviceEncryptionKey,
1685
- pregenIds: JSON.stringify(this.pregenIds),
1686
- displayName: opts.displayName,
1687
- pfpUrl: opts.pfpUrl
1688
- } : {}), opts.params || {});
1689
- return constructUrl({ base, path, params });
1830
+ isForNewDevice: opts.isForNewDevice ? opts.isForNewDevice.toString() : void 0
1831
+ }, auth && (isCreate || isLogin) ? auth : {}), isOnRamp ? { sessionId } : {}), isLogin ? __spreadProps(__spreadValues({
1832
+ sessionId: thisDevice.sessionId,
1833
+ encryptionKey: thisDevice.encryptionKey
1834
+ }, opts.newDevice ? {
1835
+ newDeviceSessionLookupId: opts.newDevice.sessionId,
1836
+ newDeviceEncryptionKey: opts.newDevice.encryptionKey
1837
+ } : {}), {
1838
+ pregenIds: JSON.stringify(this.pregenIds)
1839
+ }) : {}), opts.params || {});
1840
+ const url = constructUrl({ base, path, params });
1841
+ if (opts.shorten) {
1842
+ return shortenUrl(this.ctx, url);
1843
+ }
1844
+ return url;
1690
1845
  });
1691
1846
  }
1692
1847
  touchSession(regenerate = false) {
1693
1848
  return __async(this, null, function* () {
1694
- const res = yield this.ctx.client.touchSession(regenerate);
1695
- this.setSupportedWalletTypes(res.data.supportedWalletTypes, res.data.cosmosPrefix);
1696
- return res;
1849
+ var _a, _b, _c;
1850
+ const session = yield this.ctx.client.touchSession(regenerate);
1851
+ if (!__privateGet(this, _partner) || ((_a = __privateGet(this, _partner)) == null ? void 0 : _a.id) !== session.partnerId || !supportedWalletTypesEq(((_b = __privateGet(this, _partner)) == null ? void 0 : _b.supportedWalletTypes) || [], session.supportedWalletTypes) || (((_c = __privateGet(this, _partner)) == null ? void 0 : _c.cosmosPrefix) || "cosmos") !== session.cosmosPrefix) {
1852
+ yield __privateMethod(this, _ParaCore_instances, getPartner_fn).call(this, session.partnerId);
1853
+ }
1854
+ return session;
1697
1855
  });
1698
1856
  }
1699
- setSupportedWalletTypes(supportedWalletTypes, cosmosPrefix) {
1700
- if (supportedWalletTypes && !__privateGet(this, _supportedWalletTypes)) {
1701
- __privateSet(this, _supportedWalletTypes, supportedWalletTypes);
1702
- Object.keys(this.currentWalletIds).forEach((type) => {
1703
- var _a;
1704
- if (!((_a = __privateGet(this, _supportedWalletTypes)) == null ? void 0 : _a.some(({ type: supportedType }) => supportedType === type))) {
1705
- delete this.currentWalletIds[type];
1706
- }
1707
- });
1708
- }
1709
- if (cosmosPrefix && !this.cosmosPrefix) {
1710
- this.cosmosPrefix = cosmosPrefix;
1711
- }
1712
- }
1713
1857
  getVerificationEmailProps() {
1714
1858
  return {
1715
1859
  brandColor: this.emailPrimaryColor,
@@ -1739,12 +1883,26 @@ var _ParaCore = class _ParaCore {
1739
1883
  */
1740
1884
  init() {
1741
1885
  return __async(this, null, function* () {
1742
- var _a;
1743
- this.email = (yield this.localStorageGetItem(LOCAL_STORAGE_EMAIL)) || void 0;
1744
- this.countryCode = (yield this.localStorageGetItem(LOCAL_STORAGE_COUNTRY_CODE)) || void 0;
1745
- this.phone = (yield this.localStorageGetItem(LOCAL_STORAGE_PHONE)) || void 0;
1886
+ var _a, _b;
1746
1887
  this.userId = (yield this.localStorageGetItem(LOCAL_STORAGE_USER_ID)) || void 0;
1747
- this.telegramUserId = (yield this.localStorageGetItem(LOCAL_STORAGE_TELEGRAM_USER_ID)) || void 0;
1888
+ const storageAuthInfo = (yield this.localStorageGetItem(LOCAL_STORAGE_AUTH_INFO)) || void 0;
1889
+ const stringExternalWallets = yield this.localStorageGetItem(LOCAL_STORAGE_EXTERNAL_WALLETS);
1890
+ const _externalWallets = JSON.parse(stringExternalWallets || "{}");
1891
+ yield this.setExternalWallets(_externalWallets);
1892
+ let authInfo = jsonParse(storageAuthInfo);
1893
+ if (!authInfo) {
1894
+ const authParams = {
1895
+ email: (yield this.localStorageGetItem(LOCAL_STORAGE_EMAIL)) || void 0,
1896
+ phone: (yield this.localStorageGetItem(LOCAL_STORAGE_PHONE)) || void 0,
1897
+ countryCode: (yield this.localStorageGetItem(LOCAL_STORAGE_COUNTRY_CODE)) || void 0,
1898
+ farcasterUsername: (yield this.localStorageGetItem(LOCAL_STORAGE_FARCASTER_USERNAME)) || void 0,
1899
+ telegramUserId: (yield this.localStorageGetItem(LOCAL_STORAGE_TELEGRAM_USER_ID)) || void 0,
1900
+ // Using id here since we store the bech32 address for cosmos in the address field of the wallet
1901
+ externalWalletAddress: ((_a = this.externalWalletWithParaAuth) == null ? void 0 : _a.id) || void 0
1902
+ };
1903
+ authInfo = __privateMethod(this, _ParaCore_instances, toAuthInfo_fn).call(this, authParams);
1904
+ }
1905
+ __privateSet(this, _authInfo, authInfo);
1748
1906
  const stringWallets = this.platformUtils.secureStorage ? yield this.platformUtils.secureStorage.get(LOCAL_STORAGE_WALLETS) : yield this.localStorageGetItem(LOCAL_STORAGE_WALLETS);
1749
1907
  const _wallets = JSON.parse(stringWallets || "{}");
1750
1908
  const stringEd25519Wallets = this.platformUtils.secureStorage ? yield this.platformUtils.secureStorage.get(LOCAL_STORAGE_ED25519_WALLETS) : yield this.localStorageGetItem(LOCAL_STORAGE_ED25519_WALLETS);
@@ -1757,7 +1915,7 @@ var _ParaCore = class _ParaCore {
1757
1915
  return __spreadValues(__spreadValues({}, res), !res[key] ? { [key]: migrateWallet(_ed25519Wallets[key]) } : {});
1758
1916
  }, {}));
1759
1917
  yield this.setWallets(wallets);
1760
- const _currentWalletIds = (_a = yield this.localStorageGetItem(LOCAL_STORAGE_CURRENT_WALLET_IDS)) != null ? _a : void 0;
1918
+ const _currentWalletIds = (_b = yield this.localStorageGetItem(LOCAL_STORAGE_CURRENT_WALLET_IDS)) != null ? _b : void 0;
1761
1919
  const currentWalletIds = [void 0, null, "undefined", "null"].includes(_currentWalletIds) ? {} : (() => {
1762
1920
  const fromJson = JSON.parse(_currentWalletIds);
1763
1921
  return Array.isArray(fromJson) ? Object.keys(import_user_management_client5.WalletType).reduce((acc, type) => {
@@ -1776,21 +1934,42 @@ var _ParaCore = class _ParaCore {
1776
1934
  if (loginEncryptionKey && loginEncryptionKey !== "undefined") {
1777
1935
  this.loginEncryptionKeyPair = this.convertEncryptionKeyPair(JSON.parse(loginEncryptionKey));
1778
1936
  }
1779
- const stringExternalWallets = yield this.localStorageGetItem(LOCAL_STORAGE_EXTERNAL_WALLETS);
1780
- const _externalWallets = JSON.parse(stringExternalWallets || "{}");
1781
- yield this.setExternalWallets(_externalWallets);
1782
1937
  setupListeners.bind(this)();
1783
1938
  yield this.touchSession();
1784
1939
  });
1785
1940
  }
1941
+ setAuth(_0) {
1942
+ return __async(this, arguments, function* (auth, { extras = {}, userId } = {}) {
1943
+ const authInfo = __spreadValues(__spreadValues({}, (0, import_user_management_client5.extractAuthInfo)(auth, { isRequired: true })), extras || {});
1944
+ yield __privateMethod(this, _ParaCore_instances, setAuthInfo_fn).call(this, authInfo);
1945
+ if (!!userId) {
1946
+ yield this.setUserId(userId);
1947
+ }
1948
+ return __privateGet(this, _authInfo);
1949
+ });
1950
+ }
1951
+ assertUserId() {
1952
+ if (!this.userId) {
1953
+ throw new Error("no userId is set");
1954
+ }
1955
+ return this.userId;
1956
+ }
1957
+ assertIsAuthSet(allowed) {
1958
+ if (!__privateGet(this, _authInfo)) {
1959
+ throw new Error("auth is not set");
1960
+ }
1961
+ if (allowed && !allowed.includes(__privateGet(this, _authInfo).authType)) {
1962
+ throw new Error(`invalid auth type, expected ${allowed.join(", ")}`);
1963
+ }
1964
+ return __privateGet(this, _authInfo);
1965
+ }
1786
1966
  /**
1787
1967
  * Sets the email associated with the `ParaCore` instance.
1788
1968
  * @param email - Email to set.
1789
1969
  */
1790
1970
  setEmail(email) {
1791
1971
  return __async(this, null, function* () {
1792
- this.email = email;
1793
- yield this.localStorageSetItem(LOCAL_STORAGE_EMAIL, email);
1972
+ yield this.setAuth({ email });
1794
1973
  });
1795
1974
  }
1796
1975
  /**
@@ -1799,8 +1978,7 @@ var _ParaCore = class _ParaCore {
1799
1978
  */
1800
1979
  setTelegramUserId(telegramUserId) {
1801
1980
  return __async(this, null, function* () {
1802
- this.telegramUserId = telegramUserId;
1803
- yield this.localStorageSetItem(LOCAL_STORAGE_TELEGRAM_USER_ID, telegramUserId);
1981
+ yield this.setAuth({ telegramUserId });
1804
1982
  });
1805
1983
  }
1806
1984
  /**
@@ -1808,12 +1986,9 @@ var _ParaCore = class _ParaCore {
1808
1986
  * @param phone - Phone number to set.
1809
1987
  * @param countryCode - Country Code to set.
1810
1988
  */
1811
- setPhoneNumber(phone, countryCode) {
1989
+ setPhone(phone, countryCode) {
1812
1990
  return __async(this, null, function* () {
1813
- this.phone = phone;
1814
- this.countryCode = countryCode;
1815
- yield this.localStorageSetItem(LOCAL_STORAGE_PHONE, phone);
1816
- yield this.localStorageSetItem(LOCAL_STORAGE_COUNTRY_CODE, countryCode);
1991
+ yield this.setAuth({ phone: formatPhoneNumber(phone, countryCode) });
1817
1992
  });
1818
1993
  }
1819
1994
  /**
@@ -1822,8 +1997,7 @@ var _ParaCore = class _ParaCore {
1822
1997
  */
1823
1998
  setFarcasterUsername(farcasterUsername) {
1824
1999
  return __async(this, null, function* () {
1825
- this.farcasterUsername = farcasterUsername;
1826
- yield this.localStorageSetItem(LOCAL_STORAGE_FARCASTER_USERNAME, farcasterUsername);
2000
+ yield this.setAuth({ farcasterUsername });
1827
2001
  });
1828
2002
  }
1829
2003
  /**
@@ -1915,22 +2089,12 @@ var _ParaCore = class _ParaCore {
1915
2089
  getEmail() {
1916
2090
  return this.email;
1917
2091
  }
1918
- /**
1919
- * Gets the phone object associated with the `ParaCore` instance.
1920
- * @returns - phone object with phone number and country code associated with the `ParaCore` instance.
1921
- */
1922
- getPhone() {
1923
- return { phone: this.phone, countryCode: this.countryCode };
1924
- }
1925
2092
  /**
1926
2093
  * Gets the formatted phone number associated with the `ParaCore` instance.
1927
2094
  * @returns - formatted phone number associated with the `ParaCore` instance.
1928
2095
  */
1929
2096
  getPhoneNumber() {
1930
- if (!this.phone || !this.countryCode) {
1931
- return void 0;
1932
- }
1933
- return normalizePhoneNumber(this.countryCode, this.phone);
2097
+ return this.phone;
1934
2098
  }
1935
2099
  /**
1936
2100
  * Gets the farcaster username associated with the `ParaCore` instance.
@@ -1959,23 +2123,6 @@ var _ParaCore = class _ParaCore {
1959
2123
  dispatchEvent(ParaEvent.WALLETS_CHANGE_EVENT, null);
1960
2124
  });
1961
2125
  }
1962
- /**
1963
- * Fetches the most recent OAuth account metadata for the signed-in user.
1964
- * If applicable, this will include the user's most recent metadata from their Google, Apple, Facebook, X, Discord, Farcaster, or Telegram account, the last time they signed in to your app.
1965
- * @returns {Promise<AccountMetadata>} the user's account metadata.
1966
- */
1967
- getAccountMetadata() {
1968
- return __async(this, null, function* () {
1969
- if (!(yield this.isSessionActive()) || !this.userId) {
1970
- throw new Error("no signed-in user");
1971
- }
1972
- const {
1973
- data: { partnerId }
1974
- } = yield this.touchSession();
1975
- const { accountMetadata } = yield this.ctx.client.getAccountMetadata(this.userId, partnerId);
1976
- return accountMetadata;
1977
- });
1978
- }
1979
2126
  /**
1980
2127
  * Validates that a wallet ID is present on the instance, usable, and matches the desired filters.
1981
2128
  * If no ID is passed, this will instead return the first valid, usable wallet ID that matches the filters.
@@ -2029,8 +2176,10 @@ var _ParaCore = class _ParaCore {
2029
2176
  }
2030
2177
  findWallet(idOrAddress, overrideType, filter = {}) {
2031
2178
  var _a, _c, _d;
2032
- if (!this.isExternalWalletAuth && !idOrAddress && Object.keys(this.externalWallets).length > 0) {
2033
- return Object.values(this.externalWallets)[0];
2179
+ if (!this.isExternalWalletAuth) {
2180
+ if (!idOrAddress && Object.keys(this.externalWallets).length > 0) {
2181
+ return Object.values(this.externalWallets)[0];
2182
+ }
2034
2183
  }
2035
2184
  if ((_a = this.externalWallets) == null ? void 0 : _a[idOrAddress]) {
2036
2185
  return this.externalWallets[idOrAddress];
@@ -2077,10 +2226,8 @@ var _ParaCore = class _ParaCore {
2077
2226
  }
2078
2227
  assertIsValidWalletType(type, walletTypes) {
2079
2228
  return __async(this, null, function* () {
2080
- if (!__privateGet(this, _supportedWalletTypes)) {
2081
- yield this.touchSession();
2082
- }
2083
- if (!type || !Object.values(import_user_management_client5.WalletType).includes(type) || !(walletTypes != null ? walletTypes : this.supportedWalletTypes.map(({ type: type2 }) => type2)).includes(type)) {
2229
+ const { supportedWalletTypes } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
2230
+ if (!type || !Object.values(import_user_management_client5.WalletType).includes(type) || !(walletTypes != null ? walletTypes : supportedWalletTypes.map(({ type: type2 }) => type2)).includes(type)) {
2084
2231
  throw new Error(`wallet type ${type} is not supported`);
2085
2232
  }
2086
2233
  return type;
@@ -2088,33 +2235,29 @@ var _ParaCore = class _ParaCore {
2088
2235
  }
2089
2236
  getMissingTypes() {
2090
2237
  return __async(this, null, function* () {
2091
- if (!__privateGet(this, _supportedWalletTypes)) {
2092
- yield this.touchSession();
2093
- }
2094
- return this.supportedWalletTypes.filter(
2238
+ const { supportedWalletTypes } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
2239
+ return supportedWalletTypes.filter(
2095
2240
  ({ type: t, optional }) => !optional && Object.values(this.wallets).every((w) => !this.isWalletOwned(w) || !WalletSchemeTypeMap[w.scheme][t])
2096
2241
  ).map(({ type }) => type);
2097
2242
  });
2098
2243
  }
2099
2244
  getTypesToCreate(types) {
2100
2245
  return __async(this, null, function* () {
2101
- if (!__privateGet(this, _supportedWalletTypes)) {
2102
- yield this.touchSession();
2103
- }
2246
+ const { supportedWalletTypes } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
2104
2247
  return getSchemes(types != null ? types : yield this.getMissingTypes()).map((scheme) => {
2105
2248
  switch (scheme) {
2106
2249
  case import_user_management_client5.WalletScheme.ED25519:
2107
2250
  return import_user_management_client5.WalletType.SOLANA;
2108
2251
  default:
2109
- return this.supportedWalletTypes.some(({ type, optional }) => type === import_user_management_client5.WalletType.COSMOS && !optional) ? import_user_management_client5.WalletType.COSMOS : import_user_management_client5.WalletType.EVM;
2252
+ return supportedWalletTypes.some(({ type, optional }) => type === import_user_management_client5.WalletType.COSMOS && !optional) ? import_user_management_client5.WalletType.COSMOS : import_user_management_client5.WalletType.EVM;
2110
2253
  }
2111
2254
  });
2112
2255
  });
2113
2256
  }
2114
- getPartnerURL(partnerId) {
2257
+ getPartnerURL() {
2115
2258
  return __async(this, null, function* () {
2116
- const res = yield this.ctx.client.getPartner(partnerId);
2117
- return res.data.partner.portalUrl;
2259
+ const { portalUrl } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
2260
+ return portalUrl;
2118
2261
  });
2119
2262
  }
2120
2263
  /**
@@ -2122,75 +2265,9 @@ var _ParaCore = class _ParaCore {
2122
2265
  * @param partnerId: string - id of the partner to get the portal URL for
2123
2266
  * @returns - portal URL
2124
2267
  */
2125
- getPortalURL(partnerId) {
2126
- return __async(this, null, function* () {
2127
- return partnerId && (yield this.getPartnerURL(partnerId)) || getPortalBaseURL(this.ctx);
2128
- });
2129
- }
2130
- getWebAuthURLForCreate(_a) {
2131
- return __async(this, null, function* () {
2132
- var _b = _a, {
2133
- webAuthId
2134
- } = _b, options = __objRest(_b, [
2135
- "webAuthId"
2136
- ]);
2137
- return this.constructPortalUrl("createAuth", __spreadProps(__spreadValues({}, options), { pathId: webAuthId }));
2138
- });
2139
- }
2140
- getPasswordURLForCreate(_c) {
2141
- return __async(this, null, function* () {
2142
- var _d = _c, {
2143
- passwordId
2144
- } = _d, options = __objRest(_d, [
2145
- "passwordId"
2146
- ]);
2147
- return this.constructPortalUrl("createPassword", __spreadProps(__spreadValues({}, options), {
2148
- pathId: passwordId
2149
- }));
2150
- });
2151
- }
2152
- getShortUrl(compressedUrl) {
2153
- return constructUrl({
2154
- base: getPortalBaseURL(this.ctx),
2155
- path: `/short/${compressedUrl}`
2156
- });
2157
- }
2158
- shortenLoginLink(link) {
2159
- return __async(this, null, function* () {
2160
- const url = yield upload(link, this.ctx.client);
2161
- return this.getShortUrl(url);
2162
- });
2163
- }
2164
- /**
2165
- * Generates a URL for registering a new WebAuth passkey.
2166
- * @param {GetWebAuthUrlForLoginParams} opts the options object
2167
- * @returns - the URL for creating a new passkey
2168
- */
2169
- getWebAuthURLForLogin(opts) {
2170
- return __async(this, null, function* () {
2171
- return this.constructPortalUrl("loginAuth", opts);
2172
- });
2173
- }
2174
- /**
2175
- * Generates a URL for registering a new user password.
2176
- * @param {GetWebAuthUrlForLoginParams} opts the options object
2177
- * @returns - the URL for creating a new password
2178
- */
2179
- getPasswordURLForLogin(opts) {
2180
- return __async(this, null, function* () {
2181
- return this.constructPortalUrl("loginPassword", opts);
2182
- });
2183
- }
2184
- /**
2185
- * Generates a URL for registering a new WebAuth passkey for a phone number.
2186
- * @param {Omit<GetWebAuthUrlForLoginParams, 'authType'>} opts the options object
2187
- * @returns - web auth url
2188
- */
2189
- getWebAuthURLForLoginForPhone(opts) {
2268
+ getPortalURL() {
2190
2269
  return __async(this, null, function* () {
2191
- return this.constructPortalUrl("loginAuth", __spreadValues({
2192
- authType: "phone"
2193
- }, opts));
2270
+ return (yield this.getPartnerURL()) || getPortalBaseURL(this.ctx);
2194
2271
  });
2195
2272
  }
2196
2273
  /**
@@ -2253,1769 +2330,1680 @@ var _ParaCore = class _ParaCore {
2253
2330
  });
2254
2331
  }
2255
2332
  /**
2256
- * Checks if a user exists for an email address.
2257
- * @param {Object} opts the options object
2258
- * @param {string} opts.email the email to check.
2259
- * @returns true if user exists, false otherwise.
2333
+ * Resend a verification email for the current user.
2260
2334
  */
2261
- checkIfUserExists(_0) {
2262
- return __async(this, arguments, function* ({ email }) {
2263
- const res = yield this.ctx.client.checkUserExists({ email });
2264
- return res.data.exists;
2335
+ resendVerificationCode() {
2336
+ return __async(this, null, function* () {
2337
+ yield this.ctx.client.resendVerificationCode(__spreadValues({
2338
+ userId: this.userId
2339
+ }, this.getVerificationEmailProps()));
2265
2340
  });
2266
2341
  }
2267
2342
  /**
2268
- * Checks if a user exists for a phone number.
2269
- * @param {Object} opts the options object
2270
- * @param {string} opts.phone - phone number to check.
2271
- * @param {string} opts.countryCode - the country code.
2272
- * @returns true if user exists, false otherwise.
2343
+ * Checks if the current session is active.
2344
+ * @returns `true` if active, `false` otherwise
2273
2345
  */
2274
- checkIfUserExistsByPhone(_0) {
2275
- return __async(this, arguments, function* ({ phone, countryCode }) {
2276
- const res = yield this.ctx.client.checkUserExists({ phone, countryCode });
2277
- return res.data.exists;
2346
+ isSessionActive() {
2347
+ return __async(this, null, function* () {
2348
+ if (this.externalWalletConnectionType === "CONNECTION_ONLY") {
2349
+ return true;
2350
+ }
2351
+ const { isAuthenticated } = yield this.touchSession();
2352
+ return !!isAuthenticated;
2278
2353
  });
2279
2354
  }
2280
2355
  /**
2281
- * Creates a new user.
2282
- * @param {Object} opts the options object
2283
- * @param {string} opts.email the email to use.
2284
- */
2285
- createUser(_0) {
2286
- return __async(this, arguments, function* ({ email }) {
2287
- this.requireApiKey();
2288
- yield this.setEmail(email);
2289
- const { userId } = yield this.ctx.client.createUser(__spreadValues({
2290
- email: this.email
2291
- }, this.getVerificationEmailProps()));
2292
- yield this.setUserId(userId);
2356
+ * Checks if a session is active and a wallet exists.
2357
+ * @returns `true` if active, `false` otherwise
2358
+ **/
2359
+ isFullyLoggedIn() {
2360
+ return __async(this, null, function* () {
2361
+ if (this.externalWalletConnectionType === "CONNECTION_ONLY") {
2362
+ return true;
2363
+ }
2364
+ const isSessionActive = yield this.isSessionActive();
2365
+ return isSessionActive && this.currentWalletIdsArray.length > 0 && this.currentWalletIdsArray.reduce((acc, [id]) => acc && !!this.wallets[id], true);
2293
2366
  });
2294
2367
  }
2295
- /**
2296
- * Creates a new user with a phone number.
2297
- * @param {Object} opts the options object
2298
- * @param {string} opts.phone - the phone number to use for creating the user.
2299
- * @param {string} opts.countryCode - the country code to use for creating the user.
2300
- */
2301
- createUserByPhone(_0) {
2302
- return __async(this, arguments, function* ({ phone, countryCode }) {
2303
- this.requireApiKey();
2304
- yield this.setPhoneNumber(phone, countryCode);
2305
- const { userId } = yield this.ctx.client.createUser({
2306
- phone: this.phone,
2307
- countryCode: this.countryCode
2308
- });
2309
- yield this.setUserId(userId);
2368
+ supportedAuthMethods(auth) {
2369
+ return __async(this, null, function* () {
2370
+ const { supportedAuthMethods } = yield this.ctx.client.getSupportedAuthMethods(auth);
2371
+ const authMethods = /* @__PURE__ */ new Set();
2372
+ for (const type of supportedAuthMethods) {
2373
+ switch (type) {
2374
+ case "PASSWORD":
2375
+ authMethods.add(import_user_management_client5.AuthMethod.PASSWORD);
2376
+ break;
2377
+ case "BIOMETRIC":
2378
+ authMethods.add(import_user_management_client5.AuthMethod.PASSKEY);
2379
+ break;
2380
+ }
2381
+ }
2382
+ return authMethods;
2310
2383
  });
2311
2384
  }
2312
2385
  /**
2313
- * Logs in or creates a new user using an external wallet address.
2314
- * @param {Object} opts the options object
2315
- * @param {string} opts.address the external wallet address to use for identification.
2316
- * @param {WalletType} opts.type type of external wallet to use for identification.
2317
- * @param {string} opts.provider the name of the provider for the external wallet.
2386
+ * Get hints associated with the users stored biometrics.
2387
+ * @deprecated
2388
+ * @returns Array containing useragents and AAGuids for stored biometrics
2318
2389
  */
2319
- externalWalletLogin(wallet) {
2390
+ getUserBiometricLocationHints() {
2320
2391
  return __async(this, null, function* () {
2321
- this.requireApiKey();
2322
- const res = yield this.ctx.client.externalWalletLogin({
2323
- externalAddress: wallet.address,
2324
- type: wallet.type,
2325
- externalWalletProvider: wallet.provider,
2326
- // If the wallet isn't using full Para auth we want to track the login here
2327
- shouldTrackUser: !wallet.withFullParaAuth
2328
- });
2329
- yield this.setExternalWallet(wallet);
2330
- yield this.setUserId(res.userId);
2331
- return res;
2392
+ const { auth } = this.assertIsAuthSet();
2393
+ return yield this.ctx.client.getBiometricLocationHints(auth);
2332
2394
  });
2333
2395
  }
2334
2396
  /**
2335
- * Returns whether or not the user is connected with only an external wallet, not an external wallet with Para auth.
2336
- */
2337
- isUsingExternalWallet() {
2338
- return !this.isExternalWalletAuth && !!Object.keys(this.externalWallets).length;
2339
- }
2340
- /**
2341
- * Passes the email code obtained from the user for verification.
2342
- * @param {Object} opts the options object
2343
- * @param {string} verificationCode the six-digit code to check
2344
- * @returns {string} the web auth url for creating a new credential
2345
- */
2346
- verifyEmail(_0) {
2347
- return __async(this, arguments, function* ({ verificationCode }) {
2348
- yield this.ctx.client.verifyEmail(this.userId, { verificationCode });
2349
- return this.getSetUpBiometricsURL();
2350
- });
2351
- }
2352
- verifyExternalWallet(_0) {
2397
+ * Updates the session with the user management server, possibly
2398
+ * opening a popup to refresh the session.
2399
+ *
2400
+ * @param {Object} opts the options object.
2401
+ * @param {boolean} [shouldOpenPopup] - if `true`, the running device will open a popup to reauthenticate the user.
2402
+ * @returns a URL for the user to reauthenticate.
2403
+ **/
2404
+ refreshSession() {
2353
2405
  return __async(this, arguments, function* ({
2354
- address,
2355
- signedMessage,
2356
- cosmosPublicKeyHex,
2357
- cosmosSigner
2358
- }) {
2359
- yield this.ctx.client.verifyExternalWallet(this.userId, { address, signedMessage, cosmosPublicKeyHex, cosmosSigner });
2360
- return this.getSetUpBiometricsURL({ authType: "externalWallet" });
2361
- });
2362
- }
2363
- /**
2364
- * Passes the phone code obtained from the user for verification.
2365
- * @param {Object} opts the options object
2366
- * @param {string} verificationCode the six-digit code to check
2367
- * @returns {string} the web auth url for creating a new credential
2368
- */
2369
- verifyPhone(_0) {
2370
- return __async(this, arguments, function* ({ verificationCode }) {
2371
- yield this.ctx.client.verifyPhone(this.userId, { verificationCode });
2372
- return this.getSetUpBiometricsURLForPhone();
2406
+ shouldOpenPopup = false
2407
+ } = {}) {
2408
+ const { sessionId } = yield this.touchSession(true);
2409
+ if (!this.loginEncryptionKeyPair) {
2410
+ yield this.setLoginEncryptionKeyPair();
2411
+ }
2412
+ const link = yield this.getLoginUrl({
2413
+ sessionId
2414
+ });
2415
+ if (shouldOpenPopup) {
2416
+ this.platformUtils.openPopup(link);
2417
+ }
2418
+ return link;
2373
2419
  });
2374
2420
  }
2375
2421
  /**
2376
- * Validates the response received from an attempted Telegram login for authenticity, then
2377
- * creates or retrieves the corresponding Para user and prepares the Para instance to sign in with that user.
2378
- * @param authResponse - the response JSON object received from the Telegram widget.
2379
- * @returns `{ isValid: boolean; telegramUserId?: string; userId?: string; isNewUser?: boolean; supportedAuthMethods?: AuthMethod[]; biometricHints?: BiometricLocationHint[] }`
2380
- */
2381
- verifyTelegram(authObject) {
2422
+ * Call this method after login to ensure that the user ID is set
2423
+ * internally.
2424
+ **/
2425
+ userSetupAfterLogin() {
2382
2426
  return __async(this, null, function* () {
2383
- const res = yield this.ctx.client.verifyTelegram(authObject);
2384
- if (res.isValid) {
2385
- yield this.setUserId(res.userId);
2386
- yield this.setTelegramUserId(res.telegramUserId);
2387
- yield this.touchSession(true);
2388
- if (!this.loginEncryptionKeyPair) {
2389
- yield this.setLoginEncryptionKeyPair();
2390
- }
2391
- }
2392
- return res;
2427
+ const session = yield this.touchSession();
2428
+ yield this.setUserId(session.userId);
2429
+ if (session.currentWalletIds && session.currentWalletIds !== this.currentWalletIds)
2430
+ yield this.setCurrentWalletIds(session.currentWalletIds, {
2431
+ sessionLookupId: this.isPortal() ? session.sessionLookupId : void 0
2432
+ });
2433
+ return session;
2393
2434
  });
2394
2435
  }
2395
2436
  /**
2396
- * Performs 2FA verification.
2397
- * @param {Object} opts the options object
2398
- * @param {string} opts.email the email to use for performing a 2FA verification.
2399
- * @param {string} opts.verificationCode the verification code to received via 2FA.
2400
- * @returns {Object} `{ address, initiatedAt, status, userId, walletId }`
2401
- */
2402
- verify2FA(_0) {
2403
- return __async(this, arguments, function* ({ email, verificationCode }) {
2404
- const res = yield this.ctx.client.verify2FA(email, verificationCode);
2405
- return {
2406
- initiatedAt: res.data.initiatedAt,
2407
- status: res.data.status,
2408
- userId: res.data.userId,
2409
- wallets: res.data.wallets
2410
- };
2437
+ * Get transmission shares associated with session.
2438
+ * @param {Object} opts the options object.
2439
+ * @param {boolean} opts.isForNewDevice - true if this device is registering.
2440
+ * @returns - transmission keyshares.
2441
+ **/
2442
+ getTransmissionKeyShares() {
2443
+ return __async(this, arguments, function* ({ isForNewDevice = false } = {}) {
2444
+ const session = yield this.touchSession();
2445
+ const sessionLookupId = isForNewDevice ? `${session.sessionLookupId}-new-device` : session.sessionLookupId;
2446
+ return this.ctx.client.getTransmissionKeyshares(this.userId, sessionLookupId);
2411
2447
  });
2412
2448
  }
2413
2449
  /**
2414
- * Performs 2FA verification.
2415
- * @param {Object} opts the options object
2416
- * @param {string} opts.phone the phone number
2417
- * @param {string} opts.countryCode - the country code
2418
- * @param {string} opts.verificationCode - verification code to received via 2FA.
2419
- * @returns {Object} `{ address, initiatedAt, status, userId, walletId }`
2420
- */
2421
- verify2FAForPhone(_0) {
2422
- return __async(this, arguments, function* ({
2423
- phone,
2424
- countryCode,
2425
- verificationCode
2426
- }) {
2427
- const res = yield this.ctx.client.verify2FAForPhone(phone, countryCode, verificationCode);
2428
- return {
2429
- initiatedAt: res.data.initiatedAt,
2430
- status: res.data.status,
2431
- userId: res.data.userId,
2432
- wallets: res.data.wallets
2433
- };
2434
- });
2435
- }
2436
- /**
2437
- * Sets up two-factor authentication for the current user.
2438
- * @returns {string} uri - uri to use for setting up 2FA
2439
- * */
2440
- setup2FA() {
2441
- return __async(this, null, function* () {
2442
- const res = yield this.ctx.client.setup2FA(this.userId);
2443
- return {
2444
- uri: res.data.uri
2445
- };
2446
- });
2447
- }
2448
- /**
2449
- * Enables 2FA.
2450
- * @param {Object} opts the options object
2451
- * @param {string} opts.verificationCode - the verification code received via 2FA.
2452
- */
2453
- enable2FA(_0) {
2454
- return __async(this, arguments, function* ({ verificationCode }) {
2455
- yield this.ctx.client.enable2FA(this.userId, verificationCode);
2456
- });
2457
- }
2458
- /**
2459
- * Determines if 2FA has been set up.
2460
- * @returns {Object} `{ isSetup: boolean }` - true if 2FA is setup, false otherwise
2461
- */
2462
- check2FAStatus() {
2463
- return __async(this, null, function* () {
2464
- if (!this.userId) {
2465
- return { isSetup: false };
2466
- }
2467
- const res = yield this.ctx.client.check2FAStatus(this.userId);
2468
- return {
2469
- isSetup: res.data.isSetup
2470
- };
2471
- });
2472
- }
2473
- /**
2474
- * Resend a verification email for the current user.
2475
- */
2476
- resendVerificationCode() {
2477
- return __async(this, null, function* () {
2478
- yield this.ctx.client.resendVerificationCode(__spreadValues({
2479
- userId: this.userId
2480
- }, this.getVerificationEmailProps()));
2481
- });
2482
- }
2483
- /**
2484
- * Resend a verification SMS for the current user.
2485
- */
2486
- resendVerificationCodeByPhone() {
2487
- return __async(this, null, function* () {
2488
- yield this.ctx.client.resendVerificationCodeByPhone({
2489
- userId: this.userId
2490
- });
2491
- });
2492
- }
2493
- /**
2494
- * Returns a URL for setting up a new WebAuth passkey.
2495
- * @param {Object} opts the options object
2496
- * @param {string} opts.authType - the auth type to use
2497
- * @param {boolean} opts.isForNewDevice whether the passkey is for a new device of an existing user
2498
- * @returns {string} the URL
2499
- */
2500
- getSetUpBiometricsURL() {
2501
- return __async(this, arguments, function* ({
2502
- authType = "email",
2503
- isForNewDevice = false
2504
- } = {}) {
2505
- const res = yield this.ctx.client.addSessionPublicKey(this.userId, {
2506
- status: import_user_management_client5.PublicKeyStatus.PENDING,
2507
- type: import_user_management_client5.PublicKeyType.WEB
2508
- });
2509
- return this.getWebAuthURLForCreate({
2510
- authType,
2511
- isForNewDevice,
2512
- webAuthId: res.data.id,
2513
- partnerId: res.data.partnerId
2514
- });
2515
- });
2516
- }
2517
- /**
2518
- * Returns a URL for setting up a new WebAuth passkey for a phone number.
2519
- * @param {Object} opts the options object
2520
- * @param {boolean} opts.isForNewDevice whether the passkey is for a new device of an existing user
2521
- * @returns {string} the URL
2522
- */
2523
- getSetUpBiometricsURLForPhone() {
2450
+ * Call this method after login to perform setup.
2451
+ * @param {Object} opts the options object.
2452
+ * @param {any[]} opts.temporaryShares optional temporary shares to use for decryption.
2453
+ * @param {boolean} [opts.skipSessionRefresh] - whether or not to skip refreshing the session.
2454
+ **/
2455
+ setupAfterLogin() {
2524
2456
  return __async(this, arguments, function* ({
2525
- isForNewDevice = false
2457
+ temporaryShares,
2458
+ skipSessionRefresh = false
2526
2459
  } = {}) {
2527
- const res = yield this.ctx.client.addSessionPublicKey(this.userId, {
2528
- status: import_user_management_client5.PublicKeyStatus.PENDING,
2529
- type: import_user_management_client5.PublicKeyType.WEB
2530
- });
2531
- return this.getWebAuthURLForCreate({
2532
- authType: "phone",
2533
- isForNewDevice,
2534
- webAuthId: res.data.id,
2535
- partnerId: res.data.partnerId
2460
+ if (!temporaryShares) {
2461
+ temporaryShares = (yield this.getTransmissionKeyShares()).data.temporaryShares;
2462
+ }
2463
+ temporaryShares.forEach((share) => {
2464
+ const signer = decryptWithPrivateKey(this.loginEncryptionKeyPair.privateKey, share.encryptedShare, share.encryptedKey);
2465
+ this.wallets[share.walletId] = {
2466
+ id: share.walletId,
2467
+ signer
2468
+ };
2536
2469
  });
2470
+ yield this.deleteLoginEncryptionKeyPair();
2471
+ yield this.populateWalletAddresses();
2472
+ yield this.touchSession(!skipSessionRefresh);
2537
2473
  });
2538
2474
  }
2539
2475
  /**
2540
- * Returns a URL for setting up a new password.
2541
- * @param {Object} opts the options object
2542
- * @param {string} opts.authType - the auth type to use
2543
- * @param {boolean} opts.isForNewDevice whether the passkey is for a new device of an existing user
2544
- * @param {Theme} [opts.theme] the portal theme to use in place of the partner's default
2545
- * @returns {string} the URL
2546
- */
2547
- getSetupPasswordURL() {
2476
+ * Distributes a new wallet recovery share.
2477
+ * @param {Object} opts the options object.
2478
+ * @param {string} opts.walletId the wallet to distribute the recovery share for.
2479
+ * @param {string} opts.userShare optional user share generate the recovery share from. Defaults to the signer from the passed in walletId
2480
+ * @param {boolean} opts.skipBiometricShareCreation whether or not to skip biometric share creation. Used when regenerating recovery shares.
2481
+ * @param {boolean} opts.forceRefreshRecovery whether or not to force recovery secret regeneration. Used when regenerating recovery shares.
2482
+ * @returns {string} the recovery share.
2483
+ **/
2484
+ distributeNewWalletShare(_0) {
2548
2485
  return __async(this, arguments, function* ({
2549
- authType = "email",
2550
- isForNewDevice = false,
2551
- theme
2552
- } = {}) {
2553
- const res = yield this.ctx.client.addSessionPasswordPublicKey(this.userId, {
2554
- status: import_user_management_client5.PasswordStatus.PENDING
2555
- });
2556
- return this.getPasswordURLForCreate({
2557
- authType,
2558
- isForNewDevice,
2559
- passwordId: res.data.id,
2560
- partnerId: res.data.partnerId,
2561
- theme
2486
+ walletId,
2487
+ userShare,
2488
+ skipBiometricShareCreation = false,
2489
+ forceRefresh = false
2490
+ }) {
2491
+ let userSigner = userShare;
2492
+ if (!userSigner) {
2493
+ userSigner = this.wallets[walletId].signer;
2494
+ }
2495
+ const recoveryShare = skipBiometricShareCreation ? yield sendRecoveryForShare({
2496
+ ctx: this.ctx,
2497
+ userId: this.userId,
2498
+ walletId,
2499
+ userSigner,
2500
+ emailProps: this.getBackupKitEmailProps(),
2501
+ forceRefresh
2502
+ }) : yield distributeNewShare({
2503
+ ctx: this.ctx,
2504
+ userId: this.userId,
2505
+ walletId,
2506
+ userShare: userSigner,
2507
+ emailProps: this.getBackupKitEmailProps()
2562
2508
  });
2509
+ return recoveryShare;
2563
2510
  });
2564
2511
  }
2565
- /**
2566
- * Checks if the current session is active.
2567
- * @returns `true` if active, `false` otherwise
2568
- */
2569
- isSessionActive() {
2512
+ waitForWalletAddress(walletId) {
2570
2513
  return __async(this, null, function* () {
2571
- if (this.isUsingExternalWallet()) {
2572
- return true;
2514
+ let maxPolls = 0;
2515
+ while (true) {
2516
+ try {
2517
+ if (maxPolls === 10) {
2518
+ break;
2519
+ }
2520
+ ++maxPolls;
2521
+ const res = yield this.ctx.client.getWallets(this.userId);
2522
+ const wallet = res.data.wallets.find((w) => w.id === walletId);
2523
+ if (wallet && wallet.address) {
2524
+ return;
2525
+ }
2526
+ yield new Promise((resolve) => setTimeout(resolve, SHORT_POLLING_INTERVAL_MS));
2527
+ } catch (err) {
2528
+ console.error(err);
2529
+ }
2573
2530
  }
2574
- const res = yield this.touchSession();
2575
- return !!res.data.isAuthenticated;
2531
+ throw new Error("timed out waiting for wallet address");
2576
2532
  });
2577
2533
  }
2578
2534
  /**
2579
- * Checks if a session is active and a wallet exists.
2580
- * @returns `true` if active, `false` otherwise
2535
+ * Waits for a pregen wallet address to be created.
2536
+ *
2537
+ * @param pregenIdentifier - the identifier of the user the pregen wallet is associated with.
2538
+ * @param walletId - the wallet id
2539
+ * @param pregenIdentifierType - the identifier type of the user the pregen wallet is associated with.
2540
+ * @returns - recovery share.
2581
2541
  **/
2582
- isFullyLoggedIn() {
2583
- return __async(this, null, function* () {
2584
- if (this.isUsingExternalWallet()) {
2585
- return true;
2586
- }
2587
- const isSessionActive = yield this.isSessionActive();
2588
- return isSessionActive && this.currentWalletIdsArray.length > 0 && this.currentWalletIdsArray.reduce((acc, [id]) => acc && !!this.wallets[id], true);
2589
- });
2590
- }
2591
- supportedAuthMethods(auth) {
2542
+ waitForPregenWalletAddress(walletId) {
2592
2543
  return __async(this, null, function* () {
2593
- const { supportedAuthMethods } = yield this.ctx.client.getSupportedAuthMethods(auth);
2594
- const authMethods = /* @__PURE__ */ new Set();
2595
- for (const type of supportedAuthMethods) {
2596
- switch (type) {
2597
- case "PASSWORD":
2598
- authMethods.add(import_user_management_client5.AuthMethod.PASSWORD);
2599
- break;
2600
- case "BIOMETRIC":
2601
- authMethods.add(import_user_management_client5.AuthMethod.PASSKEY);
2544
+ let maxPolls = 0;
2545
+ while (true) {
2546
+ try {
2547
+ if (maxPolls === 10) {
2602
2548
  break;
2549
+ }
2550
+ ++maxPolls;
2551
+ const res = yield this.getPregenWallets();
2552
+ const wallet = res.find((w) => w.id === walletId);
2553
+ if (wallet && wallet.address) {
2554
+ return;
2555
+ }
2556
+ yield new Promise((resolve) => setTimeout(resolve, SHORT_POLLING_INTERVAL_MS));
2557
+ } catch (err) {
2558
+ console.error(err);
2603
2559
  }
2604
2560
  }
2605
- return authMethods;
2606
- });
2607
- }
2608
- /**
2609
- * Get hints associated with the users stored biometrics.
2610
- * @returns Array containing useragents and AAGuids for stored biometrics
2611
- */
2612
- getUserBiometricLocationHints() {
2613
- return __async(this, null, function* () {
2614
- var _a;
2615
- if (!this.email && !this.phone && !this.farcasterUsername && !this.telegramUserId && !this.isExternalWalletAuth) {
2616
- throw new Error(
2617
- "one of email, phone, farcaster username, telegram user id or external wallet with Para auth are required to get biometric location hints"
2618
- );
2619
- }
2620
- return yield this.ctx.client.getBiometricLocationHints({
2621
- email: this.email,
2622
- phone: this.phone,
2623
- countryCode: this.countryCode,
2624
- farcasterUsername: this.farcasterUsername,
2625
- telegramUserId: this.telegramUserId,
2626
- // Using id here since we store the bech32 address for cosmos in the address field of the wallet
2627
- externalWalletAddress: (_a = this.externalWalletWithParaAuth) == null ? void 0 : _a.id
2628
- });
2629
- });
2630
- }
2631
- setAuth(auth) {
2632
- return __async(this, null, function* () {
2633
- const authInfo = (0, import_user_management_client5.extractAuthInfo)(auth);
2634
- if (!authInfo) {
2635
- return void 0;
2636
- }
2637
- switch (authInfo.authType) {
2638
- case "email":
2639
- yield this.setEmail(authInfo.identifier);
2640
- break;
2641
- case "phone":
2642
- yield this.setPhoneNumber(authInfo.auth.phone, authInfo.auth.countryCode);
2643
- break;
2644
- case "farcaster":
2645
- yield this.setFarcasterUsername(authInfo.identifier);
2646
- break;
2647
- case "telegram":
2648
- yield this.setTelegramUserId(authInfo.identifier);
2649
- break;
2650
- }
2651
- return authInfo;
2561
+ throw new Error("timed out waiting for wallet address");
2652
2562
  });
2653
2563
  }
2654
2564
  /**
2655
- * Initiates a login.
2656
- * @param {Object} opts the options object
2657
- * @param {String} opts.email - the email to login with
2658
- * @param {boolean} opts.useShortURL - whether to shorten the link
2659
- * @returns - the WebAuth URL for logging in
2565
+ * Creates several new wallets with the desired types. If no types are provided, this method
2566
+ * will create one for each of the non-optional types specified in the instance's `supportedWalletTypes`
2567
+ * object that are not already present. This is automatically called upon account creation to ensure that
2568
+ * the user has a wallet of each required type.
2569
+ *
2570
+ * @param {Object} [opts] the options object.
2571
+ * @param {boolean} [opts.skipDistribute] if `true`, the wallets' recovery share will not be distributed.
2572
+ * @param {WalletType[]} [opts.types] the types of wallets to create.
2573
+ * @returns {Object} the wallets created, their ids, and the recovery secret.
2660
2574
  **/
2661
- initiateUserLogin(_e) {
2662
- return __async(this, null, function* () {
2663
- var _f = _e, { useShortUrl = false } = _f, auth = __objRest(_f, ["useShortUrl"]);
2664
- const authInfo = yield this.setAuth(auth);
2665
- if (!authInfo) {
2666
- return;
2667
- }
2668
- const res = yield this.touchSession(true);
2669
- if (!this.loginEncryptionKeyPair) {
2670
- yield this.setLoginEncryptionKeyPair();
2671
- }
2672
- const webAuthLoginURL = yield this.getWebAuthURLForLogin({
2673
- authType: authInfo.authType,
2674
- sessionId: res.data.sessionId,
2675
- partnerId: res.data.partnerId,
2676
- loginEncryptionPublicKey: getPublicKeyHex(this.loginEncryptionKeyPair)
2677
- });
2678
- if (!useShortUrl) {
2679
- return webAuthLoginURL;
2575
+ createWalletPerType() {
2576
+ return __async(this, arguments, function* ({
2577
+ skipDistribute = false,
2578
+ types
2579
+ } = {}) {
2580
+ const wallets = [];
2581
+ const walletIds = {};
2582
+ let recoverySecret;
2583
+ for (const type of yield this.getTypesToCreate(types)) {
2584
+ const [wallet, recoveryShare] = yield this.createWallet({ type, skipDistribute });
2585
+ wallets.push(wallet);
2586
+ getEquivalentTypes(type).filter((t) => !!this.isWalletTypeEnabled[t]).forEach((t) => {
2587
+ walletIds[t] = [wallet.id];
2588
+ });
2589
+ if (recoveryShare) {
2590
+ recoverySecret = recoveryShare;
2591
+ }
2680
2592
  }
2681
- return this.shortenLoginLink(webAuthLoginURL);
2593
+ return { wallets, walletIds, recoverySecret };
2682
2594
  });
2683
2595
  }
2684
2596
  /**
2685
- * Initiates a login.
2686
- * @param email - the email to login with
2687
- * @returns - a set of supported auth methods for the user
2688
- **/
2689
- initiateUserLoginV2(auth) {
2690
- return __async(this, null, function* () {
2691
- const authInfo = yield this.setAuth(auth);
2692
- if (!authInfo) {
2693
- return;
2694
- }
2695
- yield this.touchSession(true);
2696
- if (!this.loginEncryptionKeyPair) {
2697
- yield this.setLoginEncryptionKeyPair();
2698
- }
2699
- return yield this.supportedAuthMethods(authInfo.auth);
2700
- });
2701
- }
2702
- /**
2703
- * Initiates a login.
2704
- * @param opts the options object
2705
- * @param opts.phone the phone number
2706
- * @param opts.countryCode the country code
2707
- * @param opts.useShortURL - whether to shorten the link
2708
- * @returns - the WebAuth URL for logging in
2597
+ * Refresh the current user share for a wallet.
2598
+ *
2599
+ * @param {Object} opts the options object.
2600
+ * @param {string} opts.walletId the wallet id to refresh.
2601
+ * @param {string} opts.share the current user share.
2602
+ * @param {string} [opts.oldPartnerId] the current partner id.
2603
+ * @param {string} [opts.newPartnerId] the new partner id to set, if any.
2604
+ * @param {string} [opts.keyShareProtocolId]
2605
+ * @param {boolean} [opts.redistributeBackupEncryptedShares] whether or not to redistribute backup encrypted shares.
2606
+ * @returns {Object} the new user share and recovery secret.
2709
2607
  **/
2710
- initiateUserLoginForPhone(_g) {
2711
- return __async(this, null, function* () {
2712
- var _h = _g, {
2713
- useShortUrl = false
2714
- } = _h, auth = __objRest(_h, [
2715
- "useShortUrl"
2716
- ]);
2717
- yield this.setAuth(auth);
2718
- const res = yield this.touchSession(true);
2719
- if (!this.loginEncryptionKeyPair) {
2720
- yield this.setLoginEncryptionKeyPair();
2721
- }
2722
- const webAuthLoginURL = yield this.getWebAuthURLForLoginForPhone({
2723
- sessionId: res.data.sessionId,
2724
- loginEncryptionPublicKey: getPublicKeyHex(this.loginEncryptionKeyPair),
2725
- partnerId: res.data.partnerId
2608
+ refreshShare(_0) {
2609
+ return __async(this, arguments, function* ({
2610
+ walletId,
2611
+ share,
2612
+ oldPartnerId,
2613
+ newPartnerId,
2614
+ keyShareProtocolId,
2615
+ redistributeBackupEncryptedShares
2616
+ }) {
2617
+ const { signer, protocolId } = yield this.platformUtils.refresh(
2618
+ this.ctx,
2619
+ this.retrieveSessionCookie(),
2620
+ this.userId,
2621
+ walletId,
2622
+ share,
2623
+ oldPartnerId,
2624
+ newPartnerId,
2625
+ keyShareProtocolId
2626
+ );
2627
+ const recoverySecret = yield distributeNewShare({
2628
+ ctx: this.ctx,
2629
+ userId: this.userId,
2630
+ walletId,
2631
+ userShare: signer,
2632
+ ignoreRedistributingBackupEncryptedShare: !redistributeBackupEncryptedShares,
2633
+ emailProps: this.getBackupKitEmailProps(),
2634
+ partnerId: newPartnerId,
2635
+ protocolId
2726
2636
  });
2727
- if (!useShortUrl) {
2728
- return webAuthLoginURL;
2729
- }
2730
- return this.shortenLoginLink(webAuthLoginURL);
2637
+ return { signer, recoverySecret, protocolId };
2731
2638
  });
2732
2639
  }
2733
2640
  /**
2734
- * Waits for the session to be active.
2641
+ * Creates a new wallet.
2642
+ * @param {Object} opts the options object.
2643
+ * @param {WalletType} opts.type the type of wallet to create.
2644
+ * @param {boolean} opts.skipDistribute - if true, recovery share will not be distributed.
2645
+ * @returns {[Wallet, string | null]} `[wallet, recoveryShare]` - the wallet object and the new recovery share.
2735
2646
  **/
2736
- waitForAccountCreation() {
2737
- return __async(this, arguments, function* ({ popupWindow } = {}) {
2738
- yield this.touchSession();
2739
- if (!this.isExternalWalletAuth) {
2740
- this.externalWallets = {};
2741
- }
2742
- this.isAwaitingAccountCreation = true;
2743
- while (this.isAwaitingAccountCreation) {
2744
- try {
2745
- yield new Promise((resolve) => setTimeout(resolve, POLLING_INTERVAL_MS));
2746
- if (yield this.isSessionActive()) {
2747
- this.isAwaitingAccountCreation = false;
2748
- dispatchEvent(ParaEvent.ACCOUNT_CREATION_EVENT, true);
2749
- return true;
2750
- } else {
2751
- if (popupWindow == null ? void 0 : popupWindow.closed) {
2752
- this.isAwaitingAccountCreation = false;
2753
- return false;
2754
- }
2755
- }
2756
- } catch (err) {
2757
- console.error(err);
2758
- }
2759
- }
2760
- return false;
2761
- });
2762
- }
2763
- waitForPasskeyAndCreateWallet() {
2647
+ createWallet() {
2764
2648
  return __async(this, arguments, function* ({
2765
- popupWindow
2649
+ type: _type,
2650
+ skipDistribute = false
2766
2651
  } = {}) {
2767
- yield this.waitForAccountCreation({ popupWindow });
2768
- const pregenWallets = yield this.getPregenWallets();
2769
- let recoverySecret, walletIds = {};
2770
- if (pregenWallets.length > 0) {
2771
- recoverySecret = yield this.claimPregenWallets();
2772
- walletIds = this.supportedWalletTypes.reduce((acc, { type }) => {
2773
- var _a;
2774
- return __spreadProps(__spreadValues({}, acc), {
2775
- [type]: [(_a = pregenWallets.find((w) => !!WalletSchemeTypeMap[w.scheme][type])) == null ? void 0 : _a.id]
2776
- });
2777
- }, {});
2652
+ var _a, _b;
2653
+ this.requireApiKey();
2654
+ const { supportedWalletTypes } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
2655
+ const walletType = yield this.assertIsValidWalletType(
2656
+ _type != null ? _type : (_a = supportedWalletTypes.find(({ optional }) => !optional)) == null ? void 0 : _a.type
2657
+ );
2658
+ let signer;
2659
+ let wallet;
2660
+ let keygenRes;
2661
+ switch (walletType) {
2662
+ case import_user_management_client5.WalletType.SOLANA: {
2663
+ keygenRes = yield this.platformUtils.ed25519Keygen(
2664
+ this.ctx,
2665
+ this.userId,
2666
+ this.retrieveSessionCookie(),
2667
+ this.getBackupKitEmailProps()
2668
+ );
2669
+ break;
2670
+ }
2671
+ default: {
2672
+ keygenRes = yield this.platformUtils.keygen(
2673
+ this.ctx,
2674
+ this.userId,
2675
+ walletType,
2676
+ null,
2677
+ this.retrieveSessionCookie(),
2678
+ this.getBackupKitEmailProps()
2679
+ );
2680
+ break;
2681
+ }
2778
2682
  }
2779
- const created = yield this.createWalletPerType();
2780
- recoverySecret = recoverySecret != null ? recoverySecret : created.recoverySecret;
2781
- walletIds = __spreadValues(__spreadValues({}, walletIds), created.walletIds);
2782
- const resp = { walletIds, recoverySecret };
2783
- dispatchEvent(ParaEvent.ACCOUNT_SETUP_EVENT, resp);
2784
- return resp;
2683
+ const walletId = keygenRes.walletId;
2684
+ signer = keygenRes.signer;
2685
+ this.wallets[walletId] = {
2686
+ id: walletId,
2687
+ signer,
2688
+ scheme: walletType === import_user_management_client5.WalletType.SOLANA ? import_user_management_client5.WalletScheme.ED25519 : import_user_management_client5.WalletScheme.DKLS,
2689
+ type: walletType
2690
+ };
2691
+ wallet = this.wallets[walletId];
2692
+ yield this.waitForWalletAddress(wallet.id);
2693
+ yield this.populateWalletAddresses();
2694
+ let recoveryShare = null;
2695
+ if (!skipDistribute) {
2696
+ recoveryShare = yield distributeNewShare({
2697
+ ctx: this.ctx,
2698
+ userId: this.userId,
2699
+ walletId: wallet.id,
2700
+ userShare: signer,
2701
+ emailProps: this.getBackupKitEmailProps()
2702
+ });
2703
+ }
2704
+ yield this.setCurrentWalletIds(__spreadProps(__spreadValues({}, this.currentWalletIds), {
2705
+ [walletType]: [.../* @__PURE__ */ new Set([...(_b = this.currentWalletIds[walletType]) != null ? _b : [], walletId])]
2706
+ }));
2707
+ const walletNoSigner = __spreadValues({}, wallet);
2708
+ delete walletNoSigner.signer;
2709
+ dispatchEvent(ParaEvent.WALLET_CREATED, {
2710
+ wallet: walletNoSigner,
2711
+ recoverySecret: recoveryShare
2712
+ });
2713
+ return [wallet, recoveryShare];
2785
2714
  });
2786
2715
  }
2716
+ encodeWalletBase64(wallet) {
2717
+ const walletJson = JSON.stringify(wallet);
2718
+ const base64Wallet = Buffer.from(walletJson).toString("base64");
2719
+ return base64Wallet;
2720
+ }
2787
2721
  /**
2788
- * Initiates a Farcaster login attempt and return the URI for the user to connect.
2789
- * You can create a QR code with this URI that works with Farcaster's mobile app.
2790
- * @return {string} the Farcaster connect URI
2791
- */
2792
- getFarcasterConnectURL() {
2793
- return __async(this, null, function* () {
2794
- yield this.logout();
2795
- yield this.touchSession(true);
2796
- const {
2797
- data: { connect_uri }
2798
- } = yield this.ctx.client.initializeFarcasterLogin();
2799
- return connect_uri;
2800
- });
2722
+ * Encodes the current wallets encoded in Base 64.
2723
+ * @returns {string} the encoded wallet string
2724
+ **/
2725
+ getUserShare() {
2726
+ if (Object.values(this.wallets).length === 0) {
2727
+ return null;
2728
+ }
2729
+ return Object.values(this.wallets).map((wallet) => this.encodeWalletBase64(wallet)).join("-");
2801
2730
  }
2802
2731
  /**
2803
- * Awaits the response from a user's attempt to log in with Farcaster.
2804
- * If successful, this returns the user's Farcaster username and profile picture and indicates whether the user already exists.
2805
- * @return {Object} `{userExists: boolean; username: string; pfpUrl?: string | null }` - the user's information and whether the user already exists.
2806
- */
2807
- waitForFarcasterStatus() {
2732
+ * Sets the current wallets from a Base 64 string.
2733
+ * @param {string} base64Wallet the encoded wallet string
2734
+ **/
2735
+ setUserShare(base64Wallets) {
2808
2736
  return __async(this, null, function* () {
2809
- this.isAwaitingFarcaster = true;
2810
- while (this.isAwaitingFarcaster) {
2811
- try {
2812
- yield new Promise((resolve) => setTimeout(resolve, POLLING_INTERVAL_MS));
2813
- const res = yield this.ctx.client.getFarcasterAuthStatus();
2814
- if (res.data.state === "completed") {
2815
- const { userId, userExists, username, pfpUrl } = res.data;
2816
- yield this.setUserId(userId);
2817
- yield this.setFarcasterUsername(username);
2818
- return {
2819
- userExists,
2820
- username,
2821
- pfpUrl
2822
- };
2823
- }
2824
- } catch (err) {
2825
- console.error(err);
2826
- this.isAwaitingFarcaster = false;
2827
- }
2737
+ if (!base64Wallets) {
2738
+ return;
2739
+ }
2740
+ const base64WalletsSplit = base64Wallets.split("-");
2741
+ for (const base64Wallet of base64WalletsSplit) {
2742
+ const walletJson = Buffer.from(base64Wallet, "base64").toString();
2743
+ const wallet = migrateWallet(JSON.parse(walletJson));
2744
+ this.wallets[wallet.id] = wallet;
2745
+ yield this.setWallets(this.wallets);
2828
2746
  }
2829
2747
  });
2830
2748
  }
2831
- /**
2832
- * Generates a URL for the user to log in with OAuth using a desire method.
2833
- *
2834
- * @param {Object} opts the options object
2835
- * @param {OAuthMethod} opts.method the third-party service to use for OAuth.
2836
- * @param {string} [opts.deeplinkUrl] the deeplink to redirect to after the OAuth flow. This is for mobile only.
2837
- * @returns {string} the URL for the user to log in with OAuth.
2838
- */
2839
- getOAuthURL(_0) {
2840
- return __async(this, arguments, function* ({ method, deeplinkUrl }) {
2841
- yield this.logout();
2842
- const res = yield this.touchSession(true);
2843
- return constructUrl({
2844
- base: method === import_user_management_client5.OAuthMethod.TELEGRAM ? getPortalBaseURL(this.ctx, true) : getBaseOAuthUrl(this.ctx.env),
2845
- path: `/auth/${method.toLowerCase()}`,
2749
+ getTransactionReviewUrl(transactionId, timeoutMs) {
2750
+ return __async(this, null, function* () {
2751
+ return this.constructPortalUrl("txReview", {
2752
+ pathId: transactionId,
2846
2753
  params: {
2847
- apiKey: this.ctx.apiKey,
2848
- sessionLookupId: res.data.sessionLookupId,
2849
- deeplinkUrl
2754
+ email: this.email,
2755
+ timeoutMs: timeoutMs == null ? void 0 : timeoutMs.toString()
2850
2756
  }
2851
2757
  });
2852
2758
  });
2853
2759
  }
2854
- /**
2855
- * Awaits the response from a user's attempt to log in with OAuth.
2856
- * If successful, this returns the user's email address and indicates whether the user already exists.
2857
- *
2858
- * @param {Object} opts the options object.
2859
- * @param {Window} [opts.popupWindow] the popup window being used for login.
2860
- * @return {Object} `{ email?: string; isError?: boolean; userExists: boolean; }` the result data
2861
- */
2862
- waitForOAuth() {
2863
- return __async(this, arguments, function* ({ popupWindow } = {}) {
2864
- this.isAwaitingOAuth = true;
2865
- while (this.isAwaitingOAuth) {
2866
- try {
2867
- if (popupWindow == null ? void 0 : popupWindow.closed) {
2868
- return { isError: true, userExists: false };
2869
- }
2870
- yield new Promise((resolve) => setTimeout(resolve, POLLING_INTERVAL_MS));
2871
- if (this.isAwaitingOAuth) {
2872
- const res = yield this.touchSession();
2873
- if (res.data.userId) {
2874
- const { userId, email } = res.data;
2875
- if (!this.loginEncryptionKeyPair) {
2876
- yield this.setLoginEncryptionKeyPair();
2877
- }
2878
- yield this.setUserId(userId);
2879
- yield this.setEmail(email);
2880
- const userExists = yield this.checkIfUserExists({ email });
2881
- this.isAwaitingOAuth = false;
2882
- return {
2883
- userExists,
2884
- email
2885
- };
2886
- }
2887
- }
2888
- } catch (err) {
2889
- console.error(err);
2760
+ getOnRampTransactionUrl(_a) {
2761
+ return __async(this, null, function* () {
2762
+ var _b = _a, {
2763
+ purchaseId,
2764
+ providerKey
2765
+ } = _b, walletParams = __objRest(_b, [
2766
+ "purchaseId",
2767
+ "providerKey"
2768
+ ]);
2769
+ const { sessionId } = yield this.touchSession();
2770
+ const [key, identifier] = (0, import_user_management_client5.extractWalletRef)(walletParams);
2771
+ return this.constructPortalUrl("onRamp", {
2772
+ pathId: purchaseId,
2773
+ sessionId,
2774
+ params: {
2775
+ [key]: identifier,
2776
+ providerKey,
2777
+ currentWalletIds: JSON.stringify(this.currentWalletIds)
2890
2778
  }
2891
- }
2892
- return { userExists: false };
2779
+ });
2893
2780
  });
2894
2781
  }
2895
2782
  /**
2896
- * Waits for the session to be active and sets up the user.
2783
+ * Signs a message using one of the current wallets.
2897
2784
  *
2898
- * @param {Object} opts the options object
2899
- * @param {Window} [opts.popupWindow] the popup window being used for login.
2900
- * @param {boolean} [opts.skipSessionRefresh] whether to skip refreshing the session.
2901
- * @returns {Object} `{ isComplete: boolean; isError: boolean; needsWallet: boolean; partnerId: string; }` the result data
2785
+ * If you want to sign the keccak256 hash of a message, hash the
2786
+ * message first and then pass in the base64 encoded hash.
2787
+ * @param {Object} opts the options object.
2788
+ * @param {string} opts.walletId the id of the wallet to sign with.
2789
+ * @param {string} opts.messageBase64 the base64 encoding of exact message that should be signed
2790
+ * @param {number} [opts.timeout] optional timeout in milliseconds. If not present, defaults to 30 seconds.
2791
+ * @param {string} [opts.cosmosSignDocBase64] the Cosmos `SignDoc` in base64, if applicable
2902
2792
  **/
2903
- waitForLoginAndSetup() {
2793
+ signMessage(_0) {
2904
2794
  return __async(this, arguments, function* ({
2905
- popupWindow,
2906
- skipSessionRefresh = false
2907
- } = {}) {
2908
- var _a;
2909
- if (!this.isExternalWalletAuth) {
2910
- this.externalWallets = {};
2795
+ walletId,
2796
+ messageBase64,
2797
+ timeoutMs = 3e4,
2798
+ cosmosSignDocBase64,
2799
+ isCanceled = () => false,
2800
+ onCancel,
2801
+ onPoll
2802
+ }) {
2803
+ this.assertIsValidWalletId(walletId);
2804
+ const wallet = this.wallets[walletId];
2805
+ let signerId = this.userId;
2806
+ if (wallet.partnerId && !wallet.userId) {
2807
+ signerId = wallet.partnerId;
2911
2808
  }
2912
- this.isAwaitingLogin = true;
2913
- while (this.isAwaitingLogin) {
2914
- try {
2915
- yield new Promise((resolve) => setTimeout(resolve, POLLING_INTERVAL_MS));
2916
- if (!(yield this.isSessionActive())) {
2917
- if (popupWindow == null ? void 0 : popupWindow.closed) {
2918
- const resp2 = { isComplete: false, isError: true };
2919
- dispatchEvent(ParaEvent.LOGIN_EVENT, resp2, "failed to setup user");
2920
- return resp2;
2921
- }
2922
- continue;
2923
- }
2924
- const postLoginData = yield this.userSetupAfterLogin();
2925
- const needsWallet = (_a = postLoginData.data.needsWallet) != null ? _a : false;
2926
- if (!needsWallet) {
2927
- if (this.currentWalletIdsArray.length === 0) {
2928
- if (popupWindow == null ? void 0 : popupWindow.closed) {
2929
- const resp2 = { isComplete: false, isError: true };
2930
- dispatchEvent(ParaEvent.LOGIN_EVENT, resp2, "failed to setup user");
2931
- return resp2;
2932
- } else {
2933
- continue;
2934
- }
2935
- }
2936
- }
2937
- const fetchedWallets = yield this.fetchWallets();
2938
- const tempSharesRes = yield this.getTransmissionKeyShares();
2939
- if (tempSharesRes.data.temporaryShares.length === fetchedWallets.length) {
2940
- yield this.setupAfterLogin({ temporaryShares: tempSharesRes.data.temporaryShares, skipSessionRefresh });
2941
- yield this.claimPregenWallets();
2942
- const resp2 = {
2943
- isComplete: true,
2944
- needsWallet: needsWallet || Object.values(this.wallets).length === 0,
2945
- partnerId: postLoginData.data.partnerId
2946
- };
2947
- dispatchEvent(ParaEvent.LOGIN_EVENT, resp2);
2948
- return resp2;
2949
- }
2809
+ let signRes = yield this.signMessageInner({ wallet, signerId, messageBase64, cosmosSignDocBase64 });
2810
+ let timeStart = Date.now();
2811
+ if (signRes.pendingTransactionId) {
2812
+ this.platformUtils.openPopup(
2813
+ yield this.getTransactionReviewUrl(signRes.pendingTransactionId, timeoutMs),
2814
+ { type: cosmosSignDocBase64 ? "SIGN_TRANSACTION_REVIEW" /* SIGN_TRANSACTION_REVIEW */ : "SIGN_MESSAGE_REVIEW" /* SIGN_MESSAGE_REVIEW */ }
2815
+ );
2816
+ } else {
2817
+ dispatchEvent(ParaEvent.SIGN_MESSAGE_EVENT, signRes);
2818
+ return signRes;
2819
+ }
2820
+ while (true) {
2821
+ if (isCanceled() || Date.now() - timeStart > timeoutMs) {
2822
+ onCancel == null ? void 0 : onCancel();
2823
+ break;
2824
+ }
2825
+ yield new Promise((resolve) => setTimeout(resolve, POLLING_INTERVAL_MS));
2826
+ try {
2827
+ yield this.ctx.client.getPendingTransaction(this.userId, signRes.pendingTransactionId);
2950
2828
  } catch (err) {
2951
- console.error(err);
2829
+ const error = new TransactionReviewDenied();
2830
+ dispatchEvent(ParaEvent.SIGN_MESSAGE_EVENT, signRes, error.message);
2831
+ throw error;
2832
+ }
2833
+ signRes = yield this.signMessageInner({ wallet, signerId, messageBase64, cosmosSignDocBase64 });
2834
+ if (signRes.pendingTransactionId) {
2835
+ onPoll == null ? void 0 : onPoll();
2836
+ continue;
2837
+ } else {
2838
+ break;
2952
2839
  }
2953
2840
  }
2954
- const resp = { isComplete: false };
2955
- dispatchEvent(ParaEvent.LOGIN_EVENT, resp, "exitted login without setting up user");
2956
- return resp;
2957
- });
2958
- }
2959
- /**
2960
- * Updates the session with the user management server, possibly
2961
- * opening a popup to refresh the session.
2962
- *
2963
- * @param {Object} opts the options object.
2964
- * @param {boolean} [shouldOpenPopup] - if `true`, the running device will open a popup to reauthenticate the user.
2965
- * @returns a URL for the user to reauthenticate.
2966
- **/
2967
- refreshSession() {
2968
- return __async(this, arguments, function* ({ shouldOpenPopup = false } = {}) {
2969
- const res = yield this.touchSession(true);
2970
- if (!this.loginEncryptionKeyPair) {
2971
- yield this.setLoginEncryptionKeyPair();
2972
- }
2973
- const link = yield this.getWebAuthURLForLogin({
2974
- sessionId: res.data.sessionId,
2975
- loginEncryptionPublicKey: getPublicKeyHex(this.loginEncryptionKeyPair)
2976
- });
2977
- if (shouldOpenPopup) {
2978
- this.platformUtils.openPopup(link);
2841
+ if (signRes.pendingTransactionId) {
2842
+ const error = new TransactionReviewTimeout(
2843
+ yield this.getTransactionReviewUrl(signRes.pendingTransactionId),
2844
+ signRes.pendingTransactionId
2845
+ );
2846
+ dispatchEvent(ParaEvent.SIGN_MESSAGE_EVENT, signRes, error.message);
2847
+ throw error;
2979
2848
  }
2980
- return link;
2981
- });
2982
- }
2983
- /**
2984
- * Call this method after login to ensure that the user ID is set
2985
- * internally.
2986
- **/
2987
- userSetupAfterLogin() {
2988
- return __async(this, null, function* () {
2989
- const res = yield this.touchSession();
2990
- yield this.setUserId(res.data.userId);
2991
- if (res.data.currentWalletIds && res.data.currentWalletIds !== this.currentWalletIds)
2992
- yield this.setCurrentWalletIds(res.data.currentWalletIds, {
2993
- sessionLookupId: this.isPortal() ? res.data.sessionLookupId : void 0
2994
- });
2995
- return res;
2996
- });
2997
- }
2998
- /**
2999
- * Get transmission shares associated with session.
3000
- * @param {Object} opts the options object.
3001
- * @param {boolean} opts.isForNewDevice - true if this device is registering.
3002
- * @returns - transmission keyshares.
3003
- **/
3004
- getTransmissionKeyShares() {
3005
- return __async(this, arguments, function* ({ isForNewDevice = false } = {}) {
3006
- const res = yield this.touchSession();
3007
- const sessionLookupId = isForNewDevice ? `${res.data.sessionLookupId}-new-device` : res.data.sessionLookupId;
3008
- return this.ctx.client.getTransmissionKeyshares(this.userId, sessionLookupId);
2849
+ dispatchEvent(ParaEvent.SIGN_MESSAGE_EVENT, signRes);
2850
+ return signRes;
3009
2851
  });
3010
2852
  }
3011
- /**
3012
- * Call this method after login to perform setup.
3013
- * @param {Object} opts the options object.
3014
- * @param {any[]} opts.temporaryShares optional temporary shares to use for decryption.
3015
- * @param {boolean} [opts.skipSessionRefresh] - whether or not to skip refreshing the session.
3016
- **/
3017
- setupAfterLogin() {
2853
+ signMessageInner(_0) {
3018
2854
  return __async(this, arguments, function* ({
3019
- temporaryShares,
3020
- skipSessionRefresh = false
3021
- } = {}) {
3022
- if (!temporaryShares) {
3023
- temporaryShares = (yield this.getTransmissionKeyShares()).data.temporaryShares;
2855
+ wallet,
2856
+ signerId,
2857
+ messageBase64,
2858
+ cosmosSignDocBase64
2859
+ }) {
2860
+ let signRes;
2861
+ switch (wallet.scheme) {
2862
+ case import_user_management_client5.WalletScheme.ED25519:
2863
+ signRes = yield this.platformUtils.ed25519Sign(
2864
+ this.ctx,
2865
+ signerId,
2866
+ wallet.id,
2867
+ wallet.signer,
2868
+ messageBase64,
2869
+ this.retrieveSessionCookie()
2870
+ );
2871
+ break;
2872
+ default:
2873
+ signRes = yield this.platformUtils.signMessage(
2874
+ this.ctx,
2875
+ signerId,
2876
+ wallet.id,
2877
+ wallet.signer,
2878
+ messageBase64,
2879
+ this.retrieveSessionCookie(),
2880
+ wallet.scheme === import_user_management_client5.WalletScheme.DKLS,
2881
+ cosmosSignDocBase64
2882
+ );
2883
+ break;
3024
2884
  }
3025
- temporaryShares.forEach((share) => {
3026
- const signer = decryptWithPrivateKey(this.loginEncryptionKeyPair.privateKey, share.encryptedShare, share.encryptedKey);
3027
- this.wallets[share.walletId] = {
3028
- id: share.walletId,
3029
- signer
3030
- };
3031
- });
3032
- yield this.deleteLoginEncryptionKeyPair();
3033
- yield this.populateWalletAddresses();
3034
- yield this.touchSession(!skipSessionRefresh);
2885
+ return signRes;
3035
2886
  });
3036
2887
  }
3037
2888
  /**
3038
- * Distributes a new wallet recovery share.
2889
+ * Signs a transaction.
3039
2890
  * @param {Object} opts the options object.
3040
- * @param {string} opts.walletId the wallet to distribute the recovery share for.
3041
- * @param {string} opts.userShare optional user share generate the recovery share from. Defaults to the signer from the passed in walletId
3042
- * @param {boolean} opts.skipBiometricShareCreation whether or not to skip biometric share creation. Used when regenerating recovery shares.
3043
- * @param {boolean} opts.forceRefreshRecovery whether or not to force recovery secret regeneration. Used when regenerating recovery shares.
3044
- * @returns {string} the recovery share.
2891
+ * @param {string} opts.walletId the id of the wallet to sign with.
2892
+ * @param {string} opts.rlpEncodedTxBase64 the transaction to sign, in RLP base64 encoding
2893
+ * @param {string} [opts.chainId] the EVM chain id of the chain the transaction is being sent on, if applicable
2894
+ * @param {number} [opts.timeoutMs] the amount of time to wait for the user to sign the transaction, in milliseconds
3045
2895
  **/
3046
- distributeNewWalletShare(_0) {
2896
+ signTransaction(_0) {
3047
2897
  return __async(this, arguments, function* ({
3048
2898
  walletId,
3049
- userShare,
3050
- skipBiometricShareCreation = false,
3051
- forceRefresh = false
2899
+ rlpEncodedTxBase64,
2900
+ chainId,
2901
+ timeoutMs = 3e4,
2902
+ isCanceled = () => false,
2903
+ onCancel,
2904
+ onPoll
3052
2905
  }) {
3053
- let userSigner = userShare;
3054
- if (!userSigner) {
3055
- userSigner = this.wallets[walletId].signer;
2906
+ this.assertIsValidWalletId(walletId);
2907
+ const wallet = this.wallets[walletId];
2908
+ let signerId = this.userId;
2909
+ if (wallet.partnerId && !wallet.userId) {
2910
+ signerId = wallet.partnerId;
3056
2911
  }
3057
- const recoveryShare = skipBiometricShareCreation ? yield sendRecoveryForShare({
3058
- ctx: this.ctx,
3059
- userId: this.userId,
3060
- walletId,
3061
- userSigner,
3062
- emailProps: this.getBackupKitEmailProps(),
3063
- forceRefresh
3064
- }) : yield distributeNewShare({
3065
- ctx: this.ctx,
3066
- userId: this.userId,
2912
+ let signRes = yield this.platformUtils.signTransaction(
2913
+ this.ctx,
2914
+ signerId,
3067
2915
  walletId,
3068
- userShare: userSigner,
3069
- emailProps: this.getBackupKitEmailProps()
3070
- });
3071
- return recoveryShare;
3072
- });
3073
- }
3074
- waitForWalletAddress(walletId) {
3075
- return __async(this, null, function* () {
3076
- let maxPolls = 0;
2916
+ this.wallets[walletId].signer,
2917
+ rlpEncodedTxBase64,
2918
+ chainId,
2919
+ this.retrieveSessionCookie(),
2920
+ wallet.scheme === import_user_management_client5.WalletScheme.DKLS
2921
+ );
2922
+ let timeStart = Date.now();
2923
+ if (signRes.pendingTransactionId) {
2924
+ this.platformUtils.openPopup(
2925
+ yield this.getTransactionReviewUrl(signRes.pendingTransactionId, timeoutMs),
2926
+ { type: "SIGN_TRANSACTION_REVIEW" /* SIGN_TRANSACTION_REVIEW */ }
2927
+ );
2928
+ } else {
2929
+ dispatchEvent(ParaEvent.SIGN_TRANSACTION_EVENT, signRes);
2930
+ return signRes;
2931
+ }
3077
2932
  while (true) {
2933
+ if (isCanceled() || Date.now() - timeStart > timeoutMs) {
2934
+ onCancel == null ? void 0 : onCancel();
2935
+ break;
2936
+ }
2937
+ yield new Promise((resolve) => setTimeout(resolve, POLLING_INTERVAL_MS));
3078
2938
  try {
3079
- if (maxPolls === 10) {
3080
- break;
3081
- }
3082
- ++maxPolls;
3083
- const res = yield this.ctx.client.getWallets(this.userId);
3084
- const wallet = res.data.wallets.find((w) => w.id === walletId);
3085
- if (wallet && wallet.address) {
3086
- return;
3087
- }
3088
- yield new Promise((resolve) => setTimeout(resolve, SHORT_POLLING_INTERVAL_MS));
2939
+ yield this.ctx.client.getPendingTransaction(this.userId, signRes.pendingTransactionId);
3089
2940
  } catch (err) {
3090
- console.error(err);
2941
+ const error = new TransactionReviewDenied();
2942
+ dispatchEvent(ParaEvent.SIGN_TRANSACTION_EVENT, signRes, error.message);
2943
+ throw error;
2944
+ }
2945
+ signRes = yield this.platformUtils.signTransaction(
2946
+ this.ctx,
2947
+ signerId,
2948
+ walletId,
2949
+ this.wallets[walletId].signer,
2950
+ rlpEncodedTxBase64,
2951
+ chainId,
2952
+ this.retrieveSessionCookie(),
2953
+ wallet.scheme === import_user_management_client5.WalletScheme.DKLS
2954
+ );
2955
+ if (signRes.pendingTransactionId) {
2956
+ onPoll == null ? void 0 : onPoll();
2957
+ continue;
2958
+ } else {
2959
+ break;
3091
2960
  }
3092
2961
  }
3093
- throw new Error("timed out waiting for wallet address");
2962
+ if (signRes.pendingTransactionId) {
2963
+ const error = new TransactionReviewTimeout(
2964
+ yield this.getTransactionReviewUrl(signRes.pendingTransactionId),
2965
+ signRes.pendingTransactionId
2966
+ );
2967
+ dispatchEvent(ParaEvent.SIGN_TRANSACTION_EVENT, signRes, error.message);
2968
+ throw error;
2969
+ }
2970
+ dispatchEvent(ParaEvent.SIGN_TRANSACTION_EVENT, signRes);
2971
+ return signRes;
3094
2972
  });
3095
2973
  }
2974
+ isProviderModalDisabled() {
2975
+ return !!this.disableProviderModal;
2976
+ }
3096
2977
  /**
3097
- * Waits for a pregen wallet address to be created.
3098
- *
3099
- * @param pregenIdentifier - the identifier of the user the pregen wallet is associated with.
3100
- * @param walletId - the wallet id
3101
- * @param pregenIdentifierType - the identifier type of the user the pregen wallet is associated with.
3102
- * @returns - recovery share.
2978
+ * Starts a on-ramp or off-ramp transaction and returns the Para Portal link for the user to finalize and complete it.
2979
+ * @param {Object} opts the options object
2980
+ * @param {OnRampPurchaseCreateParams} opts.params the transaction settings.
2981
+ * @param {boolean} opts.shouldOpenPopup if `true`, a popup window with the link will be opened.
2982
+ * @param {string} opts.walletId the wallet ID to use for the transaction, where funds will be sent or withdrawn.
2983
+ * @param {string} opts.externalWalletAddress the external wallet address to send funds to or withdraw funds from, if using an external wallet.
3103
2984
  **/
3104
- waitForPregenWalletAddress(walletId) {
2985
+ initiateOnRampTransaction(options) {
3105
2986
  return __async(this, null, function* () {
3106
- let maxPolls = 0;
3107
- while (true) {
3108
- try {
3109
- if (maxPolls === 10) {
3110
- break;
3111
- }
3112
- ++maxPolls;
3113
- const res = yield this.getPregenWallets();
3114
- const wallet = res.find((w) => w.id === walletId);
3115
- if (wallet && wallet.address) {
3116
- return;
3117
- }
3118
- yield new Promise((resolve) => setTimeout(resolve, SHORT_POLLING_INTERVAL_MS));
3119
- } catch (err) {
3120
- console.error(err);
3121
- }
2987
+ var _b;
2988
+ const _a = options, { params, shouldOpenPopup } = _a, walletParams = __objRest(_a, ["params", "shouldOpenPopup"]);
2989
+ const onRampPurchase = yield this.ctx.client.createOnRampPurchase(__spreadValues({
2990
+ userId: this.userId,
2991
+ params: __spreadProps(__spreadValues({}, params), {
2992
+ address: (_b = walletParams.externalWalletAddress) != null ? _b : this.getDisplayAddress(walletParams.walletId, { addressType: params.walletType })
2993
+ })
2994
+ }, walletParams));
2995
+ const portalUrl = yield this.getOnRampTransactionUrl(__spreadValues({
2996
+ purchaseId: onRampPurchase.id,
2997
+ providerKey: onRampPurchase.providerKey
2998
+ }, walletParams));
2999
+ if (shouldOpenPopup) {
3000
+ this.platformUtils.openPopup(portalUrl, { type: "ON_RAMP_TRANSACTION" /* ON_RAMP_TRANSACTION */ });
3122
3001
  }
3123
- throw new Error("timed out waiting for wallet address");
3002
+ return { onRampPurchase, portalUrl };
3124
3003
  });
3125
3004
  }
3126
3005
  /**
3127
- * Creates several new wallets with the desired types. If no types are provided, this method
3128
- * will create one for each of the non-optional types specified in the instance's `supportedWalletTypes`
3129
- * object that are not already present. This is automatically called upon account creation to ensure that
3130
- * the user has a wallet of each required type.
3131
- *
3132
- * @param {Object} [opts] the options object.
3133
- * @param {boolean} [opts.skipDistribute] if `true`, the wallets' recovery share will not be distributed.
3134
- * @param {WalletType[]} [opts.types] the types of wallets to create.
3135
- * @returns {Object} the wallets created, their ids, and the recovery secret.
3006
+ * Returns `true` if session was successfully kept alive, `false` otherwise.
3136
3007
  **/
3137
- createWalletPerType() {
3138
- return __async(this, arguments, function* ({
3139
- skipDistribute = false,
3140
- types
3141
- } = {}) {
3142
- const wallets = [];
3143
- const walletIds = {};
3144
- let recoverySecret;
3145
- for (const type of yield this.getTypesToCreate(types)) {
3146
- const [wallet, recoveryShare] = yield this.createWallet({ type, skipDistribute });
3147
- wallets.push(wallet);
3148
- getEquivalentTypes(type).filter((t) => !!this.isWalletTypeEnabled[t]).forEach((t) => {
3149
- walletIds[t] = [wallet.id];
3150
- });
3151
- if (recoveryShare) {
3152
- recoverySecret = recoveryShare;
3153
- }
3008
+ keepSessionAlive() {
3009
+ return __async(this, null, function* () {
3010
+ try {
3011
+ yield this.ctx.client.keepSessionAlive(this.userId);
3012
+ return true;
3013
+ } catch (err) {
3014
+ return false;
3154
3015
  }
3155
- return { wallets, walletIds, recoverySecret };
3156
3016
  });
3157
3017
  }
3158
3018
  /**
3159
- * Refresh the current user share for a wallet.
3160
- *
3161
- * @param {Object} opts the options object.
3162
- * @param {string} opts.walletId the wallet id to refresh.
3163
- * @param {string} opts.share the current user share.
3164
- * @param {string} [opts.oldPartnerId] the current partner id.
3165
- * @param {string} [opts.newPartnerId] the new partner id to set, if any.
3166
- * @param {string} [opts.keyShareProtocolId]
3167
- * @param {boolean} [opts.redistributeBackupEncryptedShares] whether or not to redistribute backup encrypted shares.
3168
- * @returns {Object} the new user share and recovery secret.
3169
- **/
3170
- refreshShare(_0) {
3171
- return __async(this, arguments, function* ({
3172
- walletId,
3173
- share,
3174
- oldPartnerId,
3175
- newPartnerId,
3176
- keyShareProtocolId,
3177
- redistributeBackupEncryptedShares
3178
- }) {
3179
- const { signer, protocolId } = yield this.platformUtils.refresh(
3180
- this.ctx,
3181
- this.retrieveSessionCookie(),
3182
- this.userId,
3183
- walletId,
3184
- share,
3185
- oldPartnerId,
3186
- newPartnerId,
3187
- keyShareProtocolId
3188
- );
3189
- const recoverySecret = yield distributeNewShare({
3190
- ctx: this.ctx,
3191
- userId: this.userId,
3192
- walletId,
3193
- userShare: signer,
3194
- ignoreRedistributingBackupEncryptedShare: !redistributeBackupEncryptedShares,
3195
- emailProps: this.getBackupKitEmailProps(),
3196
- partnerId: newPartnerId,
3197
- protocolId
3198
- });
3199
- return { signer, recoverySecret, protocolId };
3200
- });
3019
+ * Serialize the current session for import by another Para instance.
3020
+ * @returns {string} the serialized session
3021
+ */
3022
+ exportSession() {
3023
+ const sessionInfo = {
3024
+ authInfo: __privateGet(this, _authInfo),
3025
+ userId: this.userId,
3026
+ wallets: this.wallets,
3027
+ currentWalletIds: this.currentWalletIds,
3028
+ sessionCookie: this.retrieveSessionCookie(),
3029
+ externalWallets: this.externalWallets
3030
+ };
3031
+ return Buffer.from(JSON.stringify(sessionInfo)).toString("base64");
3201
3032
  }
3202
3033
  /**
3203
- * Creates a new wallet.
3204
- * @param {Object} opts the options object.
3205
- * @param {WalletType} opts.type the type of wallet to create.
3206
- * @param {boolean} opts.skipDistribute - if true, recovery share will not be distributed.
3207
- * @returns {[Wallet, string | null]} `[wallet, recoveryShare]` - the wallet object and the new recovery share.
3208
- **/
3209
- createWallet() {
3210
- return __async(this, arguments, function* ({
3211
- type: _type,
3212
- skipDistribute = false
3213
- } = {}) {
3034
+ * Imports a session serialized by another Para instance.
3035
+ * @param {string} serializedInstanceBase64 the serialized session
3036
+ */
3037
+ importSession(serializedInstanceBase64) {
3038
+ return __async(this, null, function* () {
3214
3039
  var _a, _b;
3215
- this.requireApiKey();
3216
- const walletType = yield this.assertIsValidWalletType(
3217
- _type != null ? _type : (_a = this.supportedWalletTypes.find(({ optional }) => !optional)) == null ? void 0 : _a.type
3218
- );
3219
- let signer;
3220
- let wallet;
3221
- let keygenRes;
3222
- switch (walletType) {
3223
- case import_user_management_client5.WalletType.SOLANA: {
3224
- keygenRes = yield this.platformUtils.ed25519Keygen(
3225
- this.ctx,
3226
- this.userId,
3227
- this.retrieveSessionCookie(),
3228
- this.getBackupKitEmailProps()
3229
- );
3230
- break;
3231
- }
3232
- default: {
3233
- keygenRes = yield this.platformUtils.keygen(
3234
- this.ctx,
3235
- this.userId,
3236
- walletType,
3237
- null,
3238
- this.retrieveSessionCookie(),
3239
- this.getBackupKitEmailProps()
3240
- );
3241
- break;
3040
+ const serializedInstance = Buffer.from(serializedInstanceBase64, "base64").toString("utf8");
3041
+ const sessionInfo = jsonParse(serializedInstance);
3042
+ const authInfo = (_a = sessionInfo.authInfo) != null ? _a : __privateMethod(this, _ParaCore_instances, toAuthInfo_fn).call(this, sessionInfo);
3043
+ yield __privateMethod(this, _ParaCore_instances, setAuthInfo_fn).call(this, authInfo);
3044
+ yield this.setUserId(sessionInfo.userId);
3045
+ yield this.setWallets(sessionInfo.wallets);
3046
+ yield this.setExternalWallets(sessionInfo.externalWallets || {});
3047
+ for (const walletId of Object.keys(this.wallets)) {
3048
+ if (!this.wallets[walletId].userId) {
3049
+ this.wallets[walletId].userId = this.userId;
3242
3050
  }
3243
3051
  }
3244
- const walletId = keygenRes.walletId;
3245
- signer = keygenRes.signer;
3246
- this.wallets[walletId] = {
3247
- id: walletId,
3248
- signer,
3249
- scheme: walletType === import_user_management_client5.WalletType.SOLANA ? import_user_management_client5.WalletScheme.ED25519 : import_user_management_client5.WalletScheme.DKLS,
3250
- type: walletType
3251
- };
3252
- wallet = this.wallets[walletId];
3253
- yield this.waitForWalletAddress(wallet.id);
3254
- yield this.populateWalletAddresses();
3255
- let recoveryShare = null;
3256
- if (!skipDistribute) {
3257
- recoveryShare = yield distributeNewShare({
3258
- ctx: this.ctx,
3259
- userId: this.userId,
3260
- walletId: wallet.id,
3261
- userShare: signer,
3262
- emailProps: this.getBackupKitEmailProps()
3263
- });
3052
+ if (Object.keys(sessionInfo.currentWalletIds).length !== 0) {
3053
+ yield this.setCurrentWalletIds(sessionInfo.currentWalletIds);
3054
+ } else {
3055
+ const currentWalletIds = {};
3056
+ for (const walletId of Object.keys(sessionInfo.wallets)) {
3057
+ currentWalletIds[sessionInfo.wallets[walletId].type] = [
3058
+ ...(_b = currentWalletIds[sessionInfo.wallets[walletId].type]) != null ? _b : [],
3059
+ walletId
3060
+ ];
3061
+ }
3062
+ yield this.setCurrentWalletIds(currentWalletIds);
3264
3063
  }
3265
- yield this.setCurrentWalletIds(__spreadProps(__spreadValues({}, this.currentWalletIds), {
3266
- [walletType]: [...(_b = this.currentWalletIds[walletType]) != null ? _b : [], walletId]
3267
- }));
3268
- const walletNoSigner = __spreadValues({}, wallet);
3269
- delete walletNoSigner.signer;
3270
- dispatchEvent(ParaEvent.WALLET_CREATED, {
3271
- wallet: walletNoSigner,
3272
- recoverySecret: recoveryShare
3273
- });
3274
- return [wallet, recoveryShare];
3064
+ this.persistSessionCookie(sessionInfo.sessionCookie);
3275
3065
  });
3276
3066
  }
3277
3067
  /**
3278
- * Creates a new pregenerated wallet.
3279
- *
3280
- * @param {Object} opts the options object.
3281
- * @param {string} opts.pregenIdentifier the identifier associated with the new wallet.
3282
- * @param {TPregenIdentifierType} [opts.pregenIdentifierType] the identifier type. Defaults to `EMAIL`.
3283
- * @param {WalletType} [opts.type] the type of wallet to create. Defaults to the first non-optional type in the instance's `supportedWalletTypes` array.
3284
- * @returns {Wallet} the created wallet.
3285
- **/
3286
- createPregenWallet(opts) {
3287
- return __async(this, null, function* () {
3288
- var _a, _b;
3289
- const {
3290
- type: _type = (_a = this.supportedWalletTypes.find(({ optional }) => !optional)) == null ? void 0 : _a.type,
3291
- pregenIdentifier,
3292
- pregenIdentifierType = "EMAIL"
3293
- } = opts;
3294
- this.requireApiKey();
3295
- const walletType = yield this.assertIsValidWalletType(
3296
- _type != null ? _type : (_b = this.supportedWalletTypes.find(({ optional }) => !optional)) == null ? void 0 : _b.type
3297
- );
3298
- let keygenRes;
3299
- switch (walletType) {
3300
- case import_user_management_client5.WalletType.SOLANA:
3301
- keygenRes = yield this.platformUtils.ed25519PreKeygen(
3302
- this.ctx,
3303
- pregenIdentifier,
3304
- pregenIdentifierType,
3305
- this.retrieveSessionCookie()
3306
- );
3307
- break;
3308
- default:
3309
- keygenRes = yield this.platformUtils.preKeygen(
3310
- this.ctx,
3311
- void 0,
3312
- pregenIdentifier,
3313
- pregenIdentifierType,
3314
- walletType,
3315
- null,
3316
- this.retrieveSessionCookie()
3317
- );
3318
- break;
3319
- }
3320
- const { signer, walletId } = keygenRes;
3321
- this.wallets[walletId] = {
3322
- id: walletId,
3323
- signer,
3324
- scheme: walletType === import_user_management_client5.WalletType.SOLANA ? import_user_management_client5.WalletScheme.ED25519 : import_user_management_client5.WalletScheme.DKLS,
3325
- type: walletType,
3326
- isPregen: true,
3327
- pregenIdentifier,
3328
- pregenIdentifierType
3329
- };
3330
- yield this.waitForPregenWalletAddress(walletId);
3331
- yield this.populatePregenWalletAddresses();
3332
- return this.wallets[walletId];
3333
- });
3334
- }
3068
+ * @deprecated
3069
+ */
3070
+ // protected exitAccountCreation() {
3071
+ // this.isAwaitingAccountCreation = false;
3072
+ // }
3335
3073
  /**
3336
- * Creates new pregenerated wallets for each desired type.
3337
- * If no types are provided, this method will create one for each of the non-optional types
3338
- * specified in the instance's `supportedWalletTypes` array that are not already present.
3339
- * @param {Object} opts the options object.
3340
- * @param {string} opts.pregenIdentifier the identifier to associate each wallet with.
3341
- * @param {TPregenIdentifierType} opts.pregenIdentifierType - either `'EMAIL'` or `'PHONE'`.
3342
- * @param {WalletType[]} [opts.types] the wallet types to create. Defaults to any types the instance supports that are not already present.
3343
- * @returns {Wallet[]} an array containing the created wallets.
3344
- **/
3345
- createPregenWalletPerType(_0) {
3346
- return __async(this, arguments, function* ({
3347
- types,
3348
- pregenIdentifier,
3349
- pregenIdentifierType = "EMAIL"
3350
- }) {
3351
- const wallets = [];
3352
- for (const type of yield this.getTypesToCreate(types)) {
3353
- const wallet = yield this.createPregenWallet({ type, pregenIdentifier, pregenIdentifierType });
3354
- wallets.push(wallet);
3355
- }
3356
- return wallets;
3357
- });
3358
- }
3074
+ * @deprecated
3075
+ */
3076
+ // protected exitLogin() {
3077
+ // this.isAwaitingLogin = false;
3078
+ // }
3359
3079
  /**
3360
- * Claims a pregenerated wallet.
3361
- *
3362
- * @param {Object} opts the options object.
3363
- * @param {string} opts.pregenIdentifier string the identifier of the user claiming the wallet
3364
- * @param {TPregenIdentifierType} opts.pregenIdentifierType type of the identifier of the user claiming the wallet
3365
- * @returns {[Wallet, string | null]} `[wallet, recoveryShare]` - the wallet object and the new recovery share.
3366
- **/
3367
- claimPregenWallets() {
3368
- return __async(this, arguments, function* ({
3369
- pregenIdentifier,
3370
- pregenIdentifierType = !!pregenIdentifier ? "EMAIL" : void 0
3371
- } = {}) {
3372
- var _a;
3373
- this.requireApiKey();
3374
- const pregenWallets = pregenIdentifier && pregenIdentifierType ? yield this.getPregenWallets({ pregenIdentifier, pregenIdentifierType }) : yield this.getPregenWallets();
3375
- if (pregenWallets.length === 0) {
3376
- return void 0;
3377
- }
3378
- const missingWallets = pregenWallets.filter((wallet) => !this.wallets[wallet.id]);
3379
- if (missingWallets.length > 0) {
3380
- throw new Error(
3381
- `Cannot claim pregen wallets because wallet data is missing. Please call setUserShare first to load the wallet data for the following wallet IDs: ${missingWallets.map((w) => w.id).join(", ")}`
3382
- );
3383
- }
3384
- let newRecoverySecret;
3385
- const { walletIds } = yield this.ctx.client.claimPregenWallets({
3386
- userId: this.userId,
3387
- walletIds: pregenWallets.map((w) => w.id)
3388
- });
3389
- for (const walletId of walletIds) {
3390
- const wallet = this.wallets[walletId];
3391
- let refreshedShare;
3392
- if (wallet.scheme === import_user_management_client5.WalletScheme.ED25519) {
3393
- const distributeRes = yield distributeNewShare({
3394
- ctx: this.ctx,
3395
- userId: this.userId,
3396
- walletId: wallet.id,
3397
- userShare: this.wallets[wallet.id].signer,
3398
- emailProps: this.getBackupKitEmailProps(),
3399
- partnerId: wallet.partnerId
3400
- });
3401
- if (distributeRes.length > 0) {
3402
- newRecoverySecret = distributeRes;
3403
- }
3404
- } else {
3405
- refreshedShare = yield this.refreshShare({
3406
- walletId: wallet.id,
3407
- share: this.wallets[wallet.id].signer,
3408
- oldPartnerId: wallet.partnerId,
3409
- newPartnerId: wallet.partnerId,
3410
- redistributeBackupEncryptedShares: true
3411
- });
3412
- if (refreshedShare.recoverySecret) {
3413
- newRecoverySecret = refreshedShare.recoverySecret;
3414
- }
3415
- }
3416
- this.wallets[wallet.id] = __spreadProps(__spreadValues({}, this.wallets[wallet.id]), {
3417
- signer: (_a = refreshedShare == null ? void 0 : refreshedShare.signer) != null ? _a : wallet.signer,
3418
- userId: this.userId,
3419
- pregenIdentifier: void 0,
3420
- pregenIdentifierType: void 0
3421
- });
3422
- const walletNoSigner = __spreadValues({}, this.wallets[wallet.id]);
3423
- delete walletNoSigner.signer;
3424
- dispatchEvent(ParaEvent.PREGEN_WALLET_CLAIMED, {
3425
- wallet: walletNoSigner,
3426
- recoverySecret: newRecoverySecret
3427
- });
3428
- }
3429
- yield this.setWallets(this.wallets);
3430
- return newRecoverySecret;
3431
- });
3432
- }
3080
+ * @deprecated
3081
+ */
3082
+ // protected exitFarcaster() {
3083
+ // this.isAwaitingFarcaster = false;
3084
+ // }
3433
3085
  /**
3434
- * Updates the identifier for a pregen wallet.
3435
- * @param {Object} opts the options object.
3436
- * @param {string} opts.walletId the pregen wallet ID
3437
- * @param {string} opts.newPregenIdentifier the new identtifier
3438
- * @param {TPregenIdentifierType} opts.newPregenIdentifierType: the new identifier type
3439
- **/
3440
- updatePregenWalletIdentifier(_0) {
3441
- return __async(this, arguments, function* ({
3442
- walletId,
3443
- newPregenIdentifier,
3444
- newPregenIdentifierType
3445
- }) {
3446
- this.requireApiKey();
3447
- yield this.ctx.client.updatePregenWallet(walletId, {
3448
- pregenIdentifier: newPregenIdentifier,
3449
- pregenIdentifierType: newPregenIdentifierType
3450
- });
3451
- if (!!this.wallets[walletId]) {
3452
- this.wallets[walletId] = __spreadProps(__spreadValues({}, this.wallets[walletId]), {
3453
- pregenIdentifier: newPregenIdentifier,
3454
- pregenIdentifierType: newPregenIdentifierType
3455
- });
3456
- yield this.setWallets(this.wallets);
3457
- }
3458
- });
3459
- }
3086
+ * @deprecated
3087
+ */
3088
+ // protected exitOAuth() {
3089
+ // this.isAwaitingOAuth = false;
3090
+ // }
3460
3091
  /**
3461
- * Checks if a pregen Wallet exists for the given identifier with the current partner.
3462
- * @param {Object} opts the options object.
3463
- * @param {string} opts.pregenIdentifier string the identifier of the user claiming the wallet
3464
- * @param {TPregenIdentifierType} opts.pregenIdentifierType type of the string of the identifier of the user claiming the wallet
3465
- * @returns {boolean} whether the pregen wallet exists
3466
- **/
3467
- hasPregenWallet(_0) {
3468
- return __async(this, arguments, function* ({
3469
- pregenIdentifier,
3470
- pregenIdentifierType
3471
- }) {
3472
- this.requireApiKey();
3473
- const res = yield this.getPregenWallets({ pregenIdentifier, pregenIdentifierType });
3474
- const wallet = res.find((w) => w.pregenIdentifier === pregenIdentifier && w.pregenIdentifierType === pregenIdentifierType);
3475
- if (!wallet) {
3476
- return false;
3477
- }
3478
- return true;
3479
- });
3480
- }
3092
+ * @deprecated
3093
+ */
3094
+ // protected exitLoops() {
3095
+ // this.exitAccountCreation();
3096
+ // this.exitLogin();
3097
+ // this.exitFarcaster();
3098
+ // this.exitOAuth();
3099
+ // }
3481
3100
  /**
3482
- * Get pregen wallets for the given identifier.
3483
- * @param {Object} opts the options object.
3484
- * @param {string} opts.pregenIdentifier - the identifier of the user claiming the wallet
3485
- * @param {TPregenIdentifierType} opts.pregenIdentifierType - type of the identifier of the user claiming the wallet
3486
- * @returns {Promise<WalletEntity[]>} the array of found wallets
3101
+ * Retrieves a token to verify the current session.
3102
+ * @returns {Promise<string>} the ID
3487
3103
  **/
3488
- getPregenWallets() {
3489
- return __async(this, arguments, function* ({
3490
- pregenIdentifier,
3491
- pregenIdentifierType = !!pregenIdentifier ? "EMAIL" : void 0
3492
- } = {}) {
3493
- this.requireApiKey();
3494
- const res = yield this.ctx.client.getPregenWallets(
3495
- pregenIdentifier && pregenIdentifierType ? { [pregenIdentifierType]: [pregenIdentifier] } : this.pregenIds,
3496
- this.isPortal(),
3497
- this.userId
3498
- );
3499
- return res.wallets.filter((w) => this.isWalletSupported(entityToWallet(w)));
3104
+ getVerificationToken() {
3105
+ return __async(this, null, function* () {
3106
+ const { sessionLookupId } = yield this.touchSession();
3107
+ return sessionLookupId;
3500
3108
  });
3501
3109
  }
3502
- encodeWalletBase64(wallet) {
3503
- const walletJson = JSON.stringify(wallet);
3504
- const base64Wallet = Buffer.from(walletJson).toString("base64");
3505
- return base64Wallet;
3506
- }
3507
- /**
3508
- * Encodes the current wallets encoded in Base 64.
3509
- * @returns {string} the encoded wallet string
3510
- **/
3511
- getUserShare() {
3512
- if (Object.values(this.wallets).length === 0) {
3513
- return null;
3514
- }
3515
- return Object.values(this.wallets).map((wallet) => this.encodeWalletBase64(wallet)).join("-");
3516
- }
3517
3110
  /**
3518
- * Sets the current wallets from a Base 64 string.
3519
- * @param {string} base64Wallet the encoded wallet string
3520
- **/
3521
- setUserShare(base64Wallets) {
3522
- return __async(this, null, function* () {
3523
- if (!base64Wallets) {
3524
- return;
3525
- }
3526
- const base64WalletsSplit = base64Wallets.split("-");
3527
- for (const base64Wallet of base64WalletsSplit) {
3528
- const walletJson = Buffer.from(base64Wallet, "base64").toString();
3529
- const wallet = migrateWallet(JSON.parse(walletJson));
3530
- this.wallets[wallet.id] = wallet;
3111
+ * Logs the user out.
3112
+ * @param {Object} opts the options object.
3113
+ * @param {boolean} opts.clearPregenWallets if `true`, will remove all pregen wallets from storage
3114
+ **/
3115
+ logout() {
3116
+ return __async(this, arguments, function* ({ clearPregenWallets = false } = {}) {
3117
+ yield this.ctx.client.logout();
3118
+ yield this.clearStorage();
3119
+ if (!clearPregenWallets) {
3120
+ Object.entries(this.wallets).forEach(([id, wallet]) => {
3121
+ if (!wallet.pregenIdentifier) {
3122
+ delete this.wallets[id];
3123
+ }
3124
+ });
3531
3125
  yield this.setWallets(this.wallets);
3126
+ } else {
3127
+ this.wallets = {};
3532
3128
  }
3129
+ this.currentWalletIds = {};
3130
+ this.externalWallets = {};
3131
+ this.loginEncryptionKeyPair = void 0;
3132
+ __privateSet(this, _authInfo, void 0);
3133
+ this.userId = void 0;
3134
+ this.sessionCookie = void 0;
3135
+ dispatchEvent(ParaEvent.LOGOUT_EVENT, null);
3533
3136
  });
3534
3137
  }
3535
- getTransactionReviewUrl(transactionId, timeoutMs) {
3536
- return __async(this, null, function* () {
3537
- const res = yield this.touchSession();
3538
- return this.constructPortalUrl("txReview", {
3539
- partnerId: res.data.partnerId,
3540
- pathId: transactionId,
3541
- params: {
3542
- email: this.email,
3543
- timeoutMs: timeoutMs == null ? void 0 : timeoutMs.toString()
3544
- }
3545
- });
3546
- });
3547
- }
3548
- getOnRampTransactionUrl(_i) {
3138
+ /** @deprecated */
3139
+ getSupportedCreateAuthMethods() {
3549
3140
  return __async(this, null, function* () {
3550
- var _j = _i, {
3551
- purchaseId,
3552
- providerKey
3553
- } = _j, walletParams = __objRest(_j, [
3554
- "purchaseId",
3555
- "providerKey"
3556
- ]);
3557
- const res = yield this.touchSession();
3558
- const [key, identifier] = (0, import_user_management_client5.extractWalletRef)(walletParams);
3559
- return this.constructPortalUrl("onRamp", {
3560
- partnerId: res.data.partnerId,
3561
- pathId: purchaseId,
3562
- sessionId: res.data.sessionId,
3563
- params: {
3564
- [key]: identifier,
3565
- providerKey,
3566
- currentWalletIds: JSON.stringify(this.currentWalletIds)
3567
- }
3568
- });
3141
+ const partner = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
3142
+ let supportedAuthMethods = /* @__PURE__ */ new Set();
3143
+ for (const authMethod of partner.supportedAuthMethods) {
3144
+ supportedAuthMethods.add(import_user_management_client5.AuthMethod[authMethod]);
3145
+ }
3146
+ return supportedAuthMethods;
3569
3147
  });
3570
3148
  }
3571
3149
  /**
3572
- * Signs a message using one of the current wallets.
3150
+ * Converts to a string, removing sensitive data when logging this class.
3573
3151
  *
3574
- * If you want to sign the keccak256 hash of a message, hash the
3575
- * message first and then pass in the base64 encoded hash.
3576
- * @param {Object} opts the options object.
3577
- * @param {string} opts.walletId the id of the wallet to sign with.
3578
- * @param {string} opts.messageBase64 the base64 encoding of exact message that should be signed
3579
- * @param {number} [opts.timeout] optional timeout in milliseconds. If not present, defaults to 30 seconds.
3580
- * @param {string} [opts.cosmosSignDocBase64] the Cosmos `SignDoc` in base64, if applicable
3152
+ * Doesn't work for all types of logging.
3581
3153
  **/
3582
- signMessage(_0) {
3583
- return __async(this, arguments, function* ({
3584
- walletId,
3585
- messageBase64,
3586
- timeoutMs = 3e4,
3587
- cosmosSignDocBase64
3588
- }) {
3589
- this.assertIsValidWalletId(walletId);
3590
- const wallet = this.wallets[walletId];
3591
- let signerId = this.userId;
3592
- if (wallet.partnerId && !wallet.userId) {
3593
- signerId = wallet.partnerId;
3594
- }
3595
- let signRes = yield this.signMessageInner({ wallet, signerId, messageBase64, cosmosSignDocBase64 });
3596
- let timeStart = Date.now();
3597
- if (signRes.pendingTransactionId) {
3598
- this.platformUtils.openPopup(
3599
- yield this.getTransactionReviewUrl(signRes.pendingTransactionId, timeoutMs),
3600
- { type: cosmosSignDocBase64 ? "SIGN_TRANSACTION_REVIEW" /* SIGN_TRANSACTION_REVIEW */ : "SIGN_MESSAGE_REVIEW" /* SIGN_MESSAGE_REVIEW */ }
3601
- );
3602
- } else {
3603
- dispatchEvent(ParaEvent.SIGN_MESSAGE_EVENT, signRes);
3604
- return signRes;
3154
+ toString() {
3155
+ var _a, _b, _c;
3156
+ const redactedWallets = Object.keys(this.wallets).reduce(
3157
+ (acc, walletId) => __spreadProps(__spreadValues({}, acc), {
3158
+ [walletId]: __spreadProps(__spreadValues({}, this.wallets[walletId]), {
3159
+ signer: this.wallets[walletId].signer ? "[REDACTED]" : void 0
3160
+ })
3161
+ }),
3162
+ {}
3163
+ );
3164
+ const redactedExternalWallets = Object.keys(this.externalWallets).reduce(
3165
+ (acc, walletId) => __spreadProps(__spreadValues({}, acc), {
3166
+ [walletId]: __spreadProps(__spreadValues({}, this.externalWallets[walletId]), {
3167
+ signer: this.externalWallets[walletId].signer ? "[REDACTED]" : void 0
3168
+ })
3169
+ }),
3170
+ {}
3171
+ );
3172
+ const obj = {
3173
+ partnerId: (_a = __privateGet(this, _partner)) == null ? void 0 : _a.id,
3174
+ supportedWalletTypes: (_b = __privateGet(this, _partner)) == null ? void 0 : _b.supportedWalletTypes,
3175
+ cosmosPrefix: (_c = __privateGet(this, _partner)) == null ? void 0 : _c.cosmosPrefix,
3176
+ authInfo: __privateGet(this, _authInfo),
3177
+ userId: this.userId,
3178
+ pregenIds: this.pregenIds,
3179
+ currentWalletIds: this.currentWalletIds,
3180
+ wallets: redactedWallets,
3181
+ externalWallets: redactedExternalWallets,
3182
+ loginEncryptionKeyPair: this.loginEncryptionKeyPair ? "[REDACTED]" : void 0,
3183
+ ctx: {
3184
+ apiKey: this.ctx.apiKey,
3185
+ disableWorkers: this.ctx.disableWorkers,
3186
+ disableWebSockets: this.ctx.disableWebSockets,
3187
+ env: this.ctx.env,
3188
+ offloadMPCComputationURL: this.ctx.offloadMPCComputationURL,
3189
+ useLocalFiles: this.ctx.useLocalFiles,
3190
+ useDKLS: this.ctx.useDKLS,
3191
+ cosmosPrefix: this.ctx.cosmosPrefix
3605
3192
  }
3606
- yield new Promise((resolve) => setTimeout(resolve, POLLING_INTERVAL_MS));
3607
- while (true) {
3608
- if (Date.now() - timeStart > timeoutMs) {
3193
+ };
3194
+ return `Para ${JSON.stringify(obj, null, 2)}`;
3195
+ }
3196
+ /** NEW METHODS */
3197
+ getNewCredentialAndUrl() {
3198
+ return __async(this, arguments, function* ({
3199
+ authMethod = "PASSKEY",
3200
+ isForNewDevice = false,
3201
+ portalTheme,
3202
+ shorten = false
3203
+ } = {}) {
3204
+ this.assertIsAuthSet();
3205
+ let credentialId, urlType;
3206
+ switch (authMethod) {
3207
+ case "PASSKEY":
3208
+ ({
3209
+ data: { id: credentialId }
3210
+ } = yield this.ctx.client.addSessionPublicKey(this.userId, {
3211
+ status: import_user_management_client5.PublicKeyStatus.PENDING,
3212
+ type: import_user_management_client5.PublicKeyType.WEB
3213
+ }));
3214
+ urlType = "createAuth";
3609
3215
  break;
3610
- }
3611
- try {
3612
- yield this.ctx.client.getPendingTransaction(this.userId, signRes.pendingTransactionId);
3613
- } catch (err) {
3614
- const error = new TransactionReviewDenied();
3615
- dispatchEvent(ParaEvent.SIGN_MESSAGE_EVENT, signRes, error.message);
3616
- throw error;
3617
- }
3618
- signRes = yield this.signMessageInner({ wallet, signerId, messageBase64, cosmosSignDocBase64 });
3619
- if (signRes.pendingTransactionId) {
3620
- yield new Promise((resolve) => setTimeout(resolve, POLLING_INTERVAL_MS));
3621
- } else {
3216
+ case "PASSWORD":
3217
+ ({
3218
+ data: { id: credentialId }
3219
+ } = yield this.ctx.client.addSessionPasswordPublicKey(this.userId, {
3220
+ status: import_user_management_client5.PasswordStatus.PENDING
3221
+ }));
3222
+ urlType = "createPassword";
3622
3223
  break;
3623
- }
3624
- }
3625
- if (signRes.pendingTransactionId) {
3626
- const error = new TransactionReviewTimeout(
3627
- yield this.getTransactionReviewUrl(signRes.pendingTransactionId),
3628
- signRes.pendingTransactionId
3629
- );
3630
- dispatchEvent(ParaEvent.SIGN_MESSAGE_EVENT, signRes, error.message);
3631
- throw error;
3632
3224
  }
3633
- dispatchEvent(ParaEvent.SIGN_MESSAGE_EVENT, signRes);
3634
- return signRes;
3225
+ const url = yield this.constructPortalUrl(urlType, {
3226
+ isForNewDevice,
3227
+ pathId: credentialId,
3228
+ portalTheme,
3229
+ shorten
3230
+ });
3231
+ return { credentialId, url };
3635
3232
  });
3636
3233
  }
3637
- signMessageInner(_0) {
3234
+ /**
3235
+ * Returns a Para Portal URL for logging in with a WebAuth passkey or a password.
3236
+ * @param {Object} opts the options object
3237
+ * @param {String} opts.auth - the user auth to sign up or log in with, in the form ` { email: string } | { phone: `+${number}` } `
3238
+ * @param {boolean} opts.useShortUrls - whether to shorten the generated portal URLs
3239
+ * @param {Theme} opts.portalTheme the Para Portal theme to apply to the password creation URL, if other than the default theme
3240
+ * @returns {SignUpOrLogInResponse} an object in the form of either: `{ stage: 'verify' }` or `{ stage: 'login'; passkeyUrl?: string; passwordUrl?: string; biometricHints?: BiometricLocationHint[] }`
3241
+ */
3242
+ getLoginUrl(_0) {
3638
3243
  return __async(this, arguments, function* ({
3639
- wallet,
3640
- signerId,
3641
- messageBase64,
3642
- cosmosSignDocBase64
3244
+ authMethod = "PASSKEY",
3245
+ shorten = false,
3246
+ portalTheme,
3247
+ sessionId
3643
3248
  }) {
3644
- let signRes;
3645
- switch (wallet.scheme) {
3646
- case import_user_management_client5.WalletScheme.ED25519:
3647
- signRes = yield this.platformUtils.ed25519Sign(
3648
- this.ctx,
3649
- signerId,
3650
- wallet.id,
3651
- wallet.signer,
3652
- messageBase64,
3653
- this.retrieveSessionCookie()
3654
- );
3249
+ if (!sessionId) {
3250
+ sessionId = (yield this.touchSession()).sessionLookupId;
3251
+ }
3252
+ this.assertIsAuthSet();
3253
+ let urlType;
3254
+ switch (authMethod) {
3255
+ case "PASSKEY":
3256
+ urlType = "loginAuth";
3655
3257
  break;
3656
- default:
3657
- signRes = yield this.platformUtils.signMessage(
3658
- this.ctx,
3659
- signerId,
3660
- wallet.id,
3661
- wallet.signer,
3662
- messageBase64,
3663
- this.retrieveSessionCookie(),
3664
- wallet.scheme === import_user_management_client5.WalletScheme.DKLS,
3665
- cosmosSignDocBase64
3666
- );
3258
+ case "PASSWORD":
3259
+ urlType = "loginPassword";
3667
3260
  break;
3261
+ default:
3262
+ throw new Error(`invalid authentication method: '${authMethod}'`);
3668
3263
  }
3669
- return signRes;
3264
+ return this.constructPortalUrl(urlType, {
3265
+ sessionId,
3266
+ shorten,
3267
+ portalTheme
3268
+ });
3670
3269
  });
3671
3270
  }
3672
- /**
3673
- * Signs a transaction.
3674
- * @param {Object} opts the options object.
3675
- * @param {string} opts.walletId the id of the wallet to sign with.
3676
- * @param {string} opts.rlpEncodedTxBase64 the transaction to sign, in RLP base64 encoding
3677
- * @param {string} [opts.chainId] the EVM chain id of the chain the transaction is being sent on, if applicable
3678
- * @param {number} [opts.timeoutMs] the amount of time to wait for the user to sign the transaction, in milliseconds
3679
- **/
3680
- signTransaction(_0) {
3681
- return __async(this, arguments, function* ({
3682
- walletId,
3683
- rlpEncodedTxBase64,
3684
- chainId,
3685
- timeoutMs = 3e4
3686
- }) {
3687
- this.assertIsValidWalletId(walletId);
3688
- const wallet = this.wallets[walletId];
3689
- let signerId = this.userId;
3690
- if (wallet.partnerId && !wallet.userId) {
3691
- signerId = wallet.partnerId;
3692
- }
3693
- let signRes = yield this.platformUtils.signTransaction(
3694
- this.ctx,
3695
- signerId,
3696
- walletId,
3697
- this.wallets[walletId].signer,
3698
- rlpEncodedTxBase64,
3699
- chainId,
3700
- this.retrieveSessionCookie(),
3701
- wallet.scheme === import_user_management_client5.WalletScheme.DKLS
3702
- );
3703
- let timeStart = Date.now();
3704
- if (signRes.pendingTransactionId) {
3705
- this.platformUtils.openPopup(
3706
- yield this.getTransactionReviewUrl(signRes.pendingTransactionId, timeoutMs),
3707
- { type: "SIGN_TRANSACTION_REVIEW" /* SIGN_TRANSACTION_REVIEW */ }
3708
- );
3709
- } else {
3710
- dispatchEvent(ParaEvent.SIGN_TRANSACTION_EVENT, signRes);
3711
- return signRes;
3712
- }
3713
- yield new Promise((resolve) => setTimeout(resolve, POLLING_INTERVAL_MS));
3714
- while (true) {
3715
- if (Date.now() - timeStart > timeoutMs) {
3716
- break;
3717
- }
3718
- try {
3719
- yield this.ctx.client.getPendingTransaction(this.userId, signRes.pendingTransactionId);
3720
- } catch (err) {
3721
- const error = new TransactionReviewDenied();
3722
- dispatchEvent(ParaEvent.SIGN_TRANSACTION_EVENT, signRes, error.message);
3723
- throw error;
3271
+ getOAuthUrl(_0) {
3272
+ return __async(this, arguments, function* ({ method, deeplinkUrl }) {
3273
+ yield this.logout();
3274
+ const { sessionLookupId } = yield this.touchSession(true);
3275
+ return constructUrl({
3276
+ base: getBaseOAuthUrl(this.ctx.env),
3277
+ path: `/auth/${method}`,
3278
+ params: {
3279
+ apiKey: this.ctx.apiKey,
3280
+ sessionLookupId,
3281
+ deeplinkUrl
3724
3282
  }
3725
- signRes = yield this.platformUtils.signTransaction(
3726
- this.ctx,
3727
- signerId,
3728
- walletId,
3729
- this.wallets[walletId].signer,
3730
- rlpEncodedTxBase64,
3731
- chainId,
3732
- this.retrieveSessionCookie(),
3733
- wallet.scheme === import_user_management_client5.WalletScheme.DKLS
3734
- );
3735
- if (signRes.pendingTransactionId) {
3736
- yield new Promise((resolve) => setTimeout(resolve, POLLING_INTERVAL_MS));
3737
- } else {
3738
- break;
3283
+ });
3284
+ });
3285
+ }
3286
+ signUpOrLogIn(_c) {
3287
+ return __async(this, null, function* () {
3288
+ var _d = _c, { auth } = _d, urlOptions = __objRest(_d, ["auth"]);
3289
+ const serverAuthState = yield this.ctx.client.signUpOrLogIn(__spreadValues(__spreadValues({}, auth), this.getVerificationEmailProps()));
3290
+ return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
3291
+ });
3292
+ }
3293
+ verifyNewAccount(_e) {
3294
+ return __async(this, null, function* () {
3295
+ var _f = _e, {
3296
+ verificationCode
3297
+ } = _f, urlOptions = __objRest(_f, [
3298
+ "verificationCode"
3299
+ ]);
3300
+ this.assertIsAuthSet(["email", "phone"]);
3301
+ const userId = this.assertUserId();
3302
+ const serverAuthState = yield this.ctx.client.verifyNewAccount(userId, {
3303
+ verificationCode
3304
+ });
3305
+ return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
3306
+ });
3307
+ }
3308
+ verifyOAuth(_g) {
3309
+ return __async(this, null, function* () {
3310
+ var _h = _g, {
3311
+ method,
3312
+ deeplinkUrl,
3313
+ isCanceled = () => false,
3314
+ onCancel,
3315
+ onPoll,
3316
+ onOAuthUrl
3317
+ } = _h, urlOptions = __objRest(_h, [
3318
+ "method",
3319
+ "deeplinkUrl",
3320
+ "isCanceled",
3321
+ "onCancel",
3322
+ "onPoll",
3323
+ "onOAuthUrl"
3324
+ ]);
3325
+ const sessionLookupId = yield __privateMethod(this, _ParaCore_instances, prepareLogin_fn).call(this);
3326
+ const oAuthUrl = constructUrl({
3327
+ base: getBaseOAuthUrl(this.ctx.env),
3328
+ path: `/auth/${method}`,
3329
+ params: {
3330
+ apiKey: this.ctx.apiKey,
3331
+ sessionLookupId,
3332
+ deeplinkUrl
3739
3333
  }
3334
+ });
3335
+ onOAuthUrl(oAuthUrl);
3336
+ const startedAt = Date.now();
3337
+ return new Promise((resolve, reject) => {
3338
+ (() => __async(this, null, function* () {
3339
+ while (true) {
3340
+ try {
3341
+ if (isCanceled() || Date.now() - startedAt > POLLING_TIMEOUT_MS) {
3342
+ onCancel == null ? void 0 : onCancel();
3343
+ return reject("canceled");
3344
+ }
3345
+ yield new Promise((_resolve) => setTimeout(_resolve, POLLING_INTERVAL_MS));
3346
+ const serverAuthState = yield this.ctx.client.verifyOAuth();
3347
+ if (isServerAuthState(serverAuthState)) {
3348
+ const authState = yield __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, __spreadProps(__spreadValues({}, urlOptions), { sessionLookupId }));
3349
+ return resolve(authState);
3350
+ }
3351
+ onPoll == null ? void 0 : onPoll();
3352
+ } catch (err) {
3353
+ console.error(err);
3354
+ onPoll == null ? void 0 : onPoll();
3355
+ }
3356
+ }
3357
+ }))();
3358
+ });
3359
+ });
3360
+ }
3361
+ verifyFarcaster(_i) {
3362
+ return __async(this, null, function* () {
3363
+ var _j = _i, {
3364
+ isCanceled = () => false,
3365
+ onConnectUri,
3366
+ onCancel,
3367
+ onPoll
3368
+ } = _j, urlOptions = __objRest(_j, [
3369
+ "isCanceled",
3370
+ "onConnectUri",
3371
+ "onCancel",
3372
+ "onPoll"
3373
+ ]);
3374
+ const {
3375
+ data: { connect_uri: connectUri }
3376
+ } = yield this.ctx.client.initializeFarcasterLogin();
3377
+ onConnectUri(connectUri);
3378
+ return new Promise((resolve, reject) => {
3379
+ (() => __async(this, null, function* () {
3380
+ const startedAt = Date.now();
3381
+ while (true) {
3382
+ try {
3383
+ if (isCanceled() || Date.now() - startedAt > POLLING_TIMEOUT_MS) {
3384
+ onCancel == null ? void 0 : onCancel();
3385
+ return reject("canceled");
3386
+ }
3387
+ yield new Promise((_resolve) => setTimeout(_resolve, POLLING_INTERVAL_MS));
3388
+ const serverAuthState = yield this.ctx.client.getFarcasterAuthStatus();
3389
+ if (isServerAuthState(serverAuthState)) {
3390
+ const authState = yield __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
3391
+ return resolve(authState);
3392
+ }
3393
+ onPoll == null ? void 0 : onPoll();
3394
+ } catch (e) {
3395
+ console.error(e);
3396
+ return reject(e);
3397
+ }
3398
+ }
3399
+ }))();
3400
+ });
3401
+ });
3402
+ }
3403
+ /**
3404
+ * Validates the response received from an attempted Telegram login for authenticity, then
3405
+ * creates or retrieves the corresponding Para user and prepares the Para instance to sign in with that user.
3406
+ * @param authResponse - the response JSON object received from the Telegram widget.
3407
+ * @returns `{ isValid: boolean; telegramUserId?: string; userId?: string; isNewUser?: boolean; supportedAuthMethods?: AuthMethod[]; biometricHints?: BiometricLocationHint[] }`
3408
+ */
3409
+ verifyTelegram(_k) {
3410
+ return __async(this, null, function* () {
3411
+ var _l = _k, {
3412
+ telegramAuthResponse
3413
+ } = _l, urlOptions = __objRest(_l, [
3414
+ "telegramAuthResponse"
3415
+ ]);
3416
+ try {
3417
+ const serverAuthState = yield this.ctx.client.verifyTelegram(telegramAuthResponse);
3418
+ return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
3419
+ } catch (e) {
3420
+ throw new Error(e.message);
3740
3421
  }
3741
- if (signRes.pendingTransactionId) {
3742
- const error = new TransactionReviewTimeout(
3743
- yield this.getTransactionReviewUrl(signRes.pendingTransactionId),
3744
- signRes.pendingTransactionId
3745
- );
3746
- dispatchEvent(ParaEvent.SIGN_TRANSACTION_EVENT, signRes, error.message);
3747
- throw error;
3748
- }
3749
- dispatchEvent(ParaEvent.SIGN_TRANSACTION_EVENT, signRes);
3750
- return signRes;
3751
3422
  });
3752
3423
  }
3753
3424
  /**
3754
- * @deprecated
3755
- * Sends a transaction.
3756
- * @param walletId - id of the wallet to send the transaction from.
3757
- * @param rlpEncodedTxBase64 - rlp encoded tx as base64 string
3758
- * @param chainId - chain id of the chain the transaction is being sent on.
3425
+ * Waits for the session to be active and sets up the user.
3426
+ *
3427
+ * @param {Object} opts the options object
3428
+ * @param {Window} [opts.popupWindow] the popup window being used for login.
3429
+ * @param {boolean} [opts.skipSessionRefresh] whether to skip refreshing the session.
3430
+ * @returns {Object} `{ isComplete: boolean; isError: boolean; needsWallet: boolean; partnerId: string; }` the result data
3759
3431
  **/
3760
- sendTransaction(_0) {
3432
+ waitForLogin() {
3761
3433
  return __async(this, arguments, function* ({
3762
- walletId,
3763
- rlpEncodedTxBase64,
3764
- chainId
3434
+ isCanceled = () => false,
3435
+ onCancel,
3436
+ onPoll,
3437
+ skipSessionRefresh = false
3438
+ } = {}) {
3439
+ const startedAt = Date.now();
3440
+ return new Promise((resolve, reject) => {
3441
+ (() => __async(this, null, function* () {
3442
+ var _a;
3443
+ if (!this.isExternalWalletAuth) {
3444
+ this.externalWallets = {};
3445
+ }
3446
+ while (true) {
3447
+ if (isCanceled() || Date.now() - startedAt > POLLING_TIMEOUT_MS) {
3448
+ dispatchEvent(ParaEvent.LOGIN_EVENT, { isComplete: false }, "failed to setup user");
3449
+ onCancel == null ? void 0 : onCancel();
3450
+ return reject("canceled");
3451
+ }
3452
+ yield new Promise((resolve2) => setTimeout(resolve2, POLLING_INTERVAL_MS));
3453
+ try {
3454
+ let session = yield this.touchSession();
3455
+ if (!session.isAuthenticated) {
3456
+ onPoll == null ? void 0 : onPoll();
3457
+ continue;
3458
+ }
3459
+ session = yield this.userSetupAfterLogin();
3460
+ const needsWallet = (_a = session.needsWallet) != null ? _a : false;
3461
+ if (!needsWallet) {
3462
+ if (this.currentWalletIdsArray.length === 0) {
3463
+ onPoll == null ? void 0 : onPoll();
3464
+ continue;
3465
+ }
3466
+ }
3467
+ const fetchedWallets = yield this.fetchWallets();
3468
+ const tempSharesRes = yield this.getTransmissionKeyShares();
3469
+ if (tempSharesRes.data.temporaryShares.length === fetchedWallets.length) {
3470
+ yield this.setupAfterLogin({ temporaryShares: tempSharesRes.data.temporaryShares, skipSessionRefresh });
3471
+ yield this.claimPregenWallets();
3472
+ const resp = {
3473
+ needsWallet: needsWallet || Object.values(this.wallets).length === 0,
3474
+ partnerId: session.partnerId
3475
+ };
3476
+ dispatchEvent(ParaEvent.LOGIN_EVENT, resp);
3477
+ return resolve(resp);
3478
+ }
3479
+ onPoll == null ? void 0 : onPoll();
3480
+ } catch (err) {
3481
+ console.error(err);
3482
+ onPoll == null ? void 0 : onPoll();
3483
+ }
3484
+ }
3485
+ }))();
3486
+ });
3487
+ });
3488
+ }
3489
+ waitForSignup(_0) {
3490
+ return __async(this, arguments, function* ({
3491
+ isCanceled = () => false,
3492
+ onCancel,
3493
+ onPoll
3765
3494
  }) {
3766
- this.assertIsValidWalletId(walletId);
3767
- const wallet = this.wallets[walletId];
3768
- const signRes = yield this.platformUtils.sendTransaction(
3769
- this.ctx,
3770
- this.userId,
3771
- walletId,
3772
- this.wallets[walletId].signer,
3773
- rlpEncodedTxBase64,
3774
- chainId,
3775
- this.retrieveSessionCookie(),
3776
- wallet.scheme === import_user_management_client5.WalletScheme.DKLS
3777
- );
3778
- if (signRes.pendingTransactionId) {
3779
- this.platformUtils.openPopup(
3780
- yield this.getTransactionReviewUrl(signRes.pendingTransactionId),
3781
- { type: "SIGN_TRANSACTION_REVIEW" /* SIGN_TRANSACTION_REVIEW */ }
3782
- );
3783
- const error = new TransactionReviewError(
3784
- yield this.getTransactionReviewUrl(signRes.pendingTransactionId)
3785
- );
3786
- throw error;
3495
+ const startedAt = Date.now();
3496
+ return new Promise((resolve, reject) => {
3497
+ (() => __async(this, null, function* () {
3498
+ yield this.touchSession();
3499
+ if (!this.isExternalWalletAuth) {
3500
+ this.externalWallets = {};
3501
+ }
3502
+ while (true) {
3503
+ try {
3504
+ if (isCanceled() || Date.now() - startedAt > POLLING_TIMEOUT_MS) {
3505
+ onCancel == null ? void 0 : onCancel();
3506
+ dispatchEvent(ParaEvent.ACCOUNT_CREATION_EVENT, false, "failed to sign up user");
3507
+ return reject("canceled");
3508
+ }
3509
+ yield new Promise((_resolve) => setTimeout(_resolve, POLLING_INTERVAL_MS));
3510
+ if (yield this.isSessionActive()) {
3511
+ dispatchEvent(ParaEvent.ACCOUNT_CREATION_EVENT, true);
3512
+ return resolve(true);
3513
+ }
3514
+ onPoll == null ? void 0 : onPoll();
3515
+ } catch (err) {
3516
+ console.error(err);
3517
+ onPoll == null ? void 0 : onPoll();
3518
+ }
3519
+ }
3520
+ }))();
3521
+ });
3522
+ });
3523
+ }
3524
+ waitForWalletCreation() {
3525
+ return __async(this, arguments, function* ({
3526
+ isCanceled = () => false,
3527
+ onCancel
3528
+ } = {}) {
3529
+ yield this.waitForSignup({ isCanceled, onCancel });
3530
+ const { supportedWalletTypes } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
3531
+ const pregenWallets = yield this.getPregenWallets();
3532
+ let recoverySecret, walletIds = {};
3533
+ if (pregenWallets.length > 0) {
3534
+ recoverySecret = yield this.claimPregenWallets();
3535
+ walletIds = supportedWalletTypes.reduce((acc, { type }) => {
3536
+ var _a;
3537
+ return __spreadProps(__spreadValues({}, acc), {
3538
+ [type]: [(_a = pregenWallets.find((w) => !!WalletSchemeTypeMap[w.scheme][type])) == null ? void 0 : _a.id]
3539
+ });
3540
+ }, {});
3787
3541
  }
3788
- return signRes;
3542
+ const created = yield this.createWalletPerType();
3543
+ recoverySecret = recoverySecret != null ? recoverySecret : created.recoverySecret;
3544
+ walletIds = __spreadValues(__spreadValues({}, walletIds), created.walletIds);
3545
+ const resp = { walletIds, recoverySecret };
3546
+ dispatchEvent(ParaEvent.ACCOUNT_SETUP_EVENT, resp);
3547
+ return resp;
3789
3548
  });
3790
3549
  }
3791
- isProviderModalDisabled() {
3792
- return !!this.disableProviderModal;
3550
+ loginExternalWallet(_m) {
3551
+ return __async(this, null, function* () {
3552
+ var _n = _m, {
3553
+ externalWallet
3554
+ } = _n, urlOptions = __objRest(_n, [
3555
+ "externalWallet"
3556
+ ]);
3557
+ this.requireApiKey();
3558
+ const serverAuthState = yield this.ctx.client.loginExternalWallet({ externalWallet });
3559
+ return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
3560
+ });
3561
+ }
3562
+ verifyExternalWallet(_o) {
3563
+ return __async(this, null, function* () {
3564
+ var _p = _o, {
3565
+ externalWallet,
3566
+ signedMessage,
3567
+ cosmosPublicKeyHex,
3568
+ cosmosSigner
3569
+ } = _p, urlOptions = __objRest(_p, [
3570
+ "externalWallet",
3571
+ "signedMessage",
3572
+ "cosmosPublicKeyHex",
3573
+ "cosmosSigner"
3574
+ ]);
3575
+ const serverAuthState = yield this.ctx.client.verifyExternalWallet(this.userId, {
3576
+ externalWallet,
3577
+ signedMessage,
3578
+ cosmosPublicKeyHex,
3579
+ cosmosSigner
3580
+ });
3581
+ return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
3582
+ });
3793
3583
  }
3794
3584
  /**
3795
- * Starts a on-ramp or off-ramp transaction and returns the Para Portal link for the user to finalize and complete it.
3585
+ * Performs 2FA verification.
3796
3586
  * @param {Object} opts the options object
3797
- * @param {OnRampPurchaseCreateParams} opts.params the transaction settings.
3798
- * @param {boolean} opts.shouldOpenPopup if `true`, a popup window with the link will be opened.
3799
- * @param {string} opts.walletId the wallet ID to use for the transaction, where funds will be sent or withdrawn.
3800
- * @param {string} opts.externalWalletAddress the external wallet address to send funds to or withdraw funds from, if using an external wallet.
3801
- **/
3802
- initiateOnRampTransaction(options) {
3587
+ * @param {string} opts.email the email to use for performing a 2FA verification.
3588
+ * @param {string} opts.verificationCode the verification code to received via 2FA.
3589
+ * @returns {Object} `{ address, initiatedAt, status, userId, walletId }`
3590
+ */
3591
+ verify2fa(_0) {
3592
+ return __async(this, arguments, function* ({ auth, verificationCode }) {
3593
+ const res = yield this.ctx.client.verify2FA(auth, verificationCode);
3594
+ return {
3595
+ initiatedAt: res.data.initiatedAt,
3596
+ status: res.data.status,
3597
+ userId: res.data.userId,
3598
+ wallets: res.data.wallets
3599
+ };
3600
+ });
3601
+ }
3602
+ /**
3603
+ * Sets up two-factor authentication for the current user.
3604
+ * @returns {string} uri - uri to use for setting up 2FA
3605
+ * */
3606
+ setup2fa() {
3803
3607
  return __async(this, null, function* () {
3804
- var _b;
3805
- const _a = options, { params, shouldOpenPopup } = _a, walletParams = __objRest(_a, ["params", "shouldOpenPopup"]);
3806
- const onRampPurchase = yield this.ctx.client.createOnRampPurchase(__spreadValues({
3807
- userId: this.userId,
3808
- params: __spreadProps(__spreadValues({}, params), {
3809
- address: (_b = walletParams.externalWalletAddress) != null ? _b : this.getDisplayAddress(walletParams.walletId, { addressType: params.walletType })
3810
- })
3811
- }, walletParams));
3812
- const portalUrl = yield this.getOnRampTransactionUrl(__spreadValues({
3813
- purchaseId: onRampPurchase.id,
3814
- providerKey: onRampPurchase.providerKey
3815
- }, walletParams));
3816
- if (shouldOpenPopup) {
3817
- this.platformUtils.openPopup(portalUrl, { type: "ON_RAMP_TRANSACTION" /* ON_RAMP_TRANSACTION */ });
3818
- }
3819
- return { onRampPurchase, portalUrl };
3608
+ const userId = this.assertUserId();
3609
+ const res = yield this.ctx.client.setup2FA(userId);
3610
+ return res;
3820
3611
  });
3821
3612
  }
3822
3613
  /**
3823
- * Returns `true` if session was successfully kept alive, `false` otherwise.
3614
+ * Enables 2FA.
3615
+ * @param {Object} opts the options object
3616
+ * @param {string} opts.verificationCode - the verification code received via 2FA.
3617
+ */
3618
+ enable2fa(_0) {
3619
+ return __async(this, arguments, function* ({ verificationCode }) {
3620
+ const userId = this.assertUserId();
3621
+ yield this.ctx.client.enable2FA(userId, verificationCode);
3622
+ });
3623
+ }
3624
+ /**
3625
+ * Creates a new pregenerated wallet.
3626
+ *
3627
+ * @param {Object} opts the options object.
3628
+ * @param {string} opts.pregenIdentifier the identifier associated with the new wallet.
3629
+ * @param {TPregenIdentifierType} [opts.pregenIdentifierType] the identifier type. Defaults to `EMAIL`.
3630
+ * @param {WalletType} [opts.type] the type of wallet to create. Defaults to the first non-optional type in the instance's `supportedWalletTypes` array.
3631
+ * @returns {Wallet} the created wallet.
3824
3632
  **/
3825
- keepSessionAlive() {
3633
+ createPregenWallet(opts) {
3826
3634
  return __async(this, null, function* () {
3827
- try {
3828
- yield this.ctx.client.keepSessionAlive(this.userId);
3829
- return true;
3830
- } catch (err) {
3831
- return false;
3635
+ var _a, _b;
3636
+ const { supportedWalletTypes } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
3637
+ const { type: _type = (_a = supportedWalletTypes.find(({ optional }) => !optional)) == null ? void 0 : _a.type, pregenId } = opts;
3638
+ this.requireApiKey();
3639
+ const walletType = yield this.assertIsValidWalletType(
3640
+ _type != null ? _type : (_b = supportedWalletTypes.find(({ optional }) => !optional)) == null ? void 0 : _b.type
3641
+ );
3642
+ const [pregenIdentifierType, pregenIdentifier] = (0, import_user_management_client5.toPregenTypeAndId)(pregenId);
3643
+ let keygenRes;
3644
+ switch (walletType) {
3645
+ case import_user_management_client5.WalletType.SOLANA:
3646
+ keygenRes = yield this.platformUtils.ed25519PreKeygen(
3647
+ this.ctx,
3648
+ pregenIdentifier,
3649
+ pregenIdentifierType,
3650
+ this.retrieveSessionCookie()
3651
+ );
3652
+ break;
3653
+ default:
3654
+ keygenRes = yield this.platformUtils.preKeygen(
3655
+ this.ctx,
3656
+ void 0,
3657
+ pregenIdentifier,
3658
+ pregenIdentifierType,
3659
+ walletType,
3660
+ null,
3661
+ this.retrieveSessionCookie()
3662
+ );
3663
+ break;
3832
3664
  }
3665
+ const { signer, walletId } = keygenRes;
3666
+ this.wallets[walletId] = {
3667
+ id: walletId,
3668
+ signer,
3669
+ scheme: walletType === import_user_management_client5.WalletType.SOLANA ? import_user_management_client5.WalletScheme.ED25519 : import_user_management_client5.WalletScheme.DKLS,
3670
+ type: walletType,
3671
+ isPregen: true,
3672
+ pregenIdentifier,
3673
+ pregenIdentifierType
3674
+ };
3675
+ yield this.waitForPregenWalletAddress(walletId);
3676
+ yield this.populatePregenWalletAddresses();
3677
+ return this.wallets[walletId];
3833
3678
  });
3834
3679
  }
3835
3680
  /**
3836
- * Serialize the current session for import by another Para instance.
3837
- * @param {boolean} excludeSigners - whether or not to exclude the signer from the exported wallets.
3838
- * @returns {string} the serialized session
3839
- */
3840
- exportSession({ excludeSigners } = {}) {
3841
- const sessionInfo = {
3842
- email: this.email,
3843
- userId: this.userId,
3844
- wallets: structuredClone(this.wallets),
3845
- currentWalletIds: this.currentWalletIds,
3846
- sessionCookie: this.sessionCookie,
3847
- phone: this.phone,
3848
- countryCode: this.countryCode,
3849
- telegramUserId: this.telegramUserId,
3850
- farcasterUsername: this.farcasterUsername,
3851
- externalWallets: this.externalWallets
3852
- };
3853
- if (excludeSigners) {
3854
- for (const wallet of Object.values(sessionInfo.wallets)) {
3855
- delete wallet.signer;
3681
+ * Creates new pregenerated wallets for each desired type.
3682
+ * If no types are provided, this method will create one for each of the non-optional types
3683
+ * specified in the instance's `supportedWalletTypes` array that are not already present.
3684
+ * @param {Object} opts the options object.
3685
+ * @param {string} opts.pregenIdentifier the identifier to associate each wallet with.
3686
+ * @param {TPregenIdentifierType} opts.pregenIdentifierType - either `'EMAIL'` or `'PHONE'`.
3687
+ * @param {WalletType[]} [opts.types] the wallet types to create. Defaults to any types the instance supports that are not already present.
3688
+ * @returns {Wallet[]} an array containing the created wallets.
3689
+ **/
3690
+ createPregenWalletPerType(_0) {
3691
+ return __async(this, arguments, function* ({
3692
+ types,
3693
+ pregenId
3694
+ }) {
3695
+ const wallets = [];
3696
+ for (const type of yield this.getTypesToCreate(types)) {
3697
+ const wallet = yield this.createPregenWallet({ type, pregenId });
3698
+ wallets.push(wallet);
3856
3699
  }
3857
- }
3858
- return Buffer.from(JSON.stringify(sessionInfo)).toString("base64");
3700
+ return wallets;
3701
+ });
3859
3702
  }
3860
3703
  /**
3861
- * Imports a session serialized by another Para instance.
3862
- * @param {string} serializedInstanceBase64 the serialized session
3863
- */
3864
- importSession(serializedInstanceBase64) {
3865
- return __async(this, null, function* () {
3704
+ * Claims a pregenerated wallet.
3705
+ * @param {Object} opts the options object.
3706
+ * @param {string} opts.pregenIdentifier string the identifier of the user claiming the wallet
3707
+ * @param {TPregenIdentifierType} opts.pregenIdentifierType type of the identifier of the user claiming the wallet
3708
+ * @returns {[Wallet, string | null]} `[wallet, recoveryShare]` - the wallet object and the new recovery share.
3709
+ **/
3710
+ claimPregenWallets() {
3711
+ return __async(this, arguments, function* ({
3712
+ pregenId
3713
+ } = {}) {
3866
3714
  var _a;
3867
- const serializedInstance = Buffer.from(serializedInstanceBase64, "base64").toString("utf8");
3868
- const sessionInfo = JSON.parse(serializedInstance);
3869
- yield this.setEmail(sessionInfo.email);
3870
- yield this.setTelegramUserId(sessionInfo.telegramUserId);
3871
- yield this.setFarcasterUsername(sessionInfo.farcasterUsername);
3872
- yield this.setUserId(sessionInfo.userId);
3873
- yield this.setWallets(sessionInfo.wallets);
3874
- yield this.setExternalWallets(sessionInfo.externalWallets || {});
3875
- for (const walletId of Object.keys(this.wallets)) {
3876
- if (!this.wallets[walletId].userId) {
3877
- this.wallets[walletId].userId = this.userId;
3878
- }
3715
+ this.requireApiKey();
3716
+ const pregenWallets = pregenId ? yield this.getPregenWallets({ pregenId }) : yield this.getPregenWallets();
3717
+ if (pregenWallets.length === 0) {
3718
+ return void 0;
3879
3719
  }
3880
- if (Object.keys(sessionInfo.currentWalletIds).length !== 0) {
3881
- yield this.setCurrentWalletIds(sessionInfo.currentWalletIds);
3882
- } else {
3883
- const currentWalletIds = {};
3884
- for (const walletId of Object.keys(sessionInfo.wallets)) {
3885
- currentWalletIds[sessionInfo.wallets[walletId].type] = [
3886
- ...(_a = currentWalletIds[sessionInfo.wallets[walletId].type]) != null ? _a : [],
3887
- walletId
3888
- ];
3720
+ let newRecoverySecret;
3721
+ const { walletIds } = yield this.ctx.client.claimPregenWallets({
3722
+ userId: this.userId,
3723
+ walletIds: pregenWallets.map((w) => w.id)
3724
+ });
3725
+ for (const walletId of walletIds) {
3726
+ const wallet = this.wallets[walletId];
3727
+ let refreshedShare;
3728
+ if (wallet.scheme === import_user_management_client5.WalletScheme.ED25519) {
3729
+ const distributeRes = yield distributeNewShare({
3730
+ ctx: this.ctx,
3731
+ userId: this.userId,
3732
+ walletId: wallet.id,
3733
+ userShare: this.wallets[wallet.id].signer,
3734
+ emailProps: this.getBackupKitEmailProps(),
3735
+ partnerId: wallet.partnerId
3736
+ });
3737
+ if (distributeRes.length > 0) {
3738
+ newRecoverySecret = distributeRes;
3739
+ }
3740
+ } else {
3741
+ refreshedShare = yield this.refreshShare({
3742
+ walletId: wallet.id,
3743
+ share: this.wallets[wallet.id].signer,
3744
+ oldPartnerId: wallet.partnerId,
3745
+ newPartnerId: wallet.partnerId,
3746
+ redistributeBackupEncryptedShares: true
3747
+ });
3748
+ if (refreshedShare.recoverySecret) {
3749
+ newRecoverySecret = refreshedShare.recoverySecret;
3750
+ }
3889
3751
  }
3890
- yield this.setCurrentWalletIds(currentWalletIds);
3752
+ this.wallets[wallet.id] = __spreadProps(__spreadValues({}, this.wallets[wallet.id]), {
3753
+ signer: (_a = refreshedShare == null ? void 0 : refreshedShare.signer) != null ? _a : wallet.signer,
3754
+ userId: this.userId,
3755
+ pregenIdentifier: void 0,
3756
+ pregenIdentifierType: void 0
3757
+ });
3758
+ const walletNoSigner = __spreadValues({}, this.wallets[wallet.id]);
3759
+ delete walletNoSigner.signer;
3760
+ dispatchEvent(ParaEvent.PREGEN_WALLET_CLAIMED, {
3761
+ wallet: walletNoSigner,
3762
+ recoverySecret: newRecoverySecret
3763
+ });
3891
3764
  }
3892
- this.persistSessionCookie(sessionInfo.sessionCookie);
3893
- yield this.setPhoneNumber(sessionInfo.phone, sessionInfo.countryCode);
3894
- });
3895
- }
3896
- exitAccountCreation() {
3897
- this.isAwaitingAccountCreation = false;
3898
- }
3899
- exitLogin() {
3900
- this.isAwaitingLogin = false;
3901
- }
3902
- exitFarcaster() {
3903
- this.isAwaitingFarcaster = false;
3904
- }
3905
- exitOAuth() {
3906
- this.isAwaitingOAuth = false;
3907
- }
3908
- exitLoops() {
3909
- this.exitAccountCreation();
3910
- this.exitLogin();
3911
- this.exitFarcaster();
3912
- this.exitOAuth();
3913
- }
3914
- /**
3915
- * Retrieves a token to verify the current session.
3916
- * @returns {Promise<string>} the ID
3917
- **/
3918
- getVerificationToken() {
3919
- return __async(this, null, function* () {
3920
- const { data } = yield this.touchSession();
3921
- return data.sessionLookupId;
3765
+ yield this.setWallets(this.wallets);
3766
+ return newRecoverySecret;
3922
3767
  });
3923
3768
  }
3924
3769
  /**
3925
- * Logs the user out.
3770
+ * Updates the identifier for a pregen wallet.
3926
3771
  * @param {Object} opts the options object.
3927
- * @param {boolean} opts.clearPregenWallets if `true`, will remove all pregen wallets from storage
3772
+ * @param {string} opts.walletId the pregen wallet ID
3773
+ * @param {string} opts.newPregenIdentifier the new identtifier
3774
+ * @param {TPregenIdentifierType} opts.newPregenIdentifierType: the new identifier type
3928
3775
  **/
3929
- logout() {
3930
- return __async(this, arguments, function* ({ clearPregenWallets = false } = {}) {
3931
- yield this.ctx.client.logout();
3932
- yield this.clearStorage();
3933
- if (!clearPregenWallets) {
3934
- Object.entries(this.wallets).forEach(([id, wallet]) => {
3935
- if (!wallet.pregenIdentifier) {
3936
- delete this.wallets[id];
3937
- }
3776
+ updatePregenWalletIdentifier(_0) {
3777
+ return __async(this, arguments, function* ({
3778
+ walletId,
3779
+ newPregenId
3780
+ }) {
3781
+ this.requireApiKey();
3782
+ const [newPregenIdentifierType, newPregenIdentifier] = (0, import_user_management_client5.toPregenTypeAndId)(newPregenId);
3783
+ yield this.ctx.client.updatePregenWallet(walletId, {
3784
+ pregenIdentifier: newPregenIdentifier,
3785
+ pregenIdentifierType: newPregenIdentifierType
3786
+ });
3787
+ if (!!this.wallets[walletId]) {
3788
+ this.wallets[walletId] = __spreadProps(__spreadValues({}, this.wallets[walletId]), {
3789
+ pregenIdentifier: newPregenIdentifier,
3790
+ pregenIdentifierType: newPregenIdentifierType
3938
3791
  });
3939
3792
  yield this.setWallets(this.wallets);
3940
- } else {
3941
- this.wallets = {};
3942
3793
  }
3943
- this.currentWalletIds = {};
3944
- this.externalWallets = {};
3945
- this.loginEncryptionKeyPair = void 0;
3946
- this.email = void 0;
3947
- this.telegramUserId = void 0;
3948
- this.phone = void 0;
3949
- this.countryCode = void 0;
3950
- this.userId = void 0;
3951
- this.sessionCookie = void 0;
3952
- dispatchEvent(ParaEvent.LOGOUT_EVENT, null);
3953
3794
  });
3954
3795
  }
3955
- getSupportedCreateAuthMethods() {
3956
- return __async(this, null, function* () {
3957
- const res = yield this.touchSession();
3958
- const partnerId = res.data.partnerId;
3959
- const partnerRes = yield this.ctx.client.getPartner(partnerId);
3960
- let supportedAuthMethods = /* @__PURE__ */ new Set();
3961
- for (const authMethod of partnerRes.data.partner.supportedAuthMethods) {
3962
- supportedAuthMethods.add(import_user_management_client5.AuthMethod[authMethod]);
3796
+ /**
3797
+ * Checks if a pregen Wallet exists for the given identifier with the current partner.
3798
+ * @param {Object} opts the options object.
3799
+ * @param {string} opts.pregenIdentifier string the identifier of the user claiming the wallet
3800
+ * @param {TPregenIdentifierType} opts.pregenIdentifierType type of the string of the identifier of the user claiming the wallet
3801
+ * @returns {boolean} whether the pregen wallet exists
3802
+ **/
3803
+ hasPregenWallet(_0) {
3804
+ return __async(this, arguments, function* ({ pregenId }) {
3805
+ this.requireApiKey();
3806
+ const [pregenIdentifierType, pregenIdentifier] = (0, import_user_management_client5.toPregenTypeAndId)(pregenId);
3807
+ const wallets = yield this.getPregenWallets({ pregenId });
3808
+ const wallet = wallets.find(
3809
+ (w) => w.pregenIdentifier === pregenIdentifier && w.pregenIdentifierType === pregenIdentifierType
3810
+ );
3811
+ if (!wallet) {
3812
+ return false;
3963
3813
  }
3964
- return supportedAuthMethods;
3814
+ return true;
3965
3815
  });
3966
3816
  }
3967
3817
  /**
3968
- * Converts to a string, removing sensitive data when logging this class.
3969
- *
3970
- * Doesn't work for all types of logging.
3818
+ * Get pregen wallets for the given identifier.
3819
+ * @param {Object} opts the options object.
3820
+ * @param {string} opts.pregenIdentifier - the identifier of the user claiming the wallet
3821
+ * @param {TPregenIdentifierType} opts.pregenIdentifierType - type of the identifier of the user claiming the wallet
3822
+ * @returns {Promise<WalletEntity[]>} the array of found wallets
3971
3823
  **/
3972
- toString() {
3973
- const redactedWallets = Object.keys(this.wallets).reduce(
3974
- (acc, walletId) => __spreadProps(__spreadValues({}, acc), {
3975
- [walletId]: __spreadProps(__spreadValues({}, this.wallets[walletId]), {
3976
- signer: this.wallets[walletId].signer ? "[REDACTED]" : void 0
3977
- })
3978
- }),
3979
- {}
3980
- );
3981
- const redactedExternalWallets = Object.keys(this.externalWallets).reduce(
3982
- (acc, walletId) => __spreadProps(__spreadValues({}, acc), {
3983
- [walletId]: __spreadProps(__spreadValues({}, this.externalWallets[walletId]), {
3984
- signer: this.externalWallets[walletId].signer ? "[REDACTED]" : void 0
3985
- })
3986
- }),
3987
- {}
3988
- );
3989
- const obj = {
3990
- supportedWalletTypes: this.supportedWalletTypes,
3991
- cosmosPrefix: this.cosmosPrefix,
3992
- email: this.email,
3993
- phone: this.phone,
3994
- countryCode: this.countryCode,
3995
- telegramUserId: this.telegramUserId,
3996
- farcasterUsername: this.farcasterUsername,
3997
- userId: this.userId,
3998
- pregenIds: this.pregenIds,
3999
- currentWalletIds: this.currentWalletIds,
4000
- wallets: redactedWallets,
4001
- externalWallets: redactedExternalWallets,
4002
- loginEncryptionKeyPair: this.loginEncryptionKeyPair ? "[REDACTED]" : void 0,
4003
- ctx: {
4004
- apiKey: this.ctx.apiKey,
4005
- disableWorkers: this.ctx.disableWorkers,
4006
- disableWebSockets: this.ctx.disableWebSockets,
4007
- env: this.ctx.env,
4008
- offloadMPCComputationURL: this.ctx.offloadMPCComputationURL,
4009
- useLocalFiles: this.ctx.useLocalFiles,
4010
- useDKLS: this.ctx.useDKLS,
4011
- cosmosPrefix: this.ctx.cosmosPrefix
4012
- }
4013
- };
4014
- return `Para ${JSON.stringify(obj, null, 2)}`;
3824
+ getPregenWallets() {
3825
+ return __async(this, arguments, function* ({ pregenId } = {}) {
3826
+ this.requireApiKey();
3827
+ const res = yield this.ctx.client.getPregenWallets(
3828
+ pregenId ? (0, import_user_management_client5.toPregenIds)(pregenId) : this.pregenIds,
3829
+ this.isPortal(),
3830
+ this.userId
3831
+ );
3832
+ return res.wallets.filter((w) => this.isWalletSupported(entityToWallet(w)));
3833
+ });
4015
3834
  }
4016
3835
  };
4017
- _supportedWalletTypes = new WeakMap();
4018
- _supportedWalletTypesOpt = new WeakMap();
3836
+ _authInfo = new WeakMap();
3837
+ _partner = new WeakMap();
3838
+ _ParaCore_instances = new WeakSet();
3839
+ assertPartner_fn = function() {
3840
+ return __async(this, null, function* () {
3841
+ var _a, _b;
3842
+ if (!__privateGet(this, _partner)) {
3843
+ yield this.touchSession();
3844
+ }
3845
+ if (((_a = __privateGet(this, _partner)) == null ? void 0 : _a.cosmosPrefix) && this.ctx.cosmosPrefix !== __privateGet(this, _partner).cosmosPrefix) {
3846
+ this.ctx.cosmosPrefix = (_b = __privateGet(this, _partner)) == null ? void 0 : _b.cosmosPrefix;
3847
+ }
3848
+ return __privateGet(this, _partner);
3849
+ });
3850
+ };
3851
+ toAuthInfo_fn = function({
3852
+ email,
3853
+ phone,
3854
+ countryCode,
3855
+ farcasterUsername,
3856
+ telegramUserId,
3857
+ externalWalletAddress
3858
+ }) {
3859
+ let auth;
3860
+ switch (true) {
3861
+ case !!email:
3862
+ auth = { email };
3863
+ break;
3864
+ case !!phone:
3865
+ {
3866
+ const validPhone = formatPhoneNumber(phone, countryCode);
3867
+ if (validPhone) auth = { phone: formatPhoneNumber(phone, countryCode) };
3868
+ }
3869
+ break;
3870
+ case !!farcasterUsername:
3871
+ auth = { farcasterUsername };
3872
+ break;
3873
+ case !!telegramUserId:
3874
+ auth = { telegramUserId };
3875
+ break;
3876
+ case !!externalWalletAddress:
3877
+ auth = { externalWalletAddress };
3878
+ break;
3879
+ }
3880
+ return (0, import_user_management_client5.extractAuthInfo)(auth);
3881
+ };
3882
+ setAuthInfo_fn = function(authInfo) {
3883
+ return __async(this, null, function* () {
3884
+ __privateSet(this, _authInfo, authInfo);
3885
+ yield this.localStorageSetItem(LOCAL_STORAGE_AUTH_INFO, JSON.stringify(authInfo));
3886
+ yield this.localStorageRemoveItem(LOCAL_STORAGE_EMAIL);
3887
+ yield this.localStorageRemoveItem(LOCAL_STORAGE_PHONE);
3888
+ yield this.localStorageRemoveItem(LOCAL_STORAGE_COUNTRY_CODE);
3889
+ yield this.localStorageRemoveItem(LOCAL_STORAGE_FARCASTER_USERNAME);
3890
+ yield this.localStorageRemoveItem(LOCAL_STORAGE_TELEGRAM_USER_ID);
3891
+ });
3892
+ };
3893
+ getPartner_fn = function(partnerId) {
3894
+ return __async(this, null, function* () {
3895
+ const res = yield this.ctx.client.getPartner(partnerId);
3896
+ __privateSet(this, _partner, res.data.partner);
3897
+ return __privateGet(this, _partner);
3898
+ });
3899
+ };
3900
+ prepareAuthState_fn = function(_0) {
3901
+ return __async(this, arguments, function* (serverAuthState, opts = {}) {
3902
+ if (!opts.sessionLookupId && serverAuthState.stage === "login") {
3903
+ opts.sessionLookupId = yield __privateMethod(this, _ParaCore_instances, prepareLogin_fn).call(this);
3904
+ }
3905
+ const { auth, externalWallet, userId, displayName, pfpUrl, username } = serverAuthState;
3906
+ const authInfo = __spreadValues(__spreadValues({}, (0, import_user_management_client5.extractAuthInfo)(auth, { isRequired: true })), Object.fromEntries(
3907
+ Object.entries({
3908
+ displayName,
3909
+ pfpUrl,
3910
+ username,
3911
+ externalWallet
3912
+ }).filter(([_, v]) => !!v)
3913
+ ));
3914
+ yield __privateMethod(this, _ParaCore_instances, setAuthInfo_fn).call(this, authInfo);
3915
+ yield this.assertIsAuthSet();
3916
+ if (!!externalWallet) {
3917
+ yield this.setExternalWallet(externalWallet);
3918
+ }
3919
+ if (!!userId) {
3920
+ yield this.setUserId(userId);
3921
+ }
3922
+ let authState;
3923
+ switch (serverAuthState.stage) {
3924
+ case "verify":
3925
+ authState = serverAuthState;
3926
+ break;
3927
+ case "login":
3928
+ authState = yield __privateMethod(this, _ParaCore_instances, prepareLoginState_fn).call(this, serverAuthState, __spreadProps(__spreadValues({}, opts), { sessionLookupId: opts.sessionLookupId }));
3929
+ break;
3930
+ case "signup":
3931
+ authState = yield __privateMethod(this, _ParaCore_instances, prepareSignUpState_fn).call(this, serverAuthState, opts);
3932
+ break;
3933
+ }
3934
+ return authState;
3935
+ });
3936
+ };
3937
+ prepareLogin_fn = function() {
3938
+ return __async(this, null, function* () {
3939
+ yield this.logout();
3940
+ const { sessionLookupId } = yield this.touchSession(true);
3941
+ if (!this.loginEncryptionKeyPair) {
3942
+ yield this.setLoginEncryptionKeyPair();
3943
+ }
3944
+ return sessionLookupId;
3945
+ });
3946
+ };
3947
+ prepareLoginState_fn = function(_0, _1) {
3948
+ return __async(this, arguments, function* (loginState, {
3949
+ useShortUrls: shorten = false,
3950
+ portalTheme,
3951
+ sessionLookupId
3952
+ }) {
3953
+ const _a = loginState, { loginAuthMethods } = _a, authState = __objRest(_a, ["loginAuthMethods"]);
3954
+ return __spreadValues(__spreadValues(__spreadValues({}, authState), !this.isNativePasskey && loginAuthMethods.includes(import_user_management_client5.AuthMethod.PASSKEY) ? {
3955
+ passkeyUrl: yield this.getLoginUrl({ sessionId: sessionLookupId, shorten, portalTheme }),
3956
+ passkeyKnownDeviceUrl: yield this.constructPortalUrl("loginAuth", {
3957
+ sessionId: sessionLookupId,
3958
+ newDevice: {
3959
+ sessionId: sessionLookupId,
3960
+ encryptionKey: getPublicKeyHex(this.loginEncryptionKeyPair)
3961
+ },
3962
+ shorten,
3963
+ portalTheme
3964
+ })
3965
+ } : {}), loginAuthMethods.includes(import_user_management_client5.AuthMethod.PASSWORD) ? {
3966
+ passwordUrl: yield this.constructPortalUrl("loginPassword", {
3967
+ sessionId: sessionLookupId,
3968
+ shorten,
3969
+ portalTheme
3970
+ })
3971
+ } : {});
3972
+ });
3973
+ };
3974
+ prepareSignUpState_fn = function(_0, _1) {
3975
+ return __async(this, arguments, function* (serverSignupState, { useShortUrls: shorten = false, portalTheme }) {
3976
+ const _a = serverSignupState, { signupAuthMethods } = _a, authState = __objRest(_a, ["signupAuthMethods"]);
3977
+ const [isPasskey, isPassword] = [
3978
+ signupAuthMethods.includes(import_user_management_client5.AuthMethod.PASSKEY),
3979
+ signupAuthMethods.includes(import_user_management_client5.AuthMethod.PASSWORD)
3980
+ ];
3981
+ if (!isPasskey && !isPassword) {
3982
+ throw new Error(
3983
+ "No supported authentication methods found. Please ensure you have enabled either WebAuth passkeys or passwords in your Developer Portal settings."
3984
+ );
3985
+ }
3986
+ const signupState = authState;
3987
+ if (isPasskey) {
3988
+ const { url: passkeyUrl, credentialId: passkeyId } = yield this.getNewCredentialAndUrl({
3989
+ authMethod: "PASSKEY",
3990
+ shorten
3991
+ });
3992
+ signupState.passkeyUrl = passkeyUrl;
3993
+ signupState.passkeyId = passkeyId;
3994
+ }
3995
+ if (isPassword) {
3996
+ const { url: passwordUrl, credentialId: passwordId } = yield this.getNewCredentialAndUrl({
3997
+ authMethod: "PASSWORD",
3998
+ portalTheme,
3999
+ shorten
4000
+ });
4001
+ signupState.passwordUrl = passwordUrl;
4002
+ signupState.passwordId = passwordId;
4003
+ }
4004
+ return signupState;
4005
+ });
4006
+ };
4019
4007
  _ParaCore.version = PARA_CORE_VERSION;
4020
4008
  var ParaCore = _ParaCore;
4021
4009
 
@@ -4038,6 +4026,7 @@ var src_default = ParaCore;
4038
4026
  OnRampProvider,
4039
4027
  OnRampPurchaseStatus,
4040
4028
  OnRampPurchaseType,
4029
+ PARA_CORE_METHODS,
4041
4030
  PREGEN_IDENTIFIER_TYPES,
4042
4031
  ParaEvent,
4043
4032
  PopupType,
@@ -4049,18 +4038,21 @@ var src_default = ParaCore;
4049
4038
  TransactionReviewTimeout,
4050
4039
  WalletScheme,
4051
4040
  WalletType,
4041
+ constructUrl,
4052
4042
  decimalToHex,
4053
4043
  decryptPrivateKey,
4054
4044
  decryptPrivateKeyAndDecryptShare,
4055
4045
  decryptPrivateKeyWithPassword,
4056
4046
  decryptWithKeyPair,
4057
4047
  decryptWithPrivateKey,
4048
+ displayPhoneNumber,
4058
4049
  distributeNewShare,
4059
4050
  encodePrivateKeyToPemHex,
4060
4051
  encryptPrivateKey,
4061
4052
  encryptPrivateKeyWithPassword,
4062
4053
  encryptWithDerivedPublicKey,
4063
4054
  entityToWallet,
4055
+ formatPhoneNumber,
4064
4056
  getAsymmetricKeyPair,
4065
4057
  getBaseMPCNetworkUrl,
4066
4058
  getBaseOAuthUrl,
@@ -4082,10 +4074,9 @@ var src_default = ParaCore;
4082
4074
  initClient,
4083
4075
  isWalletSupported,
4084
4076
  mpcComputationClient,
4085
- normalizePhoneNumber,
4086
4077
  paraVersion,
4087
4078
  publicKeyFromHex,
4088
- stringToPhoneNumber,
4079
+ shortenUrl,
4089
4080
  toAssetInfoArray,
4090
4081
  transmissionUtilsRetrieve,
4091
4082
  truncateAddress,