@getpara/core-sdk 2.0.0-fc.3 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/dist/cjs/ParaCore.js +1111 -316
  2. package/dist/cjs/constants.js +10 -1
  3. package/dist/cjs/index.js +23 -3
  4. package/dist/cjs/shares/KeyContainer.js +3 -3
  5. package/dist/cjs/shares/enclave.js +287 -0
  6. package/dist/cjs/shares/shareDistribution.js +16 -1
  7. package/dist/cjs/transmission/transmissionUtils.js +4 -3
  8. package/dist/cjs/types/{theme.js → assets.js} +2 -2
  9. package/dist/cjs/types/coreApi.js +7 -2
  10. package/dist/cjs/types/events.js +2 -0
  11. package/dist/cjs/types/index.js +0 -21
  12. package/dist/cjs/types/popup.js +1 -0
  13. package/dist/cjs/utils/config.js +108 -0
  14. package/dist/cjs/utils/index.js +5 -1
  15. package/dist/cjs/utils/onRamps.js +2 -3
  16. package/dist/cjs/utils/wallet.js +18 -0
  17. package/dist/cjs/{types/onRamps.js → utils/window.js} +17 -12
  18. package/dist/esm/ParaCore.js +1115 -320
  19. package/dist/esm/constants.js +7 -1
  20. package/dist/esm/index.js +24 -5
  21. package/dist/esm/shares/KeyContainer.js +3 -3
  22. package/dist/esm/shares/enclave.js +247 -0
  23. package/dist/esm/shares/shareDistribution.js +16 -1
  24. package/dist/esm/transmission/transmissionUtils.js +4 -3
  25. package/dist/esm/types/coreApi.js +7 -2
  26. package/dist/esm/types/events.js +2 -0
  27. package/dist/esm/types/index.js +0 -16
  28. package/dist/esm/types/popup.js +1 -0
  29. package/dist/esm/utils/config.js +86 -0
  30. package/dist/esm/utils/index.js +2 -0
  31. package/dist/esm/utils/onRamps.js +2 -3
  32. package/dist/esm/utils/wallet.js +17 -0
  33. package/dist/esm/utils/window.js +16 -0
  34. package/dist/types/ParaCore.d.ts +90 -19
  35. package/dist/types/PlatformUtils.d.ts +2 -1
  36. package/dist/types/constants.d.ts +3 -0
  37. package/dist/types/index.d.ts +6 -4
  38. package/dist/types/shares/enclave.d.ts +83 -0
  39. package/dist/types/shares/shareDistribution.d.ts +4 -2
  40. package/dist/types/types/assets.d.ts +14 -0
  41. package/dist/types/types/config.d.ts +3 -2
  42. package/dist/types/types/coreApi.d.ts +47 -7
  43. package/dist/types/types/events.d.ts +7 -2
  44. package/dist/types/types/index.d.ts +0 -4
  45. package/dist/types/types/methods.d.ts +56 -12
  46. package/dist/types/types/popup.d.ts +2 -1
  47. package/dist/types/types/wallet.d.ts +8 -4
  48. package/dist/types/utils/config.d.ts +7 -0
  49. package/dist/types/utils/index.d.ts +2 -0
  50. package/dist/types/utils/onRamps.d.ts +9 -10
  51. package/dist/types/utils/wallet.d.ts +1 -0
  52. package/dist/types/utils/window.d.ts +2 -0
  53. package/package.json +3 -3
  54. package/dist/cjs/types/recovery.js +0 -34
  55. package/dist/esm/types/onRamps.js +0 -11
  56. package/dist/esm/types/recovery.js +0 -12
  57. package/dist/types/types/onRamps.d.ts +0 -10
  58. package/dist/types/types/recovery.d.ts +0 -7
  59. package/dist/types/types/theme.d.ts +0 -12
  60. /package/dist/esm/types/{theme.js → assets.js} +0 -0
@@ -8,7 +8,7 @@ import {
8
8
  __spreadProps,
9
9
  __spreadValues
10
10
  } from "./chunk-7B52C2XE.js";
11
- var _authInfo, _partner, _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, prepareLogin_fn, prepareLoginState_fn, prepareSignUpState_fn;
11
+ var _authInfo, _ParaCore_instances, assertPartner_fn, guestWalletIds_get, guestWalletIdsArray_get, toAuthInfo_fn, setAuthInfo_fn, getPartner_fn, assertIsLinkingAccount_fn, assertIsLinkingAccountOrStart_fn, getOAuthUrl_fn, waitForLoginProcess_fn, createPregenWallet_fn, _isCreateGuestWalletsPending, prepareAuthState_fn, prepareDoneState_fn, prepareVerificationState_fn, prepareLoginState_fn, prepareSignUpState_fn;
12
12
  import { Buffer as NodeBuffer } from "buffer";
13
13
  if (typeof global !== "undefined") {
14
14
  global.Buffer = global.Buffer || NodeBuffer;
@@ -21,10 +21,8 @@ if (typeof global !== "undefined") {
21
21
  }
22
22
  import {
23
23
  AuthMethod,
24
- PublicKeyStatus,
24
+ AuthMethodStatus,
25
25
  PublicKeyType,
26
- extractWalletRef,
27
- PasswordStatus,
28
26
  extractAuthInfo,
29
27
  isEmail,
30
28
  isPhone,
@@ -72,29 +70,28 @@ import {
72
70
  WalletSchemeTypeMap,
73
71
  shortenUrl,
74
72
  isServerAuthState,
75
- splitPhoneNumber
73
+ splitPhoneNumber,
74
+ currentWalletIdsEq,
75
+ isPortal
76
76
  } from "./utils/index.js";
77
77
  import { TransactionReviewDenied, TransactionReviewTimeout } from "./errors.js";
78
78
  import * as constants from "./constants.js";
79
+ import { EnclaveClient } from "./shares/enclave.js";
79
80
  const _ParaCore = class _ParaCore {
80
- /**
81
- * Constructs a new `ParaCore` instance.
82
- * @param env - `Environment` to use.
83
- * @param apiKey - API key to use.
84
- * @param opts - Additional constructor options; see `ConstructorOpts`.
85
- * @returns - A new ParaCore instance.
86
- */
87
- constructor(env, apiKey, opts) {
81
+ constructor(envOrApiKey, apiKeyOrOpts, opts) {
88
82
  __privateAdd(this, _ParaCore_instances);
83
+ this.popupWindow = null;
89
84
  __privateAdd(this, _authInfo);
85
+ this.isSwitchingWallets = false;
90
86
  this.isNativePasskey = false;
91
87
  this.isReady = false;
92
- __privateAdd(this, _partner);
93
88
  this.accountLinkInProgress = void 0;
89
+ this.isEnclaveUser = false;
94
90
  this.isAwaitingAccountCreation = false;
95
91
  this.isAwaitingLogin = false;
96
92
  this.isAwaitingFarcaster = false;
97
93
  this.isAwaitingOAuth = false;
94
+ this.isWorkerInitialized = false;
98
95
  /**
99
96
  * 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.
100
97
  */
@@ -103,20 +100,34 @@ const _ParaCore = class _ParaCore {
103
100
  * Wallets associated with the `ParaCore` instance.
104
101
  */
105
102
  this.externalWallets = {};
103
+ this.onRampPopup = void 0;
104
+ this.nonPersistedStorageKeys = [];
106
105
  this.localStorageGetItem = (key) => {
107
- return this.platformUtils.localStorage.get(key);
106
+ var _a;
107
+ if (!((_a = this.nonPersistedStorageKeys) != null ? _a : []).includes(key)) {
108
+ return this.platformUtils.localStorage.get(key);
109
+ }
108
110
  };
109
111
  this.localStorageSetItem = (key, value) => {
110
- return this.platformUtils.localStorage.set(key, value);
112
+ var _a;
113
+ if (!((_a = this.nonPersistedStorageKeys) != null ? _a : []).includes(key)) {
114
+ return this.platformUtils.localStorage.set(key, value);
115
+ }
111
116
  };
112
117
  this.localStorageRemoveItem = (key) => {
113
118
  return this.platformUtils.localStorage.removeItem(key);
114
119
  };
115
120
  this.sessionStorageGetItem = (key) => {
116
- return this.platformUtils.sessionStorage.get(key);
121
+ var _a;
122
+ if (!((_a = this.nonPersistedStorageKeys) != null ? _a : []).includes(key)) {
123
+ return this.platformUtils.sessionStorage.get(key);
124
+ }
117
125
  };
118
126
  this.sessionStorageSetItem = (key, value) => {
119
- return this.platformUtils.sessionStorage.set(key, value);
127
+ var _a;
128
+ if (!((_a = this.nonPersistedStorageKeys) != null ? _a : []).includes(key)) {
129
+ return this.platformUtils.sessionStorage.set(key, value);
130
+ }
120
131
  };
121
132
  this.sessionStorageRemoveItem = (key) => {
122
133
  return this.platformUtils.sessionStorage.removeItem(key);
@@ -124,16 +135,29 @@ const _ParaCore = class _ParaCore {
124
135
  this.retrieveSessionCookie = () => {
125
136
  return this.sessionCookie;
126
137
  };
138
+ this.retrieveEnclaveJwt = () => {
139
+ return this.enclaveJwt;
140
+ };
141
+ this.retrieveEnclaveRefreshJwt = () => {
142
+ return this.enclaveRefreshJwt;
143
+ };
127
144
  /**
128
145
  * Remove all local storage and prefixed session storage.
129
146
  * @param {'local' | 'session' | 'secure' | 'all'} type - Type of storage to clear. Defaults to 'all'.
130
147
  */
131
148
  this.clearStorage = (type = "all") => __async(this, null, function* () {
132
149
  const isAll = type === "all";
133
- (isAll || type === "local") && this.platformUtils.localStorage.clear(constants.PREFIX);
134
- (isAll || type === "session") && this.platformUtils.sessionStorage.clear(constants.PREFIX);
150
+ if (isAll || type === "local") {
151
+ this.platformUtils.localStorage.clear(constants.PREFIX);
152
+ this.platformUtils.localStorage.clear(constants.PARA_PREFIX);
153
+ }
154
+ if (isAll || type === "session") {
155
+ this.platformUtils.sessionStorage.clear(constants.PREFIX);
156
+ this.platformUtils.sessionStorage.clear(constants.PARA_PREFIX);
157
+ }
135
158
  if ((isAll || type === "secure") && this.platformUtils.secureStorage) {
136
159
  this.platformUtils.secureStorage.clear(constants.PREFIX);
160
+ this.platformUtils.secureStorage.clear(constants.PARA_PREFIX);
137
161
  }
138
162
  });
139
163
  this.trackError = (methodName, err) => __async(this, null, function* () {
@@ -175,6 +199,7 @@ const _ParaCore = class _ParaCore {
175
199
  this.updateWalletIdsFromStorage();
176
200
  this.updateSessionCookieFromStorage();
177
201
  this.updateLoginEncryptionKeyPairFromStorage();
202
+ this.updateEnclaveJwtFromStorage();
178
203
  };
179
204
  this.updateAuthInfoFromStorage = () => {
180
205
  var _a;
@@ -194,6 +219,10 @@ const _ParaCore = class _ParaCore {
194
219
  }
195
220
  __privateSet(this, _authInfo, authInfo);
196
221
  };
222
+ this.updateEnclaveJwtFromStorage = () => {
223
+ this.enclaveJwt = this.localStorageGetItem(constants.LOCAL_STORAGE_ENCLAVE_JWT) || this.sessionStorageGetItem(constants.LOCAL_STORAGE_ENCLAVE_JWT) || void 0;
224
+ this.enclaveRefreshJwt = this.localStorageGetItem(constants.LOCAL_STORAGE_ENCLAVE_REFRESH_JWT) || this.sessionStorageGetItem(constants.LOCAL_STORAGE_ENCLAVE_REFRESH_JWT) || void 0;
225
+ };
197
226
  this.updateUserIdFromStorage = () => {
198
227
  this.userId = this.localStorageGetItem(constants.LOCAL_STORAGE_USER_ID) || void 0;
199
228
  };
@@ -254,6 +283,16 @@ const _ParaCore = class _ParaCore {
254
283
  const _externalWallets = JSON.parse(stringExternalWallets || "{}");
255
284
  this.setExternalWallets(_externalWallets);
256
285
  };
286
+ this.initializeWorker = () => __async(this, null, function* () {
287
+ if (!this.isWorkerInitialized && !this.ctx.disableWebSockets && !this.ctx.disableWorkers && !this.isPortal()) {
288
+ try {
289
+ this.isWorkerInitialized = true;
290
+ yield this.platformUtils.initializeWorker(this.ctx);
291
+ } catch (e) {
292
+ this.devLog("error initializing worker:", e);
293
+ }
294
+ }
295
+ });
257
296
  /**
258
297
  * Creates several new wallets with the desired types. If no types are provided, this method
259
298
  * will create one for each of the non-optional types specified in the instance's `supportedWalletTypes`
@@ -270,8 +309,29 @@ const _ParaCore = class _ParaCore {
270
309
  }) {
271
310
  return (yield this.ctx.client.getWalletBalance({ walletId, rpcUrl })).balance;
272
311
  });
273
- if (!apiKey) {
274
- throw new Error("A Para API key is required.");
312
+ let env, apiKey;
313
+ const actualArgs = Array.from(arguments).filter((arg) => arg !== void 0);
314
+ const actualArgumentCount = actualArgs.length;
315
+ if (actualArgumentCount === 1) {
316
+ if (Object.values(Environment).includes(envOrApiKey)) {
317
+ throw new Error("A Para API key is required.");
318
+ }
319
+ env = _ParaCore.resolveEnvironment(void 0, actualArgs[0]);
320
+ apiKey = actualArgs[0];
321
+ opts = void 0;
322
+ } else if (actualArgumentCount === 2) {
323
+ if (typeof apiKeyOrOpts === "object" && apiKeyOrOpts !== null) {
324
+ env = _ParaCore.resolveEnvironment(void 0, envOrApiKey);
325
+ apiKey = envOrApiKey;
326
+ opts = apiKeyOrOpts;
327
+ } else {
328
+ env = _ParaCore.resolveEnvironment(envOrApiKey, apiKeyOrOpts);
329
+ apiKey = apiKeyOrOpts;
330
+ opts = void 0;
331
+ }
332
+ } else {
333
+ env = _ParaCore.resolveEnvironment(envOrApiKey, apiKeyOrOpts);
334
+ apiKey = apiKeyOrOpts;
275
335
  }
276
336
  if (!opts) opts = {};
277
337
  let isE2E = false;
@@ -314,18 +374,41 @@ const _ParaCore = class _ParaCore {
314
374
  cookie
315
375
  );
316
376
  };
377
+ this.persistEnclaveJwt = (jwt) => {
378
+ this.enclaveJwt = jwt;
379
+ (opts.useSessionStorage ? this.sessionStorageSetItem : this.localStorageSetItem)(
380
+ constants.LOCAL_STORAGE_ENCLAVE_JWT,
381
+ jwt
382
+ );
383
+ };
384
+ this.persistEnclaveRefreshJwt = (refreshJwt) => {
385
+ this.enclaveRefreshJwt = refreshJwt;
386
+ (opts.useSessionStorage ? this.sessionStorageSetItem : this.localStorageSetItem)(
387
+ constants.LOCAL_STORAGE_ENCLAVE_REFRESH_JWT,
388
+ refreshJwt
389
+ );
390
+ };
391
+ const client = initClient({
392
+ env,
393
+ version: _ParaCore.version,
394
+ apiKey,
395
+ partnerId: this.isPortal(env) ? opts.portalPartnerId : void 0,
396
+ useFetchAdapter: !!opts.disableWorkers,
397
+ retrieveSessionCookie: this.retrieveSessionCookie,
398
+ persistSessionCookie: this.persistSessionCookie
399
+ });
400
+ const enclaveClient = new EnclaveClient({
401
+ userManagementClient: client,
402
+ retrieveJwt: this.retrieveEnclaveJwt,
403
+ persistJwt: this.persistEnclaveJwt,
404
+ retrieveRefreshJwt: this.retrieveEnclaveRefreshJwt,
405
+ persistRefreshJwt: this.persistEnclaveRefreshJwt
406
+ });
317
407
  this.ctx = {
318
408
  env,
319
409
  apiKey,
320
- client: initClient({
321
- env,
322
- version: _ParaCore.version,
323
- apiKey,
324
- partnerId: this.isPortal(env) ? opts.portalPartnerId : void 0,
325
- useFetchAdapter: !!opts.disableWorkers,
326
- retrieveSessionCookie: this.retrieveSessionCookie,
327
- persistSessionCookie: this.persistSessionCookie
328
- }),
410
+ client,
411
+ enclaveClient,
329
412
  disableWorkers: opts.disableWorkers,
330
413
  offloadMPCComputationURL: opts.offloadMPCComputationURL,
331
414
  useLocalFiles: opts.useLocalFiles,
@@ -360,6 +443,9 @@ const _ParaCore = class _ParaCore {
360
443
  ]);
361
444
  }
362
445
  }
446
+ setModalError(_error) {
447
+ return;
448
+ }
363
449
  get authInfo() {
364
450
  return __privateGet(this, _authInfo);
365
451
  }
@@ -389,7 +475,12 @@ const _ParaCore = class _ParaCore {
389
475
  } else if (this.isExternalWalletWithVerification) {
390
476
  return "VERIFICATION";
391
477
  } else if (!!Object.keys(this.externalWallets).length) {
392
- return "CONNECTION_ONLY";
478
+ const hasEmbeddedWallets = Object.keys(this.wallets).some((id) => !this.wallets[id].isExternal);
479
+ if (hasEmbeddedWallets) {
480
+ return "NONE";
481
+ } else {
482
+ return "CONNECTION_ONLY";
483
+ }
393
484
  }
394
485
  return "NONE";
395
486
  }
@@ -419,11 +510,19 @@ const _ParaCore = class _ParaCore {
419
510
  }
420
511
  get partnerId() {
421
512
  var _a;
422
- return (_a = __privateGet(this, _partner)) == null ? void 0 : _a.id;
513
+ return (_a = this.partner) == null ? void 0 : _a.id;
514
+ }
515
+ get partnerName() {
516
+ var _a;
517
+ return (_a = this.partner) == null ? void 0 : _a.displayName;
518
+ }
519
+ get partnerLogo() {
520
+ var _a;
521
+ return (_a = this.partner) == null ? void 0 : _a.logoUrl;
423
522
  }
424
523
  get currentWalletIdsArray() {
425
524
  var _a, _b;
426
- return ((_b = (_a = __privateGet(this, _partner)) == null ? void 0 : _a.supportedWalletTypes) != null ? _b : Object.keys(this.currentWalletIds).map((type) => ({ type }))).reduce(
525
+ return ((_b = (_a = this.partner) == null ? void 0 : _a.supportedWalletTypes) != null ? _b : Object.keys(this.currentWalletIds).map((type) => ({ type }))).reduce(
427
526
  (acc, { type }) => {
428
527
  var _a2;
429
528
  return [
@@ -463,23 +562,23 @@ const _ParaCore = class _ParaCore {
463
562
  }
464
563
  get isNoWalletConfig() {
465
564
  var _a;
466
- return !!((_a = __privateGet(this, _partner)) == null ? void 0 : _a.supportedWalletTypes) && __privateGet(this, _partner).supportedWalletTypes.length === 0;
565
+ return !!((_a = this.partner) == null ? void 0 : _a.supportedWalletTypes) && this.partner.supportedWalletTypes.length === 0;
467
566
  }
468
567
  get supportedWalletTypes() {
469
568
  var _a, _b;
470
- return (_b = (_a = __privateGet(this, _partner)) == null ? void 0 : _a.supportedWalletTypes) != null ? _b : [];
569
+ return (_b = (_a = this.partner) == null ? void 0 : _a.supportedWalletTypes) != null ? _b : [];
471
570
  }
472
571
  get cosmosPrefix() {
473
572
  var _a;
474
- return (_a = __privateGet(this, _partner)) == null ? void 0 : _a.cosmosPrefix;
573
+ return (_a = this.partner) == null ? void 0 : _a.cosmosPrefix;
475
574
  }
476
575
  get supportedAccountLinks() {
477
576
  var _a, _b;
478
- return (_b = (_a = __privateGet(this, _partner)) == null ? void 0 : _a.supportedAccountLinks) != null ? _b : [...LINKED_ACCOUNT_TYPES];
577
+ return (_b = (_a = this.partner) == null ? void 0 : _a.supportedAccountLinks) != null ? _b : [...LINKED_ACCOUNT_TYPES];
479
578
  }
480
579
  get isWalletTypeEnabled() {
481
580
  var _a;
482
- return (((_a = __privateGet(this, _partner)) == null ? void 0 : _a.supportedWalletTypes) || []).reduce((acc, { type }) => {
581
+ return (((_a = this.partner) == null ? void 0 : _a.supportedWalletTypes) || []).reduce((acc, { type }) => {
483
582
  return __spreadProps(__spreadValues({}, acc), { [type]: true });
484
583
  }, {});
485
584
  }
@@ -509,9 +608,7 @@ const _ParaCore = class _ParaCore {
509
608
  };
510
609
  }
511
610
  isPortal(envOverride) {
512
- var _a;
513
- if (typeof window === "undefined") return false;
514
- return !!((_a = window.location) == null ? void 0 : _a.host) && getPortalBaseURL(envOverride ? { env: envOverride } : this.ctx).includes(window.location.host);
611
+ return isPortal(this.ctx, envOverride);
515
612
  }
516
613
  isParaConnect() {
517
614
  var _a;
@@ -528,7 +625,7 @@ const _ParaCore = class _ParaCore {
528
625
  }
529
626
  isWalletSupported(wallet) {
530
627
  var _a, _b;
531
- return !((_a = __privateGet(this, _partner)) == null ? void 0 : _a.supportedWalletTypes) || isWalletSupported((_b = __privateGet(this, _partner).supportedWalletTypes.map(({ type }) => type)) != null ? _b : [], wallet);
628
+ return !((_a = this.partner) == null ? void 0 : _a.supportedWalletTypes) || isWalletSupported((_b = this.partner.supportedWalletTypes.map(({ type }) => type)) != null ? _b : [], wallet);
532
629
  }
533
630
  isWalletOwned(wallet) {
534
631
  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;
@@ -559,7 +656,7 @@ const _ParaCore = class _ParaCore {
559
656
  } else if (!isOwned && !isUnclaimed) {
560
657
  error = `wallet with id ${wallet == null ? void 0 : wallet.id} is not owned by the current user`;
561
658
  } else if (!this.isWalletSupported(wallet)) {
562
- 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(", ")}`;
659
+ 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(", ")}`;
563
660
  } else if (types && (!getEquivalentTypes(types).includes(wallet == null ? void 0 : wallet.type) || isOwned && !types.some((type) => {
564
661
  var _a2, _b2;
565
662
  return (_b2 = (_a2 = this.currentWalletIds) == null ? void 0 : _a2[type]) == null ? void 0 : _b2.includes(walletId);
@@ -577,6 +674,9 @@ const _ParaCore = class _ParaCore {
577
674
  }
578
675
  return true;
579
676
  }
677
+ truncateAddress(...args) {
678
+ return truncateAddress(args[0], args[1], __spreadValues({ prefix: this.cosmosPrefix }, args[2] || {}));
679
+ }
580
680
  /**
581
681
  * Returns the formatted address for the desired wallet ID, depending on your app settings.
582
682
  * @param {string} walletId the ID of the wallet address to display.
@@ -590,7 +690,7 @@ const _ParaCore = class _ParaCore {
590
690
  if (this.externalWallets[walletId]) {
591
691
  const wallet2 = this.externalWallets[walletId];
592
692
  return options.truncate ? truncateAddress(wallet2.address, wallet2.type, {
593
- prefix: (_a = __privateGet(this, _partner)) == null ? void 0 : _a.cosmosPrefix,
693
+ prefix: (_a = this.partner) == null ? void 0 : _a.cosmosPrefix,
594
694
  targetLength: options.targetLength
595
695
  }) : wallet2.address;
596
696
  }
@@ -602,7 +702,7 @@ const _ParaCore = class _ParaCore {
602
702
  let prefix;
603
703
  switch (wallet.type) {
604
704
  case "COSMOS":
605
- prefix = (_d = (_c = options.cosmosPrefix) != null ? _c : (_b = __privateGet(this, _partner)) == null ? void 0 : _b.cosmosPrefix) != null ? _d : "cosmos";
705
+ prefix = (_d = (_c = options.cosmosPrefix) != null ? _c : (_b = this.partner) == null ? void 0 : _b.cosmosPrefix) != null ? _d : "cosmos";
606
706
  str = getCosmosAddress(wallet.publicKey, prefix);
607
707
  break;
608
708
  default:
@@ -635,30 +735,55 @@ const _ParaCore = class _ParaCore {
635
735
  }
636
736
  constructPortalUrl(_0) {
637
737
  return __async(this, arguments, function* (type, opts = {}) {
638
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
639
- const [isCreate, isLogin, isOnRamp] = [
640
- ["createAuth", "createPassword"].includes(type),
641
- ["loginAuth", "loginPassword"].includes(type),
642
- type === "onRamp"
738
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
739
+ const [
740
+ isCreate,
741
+ isLogin,
742
+ isOnRamp,
743
+ isOAuth,
744
+ isOAuthCallback,
745
+ isTelegramLogin,
746
+ isFarcasterLogin,
747
+ isAddNewCredential,
748
+ isSwitchWallets,
749
+ isExportPrivateKey
750
+ ] = [
751
+ ["createAuth", "createPassword", "createPIN"].includes(type),
752
+ ["loginAuth", "loginPassword", "loginPIN", "loginOTP", "switchWallets", "loginExternalWallet"].includes(type),
753
+ type === "onRamp",
754
+ type === "oAuth",
755
+ type === "oAuthCallback",
756
+ ["telegramLogin", "telegramLoginVerify"].includes(type),
757
+ type === "loginFarcaster",
758
+ type === "addNewCredential",
759
+ type === "switchWallets",
760
+ type === "exportPrivateKey"
643
761
  ];
762
+ if (isOAuth && !opts.oAuthMethod) {
763
+ throw new Error("oAuthMethod is required for oAuth portal URLs");
764
+ }
644
765
  if (isCreate || isLogin) {
645
766
  this.assertIsAuthSet();
646
767
  }
647
768
  let sessionId = opts.sessionId;
648
- if ((isLogin || isOnRamp) && !sessionId) {
769
+ if ((isLogin || isOnRamp || isTelegramLogin || isFarcasterLogin || isExportPrivateKey) && !sessionId) {
649
770
  const session = yield this.touchSession(true);
650
771
  sessionId = session.sessionId;
651
772
  }
652
773
  if (!this.loginEncryptionKeyPair) {
653
774
  yield this.setLoginEncryptionKeyPair();
654
775
  }
655
- const base = type === "onRamp" || type === "telegramLogin" ? getPortalBaseURL(this.ctx, type === "telegramLogin") : yield this.getPortalURL();
776
+ const base = type === "onRamp" || isTelegramLogin ? getPortalBaseURL(this.ctx, isTelegramLogin) : yield this.getPortalURL();
656
777
  let path;
657
778
  switch (type) {
658
779
  case "createPassword": {
659
780
  path = `/web/users/${this.userId}/passwords/${opts.pathId}`;
660
781
  break;
661
782
  }
783
+ case "createPIN": {
784
+ path = `/web/users/${this.userId}/pin/${opts.pathId}`;
785
+ break;
786
+ }
662
787
  case "createAuth": {
663
788
  path = `/web/users/${this.userId}/biometrics/${opts.pathId}`;
664
789
  break;
@@ -671,18 +796,62 @@ const _ParaCore = class _ParaCore {
671
796
  path = "/web/biometrics/login";
672
797
  break;
673
798
  }
799
+ case "loginPIN": {
800
+ path = "/web/pin/login";
801
+ break;
802
+ }
674
803
  case "txReview": {
675
804
  path = `/web/users/${this.userId}/transaction-review/${opts.pathId}`;
676
805
  break;
677
806
  }
678
807
  case "onRamp": {
679
- path = `/web/users/${this.userId}/on-ramp-transaction/${opts.pathId}`;
808
+ path = `/web/users/${this.userId}/on-ramp-transaction/v2/${opts.pathId}`;
809
+ break;
810
+ }
811
+ case "telegramLoginVerify": {
812
+ path = `/auth/telegram/verify`;
680
813
  break;
681
814
  }
682
815
  case "telegramLogin": {
683
816
  path = `/auth/telegram`;
684
817
  break;
685
818
  }
819
+ case "oAuth": {
820
+ path = `/auth/${opts.oAuthMethod.toLowerCase()}`;
821
+ break;
822
+ }
823
+ case "oAuthCallback": {
824
+ path = `/auth/${opts.oAuthMethod.toLowerCase()}/callback`;
825
+ break;
826
+ }
827
+ case "loginOTP": {
828
+ path = "/auth/otp";
829
+ break;
830
+ }
831
+ case "loginFarcaster": {
832
+ path = "/auth/farcaster";
833
+ break;
834
+ }
835
+ case "switchWallets": {
836
+ path = `/auth/wallets`;
837
+ break;
838
+ }
839
+ case "addNewCredential": {
840
+ path = "/auth/add-new-credential";
841
+ break;
842
+ }
843
+ case "exportPrivateKey": {
844
+ path = `/web/users/${this.userId}/private-key/${opts.pathId}`;
845
+ break;
846
+ }
847
+ case "loginExternalWallet": {
848
+ path = "/auth/external-wallet";
849
+ break;
850
+ }
851
+ case "connectExternalWallet": {
852
+ path = "/auth/connect-external-wallet";
853
+ break;
854
+ }
686
855
  default: {
687
856
  throw new Error(`invalid URL type ${type}`);
688
857
  }
@@ -701,25 +870,28 @@ const _ParaCore = class _ParaCore {
701
870
  encryptionKey: getPublicKeyHex(this.loginEncryptionKeyPair),
702
871
  sessionId
703
872
  };
704
- const params = __spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({
873
+ const params = __spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadProps(__spreadValues({
705
874
  apiKey: this.ctx.apiKey,
706
- partnerId: partner == null ? void 0 : partner.id,
707
- portalFont: ((_b = opts.portalTheme) == null ? void 0 : _b.font) || (partner == null ? void 0 : partner.font) || ((_c = this.portalTheme) == null ? void 0 : _c.font),
708
- portalBorderRadius: ((_d = opts.portalTheme) == null ? void 0 : _d.borderRadius) || ((_e = this.portalTheme) == null ? void 0 : _e.borderRadius),
709
- portalThemeMode: ((_f = opts.portalTheme) == null ? void 0 : _f.mode) || (partner == null ? void 0 : partner.themeMode) || ((_g = this.portalTheme) == null ? void 0 : _g.mode),
710
- portalAccentColor: ((_h = opts.portalTheme) == null ? void 0 : _h.accentColor) || (partner == null ? void 0 : partner.accentColor) || ((_i = this.portalTheme) == null ? void 0 : _i.accentColor),
711
- portalForegroundColor: ((_j = opts.portalTheme) == null ? void 0 : _j.foregroundColor) || (partner == null ? void 0 : partner.foregroundColor) || ((_k = this.portalTheme) == null ? void 0 : _k.foregroundColor),
712
- 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),
875
+ origin: typeof window !== "undefined" ? window.location.origin : void 0,
876
+ partnerId: partner == null ? void 0 : partner.id
877
+ }, typeof window !== "undefined" && ((_b = window.location) == null ? void 0 : _b.origin) ? { origin: window.location.origin } : {}), {
878
+ portalFont: ((_c = opts.portalTheme) == null ? void 0 : _c.font) || ((_d = this.portalTheme) == null ? void 0 : _d.font) || (partner == null ? void 0 : partner.font),
879
+ portalBorderRadius: ((_e = opts.portalTheme) == null ? void 0 : _e.borderRadius) || ((_f = this.portalTheme) == null ? void 0 : _f.borderRadius),
880
+ portalThemeMode: ((_g = opts.portalTheme) == null ? void 0 : _g.mode) || ((_h = this.portalTheme) == null ? void 0 : _h.mode) || (partner == null ? void 0 : partner.themeMode),
881
+ portalAccentColor: ((_i = opts.portalTheme) == null ? void 0 : _i.accentColor) || ((_j = this.portalTheme) == null ? void 0 : _j.accentColor) || (partner == null ? void 0 : partner.accentColor),
882
+ portalForegroundColor: ((_k = opts.portalTheme) == null ? void 0 : _k.foregroundColor) || ((_l = this.portalTheme) == null ? void 0 : _l.foregroundColor) || (partner == null ? void 0 : partner.foregroundColor),
883
+ portalBackgroundColor: ((_m = opts.portalTheme) == null ? void 0 : _m.backgroundColor) || ((_n = this.portalTheme) == null ? void 0 : _n.backgroundColor) || (partner == null ? void 0 : partner.backgroundColor) || this.portalBackgroundColor,
713
884
  portalPrimaryButtonColor: this.portalPrimaryButtonColor,
714
885
  portalTextColor: this.portalTextColor,
715
886
  portalPrimaryButtonTextColor: this.portalPrimaryButtonTextColor,
716
887
  isForNewDevice: opts.isForNewDevice ? opts.isForNewDevice.toString() : void 0
717
- }, isCreate || isLogin ? __spreadProps(__spreadValues({
888
+ }), this.authInfo && (isCreate || isLogin || isAddNewCredential || isOAuthCallback || isSwitchWallets || isExportPrivateKey) ? __spreadProps(__spreadValues({
718
889
  authInfo: JSON.stringify(this.authInfo)
719
890
  }, isPhone(this.authInfo.auth) ? splitPhoneNumber(this.authInfo.auth.phone) : this.authInfo.auth), {
720
891
  pfpUrl: this.authInfo.pfpUrl,
721
- displayName: this.authInfo.displayName
722
- }) : {}), isOnRamp ? { sessionId } : {}), isLogin ? __spreadProps(__spreadValues({
892
+ displayName: this.authInfo.displayName,
893
+ userId: this.userId
894
+ }) : {}), isOnRamp ? { email: this.email } : {}), isLogin || isOAuth || isOAuthCallback || isTelegramLogin || isFarcasterLogin || isAddNewCredential ? __spreadProps(__spreadValues({
723
895
  sessionId: thisDevice.sessionId,
724
896
  encryptionKey: thisDevice.encryptionKey
725
897
  }, opts.newDevice ? {
@@ -727,7 +899,17 @@ const _ParaCore = class _ParaCore {
727
899
  newDeviceEncryptionKey: opts.newDevice.encryptionKey
728
900
  } : {}), {
729
901
  pregenIds: JSON.stringify(this.pregenIds)
730
- }) : {}), type === "telegramLogin" ? { isEmbed: "true" } : {}), opts.params || {});
902
+ }) : {}), isOAuth || isOAuthCallback || isFarcasterLogin ? {
903
+ appScheme: opts.appScheme
904
+ } : {}), isTelegramLogin ? { isEmbed: "true" } : {}), isSwitchWallets ? __spreadValues(__spreadValues({}, this.currentWalletIds ? { currentWalletIds: JSON.stringify(this.currentWalletIds) } : {}), this.userId ? { userId: this.userId } : {}) : {}), opts.params || {}), isAddNewCredential ? __spreadProps(__spreadValues({}, opts.addNewCredentialType && { addNewCredentialType: opts.addNewCredentialType.toString() }), {
905
+ addNewCredentialPasskeyId: opts.addNewCredentialPasskeyId,
906
+ addNewCredentialPasswordId: opts.addNewCredentialPasswordId
907
+ }) : {}), isLogin && {
908
+ // Prior versions won't have this param which will skip the upgrade prompt
909
+ isBasicLoginUpgradeVersion: "true"
910
+ }), isExportPrivateKey ? {
911
+ sessionId: thisDevice.sessionId
912
+ } : {});
731
913
  const url = constructUrl({ base, path, params });
732
914
  if (opts.shorten) {
733
915
  return shortenUrl(this.ctx, url);
@@ -735,15 +917,75 @@ const _ParaCore = class _ParaCore {
735
917
  return url;
736
918
  });
737
919
  }
920
+ static resolveEnvironment(env, apiKey) {
921
+ var _a;
922
+ if (!apiKey) {
923
+ throw new Error("A Para API key is required.");
924
+ }
925
+ if (apiKey.includes("_")) {
926
+ const validEnvironmentPrefixes = Object.values(Environment);
927
+ const envPrefix = (_a = apiKey.split("_")[0]) == null ? void 0 : _a.toUpperCase();
928
+ const hasValidPrefix = validEnvironmentPrefixes.some((envValue) => envValue === envPrefix);
929
+ if (!hasValidPrefix) {
930
+ throw new Error(`Invalid API key environment prefix.`);
931
+ }
932
+ return envPrefix;
933
+ }
934
+ if (!env) {
935
+ throw new Error("Environment parameter is required.");
936
+ }
937
+ return env;
938
+ }
738
939
  touchSession(regenerate = false) {
739
940
  return __async(this, null, function* () {
740
- var _a, _b, _c;
941
+ var _a, _b, _c, _d, _e;
942
+ if (!this.isWorkerInitialized) {
943
+ this.initializeWorker();
944
+ }
741
945
  if (!this.isReady) {
742
946
  yield this.ready();
743
947
  }
744
- const session = yield this.ctx.client.touchSession(regenerate);
745
- if (!__privateGet(this, _partner) || ((_a = __privateGet(this, _partner)) == null ? void 0 : _a.id) !== session.partnerId || !supportedWalletTypesEq(((_b = __privateGet(this, _partner)) == null ? void 0 : _b.supportedWalletTypes) || [], session.supportedWalletTypes) || (((_c = __privateGet(this, _partner)) == null ? void 0 : _c.cosmosPrefix) || "cosmos") !== session.cosmosPrefix) {
746
- yield __privateMethod(this, _ParaCore_instances, getPartner_fn).call(this, session.partnerId);
948
+ let session;
949
+ try {
950
+ session = yield this.ctx.client.touchSession(regenerate);
951
+ } catch (error) {
952
+ this.handleTouchSessionError(error);
953
+ throw error;
954
+ }
955
+ if (!this.partner || ((_a = this.partner) == null ? void 0 : _a.id) !== session.partnerId || !supportedWalletTypesEq(((_b = this.partner) == null ? void 0 : _b.supportedWalletTypes) || [], session.supportedWalletTypes) || (((_c = this.partner) == null ? void 0 : _c.cosmosPrefix) || "cosmos") !== session.cosmosPrefix) {
956
+ if (!session.partnerId && !this.isPortal()) {
957
+ this.displayModalError(
958
+ `Invalid API Key. Please ensure you have a valid API key for the current environment: ${(_d = this.ctx.env) == null ? void 0 : _d.toUpperCase()}.`
959
+ );
960
+ console.error(`
961
+ \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
962
+ \u{1F6A8} PARA SDK CONFIGURATION ERROR \u{1F6A8}
963
+
964
+ INVALID API KEY FOR CONFIGURED ENVIRONMENT
965
+
966
+ Your API key does not match the configured environment. This usually means:
967
+
968
+ 1. You're using a production API key with a development environment
969
+ 2. You're using a development API key with a production environment
970
+ 3. Your API key is invalid or has been regenerated
971
+
972
+ SOLUTION:
973
+ \u2022 Verify your API key at: https://developer.getpara.com
974
+ \u2022 If your API key doesn't contain an environment prefix, ensure your API key is the correct key for your target environment
975
+
976
+ Current Environment: ${this.ctx.env}
977
+ API Key Prefix: ${((_e = this.ctx.apiKey) == null ? void 0 : _e.split("_")[0].toUpperCase()) || "None"}
978
+
979
+ Need help? Visit: https://docs.getpara.com or contact support
980
+ \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
981
+ `);
982
+ throw new Error("Invalid API Key.");
983
+ } else {
984
+ yield __privateMethod(this, _ParaCore_instances, getPartner_fn).call(this, session.partnerId);
985
+ }
986
+ }
987
+ if (session.currentWalletIds && !currentWalletIdsEq(session.currentWalletIds, this.currentWalletIds)) {
988
+ yield this.setCurrentWalletIds(session.currentWalletIds);
747
989
  }
748
990
  return session;
749
991
  });
@@ -842,8 +1084,35 @@ const _ParaCore = class _ParaCore {
842
1084
  return __privateGet(this, _authInfo);
843
1085
  });
844
1086
  }
845
- assertUserId() {
846
- if (!this.userId || this.isGuestMode) {
1087
+ /**
1088
+ * Display an error message in the modal (if available)
1089
+ * @internal
1090
+ */
1091
+ displayModalError(error) {
1092
+ if (this.ctx.env !== Environment.PROD) {
1093
+ this.setModalError(error);
1094
+ }
1095
+ }
1096
+ /**
1097
+ * Handle specific touchSession errors with user-friendly messages
1098
+ * @private
1099
+ */
1100
+ handleTouchSessionError(error) {
1101
+ const errorStr = String(error);
1102
+ const errorMessage = error instanceof Error ? error.message : "";
1103
+ if (errorStr.includes("blocked by CORS policy") && errorStr.includes("Access-Control-Allow-Origin")) {
1104
+ this.displayModalError("Request rate limit reached. Please wait a couple of minutes and try again.");
1105
+ return;
1106
+ }
1107
+ if (error.status === 403 && errorMessage.includes("origin not authorized")) {
1108
+ this.displayModalError(
1109
+ "The current origin is not allowed. Update your allowed origins in the Para developer portal to allow the current origin."
1110
+ );
1111
+ return;
1112
+ }
1113
+ }
1114
+ assertUserId({ allowGuestMode = false } = {}) {
1115
+ if (!this.userId || !allowGuestMode && this.isGuestMode) {
847
1116
  throw new Error("no userId is set");
848
1117
  }
849
1118
  return this.userId;
@@ -901,11 +1170,59 @@ const _ParaCore = class _ParaCore {
901
1170
  */
902
1171
  setExternalWallet(externalWallet) {
903
1172
  return __async(this, null, function* () {
1173
+ const { id: partnerId, supportedWalletTypes } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
904
1174
  this.externalWallets = (Array.isArray(externalWallet) ? externalWallet : [externalWallet]).reduce(
1175
+ (acc, {
1176
+ partnerId: wPartnerId,
1177
+ address,
1178
+ type,
1179
+ provider,
1180
+ providerId,
1181
+ addressBech32,
1182
+ withFullParaAuth,
1183
+ isConnectionOnly,
1184
+ withVerification
1185
+ }) => {
1186
+ if (partnerId === wPartnerId && supportedWalletTypes.some(({ type: supportedType }) => supportedType === type)) {
1187
+ return __spreadProps(__spreadValues({}, acc), {
1188
+ [address]: {
1189
+ id: address,
1190
+ partnerId,
1191
+ address: addressBech32 != null ? addressBech32 : address,
1192
+ type,
1193
+ name: provider,
1194
+ isExternal: true,
1195
+ isExternalWithParaAuth: withFullParaAuth,
1196
+ externalProviderId: providerId,
1197
+ signer: "",
1198
+ isExternalConnectionOnly: isConnectionOnly,
1199
+ isExternalWithVerification: withVerification
1200
+ }
1201
+ });
1202
+ }
1203
+ return acc;
1204
+ },
1205
+ {}
1206
+ ), this.setExternalWallets(this.externalWallets);
1207
+ dispatchEvent(ParaEvent.EXTERNAL_WALLET_CHANGE_EVENT, null);
1208
+ });
1209
+ }
1210
+ addExternalWallets(externalWallets) {
1211
+ return __async(this, null, function* () {
1212
+ const { id: partnerId, supportedWalletTypes } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
1213
+ this.externalWallets = __spreadValues(__spreadValues({}, Object.entries(this.externalWallets).reduce((acc, [address, wallet]) => {
1214
+ if (partnerId === wallet.partnerId && supportedWalletTypes.some(({ type }) => type === wallet.type)) {
1215
+ return __spreadProps(__spreadValues({}, acc), {
1216
+ [address]: wallet
1217
+ });
1218
+ }
1219
+ return acc;
1220
+ }, {})), externalWallets.reduce(
905
1221
  (acc, { address, type, provider, providerId, addressBech32, withFullParaAuth, isConnectionOnly, withVerification }) => {
906
1222
  return __spreadProps(__spreadValues({}, acc), {
907
1223
  [address]: {
908
1224
  id: address,
1225
+ partnerId,
909
1226
  address: addressBech32 != null ? addressBech32 : address,
910
1227
  type,
911
1228
  name: provider,
@@ -919,7 +1236,7 @@ const _ParaCore = class _ParaCore {
919
1236
  });
920
1237
  },
921
1238
  {}
922
- );
1239
+ ));
923
1240
  this.setExternalWallets(this.externalWallets);
924
1241
  dispatchEvent(ParaEvent.EXTERNAL_WALLET_CHANGE_EVENT, null);
925
1242
  });
@@ -950,12 +1267,16 @@ const _ParaCore = class _ParaCore {
950
1267
  }
951
1268
  /**
952
1269
  * Sets the external wallets associated with the `ParaCore` instance.
953
- * @param externalWallets - External wallets to set.
1270
+ * @param externalWallets - External wallets to set, or a function that modifies the current wallets.
954
1271
  */
955
1272
  setExternalWallets(externalWallets) {
956
1273
  return __async(this, null, function* () {
957
- this.externalWallets = externalWallets;
958
- yield this.localStorageSetItem(constants.LOCAL_STORAGE_EXTERNAL_WALLETS, JSON.stringify(externalWallets));
1274
+ if (typeof externalWallets === "function") {
1275
+ this.externalWallets = externalWallets(this.externalWallets);
1276
+ } else {
1277
+ this.externalWallets = externalWallets;
1278
+ }
1279
+ yield this.localStorageSetItem(constants.LOCAL_STORAGE_EXTERNAL_WALLETS, JSON.stringify(this.externalWallets));
959
1280
  });
960
1281
  }
961
1282
  /**
@@ -1124,14 +1445,27 @@ const _ParaCore = class _ParaCore {
1124
1445
  ...[...this.currentWalletIdsArray, ...__privateGet(this, _ParaCore_instances, guestWalletIdsArray_get)].map(([address, type]) => [address, type, false]).map(([id, type]) => {
1125
1446
  const wallet = this.findWallet(id, type);
1126
1447
  if (!wallet) return null;
1448
+ const name = wallet.name;
1449
+ const address = this.getDisplayAddress(id, { addressType: type });
1450
+ const addressShort = this.getDisplayAddress(id, { addressType: type, truncate: true });
1127
1451
  return {
1128
1452
  id: wallet.id,
1453
+ partner: wallet.partner,
1129
1454
  type,
1130
- address: this.getDisplayAddress(id, { addressType: type }),
1131
- name: wallet.name
1455
+ address,
1456
+ name,
1457
+ addressShort,
1458
+ displayName: name != null ? name : addressShort,
1459
+ ensName: wallet.ensName,
1460
+ ensAvatar: wallet.ensAvatar
1132
1461
  };
1133
1462
  }).filter((obj) => obj !== null),
1134
- ...Object.values((_a = this.externalWallets) != null ? _a : {})
1463
+ ...Object.values((_a = this.externalWallets) != null ? _a : {}).map((wallet) => {
1464
+ return __spreadProps(__spreadValues({}, wallet), {
1465
+ addressShort: truncateAddress(wallet.address, wallet.type, { prefix: this.cosmosPrefix }),
1466
+ displayName: wallet.externalProviderId
1467
+ });
1468
+ })
1135
1469
  ];
1136
1470
  }
1137
1471
  /**
@@ -1230,13 +1564,13 @@ const _ParaCore = class _ParaCore {
1230
1564
  return __async(this, null, function* () {
1231
1565
  const res = yield this.isPortal() || this.isParaConnect() ? this.ctx.client.getAllWallets(this.userId) : this.ctx.client.getWallets(this.userId, true);
1232
1566
  return res.data.wallets.filter(
1233
- (wallet) => !!wallet.address && (this.isParaConnect() || !this.isParaConnect() && this.isWalletSupported(entityToWallet(wallet)))
1567
+ (wallet) => !!wallet.address && wallet.sharesPersisted && (this.isParaConnect() || !this.isParaConnect() && this.isWalletSupported(entityToWallet(wallet)))
1234
1568
  );
1235
1569
  });
1236
1570
  }
1237
1571
  populateWalletAddresses() {
1238
1572
  return __async(this, null, function* () {
1239
- const res = yield this.ctx.client.getWallets(this.userId, true);
1573
+ const res = yield (this.isPortal() ? this.ctx.client.getAllWallets : this.ctx.client.getWallets)(this.userId, true);
1240
1574
  const wallets = res.data.wallets;
1241
1575
  wallets.forEach((entity) => {
1242
1576
  if (this.wallets[entity.id]) {
@@ -1267,13 +1601,28 @@ const _ParaCore = class _ParaCore {
1267
1601
  loginExternalWallet(_a) {
1268
1602
  return __async(this, null, function* () {
1269
1603
  var _b = _a, {
1270
- externalWallet
1604
+ externalWallet,
1605
+ chainId,
1606
+ uri
1271
1607
  } = _b, urlOptions = __objRest(_b, [
1272
- "externalWallet"
1608
+ "externalWallet",
1609
+ "chainId",
1610
+ "uri"
1273
1611
  ]);
1274
1612
  const externalWallets = Array.isArray(externalWallet) ? externalWallet : [externalWallet];
1613
+ try {
1614
+ yield this.ctx.client.trackExternalWalletConnections({
1615
+ wallets: externalWallets.map((wallet) => ({
1616
+ address: wallet.address,
1617
+ type: wallet.type,
1618
+ provider: wallet.provider
1619
+ }))
1620
+ });
1621
+ } catch (err) {
1622
+ console.error("Error tracking external wallet connections:", err);
1623
+ }
1275
1624
  if (this.externalWalletConnectionOnly || externalWallets.every((wallet) => wallet.isConnectionOnly)) {
1276
- yield this.setExternalWallet(
1625
+ yield this.addExternalWallets(
1277
1626
  externalWallets.map((wallet) => __spreadProps(__spreadValues({}, wallet), {
1278
1627
  withFullParaAuth: false
1279
1628
  }))
@@ -1288,33 +1637,47 @@ const _ParaCore = class _ParaCore {
1288
1637
  );
1289
1638
  }
1290
1639
  this.requireApiKey();
1291
- const serverAuthState = yield this.ctx.client.loginExternalWallet({ externalWallet });
1640
+ const serverAuthState = yield this.ctx.client.loginExternalWallet({ externalWallet, chainId, uri });
1292
1641
  if (!externalWallet.withFullParaAuth && externalWallet.withVerification) {
1293
1642
  yield this.touchSession(true);
1294
1643
  }
1644
+ if (externalWallet.withFullParaAuth) {
1645
+ yield this.ctx.client.sessionAddPortalVerification();
1646
+ }
1295
1647
  return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
1296
1648
  });
1297
1649
  }
1298
- verifyExternalWallet(_c) {
1650
+ verifyExternalWallet(params) {
1299
1651
  return __async(this, null, function* () {
1300
- var _d = _c, {
1301
- externalWallet,
1302
- signedMessage,
1303
- cosmosPublicKeyHex,
1304
- cosmosSigner
1305
- } = _d, urlOptions = __objRest(_d, [
1306
- "externalWallet",
1307
- "signedMessage",
1308
- "cosmosPublicKeyHex",
1309
- "cosmosSigner"
1310
- ]);
1311
- const serverAuthState = yield this.ctx.client.verifyExternalWallet(this.userId, {
1312
- externalWallet,
1313
- signedMessage,
1314
- cosmosPublicKeyHex,
1315
- cosmosSigner
1316
- });
1317
- return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
1652
+ var _c;
1653
+ let serverAuthState;
1654
+ let urlOptions;
1655
+ if ("serverAuthState" in params && params.serverAuthState !== void 0) {
1656
+ const _a = params, { serverAuthState: optsServerAuthState } = _a, rest = __objRest(_a, ["serverAuthState"]);
1657
+ serverAuthState = optsServerAuthState;
1658
+ urlOptions = rest;
1659
+ } else if ("externalWallet" in params) {
1660
+ const _b = params, { externalWallet, signedMessage, cosmosPublicKeyHex, cosmosSigner } = _b, rest = __objRest(_b, ["externalWallet", "signedMessage", "cosmosPublicKeyHex", "cosmosSigner"]);
1661
+ const _serverAuthState = yield this.ctx.client.verifyExternalWallet(this.userId, {
1662
+ externalWallet,
1663
+ signedMessage,
1664
+ cosmosPublicKeyHex,
1665
+ cosmosSigner
1666
+ });
1667
+ serverAuthState = _serverAuthState;
1668
+ urlOptions = rest;
1669
+ }
1670
+ if (serverAuthState.stage === "login" && ((_c = serverAuthState.loginAuthMethods) == null ? void 0 : _c.includes(AuthMethod.PIN))) {
1671
+ const { sessionLookupId } = yield this.touchSession();
1672
+ return yield __privateMethod(this, _ParaCore_instances, prepareLoginState_fn).call(this, serverAuthState, __spreadProps(__spreadValues({}, urlOptions), { sessionLookupId }));
1673
+ }
1674
+ let state;
1675
+ try {
1676
+ state = yield __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
1677
+ } catch (err) {
1678
+ console.error("Error prepping state:", err);
1679
+ }
1680
+ return state;
1318
1681
  });
1319
1682
  }
1320
1683
  verifyExternalWalletLink(opts) {
@@ -1330,28 +1693,38 @@ const _ParaCore = class _ParaCore {
1330
1693
  return accounts;
1331
1694
  });
1332
1695
  }
1696
+ // TELEGRAM
1333
1697
  /**
1334
1698
  * Validates the response received from an attempted Telegram login for authenticity, then
1335
1699
  * creates or retrieves the corresponding Para user and prepares the Para instance to sign in with that user.
1336
1700
  * @param authResponse - the response JSON object received from the Telegram widget.
1337
1701
  * @returns `{ isValid: boolean; telegramUserId?: string; userId?: string; isNewUser?: boolean; supportedAuthMethods?: AuthMethod[]; biometricHints?: BiometricLocationHint[] }`
1338
1702
  */
1339
- verifyTelegramProcess(_e) {
1703
+ verifyTelegramProcess(_c) {
1340
1704
  return __async(this, null, function* () {
1341
- var _f = _e, {
1705
+ var _d = _c, {
1706
+ serverAuthState: optsServerAuthState,
1342
1707
  telegramAuthResponse,
1343
1708
  isLinkAccount
1344
- } = _f, urlOptions = __objRest(_f, [
1709
+ } = _d, urlOptions = __objRest(_d, [
1710
+ "serverAuthState",
1345
1711
  "telegramAuthResponse",
1346
1712
  "isLinkAccount"
1347
1713
  ]);
1348
1714
  try {
1349
1715
  switch (isLinkAccount) {
1350
1716
  case false: {
1351
- const serverAuthState = yield this.ctx.client.verifyTelegram(telegramAuthResponse);
1352
- return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
1717
+ if (!optsServerAuthState && !telegramAuthResponse) {
1718
+ throw new Error("one of serverAuthState or telegramAuthResponse are required for verifying telegram");
1719
+ }
1720
+ const serverAuthState = optsServerAuthState != null ? optsServerAuthState : yield this.ctx.client.verifyTelegram({ authObject: telegramAuthResponse });
1721
+ const { sessionLookupId } = yield this.touchSession();
1722
+ return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, __spreadProps(__spreadValues({}, urlOptions), { sessionLookupId }));
1353
1723
  }
1354
1724
  case true: {
1725
+ if (!telegramAuthResponse) {
1726
+ throw new Error("telegramAuthResponse is required for verifying telegram link");
1727
+ }
1355
1728
  const accountLinkInProgress = yield __privateMethod(this, _ParaCore_instances, assertIsLinkingAccountOrStart_fn).call(this, "TELEGRAM");
1356
1729
  const accounts = yield this.verifyLink({
1357
1730
  accountLinkInProgress,
@@ -1361,7 +1734,8 @@ const _ParaCore = class _ParaCore {
1361
1734
  }
1362
1735
  }
1363
1736
  } catch (e) {
1364
- throw new Error(e.message);
1737
+ const errorMessage = e instanceof Error ? e.message : e ? String(e) : "Unknown error occurred";
1738
+ throw new Error(errorMessage);
1365
1739
  }
1366
1740
  });
1367
1741
  }
@@ -1425,6 +1799,7 @@ const _ParaCore = class _ParaCore {
1425
1799
  let type, linkedAccountId;
1426
1800
  switch (reason) {
1427
1801
  case "SIGNUP":
1802
+ case "LOGIN":
1428
1803
  {
1429
1804
  const authInfo = this.assertIsAuthSet(["email", "phone"]);
1430
1805
  type = authInfo.authType.toUpperCase();
@@ -1438,7 +1813,7 @@ const _ParaCore = class _ParaCore {
1438
1813
  }
1439
1814
  break;
1440
1815
  }
1441
- const userId = this.assertUserId();
1816
+ const userId = this.assertUserId({ allowGuestMode: true });
1442
1817
  if (type !== "EMAIL" && type !== "PHONE") {
1443
1818
  throw new Error("invalid auth type for verification code");
1444
1819
  }
@@ -1476,6 +1851,9 @@ const _ParaCore = class _ParaCore {
1476
1851
  isFullyLoggedIn() {
1477
1852
  return __async(this, null, function* () {
1478
1853
  if (this.externalWalletConnectionType === "CONNECTION_ONLY") {
1854
+ if (!this.isReady) {
1855
+ yield this.ready();
1856
+ }
1479
1857
  return true;
1480
1858
  }
1481
1859
  if (this.isGuestMode) {
@@ -1485,17 +1863,45 @@ const _ParaCore = class _ParaCore {
1485
1863
  if (this.externalWalletConnectionType === "VERIFICATION") {
1486
1864
  return isSessionActive;
1487
1865
  }
1488
- return isSessionActive && (this.isNoWalletConfig || this.currentWalletIdsArray.length > 0 && this.currentWalletIdsArray.reduce((acc, [id]) => acc && !!this.wallets[id], true));
1866
+ if (this.isSwitchingWallets) {
1867
+ return isSessionActive;
1868
+ }
1869
+ if (!isSessionActive) {
1870
+ return false;
1871
+ }
1872
+ if (this.isNoWalletConfig) {
1873
+ return true;
1874
+ }
1875
+ const { supportedWalletTypes } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
1876
+ const requiredWalletTypes = supportedWalletTypes.filter(({ optional }) => !optional);
1877
+ for (const { type } of requiredWalletTypes) {
1878
+ const hasWalletForType = this.currentWalletIdsArray.some(([walletId, walletType]) => {
1879
+ try {
1880
+ const wallet = this.wallets[walletId];
1881
+ return wallet && walletType === type && typeof wallet.address === "string";
1882
+ } catch (e) {
1883
+ return false;
1884
+ }
1885
+ });
1886
+ if (!hasWalletForType) {
1887
+ return false;
1888
+ }
1889
+ }
1890
+ return true;
1489
1891
  });
1490
1892
  }
1491
1893
  get isGuestMode() {
1492
1894
  return __privateGet(this, _ParaCore_instances, guestWalletIdsArray_get).length > 0 && Object.values(this.wallets).every(
1493
1895
  ({ userId, partnerId }) => {
1494
1896
  var _a;
1495
- return partnerId === ((_a = __privateGet(this, _partner)) == null ? void 0 : _a.id) && (!userId || userId !== this.userId);
1897
+ return partnerId === ((_a = this.partner) == null ? void 0 : _a.id) && (!userId || userId !== this.userId);
1496
1898
  }
1497
1899
  );
1498
1900
  }
1901
+ /**
1902
+ * Get the auth methods available to an existing user
1903
+ * @deprecated Use supportedUserAuthMethods instead
1904
+ */
1499
1905
  supportedAuthMethods(auth) {
1500
1906
  return __async(this, null, function* () {
1501
1907
  const { supportedAuthMethods } = yield this.ctx.client.getSupportedAuthMethods(auth);
@@ -1513,6 +1919,37 @@ const _ParaCore = class _ParaCore {
1513
1919
  return authMethods;
1514
1920
  });
1515
1921
  }
1922
+ /**
1923
+ * Get the auth methods available to an existing user
1924
+ */
1925
+ supportedUserAuthMethods() {
1926
+ return __async(this, null, function* () {
1927
+ yield this.assertIsAuthSet();
1928
+ const { supportedAuthMethods, hasPasswordWithoutPIN } = yield this.ctx.client.getSupportedAuthMethodsV2(
1929
+ this.authInfo.auth
1930
+ );
1931
+ const authMethods = /* @__PURE__ */ new Set();
1932
+ for (const type of supportedAuthMethods) {
1933
+ switch (type) {
1934
+ case "PASSWORD":
1935
+ if (hasPasswordWithoutPIN) {
1936
+ authMethods.add(AuthMethod.PASSWORD);
1937
+ }
1938
+ break;
1939
+ case "PASSKEY":
1940
+ authMethods.add(AuthMethod.PASSKEY);
1941
+ break;
1942
+ case "PIN":
1943
+ authMethods.add(AuthMethod.PIN);
1944
+ break;
1945
+ case "BASIC_LOGIN":
1946
+ authMethods.add(AuthMethod.BASIC_LOGIN);
1947
+ break;
1948
+ }
1949
+ }
1950
+ return authMethods;
1951
+ });
1952
+ }
1516
1953
  /**
1517
1954
  * Get hints associated with the users stored biometrics.
1518
1955
  * @deprecated
@@ -1599,26 +2036,33 @@ const _ParaCore = class _ParaCore {
1599
2036
  return connectUri;
1600
2037
  });
1601
2038
  }
2039
+ // FARCASTER
1602
2040
  /**
1603
2041
  * Awaits the response from a user's attempt to log in with Farcaster.
1604
2042
  * If successful, this returns the user's Farcaster username and profile picture and indicates whether the user already exists.
1605
2043
  * @return {Object} `{userExists: boolean; username: string; pfpUrl?: string | null }` - the user's information and whether the user already exists.
1606
2044
  */
1607
- verifyFarcasterProcess(_g) {
2045
+ verifyFarcasterProcess(_e) {
1608
2046
  return __async(this, null, function* () {
1609
- var _h = _g, {
2047
+ var _f = _e, {
1610
2048
  isCanceled = () => false,
1611
2049
  onConnectUri,
1612
2050
  onCancel,
1613
2051
  onPoll,
1614
- isLinkAccount
1615
- } = _h, urlOptions = __objRest(_h, [
2052
+ isLinkAccount,
2053
+ serverAuthState: optsServerAuthState
2054
+ } = _f, urlOptions = __objRest(_f, [
1616
2055
  "isCanceled",
1617
2056
  "onConnectUri",
1618
2057
  "onCancel",
1619
2058
  "onPoll",
1620
- "isLinkAccount"
2059
+ "isLinkAccount",
2060
+ "serverAuthState"
1621
2061
  ]);
2062
+ if (optsServerAuthState) {
2063
+ const authState = yield __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, optsServerAuthState, urlOptions);
2064
+ return authState;
2065
+ }
1622
2066
  let accountLinkInProgress;
1623
2067
  if (isLinkAccount) {
1624
2068
  accountLinkInProgress = yield __privateMethod(this, _ParaCore_instances, assertIsLinkingAccountOrStart_fn).call(this, "FARCASTER");
@@ -1680,7 +2124,9 @@ const _ParaCore = class _ParaCore {
1680
2124
  }
1681
2125
  getOAuthUrl(opts) {
1682
2126
  return __async(this, null, function* () {
1683
- return __privateMethod(this, _ParaCore_instances, getOAuthUrl_fn).call(this, opts);
2127
+ var _a;
2128
+ const sessionLookupId = (_a = opts.sessionLookupId) != null ? _a : yield this.prepareLogin();
2129
+ return __privateMethod(this, _ParaCore_instances, getOAuthUrl_fn).call(this, __spreadProps(__spreadValues({}, opts), { sessionLookupId }));
1684
2130
  });
1685
2131
  }
1686
2132
  /**
@@ -1691,35 +2137,54 @@ const _ParaCore = class _ParaCore {
1691
2137
  * @param {Window} [opts.popupWindow] the popup window being used for login.
1692
2138
  * @return {Object} `{ email?: string; isError?: boolean; userExists: boolean; }` the result data
1693
2139
  */
1694
- verifyOAuthProcess(_k) {
2140
+ verifyOAuthProcess(_g) {
1695
2141
  return __async(this, null, function* () {
1696
- var _l = _k, {
2142
+ var _h = _g, {
1697
2143
  method,
1698
2144
  appScheme,
1699
2145
  isCanceled = () => false,
1700
2146
  onCancel,
1701
2147
  onPoll,
1702
2148
  onOAuthUrl,
2149
+ onOAuthPopup,
1703
2150
  isLinkAccount
1704
- } = _l, urlOptions = __objRest(_l, [
2151
+ } = _h, urlOptions = __objRest(_h, [
1705
2152
  "method",
1706
2153
  "appScheme",
1707
2154
  "isCanceled",
1708
2155
  "onCancel",
1709
2156
  "onPoll",
1710
2157
  "onOAuthUrl",
2158
+ "onOAuthPopup",
1711
2159
  "isLinkAccount"
1712
2160
  ]);
2161
+ if (onOAuthPopup) {
2162
+ try {
2163
+ this.popupWindow = yield this.platformUtils.openPopup("about:blank", { type: PopupType.OAUTH });
2164
+ } catch (error) {
2165
+ throw new Error(`Failed to open OAuth popup: ${error}`);
2166
+ }
2167
+ }
1713
2168
  let sessionLookupId, accountLinkInProgress;
1714
- if (onOAuthUrl) {
2169
+ if (onOAuthUrl || onOAuthPopup) {
1715
2170
  if (isLinkAccount) {
1716
2171
  accountLinkInProgress = yield __privateMethod(this, _ParaCore_instances, assertIsLinkingAccountOrStart_fn).call(this, method);
1717
2172
  sessionLookupId = (yield this.touchSession()).sessionLookupId;
1718
2173
  } else {
1719
- sessionLookupId = yield __privateMethod(this, _ParaCore_instances, prepareLogin_fn).call(this);
2174
+ sessionLookupId = yield this.prepareLogin();
1720
2175
  }
1721
2176
  const oAuthUrl = yield __privateMethod(this, _ParaCore_instances, getOAuthUrl_fn).call(this, { method, appScheme, sessionLookupId, accountLinkInProgress });
1722
- onOAuthUrl(oAuthUrl);
2177
+ switch (true) {
2178
+ case !!onOAuthUrl: {
2179
+ onOAuthUrl(oAuthUrl);
2180
+ break;
2181
+ }
2182
+ case (!!onOAuthPopup && !!this.popupWindow): {
2183
+ this.popupWindow.location.href = oAuthUrl;
2184
+ onOAuthPopup(this.popupWindow);
2185
+ break;
2186
+ }
2187
+ }
1723
2188
  } else {
1724
2189
  ({ sessionLookupId } = yield this.touchSession());
1725
2190
  }
@@ -1778,61 +2243,26 @@ const _ParaCore = class _ParaCore {
1778
2243
  * @param {boolean} [opts.skipSessionRefresh] whether to skip refreshing the session.
1779
2244
  * @returns {Object} `{ isComplete: boolean; isError: boolean; needsWallet: boolean; partnerId: string; }` the result data
1780
2245
  **/
1781
- waitForLogin() {
1782
- return __async(this, arguments, function* ({
1783
- isCanceled = () => false,
1784
- onCancel,
1785
- onPoll,
1786
- skipSessionRefresh = false
1787
- } = {}) {
1788
- const startedAt = Date.now();
1789
- return new Promise((resolve, reject) => {
1790
- (() => __async(this, null, function* () {
1791
- var _a;
1792
- if (!this.isExternalWalletAuth) {
1793
- this.externalWallets = {};
1794
- }
1795
- while (true) {
1796
- if (isCanceled() || Date.now() - startedAt > constants.POLLING_TIMEOUT_MS) {
1797
- dispatchEvent(ParaEvent.LOGIN_EVENT, { isComplete: false }, "failed to setup user");
1798
- onCancel == null ? void 0 : onCancel();
1799
- return reject("canceled");
1800
- }
1801
- yield new Promise((resolve2) => setTimeout(resolve2, constants.POLLING_INTERVAL_MS));
1802
- try {
1803
- let session = yield this.touchSession();
1804
- if (!session.isAuthenticated) {
1805
- onPoll == null ? void 0 : onPoll();
1806
- continue;
1807
- }
1808
- session = yield this.userSetupAfterLogin();
1809
- const needsWallet = (_a = session.needsWallet) != null ? _a : false;
1810
- if (!needsWallet) {
1811
- if (this.currentWalletIdsArray.length === 0) {
1812
- onPoll == null ? void 0 : onPoll();
1813
- continue;
1814
- }
1815
- }
1816
- const fetchedWallets = yield this.fetchWallets();
1817
- const tempSharesRes = yield this.getTransmissionKeyShares();
1818
- if (tempSharesRes.data.temporaryShares.length === fetchedWallets.length) {
1819
- yield this.setupAfterLogin({ temporaryShares: tempSharesRes.data.temporaryShares, skipSessionRefresh });
1820
- yield this.claimPregenWallets();
1821
- const resp = {
1822
- needsWallet: needsWallet || Object.values(this.wallets).length === 0,
1823
- partnerId: session.partnerId
1824
- };
1825
- dispatchEvent(ParaEvent.LOGIN_EVENT, resp);
1826
- return resolve(resp);
1827
- }
1828
- onPoll == null ? void 0 : onPoll();
1829
- } catch (err) {
1830
- console.error(err);
1831
- onPoll == null ? void 0 : onPoll();
1832
- }
1833
- }
1834
- }))();
1835
- });
2246
+ waitForLogin(args) {
2247
+ return __async(this, null, function* () {
2248
+ return yield __privateMethod(this, _ParaCore_instances, waitForLoginProcess_fn).call(this, args);
2249
+ });
2250
+ }
2251
+ waitForWalletSwitching(args) {
2252
+ return __async(this, null, function* () {
2253
+ return yield __privateMethod(this, _ParaCore_instances, waitForLoginProcess_fn).call(this, __spreadProps(__spreadValues({}, args), { isSwitchingWallets: true }));
2254
+ });
2255
+ }
2256
+ /**
2257
+ * Gets the switch wallets URL for wallet selection.
2258
+ * The authMethod is automatically included in the URL if available.
2259
+ *
2260
+ * @returns {Promise<{ url: string; authMethod: TAuthMethod }>} The switch wallets URL and authMethod
2261
+ */
2262
+ getSwitchWalletsUrl() {
2263
+ return __async(this, null, function* () {
2264
+ const url = yield this.constructPortalUrl("switchWallets");
2265
+ return url;
1836
2266
  });
1837
2267
  }
1838
2268
  /**
@@ -1855,7 +2285,7 @@ const _ParaCore = class _ParaCore {
1855
2285
  sessionId
1856
2286
  });
1857
2287
  if (shouldOpenPopup) {
1858
- this.platformUtils.openPopup(link);
2288
+ yield this.platformUtils.openPopup(link);
1859
2289
  }
1860
2290
  return link;
1861
2291
  });
@@ -1946,7 +2376,9 @@ const _ParaCore = class _ParaCore {
1946
2376
  userId: this.userId,
1947
2377
  walletId,
1948
2378
  userShare: userSigner,
1949
- emailProps: this.getBackupKitEmailProps()
2379
+ emailProps: this.getBackupKitEmailProps(),
2380
+ isEnclaveUser: this.isEnclaveUser,
2381
+ walletScheme: this.wallets[walletId].scheme
1950
2382
  });
1951
2383
  return recoveryShare;
1952
2384
  });
@@ -1960,7 +2392,7 @@ const _ParaCore = class _ParaCore {
1960
2392
  break;
1961
2393
  }
1962
2394
  ++maxPolls;
1963
- const res = yield this.ctx.client.getWallets(this.userId);
2395
+ const res = yield (this.isPortal() ? this.ctx.client.getAllWallets : this.ctx.client.getWallets)(this.userId);
1964
2396
  const wallet = res.data.wallets.find((w) => w.id === walletId);
1965
2397
  if (wallet && wallet.address) {
1966
2398
  return;
@@ -2074,7 +2506,9 @@ const _ParaCore = class _ParaCore {
2074
2506
  ignoreRedistributingBackupEncryptedShare: !redistributeBackupEncryptedShares,
2075
2507
  emailProps: this.getBackupKitEmailProps(),
2076
2508
  partnerId: newPartnerId,
2077
- protocolId
2509
+ protocolId,
2510
+ isEnclaveUser: this.isEnclaveUser,
2511
+ walletScheme: this.wallets[walletId].scheme
2078
2512
  });
2079
2513
  return { signer, recoverySecret, protocolId };
2080
2514
  });
@@ -2123,26 +2557,29 @@ const _ParaCore = class _ParaCore {
2123
2557
  }
2124
2558
  }
2125
2559
  const walletId = keygenRes.walletId;
2560
+ const walletScheme = walletType === "SOLANA" ? "ED25519" : "DKLS";
2126
2561
  signer = keygenRes.signer;
2127
- this.wallets[walletId] = {
2128
- id: walletId,
2129
- signer,
2130
- scheme: walletType === "SOLANA" ? "ED25519" : "DKLS",
2131
- type: walletType
2132
- };
2133
- wallet = this.wallets[walletId];
2134
- yield this.waitForWalletAddress(wallet.id);
2135
- yield this.populateWalletAddresses();
2562
+ yield this.waitForWalletAddress(walletId);
2136
2563
  let recoveryShare = null;
2137
2564
  if (!skipDistribute) {
2138
2565
  recoveryShare = yield distributeNewShare({
2139
2566
  ctx: this.ctx,
2140
2567
  userId: this.userId,
2141
- walletId: wallet.id,
2568
+ walletId,
2142
2569
  userShare: signer,
2143
- emailProps: this.getBackupKitEmailProps()
2570
+ emailProps: this.getBackupKitEmailProps(),
2571
+ isEnclaveUser: this.isEnclaveUser,
2572
+ walletScheme
2144
2573
  });
2145
2574
  }
2575
+ this.wallets[walletId] = {
2576
+ id: walletId,
2577
+ signer,
2578
+ scheme: walletScheme,
2579
+ type: walletType
2580
+ };
2581
+ wallet = this.wallets[walletId];
2582
+ yield this.populateWalletAddresses();
2146
2583
  yield this.setCurrentWalletIds(__spreadProps(__spreadValues({}, this.currentWalletIds), {
2147
2584
  [walletType]: [.../* @__PURE__ */ new Set([...(_b = this.currentWalletIds[walletType]) != null ? _b : [], walletId])]
2148
2585
  }));
@@ -2221,7 +2658,9 @@ const _ParaCore = class _ParaCore {
2221
2658
  walletId: wallet.id,
2222
2659
  userShare: this.wallets[wallet.id].signer,
2223
2660
  emailProps: this.getBackupKitEmailProps(),
2224
- partnerId: wallet.partnerId
2661
+ partnerId: wallet.partnerId,
2662
+ isEnclaveUser: this.isEnclaveUser,
2663
+ walletScheme: wallet.scheme
2225
2664
  });
2226
2665
  if (distributeRes.length > 0) {
2227
2666
  newRecoverySecret = distributeRes;
@@ -2348,10 +2787,10 @@ const _ParaCore = class _ParaCore {
2348
2787
  dispatchEvent(ParaEvent.GUEST_WALLETS_CREATED, wallets);
2349
2788
  __privateSet(this, _isCreateGuestWalletsPending, false);
2350
2789
  return wallets;
2351
- } catch (e) {
2352
- dispatchEvent(ParaEvent.GUEST_WALLETS_CREATED, null, error == null ? void 0 : error.message);
2790
+ } catch (error2) {
2791
+ dispatchEvent(ParaEvent.GUEST_WALLETS_CREATED, null, error2 == null ? void 0 : error2.message);
2353
2792
  __privateSet(this, _isCreateGuestWalletsPending, false);
2354
- throw error;
2793
+ throw error2;
2355
2794
  }
2356
2795
  });
2357
2796
  }
@@ -2399,25 +2838,12 @@ const _ParaCore = class _ParaCore {
2399
2838
  });
2400
2839
  });
2401
2840
  }
2402
- getOnRampTransactionUrl(_m) {
2403
- return __async(this, null, function* () {
2404
- var _n = _m, {
2405
- purchaseId,
2406
- providerKey
2407
- } = _n, walletParams = __objRest(_n, [
2408
- "purchaseId",
2409
- "providerKey"
2410
- ]);
2411
- const { sessionId } = yield this.touchSession();
2412
- const [key, identifier] = extractWalletRef(walletParams);
2841
+ getOnRampTransactionUrl(_0) {
2842
+ return __async(this, arguments, function* ({
2843
+ purchaseId
2844
+ }) {
2413
2845
  return this.constructPortalUrl("onRamp", {
2414
- pathId: purchaseId,
2415
- sessionId,
2416
- params: {
2417
- [key]: identifier,
2418
- providerKey,
2419
- currentWalletIds: JSON.stringify(this.currentWalletIds)
2420
- }
2846
+ pathId: purchaseId
2421
2847
  });
2422
2848
  });
2423
2849
  }
@@ -2442,6 +2868,7 @@ const _ParaCore = class _ParaCore {
2442
2868
  onCancel,
2443
2869
  onPoll
2444
2870
  }) {
2871
+ var _a;
2445
2872
  this.assertIsValidWalletId(walletId);
2446
2873
  const wallet = this.wallets[walletId];
2447
2874
  let signerId = this.userId;
@@ -2451,7 +2878,7 @@ const _ParaCore = class _ParaCore {
2451
2878
  let signRes = yield this.signMessageInner({ wallet, signerId, messageBase64, cosmosSignDocBase64 });
2452
2879
  let timeStart = Date.now();
2453
2880
  if (signRes.pendingTransactionId) {
2454
- this.platformUtils.openPopup(
2881
+ yield this.platformUtils.openPopup(
2455
2882
  yield this.getTransactionReviewUrl(signRes.pendingTransactionId, timeoutMs),
2456
2883
  { type: cosmosSignDocBase64 ? PopupType.SIGN_TRANSACTION_REVIEW : PopupType.SIGN_MESSAGE_REVIEW }
2457
2884
  );
@@ -2465,18 +2892,19 @@ const _ParaCore = class _ParaCore {
2465
2892
  break;
2466
2893
  }
2467
2894
  yield new Promise((resolve) => setTimeout(resolve, constants.POLLING_INTERVAL_MS));
2895
+ let pendingTransaction;
2468
2896
  try {
2469
- yield this.ctx.client.getPendingTransaction(this.userId, signRes.pendingTransactionId);
2470
- } catch (err) {
2897
+ pendingTransaction = (_a = (yield this.ctx.client.getPendingTransaction(this.userId, signRes.pendingTransactionId)).data) == null ? void 0 : _a.pendingTransaction;
2898
+ } catch (e) {
2471
2899
  const error = new TransactionReviewDenied();
2472
2900
  dispatchEvent(ParaEvent.SIGN_MESSAGE_EVENT, signRes, error.message);
2473
2901
  throw error;
2474
2902
  }
2475
- signRes = yield this.signMessageInner({ wallet, signerId, messageBase64, cosmosSignDocBase64 });
2476
- if (signRes.pendingTransactionId) {
2903
+ if (!(pendingTransaction == null ? void 0 : pendingTransaction.approvedAt)) {
2477
2904
  onPoll == null ? void 0 : onPoll();
2478
2905
  continue;
2479
2906
  } else {
2907
+ signRes = yield this.signMessageInner({ wallet, signerId, messageBase64, cosmosSignDocBase64 });
2480
2908
  break;
2481
2909
  }
2482
2910
  }
@@ -2545,6 +2973,7 @@ const _ParaCore = class _ParaCore {
2545
2973
  onCancel,
2546
2974
  onPoll
2547
2975
  }) {
2976
+ var _a;
2548
2977
  this.assertIsValidWalletId(walletId);
2549
2978
  const wallet = this.wallets[walletId];
2550
2979
  let signerId = this.userId;
@@ -2563,7 +2992,7 @@ const _ParaCore = class _ParaCore {
2563
2992
  );
2564
2993
  let timeStart = Date.now();
2565
2994
  if (signRes.pendingTransactionId) {
2566
- this.platformUtils.openPopup(
2995
+ yield this.platformUtils.openPopup(
2567
2996
  yield this.getTransactionReviewUrl(signRes.pendingTransactionId, timeoutMs),
2568
2997
  { type: PopupType.SIGN_TRANSACTION_REVIEW }
2569
2998
  );
@@ -2577,27 +3006,28 @@ const _ParaCore = class _ParaCore {
2577
3006
  break;
2578
3007
  }
2579
3008
  yield new Promise((resolve) => setTimeout(resolve, constants.POLLING_INTERVAL_MS));
3009
+ let pendingTransaction;
2580
3010
  try {
2581
- yield this.ctx.client.getPendingTransaction(this.userId, signRes.pendingTransactionId);
2582
- } catch (err) {
3011
+ pendingTransaction = (_a = (yield this.ctx.client.getPendingTransaction(this.userId, signRes.pendingTransactionId)).data) == null ? void 0 : _a.pendingTransaction;
3012
+ } catch (e) {
2583
3013
  const error = new TransactionReviewDenied();
2584
3014
  dispatchEvent(ParaEvent.SIGN_TRANSACTION_EVENT, signRes, error.message);
2585
3015
  throw error;
2586
3016
  }
2587
- signRes = yield this.platformUtils.signTransaction(
2588
- this.ctx,
2589
- signerId,
2590
- walletId,
2591
- this.wallets[walletId].signer,
2592
- rlpEncodedTxBase64,
2593
- chainId,
2594
- this.retrieveSessionCookie(),
2595
- wallet.scheme === "DKLS"
2596
- );
2597
- if (signRes.pendingTransactionId) {
3017
+ if (!(pendingTransaction == null ? void 0 : pendingTransaction.approvedAt)) {
2598
3018
  onPoll == null ? void 0 : onPoll();
2599
3019
  continue;
2600
3020
  } else {
3021
+ signRes = yield this.platformUtils.signTransaction(
3022
+ this.ctx,
3023
+ signerId,
3024
+ walletId,
3025
+ this.wallets[walletId].signer,
3026
+ rlpEncodedTxBase64,
3027
+ chainId,
3028
+ this.retrieveSessionCookie(),
3029
+ wallet.scheme === "DKLS"
3030
+ );
2601
3031
  break;
2602
3032
  }
2603
3033
  }
@@ -2639,7 +3069,8 @@ const _ParaCore = class _ParaCore {
2639
3069
  providerKey: onRampPurchase.providerKey
2640
3070
  }, walletParams));
2641
3071
  if (shouldOpenPopup) {
2642
- this.platformUtils.openPopup(portalUrl, { type: PopupType.ON_RAMP_TRANSACTION });
3072
+ const onRampWindow = yield this.platformUtils.openPopup(portalUrl, { type: PopupType.ON_RAMP_TRANSACTION });
3073
+ this.onRampPopup = { window: onRampWindow, onRampPurchase };
2643
3074
  }
2644
3075
  return { onRampPurchase, portalUrl };
2645
3076
  });
@@ -2652,7 +3083,7 @@ const _ParaCore = class _ParaCore {
2652
3083
  try {
2653
3084
  yield this.ctx.client.keepSessionAlive(this.userId);
2654
3085
  return true;
2655
- } catch (err) {
3086
+ } catch (e) {
2656
3087
  return false;
2657
3088
  }
2658
3089
  });
@@ -2724,8 +3155,16 @@ const _ParaCore = class _ParaCore {
2724
3155
  }
2725
3156
  issueJwt() {
2726
3157
  return __async(this, arguments, function* ({ keyIndex = 0 } = {}) {
2727
- const res = yield this.ctx.client.issueJwt({ keyIndex });
2728
- return res;
3158
+ try {
3159
+ return yield this.ctx.client.issueJwt({ keyIndex });
3160
+ } catch (error) {
3161
+ if (error.status === 403 || error.status === 401) {
3162
+ const errorMessage = "The user needs to be logged in to issue a JWT. Please log in and try again.";
3163
+ this.displayModalError(errorMessage);
3164
+ console.warn(errorMessage);
3165
+ }
3166
+ throw error;
3167
+ }
2729
3168
  });
2730
3169
  }
2731
3170
  /**
@@ -2735,6 +3174,7 @@ const _ParaCore = class _ParaCore {
2735
3174
  **/
2736
3175
  logout() {
2737
3176
  return __async(this, arguments, function* ({ clearPregenWallets = false } = {}) {
3177
+ const shouldDispatchLogoutEvent = yield this.isSessionActive();
2738
3178
  yield this.ctx.client.logout();
2739
3179
  yield this.clearStorage();
2740
3180
  if (!clearPregenWallets) {
@@ -2754,7 +3194,9 @@ const _ParaCore = class _ParaCore {
2754
3194
  this.accountLinkInProgress = void 0;
2755
3195
  this.userId = void 0;
2756
3196
  this.sessionCookie = void 0;
2757
- dispatchEvent(ParaEvent.LOGOUT_EVENT, null);
3197
+ if (shouldDispatchLogoutEvent) {
3198
+ dispatchEvent(ParaEvent.LOGOUT_EVENT, null);
3199
+ }
2758
3200
  });
2759
3201
  }
2760
3202
  get toStringAdditions() {
@@ -2784,9 +3226,9 @@ const _ParaCore = class _ParaCore {
2784
3226
  {}
2785
3227
  );
2786
3228
  const obj = __spreadProps(__spreadValues({
2787
- partnerId: (_a = __privateGet(this, _partner)) == null ? void 0 : _a.id,
2788
- supportedWalletTypes: (_b = __privateGet(this, _partner)) == null ? void 0 : _b.supportedWalletTypes,
2789
- cosmosPrefix: (_c = __privateGet(this, _partner)) == null ? void 0 : _c.cosmosPrefix,
3229
+ partnerId: (_a = this.partner) == null ? void 0 : _a.id,
3230
+ supportedWalletTypes: (_b = this.partner) == null ? void 0 : _b.supportedWalletTypes,
3231
+ cosmosPrefix: (_c = this.partner) == null ? void 0 : _c.cosmosPrefix,
2790
3232
  authInfo: __privateGet(this, _authInfo),
2791
3233
  isGuestMode: this.isGuestMode,
2792
3234
  userId: this.userId,
@@ -2818,43 +3260,88 @@ const _ParaCore = class _ParaCore {
2818
3260
  }
2819
3261
  getNewCredentialAndUrl() {
2820
3262
  return __async(this, arguments, function* ({
2821
- authMethod = "PASSKEY",
3263
+ authMethod: optsAuthMethod,
2822
3264
  isForNewDevice = false,
2823
3265
  portalTheme,
2824
3266
  shorten = false
2825
3267
  } = {}) {
3268
+ const userAuthMethods = yield this.supportedUserAuthMethods();
3269
+ const isEnclaveUser = userAuthMethods.has(AuthMethod.BASIC_LOGIN);
3270
+ const isAddingBasicLogin = optsAuthMethod === "BASIC_LOGIN";
3271
+ if (isEnclaveUser && isAddingBasicLogin) {
3272
+ throw new Error("That user is already using basic login");
3273
+ }
3274
+ if (isEnclaveUser || isAddingBasicLogin) {
3275
+ isForNewDevice = true;
3276
+ }
3277
+ const authMethods = optsAuthMethod ? [optsAuthMethod] : isForNewDevice ? ["PASSKEY", "PIN", "PASSWORD"] : ["PASSKEY"];
2826
3278
  this.assertIsAuthSet();
2827
- let credentialId, urlType;
2828
- switch (authMethod) {
2829
- case "PASSKEY":
3279
+ let passkeyId, passwordId, urlType, credentialId;
3280
+ if (!isAddingBasicLogin) {
3281
+ const canAddPasswordOrPIN = !userAuthMethods.has(AuthMethod.PASSWORD) && !userAuthMethods.has(AuthMethod.PIN);
3282
+ if (authMethods.includes("PASSKEY") && (yield this.isPasskeySupported())) {
2830
3283
  ({
2831
- data: { id: credentialId }
3284
+ data: { id: passkeyId }
2832
3285
  } = yield this.ctx.client.addSessionPublicKey(this.userId, {
2833
- status: PublicKeyStatus.PENDING,
3286
+ status: AuthMethodStatus.PENDING,
2834
3287
  type: PublicKeyType.WEB
2835
3288
  }));
2836
3289
  urlType = "createAuth";
2837
- break;
2838
- case "PASSWORD":
2839
- ({
2840
- data: { id: credentialId }
2841
- } = yield this.ctx.client.addSessionPasswordPublicKey(this.userId, {
2842
- status: PasswordStatus.PENDING
2843
- }));
2844
- urlType = "createPassword";
2845
- break;
3290
+ }
3291
+ if (authMethods.includes("PASSWORD")) {
3292
+ if (!canAddPasswordOrPIN) {
3293
+ if (optsAuthMethod === "PASSWORD") throw new Error("A user cannot have more than one password or PIN.");
3294
+ } else {
3295
+ ({
3296
+ data: { id: passwordId }
3297
+ } = yield this.ctx.client.addSessionPasswordPublicKey(this.userId, {
3298
+ status: AuthMethodStatus.PENDING
3299
+ }));
3300
+ urlType = "createPassword";
3301
+ }
3302
+ }
3303
+ if (authMethods.includes("PIN")) {
3304
+ if (!canAddPasswordOrPIN) {
3305
+ if (optsAuthMethod === "PIN") throw new Error("A user cannot have more than one password or PIN.");
3306
+ } else {
3307
+ ({
3308
+ data: { id: passwordId }
3309
+ } = yield this.ctx.client.addSessionPasswordPublicKey(this.userId, {
3310
+ status: AuthMethodStatus.PENDING
3311
+ }));
3312
+ urlType = "createPIN";
3313
+ }
3314
+ }
3315
+ credentialId = passkeyId != null ? passkeyId : passwordId;
3316
+ if (this.isNativePasskey && authMethods.includes("PASSKEY")) {
3317
+ return { credentialId };
3318
+ }
2846
3319
  }
2847
- const url = this.isNativePasskey && urlType === "createAuth" ? void 0 : yield this.constructPortalUrl(urlType, {
3320
+ const { sessionId } = yield this.touchSession();
3321
+ const url = (isForNewDevice || urlType) && (yield this.constructPortalUrl(isForNewDevice ? "addNewCredential" : urlType, {
2848
3322
  isForNewDevice,
2849
3323
  pathId: credentialId,
2850
3324
  portalTheme,
2851
- shorten
2852
- });
3325
+ shorten,
3326
+ sessionId: isForNewDevice ? sessionId : void 0,
3327
+ addNewCredentialType: optsAuthMethod,
3328
+ addNewCredentialPasskeyId: passkeyId,
3329
+ addNewCredentialPasswordId: passwordId
3330
+ }));
2853
3331
  return __spreadValues({ credentialId }, url ? { url } : {});
2854
3332
  });
2855
3333
  }
3334
+ addCredential(_0) {
3335
+ return __async(this, arguments, function* ({ authMethod }) {
3336
+ if (authMethod === "PASSKEY" && !(yield this.isPasskeySupported())) {
3337
+ throw new Error("Passkeys are not supported.");
3338
+ }
3339
+ const { url } = yield this.getNewCredentialAndUrl({ isForNewDevice: true, authMethod });
3340
+ return url;
3341
+ });
3342
+ }
2856
3343
  /**
2857
- * Returns a Para Portal URL for logging in with a WebAuth passkey or a password.
3344
+ * Returns a Para Portal URL for logging in with a WebAuth passkey, password, PIN or OTP.
2858
3345
  * @param {Object} opts the options object
2859
3346
  * @param {String} opts.auth - the user auth to sign up or log in with, in the form ` { email: string } | { phone: `+${number}` } `
2860
3347
  * @param {boolean} opts.useShortUrls - whether to shorten the generated portal URLs
@@ -2880,6 +3367,12 @@ const _ParaCore = class _ParaCore {
2880
3367
  case "PASSWORD":
2881
3368
  urlType = "loginPassword";
2882
3369
  break;
3370
+ case "PIN":
3371
+ urlType = "loginPIN";
3372
+ break;
3373
+ case "BASIC_LOGIN":
3374
+ urlType = this.authInfo.authType === "externalWallet" ? "loginExternalWallet" : "loginOTP";
3375
+ break;
2883
3376
  default:
2884
3377
  throw new Error(`invalid authentication method: '${authMethod}'`);
2885
3378
  }
@@ -2890,10 +3383,30 @@ const _ParaCore = class _ParaCore {
2890
3383
  });
2891
3384
  });
2892
3385
  }
2893
- signUpOrLogIn(_o) {
3386
+ prepareLogin() {
3387
+ return __async(this, null, function* () {
3388
+ yield this.logout();
3389
+ const { sessionLookupId } = yield this.touchSession(true);
3390
+ if (!this.loginEncryptionKeyPair) {
3391
+ yield this.setLoginEncryptionKeyPair();
3392
+ }
3393
+ return sessionLookupId;
3394
+ });
3395
+ }
3396
+ signUpOrLogIn(_i) {
2894
3397
  return __async(this, null, function* () {
2895
- var _p = _o, { auth } = _p, urlOptions = __objRest(_p, ["auth"]);
2896
- const serverAuthState = yield this.ctx.client.signUpOrLogIn(__spreadValues(__spreadValues({}, auth), this.getVerificationEmailProps()));
3398
+ var _j = _i, { auth } = _j, urlOptions = __objRest(_j, ["auth"]);
3399
+ let serverAuthState;
3400
+ try {
3401
+ serverAuthState = yield this.ctx.client.signUpOrLogIn(__spreadValues(__spreadValues({}, auth), this.getVerificationEmailProps()));
3402
+ } catch (error) {
3403
+ if (error.message.includes("max beta users reached")) {
3404
+ this.displayModalError(
3405
+ `50 user limit reached. [Go to Production.](https://docs.getpara.com/v2/general/checklist#go-live-checklist)`
3406
+ );
3407
+ }
3408
+ throw error;
3409
+ }
2897
3410
  const authInfo = serverAuthState.auth;
2898
3411
  if (this.fetchPregenWalletsOverride && isPregenAuth(authInfo)) {
2899
3412
  const { userShare } = yield this.fetchPregenWalletsOverride({ pregenId: authInfo });
@@ -2901,21 +3414,25 @@ const _ParaCore = class _ParaCore {
2901
3414
  yield this.setUserShare(userShare);
2902
3415
  }
2903
3416
  }
2904
- return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
3417
+ return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, __spreadValues({}, urlOptions));
2905
3418
  });
2906
3419
  }
2907
- verifyNewAccount(_q) {
3420
+ verifyNewAccount(_k) {
2908
3421
  return __async(this, null, function* () {
2909
- var _r = _q, {
3422
+ var _l = _k, {
2910
3423
  verificationCode
2911
- } = _r, urlOptions = __objRest(_r, [
3424
+ } = _l, urlOptions = __objRest(_l, [
2912
3425
  "verificationCode"
2913
3426
  ]);
2914
3427
  this.assertIsAuthSet(["email", "phone"]);
2915
- const userId = this.assertUserId();
2916
- const serverAuthState = yield this.ctx.client.verifyNewAccount(userId, {
3428
+ const userId = this.assertUserId({ allowGuestMode: true });
3429
+ const serverAuthState = yield this.ctx.client.verifyAccount(userId, {
2917
3430
  verificationCode
2918
3431
  });
3432
+ if (serverAuthState.stage === "login" || serverAuthState.stage === "done") {
3433
+ throw new Error("Account already exists.");
3434
+ }
3435
+ yield this.touchSession(true);
2919
3436
  return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
2920
3437
  });
2921
3438
  }
@@ -2963,7 +3480,7 @@ const _ParaCore = class _ParaCore {
2963
3480
  }
2964
3481
  break;
2965
3482
  default:
2966
- throw new Error("Invalid parameters for linking account, must pass `auth` or `type` or `externalWallet");
3483
+ throw new Error("Invalid parameters for linking account, must pass `auth` or `type` or `externalWallet`");
2967
3484
  }
2968
3485
  if (!isPermitted) {
2969
3486
  throw new Error(`Account linking for type '${type}' is not supported by the current API key configuration`);
@@ -3002,10 +3519,10 @@ const _ParaCore = class _ParaCore {
3002
3519
  });
3003
3520
  }
3004
3521
  verifyLink() {
3005
- return __async(this, arguments, function* (_s = {}) {
3006
- var _t = _s, {
3522
+ return __async(this, arguments, function* (_m = {}) {
3523
+ var _n = _m, {
3007
3524
  accountLinkInProgress = __privateMethod(this, _ParaCore_instances, assertIsLinkingAccount_fn).call(this)
3008
- } = _t, opts = __objRest(_t, [
3525
+ } = _n, opts = __objRest(_n, [
3009
3526
  "accountLinkInProgress"
3010
3527
  ]);
3011
3528
  try {
@@ -3034,31 +3551,80 @@ const _ParaCore = class _ParaCore {
3034
3551
  return accounts;
3035
3552
  });
3036
3553
  }
3554
+ getProfileBalance() {
3555
+ return __async(this, arguments, function* ({ config, refetch = false } = {}) {
3556
+ const { balance } = yield this.ctx.client.getProfileBalance({
3557
+ config,
3558
+ wallets: this.availableWallets.filter(({ type }) => type !== "COSMOS").map(({ type, address }) => ({ type, address })),
3559
+ refetch
3560
+ });
3561
+ return balance;
3562
+ });
3563
+ }
3564
+ sendLoginCode() {
3565
+ return __async(this, null, function* () {
3566
+ const { userId } = yield this.ctx.client.sendLoginVerificationCode(this.authInfo);
3567
+ this.setUserId(userId);
3568
+ });
3569
+ }
3570
+ exportPrivateKey() {
3571
+ return __async(this, arguments, function* (args = {}) {
3572
+ let walletId = args == null ? void 0 : args.walletId;
3573
+ if (!(args == null ? void 0 : args.walletId)) {
3574
+ walletId = this.findWalletId(void 0, { forbidPregen: true, scheme: ["DKLS"] });
3575
+ }
3576
+ const wallet = this.wallets[walletId];
3577
+ if (this.externalWallets[walletId]) {
3578
+ throw new Error("Cannot export private key for an external wallet");
3579
+ }
3580
+ if (!wallet || !wallet.signer) {
3581
+ throw new Error("Wallet not found with id: " + walletId);
3582
+ }
3583
+ if (wallet.scheme !== "DKLS") {
3584
+ throw new Error("Cannot export private key for a Solana wallet");
3585
+ }
3586
+ if (wallet.isPregen && !!wallet.pregenIdentifier && wallet.pregenIdentifierType !== "GUEST_ID") {
3587
+ throw new Error("Cannot export private key for a pregenerated wallet");
3588
+ }
3589
+ if (args.shouldOpenPopup) {
3590
+ this.popupWindow = yield this.platformUtils.openPopup("about:blank", { type: PopupType.EXPORT_PRIVATE_KEY });
3591
+ }
3592
+ const exportPrivateKeyUrl = yield this.constructPortalUrl("exportPrivateKey", {
3593
+ pathId: walletId
3594
+ });
3595
+ if (args.shouldOpenPopup) {
3596
+ this.popupWindow.location.href = exportPrivateKeyUrl;
3597
+ }
3598
+ return {
3599
+ url: exportPrivateKeyUrl,
3600
+ popupWindow: this.popupWindow
3601
+ };
3602
+ });
3603
+ }
3037
3604
  };
3038
3605
  _authInfo = new WeakMap();
3039
- _partner = new WeakMap();
3040
3606
  _ParaCore_instances = new WeakSet();
3041
3607
  assertPartner_fn = function() {
3042
3608
  return __async(this, null, function* () {
3043
3609
  var _a, _b;
3044
- if (!__privateGet(this, _partner)) {
3610
+ if (!this.partner) {
3045
3611
  yield this.touchSession();
3046
3612
  }
3047
- if (((_a = __privateGet(this, _partner)) == null ? void 0 : _a.cosmosPrefix) && this.ctx.cosmosPrefix !== __privateGet(this, _partner).cosmosPrefix) {
3048
- this.ctx.cosmosPrefix = (_b = __privateGet(this, _partner)) == null ? void 0 : _b.cosmosPrefix;
3613
+ if (((_a = this.partner) == null ? void 0 : _a.cosmosPrefix) && this.ctx.cosmosPrefix !== this.partner.cosmosPrefix) {
3614
+ this.ctx.cosmosPrefix = (_b = this.partner) == null ? void 0 : _b.cosmosPrefix;
3049
3615
  }
3050
- return __privateGet(this, _partner);
3616
+ return this.partner;
3051
3617
  });
3052
3618
  };
3053
3619
  guestWalletIds_get = function() {
3054
3620
  var _a, _b, _c;
3055
- if (!((_a = __privateGet(this, _partner)) == null ? void 0 : _a.supportedWalletTypes)) {
3621
+ if (!((_a = this.partner) == null ? void 0 : _a.supportedWalletTypes)) {
3056
3622
  return {};
3057
3623
  }
3058
3624
  const guestId = (_c = (_b = this.pregenIds) == null ? void 0 : _b.GUEST_ID) == null ? void 0 : _c[0];
3059
3625
  return !!guestId ? Object.entries(this.wallets).reduce((acc, [id, wallet]) => {
3060
3626
  if (wallet.isPregen && !wallet.userId && wallet.pregenIdentifierType === "GUEST_ID" && wallet.pregenIdentifier === guestId) {
3061
- return __spreadValues(__spreadValues({}, acc), getEquivalentTypes(wallet.type).filter((type) => __privateGet(this, _partner).supportedWalletTypes.some((entry) => entry.type === type)).reduce((acc2, eqType) => {
3627
+ return __spreadValues(__spreadValues({}, acc), getEquivalentTypes(wallet.type).filter((type) => this.partner.supportedWalletTypes.some((entry) => entry.type === type)).reduce((acc2, eqType) => {
3062
3628
  var _a2;
3063
3629
  return __spreadProps(__spreadValues({}, acc2), { [eqType]: [.../* @__PURE__ */ new Set([...(_a2 = acc2[eqType]) != null ? _a2 : [], id])] });
3064
3630
  }, {}));
@@ -3119,8 +3685,8 @@ getPartner_fn = function(partnerId) {
3119
3685
  return void 0;
3120
3686
  }
3121
3687
  const res = yield this.ctx.client.getPartner(partnerId);
3122
- __privateSet(this, _partner, res.data.partner);
3123
- return __privateGet(this, _partner);
3688
+ this.partner = res.data.partner;
3689
+ return this.partner;
3124
3690
  });
3125
3691
  };
3126
3692
  assertIsLinkingAccount_fn = function(types) {
@@ -3142,29 +3708,208 @@ assertIsLinkingAccountOrStart_fn = function(type) {
3142
3708
  return yield this.linkAccount({ type });
3143
3709
  });
3144
3710
  };
3145
- getOAuthUrl_fn = function(_i) {
3146
- return __async(this, null, function* () {
3147
- var _j = _i, {
3148
- method,
3149
- appScheme,
3150
- accountLinkInProgress
3151
- } = _j, params = __objRest(_j, [
3152
- "method",
3153
- "appScheme",
3154
- "accountLinkInProgress"
3155
- ]);
3156
- var _a;
3157
- const sessionLookupId = (_a = params.sessionLookupId) != null ? _a : yield __privateMethod(this, _ParaCore_instances, prepareLogin_fn).call(this);
3711
+ getOAuthUrl_fn = function(_0) {
3712
+ return __async(this, arguments, function* ({
3713
+ method,
3714
+ appScheme,
3715
+ accountLinkInProgress,
3716
+ sessionLookupId,
3717
+ encryptionKey,
3718
+ portalCallbackParams
3719
+ }) {
3720
+ if (!accountLinkInProgress && !this.isPortal()) {
3721
+ return yield this.constructPortalUrl("oAuth", { sessionId: sessionLookupId, oAuthMethod: method, appScheme });
3722
+ }
3723
+ let portalSessionLookupId;
3724
+ if (this.isPortal()) {
3725
+ portalSessionLookupId = (yield this.touchSession(true)).sessionLookupId;
3726
+ }
3158
3727
  return constructUrl({
3159
3728
  base: getBaseOAuthUrl(this.ctx.env),
3160
- path: `/auth/${method}`,
3161
- params: __spreadValues({
3729
+ path: `/auth/${method.toLowerCase()}`,
3730
+ params: __spreadProps(__spreadValues({
3162
3731
  apiKey: this.ctx.apiKey,
3732
+ origin: typeof window !== "undefined" ? window.location.origin : void 0,
3163
3733
  sessionLookupId,
3734
+ portalSessionLookupId,
3164
3735
  appScheme
3165
3736
  }, accountLinkInProgress ? {
3166
3737
  linkedAccountId: this.accountLinkInProgress.id
3167
- } : {})
3738
+ } : {}), {
3739
+ callback: !accountLinkInProgress && (yield this.constructPortalUrl("oAuthCallback", __spreadValues({
3740
+ sessionId: sessionLookupId,
3741
+ oAuthMethod: method,
3742
+ appScheme,
3743
+ thisDevice: {
3744
+ sessionId: sessionLookupId,
3745
+ encryptionKey
3746
+ }
3747
+ }, this.isPortal() && { params: portalCallbackParams })))
3748
+ })
3749
+ });
3750
+ });
3751
+ };
3752
+ waitForLoginProcess_fn = function() {
3753
+ return __async(this, arguments, function* ({
3754
+ isCanceled = () => false,
3755
+ onCancel,
3756
+ onPoll,
3757
+ skipSessionRefresh = false,
3758
+ isSwitchingWallets = false
3759
+ } = {}) {
3760
+ this.devLog("[waitForLoginProcess] Starting", {
3761
+ isSwitchingWallets,
3762
+ skipSessionRefresh,
3763
+ isExternalWalletAuth: this.isExternalWalletAuth
3764
+ });
3765
+ const startedAt = Date.now();
3766
+ let originalCurrentWalletIdsHash;
3767
+ if (isSwitchingWallets) {
3768
+ this.devLog("[waitForLoginProcess] Wallet switching mode enabled");
3769
+ this.isSwitchingWallets = true;
3770
+ const session = yield this.touchSession();
3771
+ originalCurrentWalletIdsHash = session.currentWalletIdsHash;
3772
+ this.devLog("[waitForLoginProcess] Original wallet IDs hash", { originalCurrentWalletIdsHash });
3773
+ }
3774
+ return new Promise((resolve, reject) => {
3775
+ (() => __async(this, null, function* () {
3776
+ var _a;
3777
+ if (!this.isExternalWalletAuth && !isSwitchingWallets) {
3778
+ this.devLog("[waitForLoginProcess] Clearing external wallets");
3779
+ this.externalWallets = {};
3780
+ }
3781
+ let pollCount = 0;
3782
+ while (true) {
3783
+ pollCount++;
3784
+ this.devLog("[waitForLoginProcess] Poll iteration", {
3785
+ pollCount,
3786
+ elapsedMs: Date.now() - startedAt
3787
+ });
3788
+ if (isCanceled() || Date.now() - startedAt > constants.POLLING_TIMEOUT_MS) {
3789
+ this.devLog("[waitForLoginProcess] Canceled or timed out", {
3790
+ wasCanceled: isCanceled(),
3791
+ timedOut: Date.now() - startedAt > constants.POLLING_TIMEOUT_MS,
3792
+ elapsedMs: Date.now() - startedAt
3793
+ });
3794
+ if (isSwitchingWallets) {
3795
+ this.isSwitchingWallets = false;
3796
+ } else {
3797
+ dispatchEvent(ParaEvent.LOGIN_EVENT, { isComplete: false }, "failed to setup user");
3798
+ }
3799
+ onCancel == null ? void 0 : onCancel();
3800
+ return reject("canceled");
3801
+ }
3802
+ yield new Promise((resolve2) => setTimeout(resolve2, constants.POLLING_INTERVAL_MS));
3803
+ try {
3804
+ this.devLog("[waitForLoginProcess] Touching session");
3805
+ let session = yield this.touchSession();
3806
+ this.devLog("[waitForLoginProcess] Session state", {
3807
+ isAuthenticated: session.isAuthenticated,
3808
+ currentWalletIdsHash: session.currentWalletIdsHash,
3809
+ needsWallet: session.needsWallet
3810
+ });
3811
+ const shouldContinuePolling = isSwitchingWallets ? originalCurrentWalletIdsHash === session.currentWalletIdsHash : !session.isAuthenticated;
3812
+ this.devLog("[waitForLoginProcess] Should continue polling", {
3813
+ shouldContinuePolling,
3814
+ isSwitchingWallets,
3815
+ originalCurrentWalletIdsHash,
3816
+ sessionCurrentWalletIdsHash: session.currentWalletIdsHash,
3817
+ isAuthenticated: session.isAuthenticated
3818
+ });
3819
+ if (shouldContinuePolling) {
3820
+ onPoll == null ? void 0 : onPoll();
3821
+ continue;
3822
+ }
3823
+ this.devLog("[waitForLoginProcess] Authentication check passed, setting up user");
3824
+ session = yield this.userSetupAfterLogin();
3825
+ const needsWallet = (_a = session.needsWallet) != null ? _a : false;
3826
+ this.devLog("[waitForLoginProcess] User setup complete", { needsWallet });
3827
+ if (isSwitchingWallets) {
3828
+ const isWalletSwitchingComplete = originalCurrentWalletIdsHash !== session.currentWalletIdsHash;
3829
+ this.devLog("[waitForLoginProcess] Wallet switching check", {
3830
+ isWalletSwitchingComplete,
3831
+ originalHash: originalCurrentWalletIdsHash,
3832
+ sessionHash: session.currentWalletIdsHash
3833
+ });
3834
+ if (!isWalletSwitchingComplete) {
3835
+ onPoll == null ? void 0 : onPoll();
3836
+ continue;
3837
+ }
3838
+ } else if (!needsWallet) {
3839
+ this.devLog("[waitForLoginProcess] Checking wallet IDs", {
3840
+ currentWalletIdsArrayLength: this.currentWalletIdsArray.length
3841
+ });
3842
+ if (this.currentWalletIdsArray.length === 0) {
3843
+ this.devLog("[waitForLoginProcess] No wallet IDs yet, continuing to poll");
3844
+ onPoll == null ? void 0 : onPoll();
3845
+ continue;
3846
+ }
3847
+ }
3848
+ this.devLog("[waitForLoginProcess] Getting transmission key shares");
3849
+ const tempSharesRes = yield this.getTransmissionKeyShares();
3850
+ this.devLog("[waitForLoginProcess] Transmission shares received", {
3851
+ shareCount: tempSharesRes.data.temporaryShares.length,
3852
+ shares: tempSharesRes.data.temporaryShares.map((s) => ({
3853
+ walletId: s.walletId,
3854
+ walletScheme: s.walletScheme
3855
+ }))
3856
+ });
3857
+ let hasSharesForCurrentWallets;
3858
+ if (!isSwitchingWallets && !this.isPortal()) {
3859
+ this.devLog("[waitForLoginProcess] Fetching wallets");
3860
+ const fetchedWallets = yield this.fetchWallets();
3861
+ this.devLog("[waitForLoginProcess] Wallets fetched", {
3862
+ walletCount: fetchedWallets.length,
3863
+ wallets: fetchedWallets.map((w) => ({ id: w.id, type: w.type, scheme: w.scheme }))
3864
+ });
3865
+ hasSharesForCurrentWallets = tempSharesRes.data.temporaryShares.length === fetchedWallets.length;
3866
+ } else {
3867
+ hasSharesForCurrentWallets = this.currentWalletIdsArray.every(([walletId]) => {
3868
+ return tempSharesRes.data.temporaryShares.some((share) => share.walletId === walletId);
3869
+ });
3870
+ }
3871
+ this.devLog("[waitForLoginProcess] Checking shares for current wallets", {
3872
+ hasSharesForCurrentWallets,
3873
+ currentWalletIdsArray: this.currentWalletIdsArray,
3874
+ shares: tempSharesRes.data.temporaryShares.map((s) => ({
3875
+ walletId: s.walletId,
3876
+ walletScheme: s.walletScheme
3877
+ }))
3878
+ });
3879
+ if (hasSharesForCurrentWallets) {
3880
+ this.devLog("[waitForLoginProcess] Setting up after login");
3881
+ yield this.setupAfterLogin({ temporaryShares: tempSharesRes.data.temporaryShares, skipSessionRefresh });
3882
+ this.devLog("[waitForLoginProcess] Setup after login complete");
3883
+ this.devLog("[waitForLoginProcess] Claiming pregen wallets");
3884
+ yield this.claimPregenWallets();
3885
+ this.devLog("[waitForLoginProcess] Pregen wallets claimed");
3886
+ const resp = {
3887
+ needsWallet: needsWallet || Object.values(this.wallets).length === 0,
3888
+ partnerId: session.partnerId
3889
+ };
3890
+ this.devLog("[waitForLoginProcess] Login process complete", {
3891
+ needsWallet: resp.needsWallet,
3892
+ partnerId: resp.partnerId,
3893
+ walletCount: Object.values(this.wallets).length,
3894
+ isSwitchingWallets
3895
+ });
3896
+ if (isSwitchingWallets) {
3897
+ this.devLog("[waitForLoginProcess] Clearing wallet switching state");
3898
+ this.isSwitchingWallets = false;
3899
+ } else {
3900
+ this.devLog("[waitForLoginProcess] Dispatching LOGIN_EVENT");
3901
+ dispatchEvent(ParaEvent.LOGIN_EVENT, resp);
3902
+ }
3903
+ return resolve(resp);
3904
+ }
3905
+ this.devLog("[waitForLoginProcess] Not all shares available yet, continuing to poll");
3906
+ onPoll == null ? void 0 : onPoll();
3907
+ } catch (err) {
3908
+ console.error("[waitForLoginProcess] Error during polling iteration", err);
3909
+ onPoll == null ? void 0 : onPoll();
3910
+ }
3911
+ }
3912
+ }))();
3168
3913
  });
3169
3914
  });
3170
3915
  };
@@ -3218,8 +3963,9 @@ createPregenWallet_fn = function(opts) {
3218
3963
  _isCreateGuestWalletsPending = new WeakMap();
3219
3964
  prepareAuthState_fn = function(_0) {
3220
3965
  return __async(this, arguments, function* (serverAuthState, opts = {}) {
3221
- if (!opts.sessionLookupId && serverAuthState.stage === "login") {
3222
- opts.sessionLookupId = yield __privateMethod(this, _ParaCore_instances, prepareLogin_fn).call(this);
3966
+ var _a, _b;
3967
+ if (!opts.sessionLookupId && serverAuthState.stage === "login" && (!serverAuthState.externalWallet || !(((_a = serverAuthState.externalWallet) == null ? void 0 : _a.withFullParaAuth) && ((_b = serverAuthState.loginAuthMethods) == null ? void 0 : _b.includes(AuthMethod.PIN))))) {
3968
+ opts.sessionLookupId = yield this.prepareLogin();
3223
3969
  }
3224
3970
  const { auth, externalWallet, userId, displayName, pfpUrl, username } = serverAuthState;
3225
3971
  const authInfo = __spreadValues(__spreadValues({}, extractAuthInfo(auth, { isRequired: true })), Object.fromEntries(
@@ -3240,8 +3986,14 @@ prepareAuthState_fn = function(_0) {
3240
3986
  }
3241
3987
  let authState;
3242
3988
  switch (serverAuthState.stage) {
3989
+ case "done": {
3990
+ authState = yield __privateMethod(this, _ParaCore_instances, prepareDoneState_fn).call(this, serverAuthState);
3991
+ break;
3992
+ }
3243
3993
  case "verify":
3244
- authState = serverAuthState;
3994
+ authState = yield __privateMethod(this, _ParaCore_instances, prepareVerificationState_fn).call(this, serverAuthState, __spreadProps(__spreadValues({}, opts), {
3995
+ sessionLookupId: opts.sessionLookupId
3996
+ }));
3245
3997
  break;
3246
3998
  case "login":
3247
3999
  if (externalWallet && !(externalWallet == null ? void 0 : externalWallet.withFullParaAuth)) {
@@ -3261,14 +4013,36 @@ prepareAuthState_fn = function(_0) {
3261
4013
  return authState;
3262
4014
  });
3263
4015
  };
3264
- prepareLogin_fn = function() {
4016
+ prepareDoneState_fn = function(doneState) {
3265
4017
  return __async(this, null, function* () {
3266
- yield this.logout();
3267
- const { sessionLookupId } = yield this.touchSession(true);
3268
- if (!this.loginEncryptionKeyPair) {
3269
- yield this.setLoginEncryptionKeyPair();
4018
+ let isSLOPossible = doneState.authMethods.includes(AuthMethod.BASIC_LOGIN);
4019
+ this.isEnclaveUser = isSLOPossible;
4020
+ return doneState;
4021
+ });
4022
+ };
4023
+ prepareVerificationState_fn = function(_0, _1) {
4024
+ return __async(this, arguments, function* (verifyState, {
4025
+ useShortUrls: shorten = false,
4026
+ portalTheme,
4027
+ sessionLookupId
4028
+ }) {
4029
+ var _a;
4030
+ let isSLOPossible = false;
4031
+ if (verifyState.nextStage === "login") {
4032
+ isSLOPossible = verifyState.loginAuthMethods.includes(AuthMethod.BASIC_LOGIN);
4033
+ } else if (verifyState.nextStage === "signup") {
4034
+ isSLOPossible = verifyState.signupAuthMethods.includes(AuthMethod.BASIC_LOGIN);
3270
4035
  }
3271
- return sessionLookupId;
4036
+ this.isEnclaveUser = isSLOPossible;
4037
+ const isExternalWalletFullAuth = (_a = verifyState.externalWallet) == null ? void 0 : _a.withFullParaAuth;
4038
+ return __spreadValues(__spreadValues({}, verifyState), isSLOPossible || isExternalWalletFullAuth ? {
4039
+ loginUrl: yield this.getLoginUrl({
4040
+ authMethod: AuthMethod.BASIC_LOGIN,
4041
+ sessionId: sessionLookupId,
4042
+ shorten,
4043
+ portalTheme
4044
+ })
4045
+ } : {});
3272
4046
  });
3273
4047
  };
3274
4048
  prepareLoginState_fn = function(_0, _1) {
@@ -3277,10 +4051,11 @@ prepareLoginState_fn = function(_0, _1) {
3277
4051
  portalTheme,
3278
4052
  sessionLookupId
3279
4053
  }) {
3280
- const _a = loginState, { loginAuthMethods } = _a, authState = __objRest(_a, ["loginAuthMethods"]);
3281
- const isPasskeySupported = yield this.isPasskeySupported(), isPasskeyPossible = loginAuthMethods.includes(AuthMethod.PASSKEY) && !this.isNativePasskey, isPasswordPossible = loginAuthMethods.includes(AuthMethod.PASSWORD);
3282
- return __spreadValues(__spreadValues(__spreadProps(__spreadValues({}, authState), {
3283
- isPasskeySupported
4054
+ const _a = loginState, { loginAuthMethods = [], hasPasswordWithoutPIN } = _a, authState = __objRest(_a, ["loginAuthMethods", "hasPasswordWithoutPIN"]);
4055
+ const isPasskeySupported = yield this.isPasskeySupported(), isPasskeyPossible = loginAuthMethods.includes(AuthMethod.PASSKEY) && !this.isNativePasskey, isPasswordPossible = loginAuthMethods.includes(AuthMethod.PASSWORD) && hasPasswordWithoutPIN, isPINPossible = loginAuthMethods.includes(AuthMethod.PIN);
4056
+ return __spreadValues(__spreadValues(__spreadValues(__spreadProps(__spreadValues({}, authState), {
4057
+ isPasskeySupported,
4058
+ loginAuthMethods
3284
4059
  }), isPasskeyPossible ? {
3285
4060
  passkeyUrl: yield this.getLoginUrl({ sessionId: sessionLookupId, shorten, portalTheme }),
3286
4061
  passkeyKnownDeviceUrl: yield this.constructPortalUrl("loginAuth", {
@@ -3299,23 +4074,34 @@ prepareLoginState_fn = function(_0, _1) {
3299
4074
  portalTheme,
3300
4075
  params: { isEmbedded: `${!loginState.isWalletSelectionNeeded}` }
3301
4076
  })
4077
+ } : {}), isPINPossible ? {
4078
+ pinUrl: yield this.constructPortalUrl("loginPIN", {
4079
+ sessionId: sessionLookupId,
4080
+ shorten,
4081
+ portalTheme,
4082
+ params: { isEmbedded: `${!loginState.isWalletSelectionNeeded}` }
4083
+ })
3302
4084
  } : {});
3303
4085
  });
3304
4086
  };
3305
4087
  prepareSignUpState_fn = function(_0, _1) {
3306
4088
  return __async(this, arguments, function* (serverSignupState, { useShortUrls: shorten = false, portalTheme }) {
3307
- const _a = serverSignupState, { signupAuthMethods } = _a, authState = __objRest(_a, ["signupAuthMethods"]);
4089
+ const _a = serverSignupState, { signupAuthMethods = [] } = _a, authState = __objRest(_a, ["signupAuthMethods"]);
3308
4090
  const isPasskeySupported = yield this.isPasskeySupported();
3309
- const [isPasskey, isPassword] = [
4091
+ const [isPasskey, isPassword, isPIN] = [
3310
4092
  signupAuthMethods.includes(AuthMethod.PASSKEY),
3311
- signupAuthMethods.includes(AuthMethod.PASSWORD) || !isPasskeySupported
4093
+ signupAuthMethods.includes(AuthMethod.PASSWORD) || !isPasskeySupported,
4094
+ signupAuthMethods.includes(AuthMethod.PIN)
3312
4095
  ];
3313
- if (!isPasskey && !isPassword) {
4096
+ if (!isPasskey && !isPassword && !isPIN) {
3314
4097
  throw new Error(
3315
- "No supported authentication methods found. Please ensure you have enabled either WebAuth passkeys or passwords in your Developer Portal settings."
4098
+ "No supported authentication methods found. Please ensure you have enabled either WebAuth passkeys, passwords or PINs in your Developer Portal settings."
3316
4099
  );
3317
4100
  }
3318
- const signupState = __spreadProps(__spreadValues({}, authState), { isPasskeySupported });
4101
+ const signupState = __spreadProps(__spreadValues({}, authState), {
4102
+ isPasskeySupported,
4103
+ signupAuthMethods
4104
+ });
3319
4105
  if (isPasskey) {
3320
4106
  const { url: passkeyUrl, credentialId: passkeyId } = yield this.getNewCredentialAndUrl({
3321
4107
  authMethod: "PASSKEY",
@@ -3333,6 +4119,15 @@ prepareSignUpState_fn = function(_0, _1) {
3333
4119
  signupState.passwordUrl = passwordUrl;
3334
4120
  signupState.passwordId = passwordId;
3335
4121
  }
4122
+ if (isPIN) {
4123
+ const { url: pinUrl, credentialId: pinId } = yield this.getNewCredentialAndUrl({
4124
+ authMethod: "PIN",
4125
+ portalTheme,
4126
+ shorten
4127
+ });
4128
+ signupState.pinUrl = pinUrl;
4129
+ signupState.pinId = pinId;
4130
+ }
3336
4131
  return signupState;
3337
4132
  });
3338
4133
  };