@getpara/core-sdk 2.0.0-alpha.6 → 2.0.0-alpha.61

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.
Files changed (75) hide show
  1. package/dist/cjs/ParaCore.js +1038 -248
  2. package/dist/cjs/constants.js +13 -1
  3. package/dist/cjs/index.js +31 -3
  4. package/dist/cjs/shares/enclave.js +266 -0
  5. package/dist/cjs/shares/shareDistribution.js +16 -1
  6. package/dist/cjs/types/{theme.js → assets.js} +2 -2
  7. package/dist/cjs/types/{onRamps.js → auth.js} +12 -12
  8. package/dist/cjs/types/coreApi.js +20 -3
  9. package/dist/cjs/types/events.js +2 -0
  10. package/dist/cjs/types/index.js +2 -21
  11. package/dist/cjs/utils/config.js +108 -0
  12. package/dist/cjs/utils/formatting.js +46 -0
  13. package/dist/cjs/utils/index.js +2 -0
  14. package/dist/cjs/utils/onRamps.js +2 -3
  15. package/dist/cjs/utils/wallet.js +3 -0
  16. package/dist/esm/ParaCore.js +1045 -254
  17. package/dist/esm/{chunk-7B52C2XE.js → chunk-W5CT3TVS.js} +2 -0
  18. package/dist/esm/constants.js +10 -2
  19. package/dist/esm/cryptography/utils.js +1 -1
  20. package/dist/esm/errors.js +1 -1
  21. package/dist/esm/external/mpcComputationClient.js +1 -1
  22. package/dist/esm/external/userManagementClient.js +1 -1
  23. package/dist/esm/index.js +31 -6
  24. package/dist/esm/shares/KeyContainer.js +1 -1
  25. package/dist/esm/shares/enclave.js +226 -0
  26. package/dist/esm/shares/recovery.js +1 -1
  27. package/dist/esm/shares/shareDistribution.js +17 -2
  28. package/dist/esm/transmission/transmissionUtils.js +1 -1
  29. package/dist/esm/types/auth.js +11 -0
  30. package/dist/esm/types/config.js +1 -1
  31. package/dist/esm/types/coreApi.js +19 -3
  32. package/dist/esm/types/events.js +3 -1
  33. package/dist/esm/types/index.js +1 -16
  34. package/dist/esm/types/popup.js +1 -1
  35. package/dist/esm/types/wallet.js +1 -1
  36. package/dist/esm/utils/autobind.js +1 -1
  37. package/dist/esm/utils/config.js +86 -0
  38. package/dist/esm/utils/events.js +1 -1
  39. package/dist/esm/utils/formatting.js +44 -1
  40. package/dist/esm/utils/index.js +1 -0
  41. package/dist/esm/utils/json.js +1 -1
  42. package/dist/esm/utils/listeners.js +1 -1
  43. package/dist/esm/utils/onRamps.js +3 -4
  44. package/dist/esm/utils/phone.js +1 -1
  45. package/dist/esm/utils/polling.js +1 -1
  46. package/dist/esm/utils/types.js +1 -1
  47. package/dist/esm/utils/url.js +1 -1
  48. package/dist/esm/utils/wallet.js +4 -1
  49. package/dist/types/ParaCore.d.ts +115 -52
  50. package/dist/types/PlatformUtils.d.ts +2 -3
  51. package/dist/types/constants.d.ts +18 -14
  52. package/dist/types/index.d.ts +6 -4
  53. package/dist/types/shares/KeyContainer.d.ts +0 -2
  54. package/dist/types/shares/enclave.d.ts +81 -0
  55. package/dist/types/shares/shareDistribution.d.ts +4 -2
  56. package/dist/types/types/assets.d.ts +14 -0
  57. package/dist/types/types/auth.d.ts +16 -0
  58. package/dist/types/types/config.d.ts +11 -2
  59. package/dist/types/types/coreApi.d.ts +101 -36
  60. package/dist/types/types/events.d.ts +7 -2
  61. package/dist/types/types/index.d.ts +1 -4
  62. package/dist/types/types/methods.d.ts +85 -13
  63. package/dist/types/types/wallet.d.ts +7 -4
  64. package/dist/types/utils/config.d.ts +7 -0
  65. package/dist/types/utils/formatting.d.ts +12 -1
  66. package/dist/types/utils/index.d.ts +1 -0
  67. package/dist/types/utils/onRamps.d.ts +9 -10
  68. package/package.json +23 -23
  69. package/dist/cjs/types/recovery.js +0 -34
  70. package/dist/esm/types/onRamps.js +0 -11
  71. package/dist/esm/types/recovery.js +0 -12
  72. package/dist/types/types/onRamps.d.ts +0 -10
  73. package/dist/types/types/recovery.d.ts +0 -7
  74. package/dist/types/types/theme.d.ts +0 -12
  75. /package/dist/esm/types/{theme.js → assets.js} +0 -0
@@ -99,7 +99,8 @@ var import_recovery = require("./shares/recovery.js");
99
99
  var import_utils2 = require("./utils/index.js");
100
100
  var import_errors = require("./errors.js");
101
101
  var constants = __toESM(require("./constants.js"));
102
- var _authInfo, _partner, _ParaCore_instances, assertPartner_fn, guestWalletIds_get, guestWalletIdsArray_get, toAuthInfo_fn, setAuthInfo_fn, getPartner_fn, createPregenWallet_fn, _isCreateGuestWalletsPending, prepareAuthState_fn, prepareLogin_fn, prepareLoginState_fn, prepareSignUpState_fn;
102
+ var import_enclave = require("./shares/enclave.js");
103
+ var _authInfo, _ParaCore_instances, assertPartner_fn, guestWalletIds_get, guestWalletIdsArray_get, toAuthInfo_fn, setAuthInfo_fn, getPartner_fn, assertIsLinkingAccount_fn, assertIsLinkingAccountOrStart_fn, getOAuthUrl_fn, createPregenWallet_fn, _isCreateGuestWalletsPending, prepareAuthState_fn, prepareDoneState_fn, prepareVerificationState_fn, prepareLoginState_fn, prepareSignUpState_fn;
103
104
  if (typeof global !== "undefined") {
104
105
  global.Buffer = global.Buffer || import_buffer.Buffer;
105
106
  } else if (typeof window !== "undefined") {
@@ -111,22 +112,19 @@ if (typeof global !== "undefined") {
111
112
  }
112
113
  const { pki, jsbn } = import_node_forge.default;
113
114
  const _ParaCore = class _ParaCore {
114
- /**
115
- * Constructs a new `ParaCore` instance.
116
- * @param env - `Environment` to use.
117
- * @param apiKey - API key to use.
118
- * @param opts - Additional constructor options; see `ConstructorOpts`.
119
- * @returns - A new ParaCore instance.
120
- */
121
- constructor(env, apiKey, opts) {
115
+ constructor(envOrApiKey, apiKeyOrOpts, opts) {
122
116
  __privateAdd(this, _ParaCore_instances);
117
+ this.popupWindow = null;
123
118
  __privateAdd(this, _authInfo);
124
119
  this.isNativePasskey = false;
125
- __privateAdd(this, _partner);
120
+ this.isReady = false;
121
+ this.accountLinkInProgress = void 0;
122
+ this.isEnclaveUser = false;
126
123
  this.isAwaitingAccountCreation = false;
127
124
  this.isAwaitingLogin = false;
128
125
  this.isAwaitingFarcaster = false;
129
126
  this.isAwaitingOAuth = false;
127
+ this.isWorkerInitialized = false;
130
128
  /**
131
129
  * 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.
132
130
  */
@@ -135,6 +133,7 @@ const _ParaCore = class _ParaCore {
135
133
  * Wallets associated with the `ParaCore` instance.
136
134
  */
137
135
  this.externalWallets = {};
136
+ this.onRampPopup = void 0;
138
137
  this.localStorageGetItem = (key) => {
139
138
  return this.platformUtils.localStorage.get(key);
140
139
  };
@@ -156,16 +155,29 @@ const _ParaCore = class _ParaCore {
156
155
  this.retrieveSessionCookie = () => {
157
156
  return this.sessionCookie;
158
157
  };
158
+ this.retrieveEnclaveJwt = () => {
159
+ return this.enclaveJwt;
160
+ };
161
+ this.retrieveEnclaveRefreshJwt = () => {
162
+ return this.enclaveRefreshJwt;
163
+ };
159
164
  /**
160
165
  * Remove all local storage and prefixed session storage.
161
166
  * @param {'local' | 'session' | 'secure' | 'all'} type - Type of storage to clear. Defaults to 'all'.
162
167
  */
163
168
  this.clearStorage = (type = "all") => __async(this, null, function* () {
164
169
  const isAll = type === "all";
165
- (isAll || type === "local") && this.platformUtils.localStorage.clear(constants.PREFIX);
166
- (isAll || type === "session") && this.platformUtils.sessionStorage.clear(constants.PREFIX);
170
+ if (isAll || type === "local") {
171
+ this.platformUtils.localStorage.clear(constants.PREFIX);
172
+ this.platformUtils.localStorage.clear(constants.PARA_PREFIX);
173
+ }
174
+ if (isAll || type === "session") {
175
+ this.platformUtils.sessionStorage.clear(constants.PREFIX);
176
+ this.platformUtils.sessionStorage.clear(constants.PARA_PREFIX);
177
+ }
167
178
  if ((isAll || type === "secure") && this.platformUtils.secureStorage) {
168
179
  this.platformUtils.secureStorage.clear(constants.PREFIX);
180
+ this.platformUtils.secureStorage.clear(constants.PARA_PREFIX);
169
181
  }
170
182
  });
171
183
  this.trackError = (methodName, err) => __async(this, null, function* () {
@@ -207,6 +219,7 @@ const _ParaCore = class _ParaCore {
207
219
  this.updateWalletIdsFromStorage();
208
220
  this.updateSessionCookieFromStorage();
209
221
  this.updateLoginEncryptionKeyPairFromStorage();
222
+ this.updateEnclaveJwtFromStorage();
210
223
  };
211
224
  this.updateAuthInfoFromStorage = () => {
212
225
  var _a;
@@ -226,6 +239,10 @@ const _ParaCore = class _ParaCore {
226
239
  }
227
240
  __privateSet(this, _authInfo, authInfo);
228
241
  };
242
+ this.updateEnclaveJwtFromStorage = () => {
243
+ this.enclaveJwt = this.localStorageGetItem(constants.LOCAL_STORAGE_ENCLAVE_JWT) || this.sessionStorageGetItem(constants.LOCAL_STORAGE_ENCLAVE_JWT) || void 0;
244
+ this.enclaveRefreshJwt = this.localStorageGetItem(constants.LOCAL_STORAGE_ENCLAVE_REFRESH_JWT) || this.sessionStorageGetItem(constants.LOCAL_STORAGE_ENCLAVE_REFRESH_JWT) || void 0;
245
+ };
229
246
  this.updateUserIdFromStorage = () => {
230
247
  this.userId = this.localStorageGetItem(constants.LOCAL_STORAGE_USER_ID) || void 0;
231
248
  };
@@ -286,6 +303,16 @@ const _ParaCore = class _ParaCore {
286
303
  const _externalWallets = JSON.parse(stringExternalWallets || "{}");
287
304
  this.setExternalWallets(_externalWallets);
288
305
  };
306
+ this.initializeWorker = () => __async(this, null, function* () {
307
+ if (!this.isWorkerInitialized && !this.ctx.disableWebSockets && !this.ctx.disableWorkers) {
308
+ try {
309
+ this.isWorkerInitialized = true;
310
+ yield this.platformUtils.initializeWorker(this.ctx);
311
+ } catch (e) {
312
+ this.devLog("error initializing worker:", e);
313
+ }
314
+ }
315
+ });
289
316
  /**
290
317
  * Creates several new wallets with the desired types. If no types are provided, this method
291
318
  * will create one for each of the non-optional types specified in the instance's `supportedWalletTypes`
@@ -302,8 +329,29 @@ const _ParaCore = class _ParaCore {
302
329
  }) {
303
330
  return (yield this.ctx.client.getWalletBalance({ walletId, rpcUrl })).balance;
304
331
  });
305
- if (!apiKey) {
306
- throw new Error("A Para API key is required.");
332
+ let env, apiKey;
333
+ const actualArgs = Array.from(arguments).filter((arg) => arg !== void 0);
334
+ const actualArgumentCount = actualArgs.length;
335
+ if (actualArgumentCount === 1) {
336
+ if (Object.values(import_types.Environment).includes(envOrApiKey)) {
337
+ throw new Error("A Para API key is required.");
338
+ }
339
+ env = _ParaCore.resolveEnvironment(void 0, actualArgs[0]);
340
+ apiKey = actualArgs[0];
341
+ opts = void 0;
342
+ } else if (actualArgumentCount === 2) {
343
+ if (typeof apiKeyOrOpts === "object" && apiKeyOrOpts !== null) {
344
+ env = _ParaCore.resolveEnvironment(void 0, envOrApiKey);
345
+ apiKey = envOrApiKey;
346
+ opts = apiKeyOrOpts;
347
+ } else {
348
+ env = _ParaCore.resolveEnvironment(envOrApiKey, apiKeyOrOpts);
349
+ apiKey = apiKeyOrOpts;
350
+ opts = void 0;
351
+ }
352
+ } else {
353
+ env = _ParaCore.resolveEnvironment(envOrApiKey, apiKeyOrOpts);
354
+ apiKey = apiKeyOrOpts;
307
355
  }
308
356
  if (!opts) opts = {};
309
357
  let isE2E = false;
@@ -326,6 +374,7 @@ const _ParaCore = class _ParaCore {
326
374
  this.portalTheme = opts.portalTheme;
327
375
  this.platformUtils = this.getPlatformUtils();
328
376
  this.disableProviderModal = this.platformUtils.disableProviderModal;
377
+ this.fetchPregenWalletsOverride = opts.fetchPregenWalletsOverride;
329
378
  if (opts.useStorageOverrides) {
330
379
  this.localStorageGetItem = opts.localStorageGetItemOverride;
331
380
  this.localStorageSetItem = opts.localStorageSetItemOverride;
@@ -345,18 +394,41 @@ const _ParaCore = class _ParaCore {
345
394
  cookie
346
395
  );
347
396
  };
397
+ this.persistEnclaveJwt = (jwt) => {
398
+ this.enclaveJwt = jwt;
399
+ (opts.useSessionStorage ? this.sessionStorageSetItem : this.localStorageSetItem)(
400
+ constants.LOCAL_STORAGE_ENCLAVE_JWT,
401
+ jwt
402
+ );
403
+ };
404
+ this.persistEnclaveRefreshJwt = (refreshJwt) => {
405
+ this.enclaveRefreshJwt = refreshJwt;
406
+ (opts.useSessionStorage ? this.sessionStorageSetItem : this.localStorageSetItem)(
407
+ constants.LOCAL_STORAGE_ENCLAVE_REFRESH_JWT,
408
+ refreshJwt
409
+ );
410
+ };
411
+ const client = (0, import_userManagementClient.initClient)({
412
+ env,
413
+ version: _ParaCore.version,
414
+ apiKey,
415
+ partnerId: this.isPortal(env) ? opts.portalPartnerId : void 0,
416
+ useFetchAdapter: !!opts.disableWorkers,
417
+ retrieveSessionCookie: this.retrieveSessionCookie,
418
+ persistSessionCookie: this.persistSessionCookie
419
+ });
420
+ const enclaveClient = new import_enclave.EnclaveClient({
421
+ userManagementClient: client,
422
+ retrieveJwt: this.retrieveEnclaveJwt,
423
+ persistJwt: this.persistEnclaveJwt,
424
+ retrieveRefreshJwt: this.retrieveEnclaveRefreshJwt,
425
+ persistRefreshJwt: this.persistEnclaveRefreshJwt
426
+ });
348
427
  this.ctx = {
349
428
  env,
350
429
  apiKey,
351
- client: (0, import_userManagementClient.initClient)({
352
- env,
353
- version: _ParaCore.version,
354
- apiKey,
355
- partnerId: this.isPortal(env) ? opts.portalPartnerId : void 0,
356
- useFetchAdapter: !!opts.disableWorkers,
357
- retrieveSessionCookie: this.retrieveSessionCookie,
358
- persistSessionCookie: this.persistSessionCookie
359
- }),
430
+ client,
431
+ enclaveClient,
360
432
  disableWorkers: opts.disableWorkers,
361
433
  offloadMPCComputationURL: opts.offloadMPCComputationURL,
362
434
  useLocalFiles: opts.useLocalFiles,
@@ -391,6 +463,9 @@ const _ParaCore = class _ParaCore {
391
463
  ]);
392
464
  }
393
465
  }
466
+ setModalError(_error) {
467
+ return;
468
+ }
394
469
  get authInfo() {
395
470
  return __privateGet(this, _authInfo);
396
471
  }
@@ -417,8 +492,15 @@ const _ParaCore = class _ParaCore {
417
492
  get externalWalletConnectionType() {
418
493
  if (this.isExternalWalletAuth) {
419
494
  return "AUTHENTICATED";
495
+ } else if (this.isExternalWalletWithVerification) {
496
+ return "VERIFICATION";
420
497
  } else if (!!Object.keys(this.externalWallets).length) {
421
- return "CONNECTION_ONLY";
498
+ const hasEmbeddedWallets = Object.keys(this.wallets).some((id) => !this.wallets[id].isExternal);
499
+ if (hasEmbeddedWallets) {
500
+ return "NONE";
501
+ } else {
502
+ return "CONNECTION_ONLY";
503
+ }
422
504
  }
423
505
  return "NONE";
424
506
  }
@@ -439,16 +521,28 @@ const _ParaCore = class _ParaCore {
439
521
  return (0, import_user_management_client.isTelegram)((_a = this.authInfo) == null ? void 0 : _a.auth);
440
522
  }
441
523
  get isExternalWalletAuth() {
442
- var _a;
443
- return (0, import_user_management_client.isExternalWallet)((_a = __privateGet(this, _authInfo)) == null ? void 0 : _a.auth);
524
+ var _a, _b, _c;
525
+ return (0, import_user_management_client.isExternalWallet)((_a = __privateGet(this, _authInfo)) == null ? void 0 : _a.auth) && !!((_c = (_b = __privateGet(this, _authInfo)) == null ? void 0 : _b.externalWallet) == null ? void 0 : _c.withFullParaAuth);
526
+ }
527
+ get isExternalWalletWithVerification() {
528
+ var _a, _b, _c;
529
+ return (0, import_user_management_client.isExternalWallet)((_a = __privateGet(this, _authInfo)) == null ? void 0 : _a.auth) && !!((_c = (_b = __privateGet(this, _authInfo)) == null ? void 0 : _b.externalWallet) == null ? void 0 : _c.withVerification);
444
530
  }
445
531
  get partnerId() {
446
532
  var _a;
447
- return (_a = __privateGet(this, _partner)) == null ? void 0 : _a.id;
533
+ return (_a = this.partner) == null ? void 0 : _a.id;
534
+ }
535
+ get partnerName() {
536
+ var _a;
537
+ return (_a = this.partner) == null ? void 0 : _a.displayName;
538
+ }
539
+ get partnerLogo() {
540
+ var _a;
541
+ return (_a = this.partner) == null ? void 0 : _a.logoUrl;
448
542
  }
449
543
  get currentWalletIdsArray() {
450
544
  var _a, _b;
451
- return ((_b = (_a = __privateGet(this, _partner)) == null ? void 0 : _a.supportedWalletTypes) != null ? _b : Object.keys(this.currentWalletIds).map((type) => ({ type }))).reduce(
545
+ return ((_b = (_a = this.partner) == null ? void 0 : _a.supportedWalletTypes) != null ? _b : Object.keys(this.currentWalletIds).map((type) => ({ type }))).reduce(
452
546
  (acc, { type }) => {
453
547
  var _a2;
454
548
  return [
@@ -488,19 +582,23 @@ const _ParaCore = class _ParaCore {
488
582
  }
489
583
  get isNoWalletConfig() {
490
584
  var _a;
491
- return !!((_a = __privateGet(this, _partner)) == null ? void 0 : _a.supportedWalletTypes) && __privateGet(this, _partner).supportedWalletTypes.length === 0;
585
+ return !!((_a = this.partner) == null ? void 0 : _a.supportedWalletTypes) && this.partner.supportedWalletTypes.length === 0;
492
586
  }
493
587
  get supportedWalletTypes() {
494
588
  var _a, _b;
495
- return (_b = (_a = __privateGet(this, _partner)) == null ? void 0 : _a.supportedWalletTypes) != null ? _b : [];
589
+ return (_b = (_a = this.partner) == null ? void 0 : _a.supportedWalletTypes) != null ? _b : [];
496
590
  }
497
591
  get cosmosPrefix() {
498
592
  var _a;
499
- return (_a = __privateGet(this, _partner)) == null ? void 0 : _a.cosmosPrefix;
593
+ return (_a = this.partner) == null ? void 0 : _a.cosmosPrefix;
594
+ }
595
+ get supportedAccountLinks() {
596
+ var _a, _b;
597
+ return (_b = (_a = this.partner) == null ? void 0 : _a.supportedAccountLinks) != null ? _b : [...import_user_management_client.LINKED_ACCOUNT_TYPES];
500
598
  }
501
599
  get isWalletTypeEnabled() {
502
600
  var _a;
503
- return (((_a = __privateGet(this, _partner)) == null ? void 0 : _a.supportedWalletTypes) || []).reduce((acc, { type }) => {
601
+ return (((_a = this.partner) == null ? void 0 : _a.supportedWalletTypes) || []).reduce((acc, { type }) => {
504
602
  return __spreadProps(__spreadValues({}, acc), { [type]: true });
505
603
  }, {});
506
604
  }
@@ -534,6 +632,12 @@ const _ParaCore = class _ParaCore {
534
632
  if (typeof window === "undefined") return false;
535
633
  return !!((_a = window.location) == null ? void 0 : _a.host) && (0, import_utils2.getPortalBaseURL)(envOverride ? { env: envOverride } : this.ctx).includes(window.location.host);
536
634
  }
635
+ isRecoveryPortal(envOverride) {
636
+ var _a, _b;
637
+ if (typeof window === "undefined") return false;
638
+ const normalizedUrl = (_b = (_a = window.location) == null ? void 0 : _a.host) == null ? void 0 : _b.replace("getpara", "usecapsule");
639
+ return !!normalizedUrl && (0, import_utils2.getPortalBaseURL)(envOverride ? { env: envOverride } : this.ctx).includes(normalizedUrl);
640
+ }
537
641
  isParaConnect() {
538
642
  var _a;
539
643
  if (typeof window === "undefined") return false;
@@ -549,7 +653,7 @@ const _ParaCore = class _ParaCore {
549
653
  }
550
654
  isWalletSupported(wallet) {
551
655
  var _a, _b;
552
- return !((_a = __privateGet(this, _partner)) == null ? void 0 : _a.supportedWalletTypes) || (0, import_utils2.isWalletSupported)((_b = __privateGet(this, _partner).supportedWalletTypes.map(({ type }) => type)) != null ? _b : [], wallet);
656
+ return !((_a = this.partner) == null ? void 0 : _a.supportedWalletTypes) || (0, import_utils2.isWalletSupported)((_b = this.partner.supportedWalletTypes.map(({ type }) => type)) != null ? _b : [], wallet);
553
657
  }
554
658
  isWalletOwned(wallet) {
555
659
  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;
@@ -575,12 +679,12 @@ const _ParaCore = class _ParaCore {
575
679
  } else {
576
680
  const wallet = this.wallets[walletId];
577
681
  const [isUnclaimed, isOwned] = [this.isPregenWalletUnclaimed(wallet), this.isWalletOwned(wallet)];
578
- if (forbidPregen && isUnclaimed) {
682
+ if (forbidPregen && isUnclaimed && wallet.pregenIdentifierType !== "GUEST_ID") {
579
683
  error = `pre-generated wallet with id ${wallet == null ? void 0 : wallet.id} cannot be selected`;
580
684
  } else if (!isOwned && !isUnclaimed) {
581
685
  error = `wallet with id ${wallet == null ? void 0 : wallet.id} is not owned by the current user`;
582
686
  } else if (!this.isWalletSupported(wallet)) {
583
- 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(", ")}`;
687
+ error = `wallet with id ${wallet.id} and type ${wallet.type} is not supported, supported types are: ${(((_b = this.partner) == null ? void 0 : _b.supportedWalletTypes) || []).map(({ type }) => type).join(", ")}`;
584
688
  } else if (types && (!(0, import_utils2.getEquivalentTypes)(types).includes(wallet == null ? void 0 : wallet.type) || isOwned && !types.some((type) => {
585
689
  var _a2, _b2;
586
690
  return (_b2 = (_a2 = this.currentWalletIds) == null ? void 0 : _a2[type]) == null ? void 0 : _b2.includes(walletId);
@@ -611,7 +715,7 @@ const _ParaCore = class _ParaCore {
611
715
  if (this.externalWallets[walletId]) {
612
716
  const wallet2 = this.externalWallets[walletId];
613
717
  return options.truncate ? (0, import_utils2.truncateAddress)(wallet2.address, wallet2.type, {
614
- prefix: (_a = __privateGet(this, _partner)) == null ? void 0 : _a.cosmosPrefix,
718
+ prefix: (_a = this.partner) == null ? void 0 : _a.cosmosPrefix,
615
719
  targetLength: options.targetLength
616
720
  }) : wallet2.address;
617
721
  }
@@ -623,7 +727,7 @@ const _ParaCore = class _ParaCore {
623
727
  let prefix;
624
728
  switch (wallet.type) {
625
729
  case "COSMOS":
626
- prefix = (_d = (_c = options.cosmosPrefix) != null ? _c : (_b = __privateGet(this, _partner)) == null ? void 0 : _b.cosmosPrefix) != null ? _d : "cosmos";
730
+ prefix = (_d = (_c = options.cosmosPrefix) != null ? _c : (_b = this.partner) == null ? void 0 : _b.cosmosPrefix) != null ? _d : "cosmos";
627
731
  str = (0, import_utils2.getCosmosAddress)(wallet.publicKey, prefix);
628
732
  break;
629
733
  default:
@@ -657,29 +761,40 @@ const _ParaCore = class _ParaCore {
657
761
  constructPortalUrl(_0) {
658
762
  return __async(this, arguments, function* (type, opts = {}) {
659
763
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
660
- const [isCreate, isLogin, isOnRamp] = [
661
- ["createAuth", "createPassword"].includes(type),
662
- ["loginAuth", "loginPassword"].includes(type),
663
- type === "onRamp"
764
+ const [isCreate, isLogin, isOnRamp, isOAuth, isOAuthCallback, isTelegramLogin, isFarcasterLogin] = [
765
+ ["createAuth", "createPassword", "createPIN"].includes(type),
766
+ ["loginAuth", "loginPassword", "loginPIN", "loginOTP"].includes(type),
767
+ type === "onRamp",
768
+ type === "oAuth",
769
+ type === "oAuthCallback",
770
+ ["telegramLogin", "telegramLoginVerify"].includes(type),
771
+ type === "loginFarcaster"
664
772
  ];
773
+ if (isOAuth && !opts.oAuthMethod) {
774
+ throw new Error("oAuthMethod is required for oAuth portal URLs");
775
+ }
665
776
  if (isCreate || isLogin) {
666
777
  this.assertIsAuthSet();
667
778
  }
668
779
  let sessionId = opts.sessionId;
669
- if ((isLogin || isOnRamp) && !sessionId) {
780
+ if ((isLogin || isOnRamp || isTelegramLogin || isFarcasterLogin) && !sessionId) {
670
781
  const session = yield this.touchSession(true);
671
782
  sessionId = session.sessionId;
672
783
  }
673
784
  if (!this.loginEncryptionKeyPair) {
674
785
  yield this.setLoginEncryptionKeyPair();
675
786
  }
676
- const base = type === "onRamp" ? (0, import_utils2.getPortalBaseURL)(this.ctx) : yield this.getPortalURL();
787
+ const base = type === "onRamp" || isTelegramLogin ? (0, import_utils2.getPortalBaseURL)(this.ctx, isTelegramLogin) : yield this.getPortalURL();
677
788
  let path;
678
789
  switch (type) {
679
790
  case "createPassword": {
680
791
  path = `/web/users/${this.userId}/passwords/${opts.pathId}`;
681
792
  break;
682
793
  }
794
+ case "createPIN": {
795
+ path = `/web/users/${this.userId}/pin/${opts.pathId}`;
796
+ break;
797
+ }
683
798
  case "createAuth": {
684
799
  path = `/web/users/${this.userId}/biometrics/${opts.pathId}`;
685
800
  break;
@@ -692,32 +807,69 @@ const _ParaCore = class _ParaCore {
692
807
  path = "/web/biometrics/login";
693
808
  break;
694
809
  }
810
+ case "loginPIN": {
811
+ path = "/web/pin/login";
812
+ break;
813
+ }
695
814
  case "txReview": {
696
815
  path = `/web/users/${this.userId}/transaction-review/${opts.pathId}`;
697
816
  break;
698
817
  }
699
818
  case "onRamp": {
700
- path = `/web/users/${this.userId}/on-ramp-transaction/${opts.pathId}`;
819
+ path = `/web/users/${this.userId}/on-ramp-transaction/v2/${opts.pathId}`;
820
+ break;
821
+ }
822
+ case "telegramLoginVerify": {
823
+ path = `/auth/telegram/verify`;
824
+ break;
825
+ }
826
+ case "telegramLogin": {
827
+ path = `/auth/telegram`;
828
+ break;
829
+ }
830
+ case "oAuth": {
831
+ path = `/auth/${opts.oAuthMethod.toLowerCase()}`;
832
+ break;
833
+ }
834
+ case "oAuthCallback": {
835
+ path = `/auth/${opts.oAuthMethod.toLowerCase()}/callback`;
836
+ break;
837
+ }
838
+ case "loginOTP": {
839
+ path = "/auth/otp";
840
+ break;
841
+ }
842
+ case "loginFarcaster": {
843
+ path = "/auth/farcaster";
701
844
  break;
702
845
  }
703
846
  default: {
704
847
  throw new Error(`invalid URL type ${type}`);
705
848
  }
706
849
  }
707
- const partner = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
850
+ let partner = void 0;
851
+ try {
852
+ partner = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
853
+ } catch (e) {
854
+ if (this.isPartnerOptional) {
855
+ partner = void 0;
856
+ } else {
857
+ throw e;
858
+ }
859
+ }
708
860
  const thisDevice = (_a = opts.thisDevice) != null ? _a : {
709
861
  encryptionKey: (0, import_utils.getPublicKeyHex)(this.loginEncryptionKeyPair),
710
862
  sessionId
711
863
  };
712
- const params = __spreadValues(__spreadValues(__spreadValues(__spreadValues({
864
+ const params = __spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({
713
865
  apiKey: this.ctx.apiKey,
714
- partnerId: partner.id,
715
- portalFont: ((_b = opts.portalTheme) == null ? void 0 : _b.font) || (partner == null ? void 0 : partner.font) || ((_c = this.portalTheme) == null ? void 0 : _c.font),
866
+ partnerId: partner == null ? void 0 : partner.id,
867
+ portalFont: ((_b = opts.portalTheme) == null ? void 0 : _b.font) || ((_c = this.portalTheme) == null ? void 0 : _c.font) || (partner == null ? void 0 : partner.font),
716
868
  portalBorderRadius: ((_d = opts.portalTheme) == null ? void 0 : _d.borderRadius) || ((_e = this.portalTheme) == null ? void 0 : _e.borderRadius),
717
- portalThemeMode: ((_f = opts.portalTheme) == null ? void 0 : _f.mode) || (partner == null ? void 0 : partner.themeMode) || ((_g = this.portalTheme) == null ? void 0 : _g.mode),
718
- portalAccentColor: ((_h = opts.portalTheme) == null ? void 0 : _h.accentColor) || (partner == null ? void 0 : partner.accentColor) || ((_i = this.portalTheme) == null ? void 0 : _i.accentColor),
719
- portalForegroundColor: ((_j = opts.portalTheme) == null ? void 0 : _j.foregroundColor) || (partner == null ? void 0 : partner.foregroundColor) || ((_k = this.portalTheme) == null ? void 0 : _k.foregroundColor),
720
- 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),
869
+ portalThemeMode: ((_f = opts.portalTheme) == null ? void 0 : _f.mode) || ((_g = this.portalTheme) == null ? void 0 : _g.mode) || (partner == null ? void 0 : partner.themeMode),
870
+ portalAccentColor: ((_h = opts.portalTheme) == null ? void 0 : _h.accentColor) || ((_i = this.portalTheme) == null ? void 0 : _i.accentColor) || (partner == null ? void 0 : partner.accentColor),
871
+ portalForegroundColor: ((_j = opts.portalTheme) == null ? void 0 : _j.foregroundColor) || ((_k = this.portalTheme) == null ? void 0 : _k.foregroundColor) || (partner == null ? void 0 : partner.foregroundColor),
872
+ portalBackgroundColor: ((_l = opts.portalTheme) == null ? void 0 : _l.backgroundColor) || ((_m = this.portalTheme) == null ? void 0 : _m.backgroundColor) || (partner == null ? void 0 : partner.backgroundColor) || this.portalBackgroundColor,
721
873
  portalPrimaryButtonColor: this.portalPrimaryButtonColor,
722
874
  portalTextColor: this.portalTextColor,
723
875
  portalPrimaryButtonTextColor: this.portalPrimaryButtonTextColor,
@@ -727,7 +879,7 @@ const _ParaCore = class _ParaCore {
727
879
  }, (0, import_user_management_client.isPhone)(this.authInfo.auth) ? (0, import_utils2.splitPhoneNumber)(this.authInfo.auth.phone) : this.authInfo.auth), {
728
880
  pfpUrl: this.authInfo.pfpUrl,
729
881
  displayName: this.authInfo.displayName
730
- }) : {}), isOnRamp ? { sessionId } : {}), isLogin ? __spreadProps(__spreadValues({
882
+ }) : {}), isOnRamp ? { origin: typeof window !== "undefined" ? window.location.origin : void 0, email: this.email } : {}), isLogin || isOAuth || isOAuthCallback || isTelegramLogin || isFarcasterLogin ? __spreadProps(__spreadValues({
731
883
  sessionId: thisDevice.sessionId,
732
884
  encryptionKey: thisDevice.encryptionKey
733
885
  }, opts.newDevice ? {
@@ -735,7 +887,9 @@ const _ParaCore = class _ParaCore {
735
887
  newDeviceEncryptionKey: opts.newDevice.encryptionKey
736
888
  } : {}), {
737
889
  pregenIds: JSON.stringify(this.pregenIds)
738
- }) : {}), opts.params || {});
890
+ }) : {}), isOAuth || isOAuthCallback || isFarcasterLogin ? {
891
+ appScheme: opts.appScheme
892
+ } : {}), isTelegramLogin ? { isEmbed: "true" } : {}), opts.params || {});
739
893
  const url = (0, import_utils2.constructUrl)({ base, path, params });
740
894
  if (opts.shorten) {
741
895
  return (0, import_utils2.shortenUrl)(this.ctx, url);
@@ -743,12 +897,72 @@ const _ParaCore = class _ParaCore {
743
897
  return url;
744
898
  });
745
899
  }
900
+ static resolveEnvironment(env, apiKey) {
901
+ var _a;
902
+ if (!apiKey) {
903
+ throw new Error("A Para API key is required.");
904
+ }
905
+ if (apiKey.includes("_")) {
906
+ const validEnvironmentPrefixes = Object.values(import_types.Environment);
907
+ const envPrefix = (_a = apiKey.split("_")[0]) == null ? void 0 : _a.toUpperCase();
908
+ const hasValidPrefix = validEnvironmentPrefixes.some((envValue) => envValue === envPrefix);
909
+ if (!hasValidPrefix) {
910
+ throw new Error(`Invalid API key environment prefix.`);
911
+ }
912
+ return envPrefix;
913
+ }
914
+ if (!env) {
915
+ throw new Error("Environment parameter is required.");
916
+ }
917
+ return env;
918
+ }
746
919
  touchSession(regenerate = false) {
747
920
  return __async(this, null, function* () {
748
- var _a, _b, _c;
749
- const session = yield this.ctx.client.touchSession(regenerate);
750
- if (!__privateGet(this, _partner) || ((_a = __privateGet(this, _partner)) == null ? void 0 : _a.id) !== session.partnerId || !(0, import_utils2.supportedWalletTypesEq)(((_b = __privateGet(this, _partner)) == null ? void 0 : _b.supportedWalletTypes) || [], session.supportedWalletTypes) || (((_c = __privateGet(this, _partner)) == null ? void 0 : _c.cosmosPrefix) || "cosmos") !== session.cosmosPrefix) {
751
- yield __privateMethod(this, _ParaCore_instances, getPartner_fn).call(this, session.partnerId);
921
+ var _a, _b, _c, _d, _e;
922
+ if (!this.isWorkerInitialized) {
923
+ this.initializeWorker();
924
+ }
925
+ if (!this.isReady) {
926
+ yield this.ready();
927
+ }
928
+ let session;
929
+ try {
930
+ session = yield this.ctx.client.touchSession(regenerate);
931
+ } catch (error) {
932
+ this.handleTouchSessionError(error);
933
+ throw error;
934
+ }
935
+ if (!this.partner || ((_a = this.partner) == null ? void 0 : _a.id) !== session.partnerId || !(0, import_utils2.supportedWalletTypesEq)(((_b = this.partner) == null ? void 0 : _b.supportedWalletTypes) || [], session.supportedWalletTypes) || (((_c = this.partner) == null ? void 0 : _c.cosmosPrefix) || "cosmos") !== session.cosmosPrefix) {
936
+ if (!session.partnerId && !this.isRecoveryPortal()) {
937
+ this.displayModalError(
938
+ `Invalid API Key. Please ensure you have a valid API key for the current environment: ${(_d = this.ctx.env) == null ? void 0 : _d.toUpperCase()}.`
939
+ );
940
+ console.error(`
941
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
942
+ \u{1F6A8} PARA SDK CONFIGURATION ERROR \u{1F6A8}
943
+
944
+ INVALID API KEY FOR CONFIGURED ENVIRONMENT
945
+
946
+ Your API key does not match the configured environment. This usually means:
947
+
948
+ 1. You're using a production API key with a development environment
949
+ 2. You're using a development API key with a production environment
950
+ 3. Your API key is invalid or has been regenerated
951
+
952
+ SOLUTION:
953
+ \u2022 Verify your API key at: https://developer.getpara.com
954
+ \u2022 If your API key doesn't contain an environment prefix, ensure your API key is the correct key for your target environment
955
+
956
+ Current Environment: ${this.ctx.env}
957
+ API Key Prefix: ${((_e = this.ctx.apiKey) == null ? void 0 : _e.split("_")[0].toUpperCase()) || "None"}
958
+
959
+ Need help? Visit: https://docs.getpara.com or contact support
960
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
961
+ `);
962
+ throw new Error("Invalid API Key.");
963
+ } else {
964
+ yield __privateMethod(this, _ParaCore_instances, getPartner_fn).call(this, session.partnerId);
965
+ }
752
966
  }
753
967
  return session;
754
968
  });
@@ -847,8 +1061,35 @@ const _ParaCore = class _ParaCore {
847
1061
  return __privateGet(this, _authInfo);
848
1062
  });
849
1063
  }
850
- assertUserId() {
851
- if (!this.userId) {
1064
+ /**
1065
+ * Display an error message in the modal (if available)
1066
+ * @internal
1067
+ */
1068
+ displayModalError(error) {
1069
+ if (this.ctx.env !== import_types.Environment.PROD) {
1070
+ this.setModalError(error);
1071
+ }
1072
+ }
1073
+ /**
1074
+ * Handle specific touchSession errors with user-friendly messages
1075
+ * @private
1076
+ */
1077
+ handleTouchSessionError(error) {
1078
+ const errorStr = String(error);
1079
+ const errorMessage = error instanceof Error ? error.message : "";
1080
+ if (errorStr.includes("blocked by CORS policy") && errorStr.includes("Access-Control-Allow-Origin")) {
1081
+ this.displayModalError("Request rate limit reached. Please wait a couple of minutes and try again.");
1082
+ return;
1083
+ }
1084
+ if (error.status === 403 && errorMessage.includes("origin not authorized")) {
1085
+ this.displayModalError(
1086
+ "The current origin is not allowed. Update your allowed origins in the Para developer portal to allow the current origin."
1087
+ );
1088
+ return;
1089
+ }
1090
+ }
1091
+ assertUserId({ allowGuestMode = false } = {}) {
1092
+ if (!this.userId || !allowGuestMode && this.isGuestMode) {
852
1093
  throw new Error("no userId is set");
853
1094
  }
854
1095
  return this.userId;
@@ -904,19 +1145,75 @@ const _ParaCore = class _ParaCore {
904
1145
  * @param externalAddress - External wallet address to set.
905
1146
  * @param externalType - Type of external wallet to set.
906
1147
  */
907
- setExternalWallet(_0) {
908
- return __async(this, arguments, function* ({ address, type, provider, addressBech32, withFullParaAuth }) {
909
- this.externalWallets = {
910
- [address]: {
911
- id: address,
912
- address: addressBech32 != null ? addressBech32 : address,
1148
+ setExternalWallet(externalWallet) {
1149
+ return __async(this, null, function* () {
1150
+ const { id: partnerId, supportedWalletTypes } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
1151
+ this.externalWallets = (Array.isArray(externalWallet) ? externalWallet : [externalWallet]).reduce(
1152
+ (acc, {
1153
+ partnerId: wPartnerId,
1154
+ address,
913
1155
  type,
914
- name: provider,
915
- isExternal: true,
916
- isExternalWithParaAuth: withFullParaAuth,
917
- signer: ""
1156
+ provider,
1157
+ providerId,
1158
+ addressBech32,
1159
+ withFullParaAuth,
1160
+ isConnectionOnly,
1161
+ withVerification
1162
+ }) => {
1163
+ if (partnerId === wPartnerId && supportedWalletTypes.some(({ type: supportedType }) => supportedType === type)) {
1164
+ return __spreadProps(__spreadValues({}, acc), {
1165
+ [address]: {
1166
+ id: address,
1167
+ partnerId,
1168
+ address: addressBech32 != null ? addressBech32 : address,
1169
+ type,
1170
+ name: provider,
1171
+ isExternal: true,
1172
+ isExternalWithParaAuth: withFullParaAuth,
1173
+ externalProviderId: providerId,
1174
+ signer: "",
1175
+ isExternalConnectionOnly: isConnectionOnly,
1176
+ isExternalWithVerification: withVerification
1177
+ }
1178
+ });
1179
+ }
1180
+ return acc;
1181
+ },
1182
+ {}
1183
+ ), this.setExternalWallets(this.externalWallets);
1184
+ (0, import_utils2.dispatchEvent)(import_types.ParaEvent.EXTERNAL_WALLET_CHANGE_EVENT, null);
1185
+ });
1186
+ }
1187
+ addExternalWallets(externalWallets) {
1188
+ return __async(this, null, function* () {
1189
+ const { id: partnerId, supportedWalletTypes } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
1190
+ this.externalWallets = __spreadValues(__spreadValues({}, Object.entries(this.externalWallets).reduce((acc, [address, wallet]) => {
1191
+ if (partnerId === wallet.partnerId && supportedWalletTypes.some(({ type }) => type === wallet.type)) {
1192
+ return __spreadProps(__spreadValues({}, acc), {
1193
+ [address]: wallet
1194
+ });
918
1195
  }
919
- };
1196
+ return acc;
1197
+ }, {})), externalWallets.reduce(
1198
+ (acc, { address, type, provider, providerId, addressBech32, withFullParaAuth, isConnectionOnly, withVerification }) => {
1199
+ return __spreadProps(__spreadValues({}, acc), {
1200
+ [address]: {
1201
+ id: address,
1202
+ partnerId,
1203
+ address: addressBech32 != null ? addressBech32 : address,
1204
+ type,
1205
+ name: provider,
1206
+ isExternal: true,
1207
+ isExternalWithParaAuth: withFullParaAuth,
1208
+ externalProviderId: providerId,
1209
+ signer: "",
1210
+ isExternalConnectionOnly: isConnectionOnly,
1211
+ isExternalWithVerification: withVerification
1212
+ }
1213
+ });
1214
+ },
1215
+ {}
1216
+ ));
920
1217
  this.setExternalWallets(this.externalWallets);
921
1218
  (0, import_utils2.dispatchEvent)(import_types.ParaEvent.EXTERNAL_WALLET_CHANGE_EVENT, null);
922
1219
  });
@@ -947,12 +1244,16 @@ const _ParaCore = class _ParaCore {
947
1244
  }
948
1245
  /**
949
1246
  * Sets the external wallets associated with the `ParaCore` instance.
950
- * @param externalWallets - External wallets to set.
1247
+ * @param externalWallets - External wallets to set, or a function that modifies the current wallets.
951
1248
  */
952
1249
  setExternalWallets(externalWallets) {
953
1250
  return __async(this, null, function* () {
954
- this.externalWallets = externalWallets;
955
- yield this.localStorageSetItem(constants.LOCAL_STORAGE_EXTERNAL_WALLETS, JSON.stringify(externalWallets));
1251
+ if (typeof externalWallets === "function") {
1252
+ this.externalWallets = externalWallets(this.externalWallets);
1253
+ } else {
1254
+ this.externalWallets = externalWallets;
1255
+ }
1256
+ yield this.localStorageSetItem(constants.LOCAL_STORAGE_EXTERNAL_WALLETS, JSON.stringify(this.externalWallets));
956
1257
  });
957
1258
  }
958
1259
  /**
@@ -1028,6 +1329,7 @@ const _ParaCore = class _ParaCore {
1028
1329
  /**
1029
1330
  * Fetches the most recent OAuth account metadata for the signed-in user.
1030
1331
  * 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.
1332
+ * @deprecated use `para.getLinkedAccounts({ withMetadata: true })` instead.
1031
1333
  * @returns {Promise<AccountMetadata>} the user's account metadata.
1032
1334
  */
1033
1335
  getAccountMetadata() {
@@ -1173,8 +1475,15 @@ const _ParaCore = class _ParaCore {
1173
1475
  }
1174
1476
  getPartnerURL() {
1175
1477
  return __async(this, null, function* () {
1176
- const { portalUrl } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
1177
- return portalUrl;
1478
+ try {
1479
+ const { portalUrl } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
1480
+ return portalUrl;
1481
+ } catch (e) {
1482
+ if (this.isPartnerOptional) {
1483
+ return void 0;
1484
+ }
1485
+ throw e;
1486
+ }
1178
1487
  });
1179
1488
  }
1180
1489
  /**
@@ -1260,15 +1569,27 @@ const _ParaCore = class _ParaCore {
1260
1569
  } = _b, urlOptions = __objRest(_b, [
1261
1570
  "externalWallet"
1262
1571
  ]);
1263
- if (this.externalWalletConnectionOnly) {
1264
- externalWallet.withFullParaAuth = false;
1265
- yield this.setExternalWallet(externalWallet);
1572
+ const externalWallets = Array.isArray(externalWallet) ? externalWallet : [externalWallet];
1573
+ if (this.externalWalletConnectionOnly || externalWallets.every((wallet) => wallet.isConnectionOnly)) {
1574
+ yield this.addExternalWallets(
1575
+ externalWallets.map((wallet) => __spreadProps(__spreadValues({}, wallet), {
1576
+ withFullParaAuth: false
1577
+ }))
1578
+ );
1266
1579
  return Promise.resolve({
1267
1580
  userId: constants.EXTERNAL_WALLET_CONNECTION_ONLY_USER_ID
1268
1581
  });
1269
1582
  }
1583
+ if (Array.isArray(externalWallet)) {
1584
+ throw new Error(
1585
+ "Cannot authenticate multiple external wallets at once. To connect multiple wallets at once, use CONNECTION_ONLY mode."
1586
+ );
1587
+ }
1270
1588
  this.requireApiKey();
1271
1589
  const serverAuthState = yield this.ctx.client.loginExternalWallet({ externalWallet });
1590
+ if (!externalWallet.withFullParaAuth && externalWallet.withVerification) {
1591
+ yield this.touchSession(true);
1592
+ }
1272
1593
  return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
1273
1594
  });
1274
1595
  }
@@ -1285,36 +1606,89 @@ const _ParaCore = class _ParaCore {
1285
1606
  "cosmosPublicKeyHex",
1286
1607
  "cosmosSigner"
1287
1608
  ]);
1609
+ var _a;
1288
1610
  const serverAuthState = yield this.ctx.client.verifyExternalWallet(this.userId, {
1289
1611
  externalWallet,
1290
1612
  signedMessage,
1291
1613
  cosmosPublicKeyHex,
1292
1614
  cosmosSigner
1293
1615
  });
1616
+ if (serverAuthState.stage === "login" && ((_a = serverAuthState.loginAuthMethods) == null ? void 0 : _a.includes(import_user_management_client.AuthMethod.PIN))) {
1617
+ const { sessionLookupId } = yield this.touchSession();
1618
+ return __privateMethod(this, _ParaCore_instances, prepareLoginState_fn).call(this, serverAuthState, __spreadProps(__spreadValues({}, urlOptions), { sessionLookupId }));
1619
+ }
1294
1620
  return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
1295
1621
  });
1296
1622
  }
1623
+ verifyExternalWalletLink(opts) {
1624
+ return __async(this, null, function* () {
1625
+ const accountLinkInProgress = yield __privateMethod(this, _ParaCore_instances, assertIsLinkingAccount_fn).call(this, ["EXTERNAL_WALLET"]);
1626
+ if (!accountLinkInProgress.externalWallet) {
1627
+ throw new Error("no external wallet account link in progress");
1628
+ }
1629
+ const accounts = yield this.verifyLink(__spreadValues({
1630
+ accountLinkInProgress,
1631
+ externalWallet: accountLinkInProgress.externalWallet
1632
+ }, opts));
1633
+ return accounts;
1634
+ });
1635
+ }
1636
+ // TELEGRAM
1297
1637
  /**
1298
1638
  * Validates the response received from an attempted Telegram login for authenticity, then
1299
1639
  * creates or retrieves the corresponding Para user and prepares the Para instance to sign in with that user.
1300
1640
  * @param authResponse - the response JSON object received from the Telegram widget.
1301
1641
  * @returns `{ isValid: boolean; telegramUserId?: string; userId?: string; isNewUser?: boolean; supportedAuthMethods?: AuthMethod[]; biometricHints?: BiometricLocationHint[] }`
1302
1642
  */
1303
- verifyTelegram(_e) {
1643
+ verifyTelegramProcess(_e) {
1304
1644
  return __async(this, null, function* () {
1305
1645
  var _f = _e, {
1306
- telegramAuthResponse
1646
+ serverAuthState: optsServerAuthState,
1647
+ telegramAuthResponse,
1648
+ isLinkAccount
1307
1649
  } = _f, urlOptions = __objRest(_f, [
1308
- "telegramAuthResponse"
1650
+ "serverAuthState",
1651
+ "telegramAuthResponse",
1652
+ "isLinkAccount"
1309
1653
  ]);
1310
1654
  try {
1311
- const serverAuthState = yield this.ctx.client.verifyTelegram(telegramAuthResponse);
1312
- return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
1655
+ switch (isLinkAccount) {
1656
+ case false: {
1657
+ if (!optsServerAuthState && !telegramAuthResponse) {
1658
+ throw new Error("one of serverAuthState or telegramAuthResponse are required for verifying telegram");
1659
+ }
1660
+ const serverAuthState = optsServerAuthState != null ? optsServerAuthState : yield this.ctx.client.verifyTelegram({ authObject: telegramAuthResponse });
1661
+ const { sessionLookupId } = yield this.touchSession();
1662
+ return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, __spreadProps(__spreadValues({}, urlOptions), { sessionLookupId }));
1663
+ }
1664
+ case true: {
1665
+ if (!telegramAuthResponse) {
1666
+ throw new Error("telegramAuthResponse is required for verifying telegram link");
1667
+ }
1668
+ const accountLinkInProgress = yield __privateMethod(this, _ParaCore_instances, assertIsLinkingAccountOrStart_fn).call(this, "TELEGRAM");
1669
+ const accounts = yield this.verifyLink({
1670
+ accountLinkInProgress,
1671
+ telegramAuthResponse
1672
+ });
1673
+ return accounts;
1674
+ }
1675
+ }
1313
1676
  } catch (e) {
1314
- throw new Error(e.message);
1677
+ const errorMessage = e instanceof Error ? e.message : e ? String(e) : "Unknown error occurred";
1678
+ throw new Error(errorMessage);
1315
1679
  }
1316
1680
  });
1317
1681
  }
1682
+ verifyTelegram(opts) {
1683
+ return __async(this, null, function* () {
1684
+ return yield this.verifyTelegramProcess(__spreadProps(__spreadValues({}, opts), { isLinkAccount: false }));
1685
+ });
1686
+ }
1687
+ verifyTelegramLink(opts) {
1688
+ return __async(this, null, function* () {
1689
+ return yield this.verifyTelegramProcess(__spreadProps(__spreadValues({}, opts), { isLinkAccount: true }));
1690
+ });
1691
+ }
1318
1692
  /**
1319
1693
  * Performs 2FA verification.
1320
1694
  * @param {Object} opts the options object
@@ -1358,10 +1732,35 @@ const _ParaCore = class _ParaCore {
1358
1732
  /**
1359
1733
  * Resend a verification email for the current user.
1360
1734
  */
1361
- resendVerificationCode() {
1362
- return __async(this, null, function* () {
1735
+ resendVerificationCode(_0) {
1736
+ return __async(this, arguments, function* ({
1737
+ type: reason = "SIGNUP"
1738
+ }) {
1739
+ let type, linkedAccountId;
1740
+ switch (reason) {
1741
+ case "SIGNUP":
1742
+ case "LOGIN":
1743
+ {
1744
+ const authInfo = this.assertIsAuthSet(["email", "phone"]);
1745
+ type = authInfo.authType.toUpperCase();
1746
+ }
1747
+ break;
1748
+ case "LINK_ACCOUNT":
1749
+ {
1750
+ const accountLinkInProgress = __privateMethod(this, _ParaCore_instances, assertIsLinkingAccount_fn).call(this, ["EMAIL", "PHONE"]);
1751
+ linkedAccountId = accountLinkInProgress.id;
1752
+ type = accountLinkInProgress.type;
1753
+ }
1754
+ break;
1755
+ }
1756
+ const userId = this.assertUserId({ allowGuestMode: true });
1757
+ if (type !== "EMAIL" && type !== "PHONE") {
1758
+ throw new Error("invalid auth type for verification code");
1759
+ }
1363
1760
  yield this.ctx.client.resendVerificationCode(__spreadValues({
1364
- userId: this.userId
1761
+ userId,
1762
+ type,
1763
+ linkedAccountId
1365
1764
  }, this.getVerificationEmailProps()));
1366
1765
  });
1367
1766
  }
@@ -1374,7 +1773,14 @@ const _ParaCore = class _ParaCore {
1374
1773
  if (this.externalWalletConnectionType === "CONNECTION_ONLY") {
1375
1774
  return true;
1376
1775
  }
1377
- const { isAuthenticated } = yield this.touchSession();
1776
+ const { isAuthenticated, verifiedExternalWalletAddresses } = yield this.touchSession();
1777
+ if (this.externalWalletConnectionType === "VERIFICATION") {
1778
+ if (!verifiedExternalWalletAddresses) {
1779
+ return false;
1780
+ }
1781
+ const externalAddresses = Object.values(this.externalWallets).map((w) => w.id);
1782
+ return externalAddresses.every((address) => verifiedExternalWalletAddresses.includes(address));
1783
+ }
1378
1784
  return !!isAuthenticated;
1379
1785
  });
1380
1786
  }
@@ -1385,12 +1791,18 @@ const _ParaCore = class _ParaCore {
1385
1791
  isFullyLoggedIn() {
1386
1792
  return __async(this, null, function* () {
1387
1793
  if (this.externalWalletConnectionType === "CONNECTION_ONLY") {
1794
+ if (!this.isReady) {
1795
+ yield this.ready();
1796
+ }
1388
1797
  return true;
1389
1798
  }
1390
1799
  if (this.isGuestMode) {
1391
1800
  return true;
1392
1801
  }
1393
1802
  const isSessionActive = yield this.isSessionActive();
1803
+ if (this.externalWalletConnectionType === "VERIFICATION") {
1804
+ return isSessionActive;
1805
+ }
1394
1806
  return isSessionActive && (this.isNoWalletConfig || this.currentWalletIdsArray.length > 0 && this.currentWalletIdsArray.reduce((acc, [id]) => acc && !!this.wallets[id], true));
1395
1807
  });
1396
1808
  }
@@ -1398,10 +1810,13 @@ const _ParaCore = class _ParaCore {
1398
1810
  return __privateGet(this, _ParaCore_instances, guestWalletIdsArray_get).length > 0 && Object.values(this.wallets).every(
1399
1811
  ({ userId, partnerId }) => {
1400
1812
  var _a;
1401
- return partnerId === ((_a = __privateGet(this, _partner)) == null ? void 0 : _a.id) && (!userId || userId !== this.userId);
1813
+ return partnerId === ((_a = this.partner) == null ? void 0 : _a.id) && (!userId || userId !== this.userId);
1402
1814
  }
1403
1815
  );
1404
1816
  }
1817
+ /**
1818
+ * Get the auth methods available to an existing user
1819
+ */
1405
1820
  supportedAuthMethods(auth) {
1406
1821
  return __async(this, null, function* () {
1407
1822
  const { supportedAuthMethods } = yield this.ctx.client.getSupportedAuthMethods(auth);
@@ -1495,36 +1910,47 @@ const _ParaCore = class _ParaCore {
1495
1910
  });
1496
1911
  }
1497
1912
  /**
1498
- * Initiates a Farcaster login attempt and return the URI for the user to connect.
1913
+ * Initiates a Farcaster login attempt and returns the URL for the user to connect.
1499
1914
  * You can create a QR code with this URI that works with Farcaster's mobile app.
1500
1915
  * @return {string} the Farcaster connect URI
1501
1916
  */
1502
1917
  getFarcasterConnectUri() {
1503
- return __async(this, null, function* () {
1504
- const {
1505
- data: { connect_uri: connectUri }
1506
- } = yield this.ctx.client.initializeFarcasterLogin();
1918
+ return __async(this, arguments, function* ({ appScheme } = {}) {
1919
+ const { connect_uri: connectUri } = yield this.ctx.client.initializeFarcasterLogin({ appScheme });
1507
1920
  return connectUri;
1508
1921
  });
1509
1922
  }
1923
+ // FARCASTER
1510
1924
  /**
1511
1925
  * Awaits the response from a user's attempt to log in with Farcaster.
1512
1926
  * If successful, this returns the user's Farcaster username and profile picture and indicates whether the user already exists.
1513
1927
  * @return {Object} `{userExists: boolean; username: string; pfpUrl?: string | null }` - the user's information and whether the user already exists.
1514
1928
  */
1515
- verifyFarcaster(_g) {
1929
+ verifyFarcasterProcess(_g) {
1516
1930
  return __async(this, null, function* () {
1517
1931
  var _h = _g, {
1518
1932
  isCanceled = () => false,
1519
1933
  onConnectUri,
1520
1934
  onCancel,
1521
- onPoll
1935
+ onPoll,
1936
+ isLinkAccount,
1937
+ serverAuthState: optsServerAuthState
1522
1938
  } = _h, urlOptions = __objRest(_h, [
1523
1939
  "isCanceled",
1524
1940
  "onConnectUri",
1525
1941
  "onCancel",
1526
- "onPoll"
1942
+ "onPoll",
1943
+ "isLinkAccount",
1944
+ "serverAuthState"
1527
1945
  ]);
1946
+ if (optsServerAuthState) {
1947
+ const authState = yield __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, optsServerAuthState, urlOptions);
1948
+ return authState;
1949
+ }
1950
+ let accountLinkInProgress;
1951
+ if (isLinkAccount) {
1952
+ accountLinkInProgress = yield __privateMethod(this, _ParaCore_instances, assertIsLinkingAccountOrStart_fn).call(this, "FARCASTER");
1953
+ }
1528
1954
  if (onConnectUri) {
1529
1955
  const connectUri = yield this.getFarcasterConnectUri();
1530
1956
  onConnectUri(connectUri);
@@ -1536,53 +1962,55 @@ const _ParaCore = class _ParaCore {
1536
1962
  try {
1537
1963
  if (isCanceled() || Date.now() - startedAt > constants.POLLING_TIMEOUT_MS) {
1538
1964
  onCancel == null ? void 0 : onCancel();
1539
- return reject("canceled");
1965
+ return reject("CANCELED");
1540
1966
  }
1541
1967
  yield new Promise((_resolve) => setTimeout(_resolve, constants.POLLING_INTERVAL_MS));
1542
- const serverAuthState = yield this.ctx.client.getFarcasterAuthStatus();
1543
- if ((0, import_utils2.isServerAuthState)(serverAuthState)) {
1544
- const authState = yield __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
1545
- return resolve(authState);
1968
+ switch (isLinkAccount) {
1969
+ case false:
1970
+ {
1971
+ const serverAuthState = yield this.ctx.client.getFarcasterAuthStatus();
1972
+ if ((0, import_utils2.isServerAuthState)(serverAuthState)) {
1973
+ const authState = yield __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
1974
+ return resolve(authState);
1975
+ }
1976
+ }
1977
+ break;
1978
+ case true: {
1979
+ const result = yield this.verifyLink({
1980
+ accountLinkInProgress
1981
+ });
1982
+ if ("isConflict" in result) {
1983
+ throw new Error(import_types.AccountLinkError.Conflict);
1984
+ }
1985
+ return resolve(result);
1986
+ }
1546
1987
  }
1547
1988
  onPoll == null ? void 0 : onPoll();
1548
1989
  } catch (e) {
1549
- console.error(e);
1550
- return reject(e);
1990
+ if (!isLinkAccount || e.message === import_types.AccountLinkError.Conflict) {
1991
+ return reject(e.message);
1992
+ }
1551
1993
  }
1552
1994
  }
1553
1995
  }))();
1554
1996
  });
1555
1997
  });
1556
1998
  }
1557
- /**
1558
- * Generates a URL for the user to log in with OAuth using a desire method.
1559
- *
1560
- * @param {Object} opts the options object
1561
- * @param {TOAuthMethod} opts.method the third-party service to use for OAuth.
1562
- * @param {string} [opts.deeplinkUrl] the deeplink to redirect to after the OAuth flow. This is for mobile only.
1563
- * @returns {string} the URL for the user to log in with OAuth.
1564
- */
1565
- getOAuthUrl(_i) {
1999
+ verifyFarcaster(opts) {
2000
+ return __async(this, null, function* () {
2001
+ return yield this.verifyFarcasterProcess(__spreadProps(__spreadValues({}, opts), { isLinkAccount: false }));
2002
+ });
2003
+ }
2004
+ verifyFarcasterLink(opts) {
2005
+ return __async(this, null, function* () {
2006
+ return yield this.verifyFarcasterProcess(__spreadProps(__spreadValues({}, opts), { isLinkAccount: true }));
2007
+ });
2008
+ }
2009
+ getOAuthUrl(opts) {
1566
2010
  return __async(this, null, function* () {
1567
- var _j = _i, { method, deeplinkUrl } = _j, params = __objRest(_j, ["method", "deeplinkUrl"]);
1568
2011
  var _a;
1569
- if (deeplinkUrl) {
1570
- try {
1571
- new URL(deeplinkUrl);
1572
- } catch (e) {
1573
- throw new Error("Invalid deeplink URL");
1574
- }
1575
- }
1576
- const sessionLookupId = (_a = params.sessionLookupId) != null ? _a : yield __privateMethod(this, _ParaCore_instances, prepareLogin_fn).call(this);
1577
- return (0, import_utils2.constructUrl)({
1578
- base: (0, import_userManagementClient.getBaseOAuthUrl)(this.ctx.env),
1579
- path: `/auth/${method}`,
1580
- params: {
1581
- apiKey: this.ctx.apiKey,
1582
- sessionLookupId,
1583
- deeplinkUrl
1584
- }
1585
- });
2012
+ const sessionLookupId = (_a = opts.sessionLookupId) != null ? _a : yield this.prepareLogin();
2013
+ return __privateMethod(this, _ParaCore_instances, getOAuthUrl_fn).call(this, __spreadProps(__spreadValues({}, opts), { sessionLookupId }));
1586
2014
  });
1587
2015
  }
1588
2016
  /**
@@ -1593,28 +2021,54 @@ const _ParaCore = class _ParaCore {
1593
2021
  * @param {Window} [opts.popupWindow] the popup window being used for login.
1594
2022
  * @return {Object} `{ email?: string; isError?: boolean; userExists: boolean; }` the result data
1595
2023
  */
1596
- verifyOAuth(_k) {
2024
+ verifyOAuthProcess(_i) {
1597
2025
  return __async(this, null, function* () {
1598
- var _l = _k, {
2026
+ var _j = _i, {
1599
2027
  method,
1600
- deeplinkUrl,
2028
+ appScheme,
1601
2029
  isCanceled = () => false,
1602
2030
  onCancel,
1603
2031
  onPoll,
1604
- onOAuthUrl
1605
- } = _l, urlOptions = __objRest(_l, [
2032
+ onOAuthUrl,
2033
+ onOAuthPopup,
2034
+ isLinkAccount
2035
+ } = _j, urlOptions = __objRest(_j, [
1606
2036
  "method",
1607
- "deeplinkUrl",
2037
+ "appScheme",
1608
2038
  "isCanceled",
1609
2039
  "onCancel",
1610
2040
  "onPoll",
1611
- "onOAuthUrl"
2041
+ "onOAuthUrl",
2042
+ "onOAuthPopup",
2043
+ "isLinkAccount"
1612
2044
  ]);
1613
- let sessionLookupId;
1614
- if (onOAuthUrl) {
1615
- sessionLookupId = yield __privateMethod(this, _ParaCore_instances, prepareLogin_fn).call(this);
1616
- const oAuthUrl = yield this.getOAuthUrl({ method, deeplinkUrl, sessionLookupId });
1617
- onOAuthUrl(oAuthUrl);
2045
+ if (onOAuthPopup) {
2046
+ try {
2047
+ this.popupWindow = yield this.platformUtils.openPopup("about:blank", { type: import_types.PopupType.OAUTH });
2048
+ } catch (error) {
2049
+ throw new Error(`Failed to open OAuth popup: ${error}`);
2050
+ }
2051
+ }
2052
+ let sessionLookupId, accountLinkInProgress;
2053
+ if (onOAuthUrl || onOAuthPopup) {
2054
+ if (isLinkAccount) {
2055
+ accountLinkInProgress = yield __privateMethod(this, _ParaCore_instances, assertIsLinkingAccountOrStart_fn).call(this, method);
2056
+ sessionLookupId = (yield this.touchSession()).sessionLookupId;
2057
+ } else {
2058
+ sessionLookupId = yield this.prepareLogin();
2059
+ }
2060
+ const oAuthUrl = yield __privateMethod(this, _ParaCore_instances, getOAuthUrl_fn).call(this, { method, appScheme, sessionLookupId, accountLinkInProgress });
2061
+ switch (true) {
2062
+ case !!onOAuthUrl: {
2063
+ onOAuthUrl(oAuthUrl);
2064
+ break;
2065
+ }
2066
+ case (!!onOAuthPopup && !!this.popupWindow): {
2067
+ this.popupWindow.location.href = oAuthUrl;
2068
+ onOAuthPopup(this.popupWindow);
2069
+ break;
2070
+ }
2071
+ }
1618
2072
  } else {
1619
2073
  ({ sessionLookupId } = yield this.touchSession());
1620
2074
  }
@@ -1625,17 +2079,29 @@ const _ParaCore = class _ParaCore {
1625
2079
  try {
1626
2080
  if (isCanceled() || Date.now() - startedAt > constants.POLLING_TIMEOUT_MS) {
1627
2081
  onCancel == null ? void 0 : onCancel();
1628
- return reject("canceled");
2082
+ return reject(import_types.AccountLinkError.Canceled);
1629
2083
  }
1630
2084
  yield new Promise((_resolve) => setTimeout(_resolve, constants.POLLING_INTERVAL_MS));
1631
- const serverAuthState = yield this.ctx.client.verifyOAuth();
1632
- if ((0, import_utils2.isServerAuthState)(serverAuthState)) {
1633
- const authState = yield __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, __spreadProps(__spreadValues({}, urlOptions), { sessionLookupId }));
1634
- return resolve(authState);
2085
+ switch (isLinkAccount) {
2086
+ case false:
2087
+ {
2088
+ const serverAuthState = yield this.ctx.client.verifyOAuth();
2089
+ if ((0, import_utils2.isServerAuthState)(serverAuthState)) {
2090
+ const authState = yield __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, __spreadProps(__spreadValues({}, urlOptions), { sessionLookupId }));
2091
+ return resolve(authState);
2092
+ }
2093
+ }
2094
+ break;
2095
+ case true: {
2096
+ const accounts = yield this.verifyLink({ accountLinkInProgress });
2097
+ return resolve(accounts);
2098
+ }
1635
2099
  }
1636
2100
  onPoll == null ? void 0 : onPoll();
1637
2101
  } catch (err) {
1638
- console.error(err);
2102
+ if (isLinkAccount && err.message === import_types.AccountLinkError.Conflict) {
2103
+ return reject(err.message);
2104
+ }
1639
2105
  onPoll == null ? void 0 : onPoll();
1640
2106
  }
1641
2107
  }
@@ -1643,6 +2109,16 @@ const _ParaCore = class _ParaCore {
1643
2109
  });
1644
2110
  });
1645
2111
  }
2112
+ verifyOAuth(opts) {
2113
+ return __async(this, null, function* () {
2114
+ return yield this.verifyOAuthProcess(__spreadProps(__spreadValues({}, opts), { isLinkAccount: false }));
2115
+ });
2116
+ }
2117
+ verifyOAuthLink(opts) {
2118
+ return __async(this, null, function* () {
2119
+ return yield this.verifyOAuthProcess(__spreadProps(__spreadValues({}, opts), { isLinkAccount: true }));
2120
+ });
2121
+ }
1646
2122
  /**
1647
2123
  * Waits for the session to be active and sets up the user.
1648
2124
  *
@@ -1728,7 +2204,7 @@ const _ParaCore = class _ParaCore {
1728
2204
  sessionId
1729
2205
  });
1730
2206
  if (shouldOpenPopup) {
1731
- this.platformUtils.openPopup(link);
2207
+ yield this.platformUtils.openPopup(link);
1732
2208
  }
1733
2209
  return link;
1734
2210
  });
@@ -1819,7 +2295,9 @@ const _ParaCore = class _ParaCore {
1819
2295
  userId: this.userId,
1820
2296
  walletId,
1821
2297
  userShare: userSigner,
1822
- emailProps: this.getBackupKitEmailProps()
2298
+ emailProps: this.getBackupKitEmailProps(),
2299
+ isEnclaveUser: this.isEnclaveUser,
2300
+ walletScheme: this.wallets[walletId].scheme
1823
2301
  });
1824
2302
  return recoveryShare;
1825
2303
  });
@@ -1947,7 +2425,9 @@ const _ParaCore = class _ParaCore {
1947
2425
  ignoreRedistributingBackupEncryptedShare: !redistributeBackupEncryptedShares,
1948
2426
  emailProps: this.getBackupKitEmailProps(),
1949
2427
  partnerId: newPartnerId,
1950
- protocolId
2428
+ protocolId,
2429
+ isEnclaveUser: this.isEnclaveUser,
2430
+ walletScheme: this.wallets[walletId].scheme
1951
2431
  });
1952
2432
  return { signer, recoverySecret, protocolId };
1953
2433
  });
@@ -2013,7 +2493,9 @@ const _ParaCore = class _ParaCore {
2013
2493
  userId: this.userId,
2014
2494
  walletId: wallet.id,
2015
2495
  userShare: signer,
2016
- emailProps: this.getBackupKitEmailProps()
2496
+ emailProps: this.getBackupKitEmailProps(),
2497
+ isEnclaveUser: this.isEnclaveUser,
2498
+ walletScheme: wallet.scheme
2017
2499
  });
2018
2500
  }
2019
2501
  yield this.setCurrentWalletIds(__spreadProps(__spreadValues({}, this.currentWalletIds), {
@@ -2094,7 +2576,9 @@ const _ParaCore = class _ParaCore {
2094
2576
  walletId: wallet.id,
2095
2577
  userShare: this.wallets[wallet.id].signer,
2096
2578
  emailProps: this.getBackupKitEmailProps(),
2097
- partnerId: wallet.partnerId
2579
+ partnerId: wallet.partnerId,
2580
+ isEnclaveUser: this.isEnclaveUser,
2581
+ walletScheme: wallet.scheme
2098
2582
  });
2099
2583
  if (distributeRes.length > 0) {
2100
2584
  newRecoverySecret = distributeRes;
@@ -2272,25 +2756,12 @@ const _ParaCore = class _ParaCore {
2272
2756
  });
2273
2757
  });
2274
2758
  }
2275
- getOnRampTransactionUrl(_m) {
2276
- return __async(this, null, function* () {
2277
- var _n = _m, {
2278
- purchaseId,
2279
- providerKey
2280
- } = _n, walletParams = __objRest(_n, [
2281
- "purchaseId",
2282
- "providerKey"
2283
- ]);
2284
- const { sessionId } = yield this.touchSession();
2285
- const [key, identifier] = (0, import_user_management_client.extractWalletRef)(walletParams);
2759
+ getOnRampTransactionUrl(_0) {
2760
+ return __async(this, arguments, function* ({
2761
+ purchaseId
2762
+ }) {
2286
2763
  return this.constructPortalUrl("onRamp", {
2287
- pathId: purchaseId,
2288
- sessionId,
2289
- params: {
2290
- [key]: identifier,
2291
- providerKey,
2292
- currentWalletIds: JSON.stringify(this.currentWalletIds)
2293
- }
2764
+ pathId: purchaseId
2294
2765
  });
2295
2766
  });
2296
2767
  }
@@ -2315,6 +2786,7 @@ const _ParaCore = class _ParaCore {
2315
2786
  onCancel,
2316
2787
  onPoll
2317
2788
  }) {
2789
+ var _a;
2318
2790
  this.assertIsValidWalletId(walletId);
2319
2791
  const wallet = this.wallets[walletId];
2320
2792
  let signerId = this.userId;
@@ -2324,7 +2796,7 @@ const _ParaCore = class _ParaCore {
2324
2796
  let signRes = yield this.signMessageInner({ wallet, signerId, messageBase64, cosmosSignDocBase64 });
2325
2797
  let timeStart = Date.now();
2326
2798
  if (signRes.pendingTransactionId) {
2327
- this.platformUtils.openPopup(
2799
+ yield this.platformUtils.openPopup(
2328
2800
  yield this.getTransactionReviewUrl(signRes.pendingTransactionId, timeoutMs),
2329
2801
  { type: cosmosSignDocBase64 ? import_types.PopupType.SIGN_TRANSACTION_REVIEW : import_types.PopupType.SIGN_MESSAGE_REVIEW }
2330
2802
  );
@@ -2338,18 +2810,19 @@ const _ParaCore = class _ParaCore {
2338
2810
  break;
2339
2811
  }
2340
2812
  yield new Promise((resolve) => setTimeout(resolve, constants.POLLING_INTERVAL_MS));
2813
+ let pendingTransaction;
2341
2814
  try {
2342
- yield this.ctx.client.getPendingTransaction(this.userId, signRes.pendingTransactionId);
2815
+ pendingTransaction = (_a = (yield this.ctx.client.getPendingTransaction(this.userId, signRes.pendingTransactionId)).data) == null ? void 0 : _a.pendingTransaction;
2343
2816
  } catch (err) {
2344
2817
  const error = new import_errors.TransactionReviewDenied();
2345
2818
  (0, import_utils2.dispatchEvent)(import_types.ParaEvent.SIGN_MESSAGE_EVENT, signRes, error.message);
2346
2819
  throw error;
2347
2820
  }
2348
- signRes = yield this.signMessageInner({ wallet, signerId, messageBase64, cosmosSignDocBase64 });
2349
- if (signRes.pendingTransactionId) {
2821
+ if (!(pendingTransaction == null ? void 0 : pendingTransaction.approvedAt)) {
2350
2822
  onPoll == null ? void 0 : onPoll();
2351
2823
  continue;
2352
2824
  } else {
2825
+ signRes = yield this.signMessageInner({ wallet, signerId, messageBase64, cosmosSignDocBase64 });
2353
2826
  break;
2354
2827
  }
2355
2828
  }
@@ -2418,6 +2891,7 @@ const _ParaCore = class _ParaCore {
2418
2891
  onCancel,
2419
2892
  onPoll
2420
2893
  }) {
2894
+ var _a;
2421
2895
  this.assertIsValidWalletId(walletId);
2422
2896
  const wallet = this.wallets[walletId];
2423
2897
  let signerId = this.userId;
@@ -2436,7 +2910,7 @@ const _ParaCore = class _ParaCore {
2436
2910
  );
2437
2911
  let timeStart = Date.now();
2438
2912
  if (signRes.pendingTransactionId) {
2439
- this.platformUtils.openPopup(
2913
+ yield this.platformUtils.openPopup(
2440
2914
  yield this.getTransactionReviewUrl(signRes.pendingTransactionId, timeoutMs),
2441
2915
  { type: import_types.PopupType.SIGN_TRANSACTION_REVIEW }
2442
2916
  );
@@ -2450,27 +2924,28 @@ const _ParaCore = class _ParaCore {
2450
2924
  break;
2451
2925
  }
2452
2926
  yield new Promise((resolve) => setTimeout(resolve, constants.POLLING_INTERVAL_MS));
2927
+ let pendingTransaction;
2453
2928
  try {
2454
- yield this.ctx.client.getPendingTransaction(this.userId, signRes.pendingTransactionId);
2929
+ pendingTransaction = (_a = (yield this.ctx.client.getPendingTransaction(this.userId, signRes.pendingTransactionId)).data) == null ? void 0 : _a.pendingTransaction;
2455
2930
  } catch (err) {
2456
2931
  const error = new import_errors.TransactionReviewDenied();
2457
2932
  (0, import_utils2.dispatchEvent)(import_types.ParaEvent.SIGN_TRANSACTION_EVENT, signRes, error.message);
2458
2933
  throw error;
2459
2934
  }
2460
- signRes = yield this.platformUtils.signTransaction(
2461
- this.ctx,
2462
- signerId,
2463
- walletId,
2464
- this.wallets[walletId].signer,
2465
- rlpEncodedTxBase64,
2466
- chainId,
2467
- this.retrieveSessionCookie(),
2468
- wallet.scheme === "DKLS"
2469
- );
2470
- if (signRes.pendingTransactionId) {
2935
+ if (!(pendingTransaction == null ? void 0 : pendingTransaction.approvedAt)) {
2471
2936
  onPoll == null ? void 0 : onPoll();
2472
2937
  continue;
2473
2938
  } else {
2939
+ signRes = yield this.platformUtils.signTransaction(
2940
+ this.ctx,
2941
+ signerId,
2942
+ walletId,
2943
+ this.wallets[walletId].signer,
2944
+ rlpEncodedTxBase64,
2945
+ chainId,
2946
+ this.retrieveSessionCookie(),
2947
+ wallet.scheme === "DKLS"
2948
+ );
2474
2949
  break;
2475
2950
  }
2476
2951
  }
@@ -2512,7 +2987,8 @@ const _ParaCore = class _ParaCore {
2512
2987
  providerKey: onRampPurchase.providerKey
2513
2988
  }, walletParams));
2514
2989
  if (shouldOpenPopup) {
2515
- this.platformUtils.openPopup(portalUrl, { type: import_types.PopupType.ON_RAMP_TRANSACTION });
2990
+ const onRampWindow = yield this.platformUtils.openPopup(portalUrl, { type: import_types.PopupType.ON_RAMP_TRANSACTION });
2991
+ this.onRampPopup = { window: onRampWindow, onRampPurchase };
2516
2992
  }
2517
2993
  return { onRampPurchase, portalUrl };
2518
2994
  });
@@ -2595,6 +3071,20 @@ const _ParaCore = class _ParaCore {
2595
3071
  return sessionLookupId;
2596
3072
  });
2597
3073
  }
3074
+ issueJwt() {
3075
+ return __async(this, arguments, function* ({ keyIndex = 0 } = {}) {
3076
+ try {
3077
+ return yield this.ctx.client.issueJwt({ keyIndex });
3078
+ } catch (error) {
3079
+ if (error.status === 403 || error.status === 401) {
3080
+ const errorMessage = "The user needs to be logged in to issue a JWT. Please log in and try again.";
3081
+ this.displayModalError(errorMessage);
3082
+ console.warn(errorMessage);
3083
+ }
3084
+ throw error;
3085
+ }
3086
+ });
3087
+ }
2598
3088
  /**
2599
3089
  * Logs the user out.
2600
3090
  * @param {Object} opts the options object.
@@ -2602,6 +3092,7 @@ const _ParaCore = class _ParaCore {
2602
3092
  **/
2603
3093
  logout() {
2604
3094
  return __async(this, arguments, function* ({ clearPregenWallets = false } = {}) {
3095
+ const shouldDispatchLogoutEvent = yield this.isSessionActive();
2605
3096
  yield this.ctx.client.logout();
2606
3097
  yield this.clearStorage();
2607
3098
  if (!clearPregenWallets) {
@@ -2618,22 +3109,17 @@ const _ParaCore = class _ParaCore {
2618
3109
  this.externalWallets = {};
2619
3110
  this.loginEncryptionKeyPair = void 0;
2620
3111
  __privateSet(this, _authInfo, void 0);
3112
+ this.accountLinkInProgress = void 0;
2621
3113
  this.userId = void 0;
2622
3114
  this.sessionCookie = void 0;
2623
- (0, import_utils2.dispatchEvent)(import_types.ParaEvent.LOGOUT_EVENT, null);
2624
- });
2625
- }
2626
- /** @deprecated */
2627
- getSupportedCreateAuthMethods() {
2628
- return __async(this, null, function* () {
2629
- const partner = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
2630
- let supportedAuthMethods = /* @__PURE__ */ new Set();
2631
- for (const authMethod of partner.supportedAuthMethods) {
2632
- supportedAuthMethods.add(import_user_management_client.AuthMethod[authMethod]);
3115
+ if (shouldDispatchLogoutEvent) {
3116
+ (0, import_utils2.dispatchEvent)(import_types.ParaEvent.LOGOUT_EVENT, null);
2633
3117
  }
2634
- return supportedAuthMethods;
2635
3118
  });
2636
3119
  }
3120
+ get toStringAdditions() {
3121
+ return {};
3122
+ }
2637
3123
  /**
2638
3124
  * Converts to a string, removing sensitive data when logging this class.
2639
3125
  *
@@ -2657,10 +3143,10 @@ const _ParaCore = class _ParaCore {
2657
3143
  }),
2658
3144
  {}
2659
3145
  );
2660
- const obj = {
2661
- partnerId: (_a = __privateGet(this, _partner)) == null ? void 0 : _a.id,
2662
- supportedWalletTypes: (_b = __privateGet(this, _partner)) == null ? void 0 : _b.supportedWalletTypes,
2663
- cosmosPrefix: (_c = __privateGet(this, _partner)) == null ? void 0 : _c.cosmosPrefix,
3146
+ const obj = __spreadProps(__spreadValues({
3147
+ partnerId: (_a = this.partner) == null ? void 0 : _a.id,
3148
+ supportedWalletTypes: (_b = this.partner) == null ? void 0 : _b.supportedWalletTypes,
3149
+ cosmosPrefix: (_c = this.partner) == null ? void 0 : _c.cosmosPrefix,
2664
3150
  authInfo: __privateGet(this, _authInfo),
2665
3151
  isGuestMode: this.isGuestMode,
2666
3152
  userId: this.userId,
@@ -2670,6 +3156,8 @@ const _ParaCore = class _ParaCore {
2670
3156
  wallets: redactedWallets,
2671
3157
  externalWallets: redactedExternalWallets,
2672
3158
  loginEncryptionKeyPair: this.loginEncryptionKeyPair ? "[REDACTED]" : void 0,
3159
+ isReady: this.isReady
3160
+ }, this.toStringAdditions), {
2673
3161
  ctx: {
2674
3162
  apiKey: this.ctx.apiKey,
2675
3163
  disableWorkers: this.ctx.disableWorkers,
@@ -2680,9 +3168,14 @@ const _ParaCore = class _ParaCore {
2680
3168
  useDKLS: this.ctx.useDKLS,
2681
3169
  cosmosPrefix: this.ctx.cosmosPrefix
2682
3170
  }
2683
- };
3171
+ });
2684
3172
  return `Para ${JSON.stringify(obj, null, 2)}`;
2685
3173
  }
3174
+ devLog(...s) {
3175
+ if (this.ctx.env === import_types.Environment.DEV || this.ctx.env === import_types.Environment.SANDBOX) {
3176
+ console.log(...s);
3177
+ }
3178
+ }
2686
3179
  getNewCredentialAndUrl() {
2687
3180
  return __async(this, arguments, function* ({
2688
3181
  authMethod = "PASSKEY",
@@ -2697,7 +3190,7 @@ const _ParaCore = class _ParaCore {
2697
3190
  ({
2698
3191
  data: { id: credentialId }
2699
3192
  } = yield this.ctx.client.addSessionPublicKey(this.userId, {
2700
- status: import_user_management_client.PublicKeyStatus.PENDING,
3193
+ status: import_user_management_client.AuthMethodStatus.PENDING,
2701
3194
  type: import_user_management_client.PublicKeyType.WEB
2702
3195
  }));
2703
3196
  urlType = "createAuth";
@@ -2706,10 +3199,18 @@ const _ParaCore = class _ParaCore {
2706
3199
  ({
2707
3200
  data: { id: credentialId }
2708
3201
  } = yield this.ctx.client.addSessionPasswordPublicKey(this.userId, {
2709
- status: import_user_management_client.PasswordStatus.PENDING
3202
+ status: import_user_management_client.AuthMethodStatus.PENDING
2710
3203
  }));
2711
3204
  urlType = "createPassword";
2712
3205
  break;
3206
+ case "PIN":
3207
+ ({
3208
+ data: { id: credentialId }
3209
+ } = yield this.ctx.client.addSessionPasswordPublicKey(this.userId, {
3210
+ status: import_user_management_client.AuthMethodStatus.PENDING
3211
+ }));
3212
+ urlType = "createPIN";
3213
+ break;
2713
3214
  }
2714
3215
  const url = this.isNativePasskey && urlType === "createAuth" ? void 0 : yield this.constructPortalUrl(urlType, {
2715
3216
  isForNewDevice,
@@ -2721,7 +3222,7 @@ const _ParaCore = class _ParaCore {
2721
3222
  });
2722
3223
  }
2723
3224
  /**
2724
- * Returns a Para Portal URL for logging in with a WebAuth passkey or a password.
3225
+ * Returns a Para Portal URL for logging in with a WebAuth passkey, password, PIN or OTP.
2725
3226
  * @param {Object} opts the options object
2726
3227
  * @param {String} opts.auth - the user auth to sign up or log in with, in the form ` { email: string } | { phone: `+${number}` } `
2727
3228
  * @param {boolean} opts.useShortUrls - whether to shorten the generated portal URLs
@@ -2747,6 +3248,12 @@ const _ParaCore = class _ParaCore {
2747
3248
  case "PASSWORD":
2748
3249
  urlType = "loginPassword";
2749
3250
  break;
3251
+ case "PIN":
3252
+ urlType = "loginPIN";
3253
+ break;
3254
+ case "BASIC_LOGIN":
3255
+ urlType = "loginOTP";
3256
+ break;
2750
3257
  default:
2751
3258
  throw new Error(`invalid authentication method: '${authMethod}'`);
2752
3259
  }
@@ -2757,53 +3264,214 @@ const _ParaCore = class _ParaCore {
2757
3264
  });
2758
3265
  });
2759
3266
  }
2760
- signUpOrLogIn(_o) {
3267
+ prepareLogin() {
2761
3268
  return __async(this, null, function* () {
2762
- var _p = _o, { auth } = _p, urlOptions = __objRest(_p, ["auth"]);
2763
- const serverAuthState = yield this.ctx.client.signUpOrLogIn(__spreadValues(__spreadValues({}, auth), this.getVerificationEmailProps()));
2764
- return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
3269
+ yield this.logout();
3270
+ const { sessionLookupId } = yield this.touchSession(true);
3271
+ if (!this.loginEncryptionKeyPair) {
3272
+ yield this.setLoginEncryptionKeyPair();
3273
+ }
3274
+ return sessionLookupId;
2765
3275
  });
2766
3276
  }
2767
- verifyNewAccount(_q) {
3277
+ signUpOrLogIn(_k) {
2768
3278
  return __async(this, null, function* () {
2769
- var _r = _q, {
3279
+ var _l = _k, { auth } = _l, urlOptions = __objRest(_l, ["auth"]);
3280
+ let serverAuthState;
3281
+ try {
3282
+ serverAuthState = yield this.ctx.client.signUpOrLogIn(__spreadValues(__spreadValues({}, auth), this.getVerificationEmailProps()));
3283
+ } catch (error) {
3284
+ if (error.message.includes("max beta users reached")) {
3285
+ this.displayModalError(
3286
+ `50 user limit reached. [Go to Production.](https://docs.getpara.com/v2/general/checklist#go-live-checklist)`
3287
+ );
3288
+ }
3289
+ throw error;
3290
+ }
3291
+ const authInfo = serverAuthState.auth;
3292
+ if (this.fetchPregenWalletsOverride && (0, import_user_management_client.isPregenAuth)(authInfo)) {
3293
+ const { userShare } = yield this.fetchPregenWalletsOverride({ pregenId: authInfo });
3294
+ if (userShare) {
3295
+ yield this.setUserShare(userShare);
3296
+ }
3297
+ }
3298
+ return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, __spreadValues({}, urlOptions));
3299
+ });
3300
+ }
3301
+ verifyNewAccount(_m) {
3302
+ return __async(this, null, function* () {
3303
+ var _n = _m, {
2770
3304
  verificationCode
2771
- } = _r, urlOptions = __objRest(_r, [
3305
+ } = _n, urlOptions = __objRest(_n, [
2772
3306
  "verificationCode"
2773
3307
  ]);
2774
3308
  this.assertIsAuthSet(["email", "phone"]);
2775
- const userId = this.assertUserId();
2776
- const serverAuthState = yield this.ctx.client.verifyNewAccount(userId, {
3309
+ const userId = this.assertUserId({ allowGuestMode: true });
3310
+ const serverAuthState = yield this.ctx.client.verifyAccount(userId, {
2777
3311
  verificationCode
2778
3312
  });
3313
+ if (serverAuthState.stage === "login" || serverAuthState.stage === "done") {
3314
+ throw new Error("Account already exists.");
3315
+ }
3316
+ yield this.touchSession(true);
2779
3317
  return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
2780
3318
  });
2781
3319
  }
3320
+ getLinkedAccounts() {
3321
+ return __async(this, arguments, function* ({
3322
+ withMetadata = false
3323
+ } = {}) {
3324
+ const userId = this.assertUserId();
3325
+ const { accounts } = yield this.ctx.client.getLinkedAccounts({ userId, withMetadata });
3326
+ return __spreadValues({
3327
+ userId
3328
+ }, accounts);
3329
+ });
3330
+ }
3331
+ linkAccount(opts) {
3332
+ return __async(this, null, function* () {
3333
+ const { supportedAccountLinks = [...import_user_management_client.LINKED_ACCOUNT_TYPES] } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
3334
+ let type, identifier, externalWallet, isPermitted;
3335
+ switch (true) {
3336
+ case "auth" in opts:
3337
+ {
3338
+ const authInfo = (0, import_user_management_client.extractAuthInfo)(opts.auth, { isRequired: true });
3339
+ if (authInfo.auth === this.authInfo.auth) {
3340
+ throw new Error(import_types.AccountLinkError.Conflict);
3341
+ }
3342
+ type = authInfo.authType.toUpperCase();
3343
+ identifier = authInfo.identifier;
3344
+ isPermitted = supportedAccountLinks.includes(type);
3345
+ }
3346
+ break;
3347
+ case "externalWallet" in opts:
3348
+ {
3349
+ externalWallet = opts.externalWallet;
3350
+ type = "EXTERNAL_WALLET";
3351
+ isPermitted = supportedAccountLinks.includes("EXTERNAL_WALLET") || supportedAccountLinks.includes(externalWallet.providerId);
3352
+ }
3353
+ break;
3354
+ case "type" in opts:
3355
+ {
3356
+ type = opts.type;
3357
+ if (type === "X") {
3358
+ type = "TWITTER";
3359
+ }
3360
+ isPermitted = supportedAccountLinks.includes(type);
3361
+ }
3362
+ break;
3363
+ default:
3364
+ throw new Error("Invalid parameters for linking account, must pass `auth` or `type` or `externalWallet`");
3365
+ }
3366
+ if (!isPermitted) {
3367
+ throw new Error(`Account linking for type '${type}' is not supported by the current API key configuration`);
3368
+ }
3369
+ const userId = this.assertUserId();
3370
+ const result = yield this.ctx.client.linkAccount(__spreadValues(__spreadValues({
3371
+ userId,
3372
+ type
3373
+ }, identifier ? { identifier } : {}), externalWallet ? { externalWallet } : {}));
3374
+ if ("isConflict" in result) {
3375
+ throw new Error(import_types.AccountLinkError.Conflict);
3376
+ }
3377
+ const { linkedAccountId, signatureVerificationMessage } = result;
3378
+ this.accountLinkInProgress = __spreadValues(__spreadValues({
3379
+ id: linkedAccountId,
3380
+ type,
3381
+ isComplete: false
3382
+ }, identifier ? { identifier } : {}), signatureVerificationMessage && externalWallet ? {
3383
+ externalWallet: __spreadProps(__spreadValues({}, externalWallet), {
3384
+ signatureVerificationMessage
3385
+ })
3386
+ } : {});
3387
+ return this.accountLinkInProgress;
3388
+ });
3389
+ }
3390
+ unlinkAccount(_0) {
3391
+ return __async(this, arguments, function* ({
3392
+ linkedAccountId
3393
+ }) {
3394
+ if (!linkedAccountId) {
3395
+ throw new Error("No linked account ID provided");
3396
+ }
3397
+ const userId = this.assertUserId();
3398
+ const accounts = yield this.ctx.client.unlinkAccount({ linkedAccountId, userId });
3399
+ return accounts;
3400
+ });
3401
+ }
3402
+ verifyLink() {
3403
+ return __async(this, arguments, function* (_o = {}) {
3404
+ var _p = _o, {
3405
+ accountLinkInProgress = __privateMethod(this, _ParaCore_instances, assertIsLinkingAccount_fn).call(this)
3406
+ } = _p, opts = __objRest(_p, [
3407
+ "accountLinkInProgress"
3408
+ ]);
3409
+ try {
3410
+ const userId = this.assertUserId(), result = yield this.ctx.client.verifyLink(__spreadValues({
3411
+ linkedAccountId: accountLinkInProgress.id,
3412
+ userId
3413
+ }, opts));
3414
+ if ("isConflict" in result) {
3415
+ throw new Error(import_types.AccountLinkError.Conflict);
3416
+ }
3417
+ this.accountLinkInProgress = void 0;
3418
+ return result.accounts;
3419
+ } catch (e) {
3420
+ throw new Error(e.message === import_types.AccountLinkError.Conflict ? import_types.AccountLinkError.Conflict : e.message);
3421
+ }
3422
+ });
3423
+ }
3424
+ verifyEmailOrPhoneLink(_0) {
3425
+ return __async(this, arguments, function* ({
3426
+ verificationCode
3427
+ }) {
3428
+ const accounts = yield this.verifyLink({
3429
+ accountLinkInProgress: __privateMethod(this, _ParaCore_instances, assertIsLinkingAccount_fn).call(this, ["EMAIL", "PHONE"]),
3430
+ verificationCode
3431
+ });
3432
+ return accounts;
3433
+ });
3434
+ }
3435
+ getProfileBalance() {
3436
+ return __async(this, arguments, function* ({ config, refetch = false } = {}) {
3437
+ const { balance } = yield this.ctx.client.getProfileBalance({
3438
+ config,
3439
+ wallets: this.availableWallets.map(({ type, address }) => ({ type, address })),
3440
+ refetch
3441
+ });
3442
+ return balance;
3443
+ });
3444
+ }
3445
+ sendLoginCode() {
3446
+ return __async(this, null, function* () {
3447
+ const { userId } = yield this.ctx.client.sendLoginVerificationCode(this.authInfo);
3448
+ this.setUserId(userId);
3449
+ });
3450
+ }
2782
3451
  };
2783
3452
  _authInfo = new WeakMap();
2784
- _partner = new WeakMap();
2785
3453
  _ParaCore_instances = new WeakSet();
2786
3454
  assertPartner_fn = function() {
2787
3455
  return __async(this, null, function* () {
2788
3456
  var _a, _b;
2789
- if (!__privateGet(this, _partner)) {
3457
+ if (!this.partner) {
2790
3458
  yield this.touchSession();
2791
3459
  }
2792
- if (((_a = __privateGet(this, _partner)) == null ? void 0 : _a.cosmosPrefix) && this.ctx.cosmosPrefix !== __privateGet(this, _partner).cosmosPrefix) {
2793
- this.ctx.cosmosPrefix = (_b = __privateGet(this, _partner)) == null ? void 0 : _b.cosmosPrefix;
3460
+ if (((_a = this.partner) == null ? void 0 : _a.cosmosPrefix) && this.ctx.cosmosPrefix !== this.partner.cosmosPrefix) {
3461
+ this.ctx.cosmosPrefix = (_b = this.partner) == null ? void 0 : _b.cosmosPrefix;
2794
3462
  }
2795
- return __privateGet(this, _partner);
3463
+ return this.partner;
2796
3464
  });
2797
3465
  };
2798
3466
  guestWalletIds_get = function() {
2799
3467
  var _a, _b, _c;
2800
- if (!((_a = __privateGet(this, _partner)) == null ? void 0 : _a.supportedWalletTypes)) {
3468
+ if (!((_a = this.partner) == null ? void 0 : _a.supportedWalletTypes)) {
2801
3469
  return {};
2802
3470
  }
2803
3471
  const guestId = (_c = (_b = this.pregenIds) == null ? void 0 : _b.GUEST_ID) == null ? void 0 : _c[0];
2804
3472
  return !!guestId ? Object.entries(this.wallets).reduce((acc, [id, wallet]) => {
2805
3473
  if (wallet.isPregen && !wallet.userId && wallet.pregenIdentifierType === "GUEST_ID" && wallet.pregenIdentifier === guestId) {
2806
- return __spreadValues(__spreadValues({}, acc), (0, import_utils2.getEquivalentTypes)(wallet.type).filter((type) => __privateGet(this, _partner).supportedWalletTypes.some((entry) => entry.type === type)).reduce((acc2, eqType) => {
3474
+ return __spreadValues(__spreadValues({}, acc), (0, import_utils2.getEquivalentTypes)(wallet.type).filter((type) => this.partner.supportedWalletTypes.some((entry) => entry.type === type)).reduce((acc2, eqType) => {
2807
3475
  var _a2;
2808
3476
  return __spreadProps(__spreadValues({}, acc2), { [eqType]: [.../* @__PURE__ */ new Set([...(_a2 = acc2[eqType]) != null ? _a2 : [], id])] });
2809
3477
  }, {}));
@@ -2860,9 +3528,70 @@ setAuthInfo_fn = function(authInfo) {
2860
3528
  };
2861
3529
  getPartner_fn = function(partnerId) {
2862
3530
  return __async(this, null, function* () {
3531
+ if (this.isPartnerOptional && !partnerId) {
3532
+ return void 0;
3533
+ }
2863
3534
  const res = yield this.ctx.client.getPartner(partnerId);
2864
- __privateSet(this, _partner, res.data.partner);
2865
- return __privateGet(this, _partner);
3535
+ this.partner = res.data.partner;
3536
+ return this.partner;
3537
+ });
3538
+ };
3539
+ assertIsLinkingAccount_fn = function(types) {
3540
+ if (!this.accountLinkInProgress || this.accountLinkInProgress.isComplete) {
3541
+ throw new Error("no account linking in progress");
3542
+ }
3543
+ if (types && !types.includes(this.accountLinkInProgress.type)) {
3544
+ throw new Error(
3545
+ `account linking in progress for type ${this.accountLinkInProgress.type}, expected one of ${types.join(", ")}`
3546
+ );
3547
+ }
3548
+ return this.accountLinkInProgress;
3549
+ };
3550
+ assertIsLinkingAccountOrStart_fn = function(type) {
3551
+ return __async(this, null, function* () {
3552
+ if (this.accountLinkInProgress && !this.accountLinkInProgress.isComplete) {
3553
+ return __privateMethod(this, _ParaCore_instances, assertIsLinkingAccount_fn).call(this, [type]);
3554
+ }
3555
+ return yield this.linkAccount({ type });
3556
+ });
3557
+ };
3558
+ getOAuthUrl_fn = function(_0) {
3559
+ return __async(this, arguments, function* ({
3560
+ method,
3561
+ appScheme,
3562
+ accountLinkInProgress,
3563
+ sessionLookupId,
3564
+ encryptionKey
3565
+ }) {
3566
+ if (!accountLinkInProgress && !this.isPortal()) {
3567
+ return yield this.constructPortalUrl("oAuth", { sessionId: sessionLookupId, oAuthMethod: method, appScheme });
3568
+ }
3569
+ let portalSessionLookupId;
3570
+ if (this.isPortal()) {
3571
+ portalSessionLookupId = (yield this.touchSession(true)).sessionLookupId;
3572
+ }
3573
+ return (0, import_utils2.constructUrl)({
3574
+ base: (0, import_userManagementClient.getBaseOAuthUrl)(this.ctx.env),
3575
+ path: `/auth/${method.toLowerCase()}`,
3576
+ params: __spreadProps(__spreadValues({
3577
+ apiKey: this.ctx.apiKey,
3578
+ sessionLookupId,
3579
+ portalSessionLookupId,
3580
+ appScheme
3581
+ }, accountLinkInProgress ? {
3582
+ linkedAccountId: this.accountLinkInProgress.id
3583
+ } : {}), {
3584
+ callback: !accountLinkInProgress && (yield this.constructPortalUrl("oAuthCallback", {
3585
+ sessionId: sessionLookupId,
3586
+ oAuthMethod: method,
3587
+ appScheme,
3588
+ thisDevice: {
3589
+ sessionId: sessionLookupId,
3590
+ encryptionKey
3591
+ }
3592
+ }))
3593
+ })
3594
+ });
2866
3595
  });
2867
3596
  };
2868
3597
  createPregenWallet_fn = function(opts) {
@@ -2915,8 +3644,9 @@ createPregenWallet_fn = function(opts) {
2915
3644
  _isCreateGuestWalletsPending = new WeakMap();
2916
3645
  prepareAuthState_fn = function(_0) {
2917
3646
  return __async(this, arguments, function* (serverAuthState, opts = {}) {
2918
- if (!opts.sessionLookupId && serverAuthState.stage === "login") {
2919
- opts.sessionLookupId = yield __privateMethod(this, _ParaCore_instances, prepareLogin_fn).call(this);
3647
+ var _a, _b;
3648
+ if (!opts.sessionLookupId && serverAuthState.stage === "login" && (!serverAuthState.externalWallet || !(((_a = serverAuthState.externalWallet) == null ? void 0 : _a.withFullParaAuth) && ((_b = serverAuthState.loginAuthMethods) == null ? void 0 : _b.includes(import_user_management_client.AuthMethod.PIN))))) {
3649
+ opts.sessionLookupId = yield this.prepareLogin();
2920
3650
  }
2921
3651
  const { auth, externalWallet, userId, displayName, pfpUrl, username } = serverAuthState;
2922
3652
  const authInfo = __spreadValues(__spreadValues({}, (0, import_user_management_client.extractAuthInfo)(auth, { isRequired: true })), Object.fromEntries(
@@ -2930,34 +3660,68 @@ prepareAuthState_fn = function(_0) {
2930
3660
  yield __privateMethod(this, _ParaCore_instances, setAuthInfo_fn).call(this, authInfo);
2931
3661
  yield this.assertIsAuthSet();
2932
3662
  if (!!externalWallet) {
2933
- yield this.setExternalWallet(externalWallet);
3663
+ yield this.setExternalWallet([externalWallet]);
2934
3664
  }
2935
3665
  if (!!userId) {
2936
3666
  yield this.setUserId(userId);
2937
3667
  }
2938
3668
  let authState;
2939
3669
  switch (serverAuthState.stage) {
3670
+ case "done": {
3671
+ authState = yield __privateMethod(this, _ParaCore_instances, prepareDoneState_fn).call(this, serverAuthState);
3672
+ break;
3673
+ }
2940
3674
  case "verify":
2941
- authState = serverAuthState;
3675
+ authState = yield __privateMethod(this, _ParaCore_instances, prepareVerificationState_fn).call(this, serverAuthState, __spreadProps(__spreadValues({}, opts), {
3676
+ sessionLookupId: opts.sessionLookupId
3677
+ }));
2942
3678
  break;
2943
3679
  case "login":
3680
+ if (externalWallet && !(externalWallet == null ? void 0 : externalWallet.withFullParaAuth)) {
3681
+ authState = serverAuthState;
3682
+ break;
3683
+ }
2944
3684
  authState = yield __privateMethod(this, _ParaCore_instances, prepareLoginState_fn).call(this, serverAuthState, __spreadProps(__spreadValues({}, opts), { sessionLookupId: opts.sessionLookupId }));
2945
3685
  break;
2946
3686
  case "signup":
3687
+ if (externalWallet && !(externalWallet == null ? void 0 : externalWallet.withFullParaAuth)) {
3688
+ authState = serverAuthState;
3689
+ break;
3690
+ }
2947
3691
  authState = yield __privateMethod(this, _ParaCore_instances, prepareSignUpState_fn).call(this, serverAuthState, opts);
2948
3692
  break;
2949
3693
  }
2950
3694
  return authState;
2951
3695
  });
2952
3696
  };
2953
- prepareLogin_fn = function() {
3697
+ prepareDoneState_fn = function(doneState) {
2954
3698
  return __async(this, null, function* () {
2955
- yield this.logout();
2956
- const { sessionLookupId } = yield this.touchSession(true);
2957
- if (!this.loginEncryptionKeyPair) {
2958
- yield this.setLoginEncryptionKeyPair();
3699
+ let isSLOPossible = doneState.authMethods.includes(import_user_management_client.AuthMethod.BASIC_LOGIN);
3700
+ this.isEnclaveUser = isSLOPossible;
3701
+ return doneState;
3702
+ });
3703
+ };
3704
+ prepareVerificationState_fn = function(_0, _1) {
3705
+ return __async(this, arguments, function* (verifyState, {
3706
+ useShortUrls: shorten = false,
3707
+ portalTheme,
3708
+ sessionLookupId
3709
+ }) {
3710
+ let isSLOPossible = false;
3711
+ if (verifyState.nextStage === "login") {
3712
+ isSLOPossible = verifyState.loginAuthMethods.includes(import_user_management_client.AuthMethod.BASIC_LOGIN);
3713
+ } else if (verifyState.nextStage === "signup") {
3714
+ isSLOPossible = verifyState.signupAuthMethods.includes(import_user_management_client.AuthMethod.BASIC_LOGIN);
2959
3715
  }
2960
- return sessionLookupId;
3716
+ this.isEnclaveUser = isSLOPossible;
3717
+ return __spreadValues(__spreadValues({}, verifyState), isSLOPossible ? {
3718
+ loginUrl: yield this.getLoginUrl({
3719
+ authMethod: import_user_management_client.AuthMethod.BASIC_LOGIN,
3720
+ sessionId: sessionLookupId,
3721
+ shorten,
3722
+ portalTheme
3723
+ })
3724
+ } : {});
2961
3725
  });
2962
3726
  };
2963
3727
  prepareLoginState_fn = function(_0, _1) {
@@ -2966,8 +3730,12 @@ prepareLoginState_fn = function(_0, _1) {
2966
3730
  portalTheme,
2967
3731
  sessionLookupId
2968
3732
  }) {
2969
- const _a = loginState, { loginAuthMethods } = _a, authState = __objRest(_a, ["loginAuthMethods"]);
2970
- return __spreadValues(__spreadValues(__spreadValues({}, authState), !this.isNativePasskey && loginAuthMethods.includes(import_user_management_client.AuthMethod.PASSKEY) ? {
3733
+ const _a = loginState, { loginAuthMethods = [], hasPasswordWithoutPIN } = _a, authState = __objRest(_a, ["loginAuthMethods", "hasPasswordWithoutPIN"]);
3734
+ const isPasskeySupported = yield this.isPasskeySupported(), isPasskeyPossible = loginAuthMethods.includes(import_user_management_client.AuthMethod.PASSKEY) && !this.isNativePasskey, isPasswordPossible = loginAuthMethods.includes(import_user_management_client.AuthMethod.PASSWORD) && hasPasswordWithoutPIN, isPINPossible = loginAuthMethods.includes(import_user_management_client.AuthMethod.PIN);
3735
+ return __spreadValues(__spreadValues(__spreadValues(__spreadProps(__spreadValues({}, authState), {
3736
+ isPasskeySupported,
3737
+ loginAuthMethods
3738
+ }), isPasskeyPossible ? {
2971
3739
  passkeyUrl: yield this.getLoginUrl({ sessionId: sessionLookupId, shorten, portalTheme }),
2972
3740
  passkeyKnownDeviceUrl: yield this.constructPortalUrl("loginAuth", {
2973
3741
  sessionId: sessionLookupId,
@@ -2978,28 +3746,41 @@ prepareLoginState_fn = function(_0, _1) {
2978
3746
  shorten,
2979
3747
  portalTheme
2980
3748
  })
2981
- } : {}), loginAuthMethods.includes(import_user_management_client.AuthMethod.PASSWORD) ? {
3749
+ } : {}), isPasswordPossible ? {
2982
3750
  passwordUrl: yield this.constructPortalUrl("loginPassword", {
2983
3751
  sessionId: sessionLookupId,
2984
3752
  shorten,
2985
- portalTheme
3753
+ portalTheme,
3754
+ params: { isEmbedded: `${!loginState.isWalletSelectionNeeded}` }
3755
+ })
3756
+ } : {}), isPINPossible ? {
3757
+ pinUrl: yield this.constructPortalUrl("loginPIN", {
3758
+ sessionId: sessionLookupId,
3759
+ shorten,
3760
+ portalTheme,
3761
+ params: { isEmbedded: `${!loginState.isWalletSelectionNeeded}` }
2986
3762
  })
2987
3763
  } : {});
2988
3764
  });
2989
3765
  };
2990
3766
  prepareSignUpState_fn = function(_0, _1) {
2991
3767
  return __async(this, arguments, function* (serverSignupState, { useShortUrls: shorten = false, portalTheme }) {
2992
- const _a = serverSignupState, { signupAuthMethods } = _a, authState = __objRest(_a, ["signupAuthMethods"]);
2993
- const [isPasskey, isPassword] = [
3768
+ const _a = serverSignupState, { signupAuthMethods = [] } = _a, authState = __objRest(_a, ["signupAuthMethods"]);
3769
+ const isPasskeySupported = yield this.isPasskeySupported();
3770
+ const [isPasskey, isPassword, isPIN] = [
2994
3771
  signupAuthMethods.includes(import_user_management_client.AuthMethod.PASSKEY),
2995
- signupAuthMethods.includes(import_user_management_client.AuthMethod.PASSWORD)
3772
+ signupAuthMethods.includes(import_user_management_client.AuthMethod.PASSWORD) || !isPasskeySupported,
3773
+ signupAuthMethods.includes(import_user_management_client.AuthMethod.PIN)
2996
3774
  ];
2997
- if (!isPasskey && !isPassword) {
3775
+ if (!isPasskey && !isPassword && !isPIN) {
2998
3776
  throw new Error(
2999
- "No supported authentication methods found. Please ensure you have enabled either WebAuth passkeys or passwords in your Developer Portal settings."
3777
+ "No supported authentication methods found. Please ensure you have enabled either WebAuth passkeys, passwords or PINs in your Developer Portal settings."
3000
3778
  );
3001
3779
  }
3002
- const signupState = authState;
3780
+ const signupState = __spreadProps(__spreadValues({}, authState), {
3781
+ isPasskeySupported,
3782
+ signupAuthMethods
3783
+ });
3003
3784
  if (isPasskey) {
3004
3785
  const { url: passkeyUrl, credentialId: passkeyId } = yield this.getNewCredentialAndUrl({
3005
3786
  authMethod: "PASSKEY",
@@ -3017,6 +3798,15 @@ prepareSignUpState_fn = function(_0, _1) {
3017
3798
  signupState.passwordUrl = passwordUrl;
3018
3799
  signupState.passwordId = passwordId;
3019
3800
  }
3801
+ if (isPIN) {
3802
+ const { url: pinUrl, credentialId: pinId } = yield this.getNewCredentialAndUrl({
3803
+ authMethod: "PIN",
3804
+ portalTheme,
3805
+ shorten
3806
+ });
3807
+ signupState.pinUrl = pinUrl;
3808
+ signupState.pinId = pinId;
3809
+ }
3020
3810
  return signupState;
3021
3811
  });
3022
3812
  };