@getpara/core-sdk 2.0.0-alpha.7 → 2.0.0-alpha.70

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 (66) hide show
  1. package/dist/cjs/ParaCore.js +1516 -382
  2. package/dist/cjs/constants.js +13 -1
  3. package/dist/cjs/index.js +35 -3
  4. package/dist/cjs/shares/KeyContainer.js +3 -3
  5. package/dist/cjs/shares/enclave.js +266 -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/{onRamps.js → auth.js} +12 -12
  10. package/dist/cjs/types/coreApi.js +23 -3
  11. package/dist/cjs/types/events.js +2 -0
  12. package/dist/cjs/types/index.js +2 -21
  13. package/dist/cjs/types/popup.js +1 -0
  14. package/dist/cjs/utils/config.js +108 -0
  15. package/dist/cjs/utils/formatting.js +4 -0
  16. package/dist/cjs/utils/index.js +5 -1
  17. package/dist/cjs/utils/onRamps.js +2 -3
  18. package/dist/cjs/utils/wallet.js +18 -0
  19. package/dist/cjs/{types/recovery.js → utils/window.js} +17 -13
  20. package/dist/esm/ParaCore.js +1525 -388
  21. package/dist/esm/constants.js +9 -1
  22. package/dist/esm/index.js +36 -5
  23. package/dist/esm/shares/KeyContainer.js +3 -3
  24. package/dist/esm/shares/enclave.js +226 -0
  25. package/dist/esm/shares/shareDistribution.js +16 -1
  26. package/dist/esm/transmission/transmissionUtils.js +4 -3
  27. package/dist/esm/types/auth.js +11 -0
  28. package/dist/esm/types/coreApi.js +21 -2
  29. package/dist/esm/types/events.js +2 -0
  30. package/dist/esm/types/index.js +1 -16
  31. package/dist/esm/types/popup.js +1 -0
  32. package/dist/esm/utils/config.js +86 -0
  33. package/dist/esm/utils/formatting.js +2 -0
  34. package/dist/esm/utils/index.js +2 -0
  35. package/dist/esm/utils/onRamps.js +2 -3
  36. package/dist/esm/utils/wallet.js +17 -0
  37. package/dist/esm/utils/window.js +16 -0
  38. package/dist/types/ParaCore.d.ts +142 -57
  39. package/dist/types/PlatformUtils.d.ts +2 -3
  40. package/dist/types/constants.d.ts +18 -14
  41. package/dist/types/index.d.ts +6 -4
  42. package/dist/types/shares/KeyContainer.d.ts +0 -2
  43. package/dist/types/shares/enclave.d.ts +81 -0
  44. package/dist/types/shares/shareDistribution.d.ts +4 -2
  45. package/dist/types/types/assets.d.ts +14 -0
  46. package/dist/types/types/auth.d.ts +16 -0
  47. package/dist/types/types/config.d.ts +11 -2
  48. package/dist/types/types/coreApi.d.ts +133 -37
  49. package/dist/types/types/events.d.ts +7 -2
  50. package/dist/types/types/index.d.ts +1 -4
  51. package/dist/types/types/methods.d.ts +94 -15
  52. package/dist/types/types/popup.d.ts +2 -1
  53. package/dist/types/types/wallet.d.ts +11 -4
  54. package/dist/types/utils/config.d.ts +7 -0
  55. package/dist/types/utils/formatting.d.ts +2 -0
  56. package/dist/types/utils/index.d.ts +2 -0
  57. package/dist/types/utils/onRamps.d.ts +9 -10
  58. package/dist/types/utils/wallet.d.ts +1 -0
  59. package/dist/types/utils/window.d.ts +2 -0
  60. package/package.json +23 -23
  61. package/dist/esm/types/onRamps.js +0 -11
  62. package/dist/esm/types/recovery.js +0 -12
  63. package/dist/types/types/onRamps.d.ts +0 -10
  64. package/dist/types/types/recovery.d.ts +0 -7
  65. package/dist/types/types/theme.d.ts +0 -12
  66. /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, 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,
@@ -33,7 +31,9 @@ import {
33
31
  toPregenTypeAndId,
34
32
  toPregenIds,
35
33
  isExternalWallet,
36
- WALLET_TYPES
34
+ WALLET_TYPES,
35
+ LINKED_ACCOUNT_TYPES,
36
+ isPregenAuth
37
37
  } from "@getpara/user-management-client";
38
38
  import forge from "node-forge";
39
39
  const { pki, jsbn } = forge;
@@ -44,7 +44,8 @@ import { distributeNewShare } from "./shares/shareDistribution.js";
44
44
  import {
45
45
  Environment,
46
46
  PopupType,
47
- ParaEvent
47
+ ParaEvent,
48
+ AccountLinkError
48
49
  } from "./types/index.js";
49
50
  import { sendRecoveryForShare } from "./shares/recovery.js";
50
51
  import {
@@ -69,27 +70,28 @@ import {
69
70
  WalletSchemeTypeMap,
70
71
  shortenUrl,
71
72
  isServerAuthState,
72
- splitPhoneNumber
73
+ splitPhoneNumber,
74
+ currentWalletIdsEq,
75
+ isPortal
73
76
  } from "./utils/index.js";
74
77
  import { TransactionReviewDenied, TransactionReviewTimeout } from "./errors.js";
75
78
  import * as constants from "./constants.js";
79
+ import { EnclaveClient } from "./shares/enclave.js";
76
80
  const _ParaCore = class _ParaCore {
77
- /**
78
- * Constructs a new `ParaCore` instance.
79
- * @param env - `Environment` to use.
80
- * @param apiKey - API key to use.
81
- * @param opts - Additional constructor options; see `ConstructorOpts`.
82
- * @returns - A new ParaCore instance.
83
- */
84
- constructor(env, apiKey, opts) {
81
+ constructor(envOrApiKey, apiKeyOrOpts, opts) {
85
82
  __privateAdd(this, _ParaCore_instances);
83
+ this.popupWindow = null;
86
84
  __privateAdd(this, _authInfo);
85
+ this.isSwitchingWallets = false;
87
86
  this.isNativePasskey = false;
88
- __privateAdd(this, _partner);
87
+ this.isReady = false;
88
+ this.accountLinkInProgress = void 0;
89
+ this.isEnclaveUser = false;
89
90
  this.isAwaitingAccountCreation = false;
90
91
  this.isAwaitingLogin = false;
91
92
  this.isAwaitingFarcaster = false;
92
93
  this.isAwaitingOAuth = false;
94
+ this.isWorkerInitialized = false;
93
95
  /**
94
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.
95
97
  */
@@ -98,20 +100,34 @@ const _ParaCore = class _ParaCore {
98
100
  * Wallets associated with the `ParaCore` instance.
99
101
  */
100
102
  this.externalWallets = {};
103
+ this.onRampPopup = void 0;
104
+ this.nonPersistedStorageKeys = [];
101
105
  this.localStorageGetItem = (key) => {
102
- 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
+ }
103
110
  };
104
111
  this.localStorageSetItem = (key, value) => {
105
- 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
+ }
106
116
  };
107
117
  this.localStorageRemoveItem = (key) => {
108
118
  return this.platformUtils.localStorage.removeItem(key);
109
119
  };
110
120
  this.sessionStorageGetItem = (key) => {
111
- 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
+ }
112
125
  };
113
126
  this.sessionStorageSetItem = (key, value) => {
114
- 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
+ }
115
131
  };
116
132
  this.sessionStorageRemoveItem = (key) => {
117
133
  return this.platformUtils.sessionStorage.removeItem(key);
@@ -119,16 +135,29 @@ const _ParaCore = class _ParaCore {
119
135
  this.retrieveSessionCookie = () => {
120
136
  return this.sessionCookie;
121
137
  };
138
+ this.retrieveEnclaveJwt = () => {
139
+ return this.enclaveJwt;
140
+ };
141
+ this.retrieveEnclaveRefreshJwt = () => {
142
+ return this.enclaveRefreshJwt;
143
+ };
122
144
  /**
123
145
  * Remove all local storage and prefixed session storage.
124
146
  * @param {'local' | 'session' | 'secure' | 'all'} type - Type of storage to clear. Defaults to 'all'.
125
147
  */
126
148
  this.clearStorage = (type = "all") => __async(this, null, function* () {
127
149
  const isAll = type === "all";
128
- (isAll || type === "local") && this.platformUtils.localStorage.clear(constants.PREFIX);
129
- (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
+ }
130
158
  if ((isAll || type === "secure") && this.platformUtils.secureStorage) {
131
159
  this.platformUtils.secureStorage.clear(constants.PREFIX);
160
+ this.platformUtils.secureStorage.clear(constants.PARA_PREFIX);
132
161
  }
133
162
  });
134
163
  this.trackError = (methodName, err) => __async(this, null, function* () {
@@ -170,6 +199,7 @@ const _ParaCore = class _ParaCore {
170
199
  this.updateWalletIdsFromStorage();
171
200
  this.updateSessionCookieFromStorage();
172
201
  this.updateLoginEncryptionKeyPairFromStorage();
202
+ this.updateEnclaveJwtFromStorage();
173
203
  };
174
204
  this.updateAuthInfoFromStorage = () => {
175
205
  var _a;
@@ -189,6 +219,10 @@ const _ParaCore = class _ParaCore {
189
219
  }
190
220
  __privateSet(this, _authInfo, authInfo);
191
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
+ };
192
226
  this.updateUserIdFromStorage = () => {
193
227
  this.userId = this.localStorageGetItem(constants.LOCAL_STORAGE_USER_ID) || void 0;
194
228
  };
@@ -249,6 +283,16 @@ const _ParaCore = class _ParaCore {
249
283
  const _externalWallets = JSON.parse(stringExternalWallets || "{}");
250
284
  this.setExternalWallets(_externalWallets);
251
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
+ });
252
296
  /**
253
297
  * Creates several new wallets with the desired types. If no types are provided, this method
254
298
  * will create one for each of the non-optional types specified in the instance's `supportedWalletTypes`
@@ -265,8 +309,29 @@ const _ParaCore = class _ParaCore {
265
309
  }) {
266
310
  return (yield this.ctx.client.getWalletBalance({ walletId, rpcUrl })).balance;
267
311
  });
268
- if (!apiKey) {
269
- 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;
270
335
  }
271
336
  if (!opts) opts = {};
272
337
  let isE2E = false;
@@ -289,6 +354,7 @@ const _ParaCore = class _ParaCore {
289
354
  this.portalTheme = opts.portalTheme;
290
355
  this.platformUtils = this.getPlatformUtils();
291
356
  this.disableProviderModal = this.platformUtils.disableProviderModal;
357
+ this.fetchPregenWalletsOverride = opts.fetchPregenWalletsOverride;
292
358
  if (opts.useStorageOverrides) {
293
359
  this.localStorageGetItem = opts.localStorageGetItemOverride;
294
360
  this.localStorageSetItem = opts.localStorageSetItemOverride;
@@ -308,18 +374,41 @@ const _ParaCore = class _ParaCore {
308
374
  cookie
309
375
  );
310
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
+ });
311
407
  this.ctx = {
312
408
  env,
313
409
  apiKey,
314
- client: initClient({
315
- env,
316
- version: _ParaCore.version,
317
- apiKey,
318
- partnerId: this.isPortal(env) ? opts.portalPartnerId : void 0,
319
- useFetchAdapter: !!opts.disableWorkers,
320
- retrieveSessionCookie: this.retrieveSessionCookie,
321
- persistSessionCookie: this.persistSessionCookie
322
- }),
410
+ client,
411
+ enclaveClient,
323
412
  disableWorkers: opts.disableWorkers,
324
413
  offloadMPCComputationURL: opts.offloadMPCComputationURL,
325
414
  useLocalFiles: opts.useLocalFiles,
@@ -354,6 +443,9 @@ const _ParaCore = class _ParaCore {
354
443
  ]);
355
444
  }
356
445
  }
446
+ setModalError(_error) {
447
+ return;
448
+ }
357
449
  get authInfo() {
358
450
  return __privateGet(this, _authInfo);
359
451
  }
@@ -380,8 +472,15 @@ const _ParaCore = class _ParaCore {
380
472
  get externalWalletConnectionType() {
381
473
  if (this.isExternalWalletAuth) {
382
474
  return "AUTHENTICATED";
475
+ } else if (this.isExternalWalletWithVerification) {
476
+ return "VERIFICATION";
383
477
  } else if (!!Object.keys(this.externalWallets).length) {
384
- 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
+ }
385
484
  }
386
485
  return "NONE";
387
486
  }
@@ -402,16 +501,28 @@ const _ParaCore = class _ParaCore {
402
501
  return isTelegram((_a = this.authInfo) == null ? void 0 : _a.auth);
403
502
  }
404
503
  get isExternalWalletAuth() {
405
- var _a;
406
- return isExternalWallet((_a = __privateGet(this, _authInfo)) == null ? void 0 : _a.auth);
504
+ var _a, _b, _c;
505
+ return isExternalWallet((_a = __privateGet(this, _authInfo)) == null ? void 0 : _a.auth) && !!((_c = (_b = __privateGet(this, _authInfo)) == null ? void 0 : _b.externalWallet) == null ? void 0 : _c.withFullParaAuth);
506
+ }
507
+ get isExternalWalletWithVerification() {
508
+ var _a, _b, _c;
509
+ return isExternalWallet((_a = __privateGet(this, _authInfo)) == null ? void 0 : _a.auth) && !!((_c = (_b = __privateGet(this, _authInfo)) == null ? void 0 : _b.externalWallet) == null ? void 0 : _c.withVerification);
407
510
  }
408
511
  get partnerId() {
409
512
  var _a;
410
- 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;
411
522
  }
412
523
  get currentWalletIdsArray() {
413
524
  var _a, _b;
414
- 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(
415
526
  (acc, { type }) => {
416
527
  var _a2;
417
528
  return [
@@ -451,19 +562,23 @@ const _ParaCore = class _ParaCore {
451
562
  }
452
563
  get isNoWalletConfig() {
453
564
  var _a;
454
- 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;
455
566
  }
456
567
  get supportedWalletTypes() {
457
568
  var _a, _b;
458
- 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 : [];
459
570
  }
460
571
  get cosmosPrefix() {
461
572
  var _a;
462
- return (_a = __privateGet(this, _partner)) == null ? void 0 : _a.cosmosPrefix;
573
+ return (_a = this.partner) == null ? void 0 : _a.cosmosPrefix;
574
+ }
575
+ get supportedAccountLinks() {
576
+ var _a, _b;
577
+ return (_b = (_a = this.partner) == null ? void 0 : _a.supportedAccountLinks) != null ? _b : [...LINKED_ACCOUNT_TYPES];
463
578
  }
464
579
  get isWalletTypeEnabled() {
465
580
  var _a;
466
- 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 }) => {
467
582
  return __spreadProps(__spreadValues({}, acc), { [type]: true });
468
583
  }, {});
469
584
  }
@@ -493,9 +608,7 @@ const _ParaCore = class _ParaCore {
493
608
  };
494
609
  }
495
610
  isPortal(envOverride) {
496
- var _a;
497
- if (typeof window === "undefined") return false;
498
- 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);
499
612
  }
500
613
  isParaConnect() {
501
614
  var _a;
@@ -512,7 +625,7 @@ const _ParaCore = class _ParaCore {
512
625
  }
513
626
  isWalletSupported(wallet) {
514
627
  var _a, _b;
515
- 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);
516
629
  }
517
630
  isWalletOwned(wallet) {
518
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;
@@ -538,12 +651,12 @@ const _ParaCore = class _ParaCore {
538
651
  } else {
539
652
  const wallet = this.wallets[walletId];
540
653
  const [isUnclaimed, isOwned] = [this.isPregenWalletUnclaimed(wallet), this.isWalletOwned(wallet)];
541
- if (forbidPregen && isUnclaimed) {
654
+ if (forbidPregen && isUnclaimed && wallet.pregenIdentifierType !== "GUEST_ID") {
542
655
  error = `pre-generated wallet with id ${wallet == null ? void 0 : wallet.id} cannot be selected`;
543
656
  } else if (!isOwned && !isUnclaimed) {
544
657
  error = `wallet with id ${wallet == null ? void 0 : wallet.id} is not owned by the current user`;
545
658
  } else if (!this.isWalletSupported(wallet)) {
546
- 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(", ")}`;
547
660
  } else if (types && (!getEquivalentTypes(types).includes(wallet == null ? void 0 : wallet.type) || isOwned && !types.some((type) => {
548
661
  var _a2, _b2;
549
662
  return (_b2 = (_a2 = this.currentWalletIds) == null ? void 0 : _a2[type]) == null ? void 0 : _b2.includes(walletId);
@@ -561,6 +674,9 @@ const _ParaCore = class _ParaCore {
561
674
  }
562
675
  return true;
563
676
  }
677
+ truncateAddress(...args) {
678
+ return truncateAddress(args[0], args[1], __spreadValues({ prefix: this.cosmosPrefix }, args[2] || {}));
679
+ }
564
680
  /**
565
681
  * Returns the formatted address for the desired wallet ID, depending on your app settings.
566
682
  * @param {string} walletId the ID of the wallet address to display.
@@ -574,7 +690,7 @@ const _ParaCore = class _ParaCore {
574
690
  if (this.externalWallets[walletId]) {
575
691
  const wallet2 = this.externalWallets[walletId];
576
692
  return options.truncate ? truncateAddress(wallet2.address, wallet2.type, {
577
- prefix: (_a = __privateGet(this, _partner)) == null ? void 0 : _a.cosmosPrefix,
693
+ prefix: (_a = this.partner) == null ? void 0 : _a.cosmosPrefix,
578
694
  targetLength: options.targetLength
579
695
  }) : wallet2.address;
580
696
  }
@@ -586,7 +702,7 @@ const _ParaCore = class _ParaCore {
586
702
  let prefix;
587
703
  switch (wallet.type) {
588
704
  case "COSMOS":
589
- 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";
590
706
  str = getCosmosAddress(wallet.publicKey, prefix);
591
707
  break;
592
708
  default:
@@ -619,30 +735,55 @@ const _ParaCore = class _ParaCore {
619
735
  }
620
736
  constructPortalUrl(_0) {
621
737
  return __async(this, arguments, function* (type, opts = {}) {
622
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
623
- const [isCreate, isLogin, isOnRamp] = [
624
- ["createAuth", "createPassword"].includes(type),
625
- ["loginAuth", "loginPassword"].includes(type),
626
- 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"
627
761
  ];
762
+ if (isOAuth && !opts.oAuthMethod) {
763
+ throw new Error("oAuthMethod is required for oAuth portal URLs");
764
+ }
628
765
  if (isCreate || isLogin) {
629
766
  this.assertIsAuthSet();
630
767
  }
631
768
  let sessionId = opts.sessionId;
632
- if ((isLogin || isOnRamp) && !sessionId) {
769
+ if ((isLogin || isOnRamp || isTelegramLogin || isFarcasterLogin || isExportPrivateKey) && !sessionId) {
633
770
  const session = yield this.touchSession(true);
634
771
  sessionId = session.sessionId;
635
772
  }
636
773
  if (!this.loginEncryptionKeyPair) {
637
774
  yield this.setLoginEncryptionKeyPair();
638
775
  }
639
- const base = type === "onRamp" ? getPortalBaseURL(this.ctx) : yield this.getPortalURL();
776
+ const base = type === "onRamp" || isTelegramLogin ? getPortalBaseURL(this.ctx, isTelegramLogin) : yield this.getPortalURL();
640
777
  let path;
641
778
  switch (type) {
642
779
  case "createPassword": {
643
780
  path = `/web/users/${this.userId}/passwords/${opts.pathId}`;
644
781
  break;
645
782
  }
783
+ case "createPIN": {
784
+ path = `/web/users/${this.userId}/pin/${opts.pathId}`;
785
+ break;
786
+ }
646
787
  case "createAuth": {
647
788
  path = `/web/users/${this.userId}/biometrics/${opts.pathId}`;
648
789
  break;
@@ -655,42 +796,102 @@ const _ParaCore = class _ParaCore {
655
796
  path = "/web/biometrics/login";
656
797
  break;
657
798
  }
799
+ case "loginPIN": {
800
+ path = "/web/pin/login";
801
+ break;
802
+ }
658
803
  case "txReview": {
659
804
  path = `/web/users/${this.userId}/transaction-review/${opts.pathId}`;
660
805
  break;
661
806
  }
662
807
  case "onRamp": {
663
- 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`;
813
+ break;
814
+ }
815
+ case "telegramLogin": {
816
+ path = `/auth/telegram`;
817
+ break;
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";
664
853
  break;
665
854
  }
666
855
  default: {
667
856
  throw new Error(`invalid URL type ${type}`);
668
857
  }
669
858
  }
670
- const partner = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
859
+ let partner = void 0;
860
+ try {
861
+ partner = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
862
+ } catch (e) {
863
+ if (this.isPartnerOptional) {
864
+ partner = void 0;
865
+ } else {
866
+ throw e;
867
+ }
868
+ }
671
869
  const thisDevice = (_a = opts.thisDevice) != null ? _a : {
672
870
  encryptionKey: getPublicKeyHex(this.loginEncryptionKeyPair),
673
871
  sessionId
674
872
  };
675
- const params = __spreadValues(__spreadValues(__spreadValues(__spreadValues({
873
+ const params = __spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadProps(__spreadValues({
676
874
  apiKey: this.ctx.apiKey,
677
- partnerId: partner.id,
678
- portalFont: ((_b = opts.portalTheme) == null ? void 0 : _b.font) || (partner == null ? void 0 : partner.font) || ((_c = this.portalTheme) == null ? void 0 : _c.font),
679
- portalBorderRadius: ((_d = opts.portalTheme) == null ? void 0 : _d.borderRadius) || ((_e = this.portalTheme) == null ? void 0 : _e.borderRadius),
680
- portalThemeMode: ((_f = opts.portalTheme) == null ? void 0 : _f.mode) || (partner == null ? void 0 : partner.themeMode) || ((_g = this.portalTheme) == null ? void 0 : _g.mode),
681
- portalAccentColor: ((_h = opts.portalTheme) == null ? void 0 : _h.accentColor) || (partner == null ? void 0 : partner.accentColor) || ((_i = this.portalTheme) == null ? void 0 : _i.accentColor),
682
- portalForegroundColor: ((_j = opts.portalTheme) == null ? void 0 : _j.foregroundColor) || (partner == null ? void 0 : partner.foregroundColor) || ((_k = this.portalTheme) == null ? void 0 : _k.foregroundColor),
683
- 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,
684
884
  portalPrimaryButtonColor: this.portalPrimaryButtonColor,
685
885
  portalTextColor: this.portalTextColor,
686
886
  portalPrimaryButtonTextColor: this.portalPrimaryButtonTextColor,
687
887
  isForNewDevice: opts.isForNewDevice ? opts.isForNewDevice.toString() : void 0
688
- }, isCreate || isLogin ? __spreadProps(__spreadValues({
888
+ }), this.authInfo && (isCreate || isLogin || isAddNewCredential || isOAuthCallback || isSwitchWallets || isExportPrivateKey) ? __spreadProps(__spreadValues({
689
889
  authInfo: JSON.stringify(this.authInfo)
690
890
  }, isPhone(this.authInfo.auth) ? splitPhoneNumber(this.authInfo.auth.phone) : this.authInfo.auth), {
691
891
  pfpUrl: this.authInfo.pfpUrl,
692
- displayName: this.authInfo.displayName
693
- }) : {}), 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({
694
895
  sessionId: thisDevice.sessionId,
695
896
  encryptionKey: thisDevice.encryptionKey
696
897
  }, opts.newDevice ? {
@@ -698,7 +899,17 @@ const _ParaCore = class _ParaCore {
698
899
  newDeviceEncryptionKey: opts.newDevice.encryptionKey
699
900
  } : {}), {
700
901
  pregenIds: JSON.stringify(this.pregenIds)
701
- }) : {}), 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
+ } : {});
702
913
  const url = constructUrl({ base, path, params });
703
914
  if (opts.shorten) {
704
915
  return shortenUrl(this.ctx, url);
@@ -706,12 +917,75 @@ const _ParaCore = class _ParaCore {
706
917
  return url;
707
918
  });
708
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
+ }
709
939
  touchSession(regenerate = false) {
710
940
  return __async(this, null, function* () {
711
- var _a, _b, _c;
712
- const session = yield this.ctx.client.touchSession(regenerate);
713
- 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) {
714
- yield __privateMethod(this, _ParaCore_instances, getPartner_fn).call(this, session.partnerId);
941
+ var _a, _b, _c, _d, _e;
942
+ if (!this.isWorkerInitialized) {
943
+ this.initializeWorker();
944
+ }
945
+ if (!this.isReady) {
946
+ yield this.ready();
947
+ }
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);
715
989
  }
716
990
  return session;
717
991
  });
@@ -810,8 +1084,35 @@ const _ParaCore = class _ParaCore {
810
1084
  return __privateGet(this, _authInfo);
811
1085
  });
812
1086
  }
813
- assertUserId() {
814
- if (!this.userId) {
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) {
815
1116
  throw new Error("no userId is set");
816
1117
  }
817
1118
  return this.userId;
@@ -867,19 +1168,75 @@ const _ParaCore = class _ParaCore {
867
1168
  * @param externalAddress - External wallet address to set.
868
1169
  * @param externalType - Type of external wallet to set.
869
1170
  */
870
- setExternalWallet(_0) {
871
- return __async(this, arguments, function* ({ address, type, provider, addressBech32, withFullParaAuth }) {
872
- this.externalWallets = {
873
- [address]: {
874
- id: address,
875
- address: addressBech32 != null ? addressBech32 : address,
1171
+ setExternalWallet(externalWallet) {
1172
+ return __async(this, null, function* () {
1173
+ const { id: partnerId, supportedWalletTypes } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
1174
+ this.externalWallets = (Array.isArray(externalWallet) ? externalWallet : [externalWallet]).reduce(
1175
+ (acc, {
1176
+ partnerId: wPartnerId,
1177
+ address,
876
1178
  type,
877
- name: provider,
878
- isExternal: true,
879
- isExternalWithParaAuth: withFullParaAuth,
880
- signer: ""
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
+ });
881
1218
  }
882
- };
1219
+ return acc;
1220
+ }, {})), externalWallets.reduce(
1221
+ (acc, { address, type, provider, providerId, addressBech32, withFullParaAuth, isConnectionOnly, withVerification }) => {
1222
+ return __spreadProps(__spreadValues({}, acc), {
1223
+ [address]: {
1224
+ id: address,
1225
+ partnerId,
1226
+ address: addressBech32 != null ? addressBech32 : address,
1227
+ type,
1228
+ name: provider,
1229
+ isExternal: true,
1230
+ isExternalWithParaAuth: withFullParaAuth,
1231
+ externalProviderId: providerId,
1232
+ signer: "",
1233
+ isExternalConnectionOnly: isConnectionOnly,
1234
+ isExternalWithVerification: withVerification
1235
+ }
1236
+ });
1237
+ },
1238
+ {}
1239
+ ));
883
1240
  this.setExternalWallets(this.externalWallets);
884
1241
  dispatchEvent(ParaEvent.EXTERNAL_WALLET_CHANGE_EVENT, null);
885
1242
  });
@@ -910,12 +1267,16 @@ const _ParaCore = class _ParaCore {
910
1267
  }
911
1268
  /**
912
1269
  * Sets the external wallets associated with the `ParaCore` instance.
913
- * @param externalWallets - External wallets to set.
1270
+ * @param externalWallets - External wallets to set, or a function that modifies the current wallets.
914
1271
  */
915
1272
  setExternalWallets(externalWallets) {
916
1273
  return __async(this, null, function* () {
917
- this.externalWallets = externalWallets;
918
- 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));
919
1280
  });
920
1281
  }
921
1282
  /**
@@ -991,6 +1352,7 @@ const _ParaCore = class _ParaCore {
991
1352
  /**
992
1353
  * Fetches the most recent OAuth account metadata for the signed-in user.
993
1354
  * If applicable, this will include the user's most recent metadata from their Google, Apple, Facebook, X, Discord, Farcaster, or Telegram account, the last time they signed in to your app.
1355
+ * @deprecated use `para.getLinkedAccounts({ withMetadata: true })` instead.
994
1356
  * @returns {Promise<AccountMetadata>} the user's account metadata.
995
1357
  */
996
1358
  getAccountMetadata() {
@@ -1083,14 +1445,27 @@ const _ParaCore = class _ParaCore {
1083
1445
  ...[...this.currentWalletIdsArray, ...__privateGet(this, _ParaCore_instances, guestWalletIdsArray_get)].map(([address, type]) => [address, type, false]).map(([id, type]) => {
1084
1446
  const wallet = this.findWallet(id, type);
1085
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 });
1086
1451
  return {
1087
1452
  id: wallet.id,
1453
+ partner: wallet.partner,
1088
1454
  type,
1089
- address: this.getDisplayAddress(id, { addressType: type }),
1090
- name: wallet.name
1455
+ address,
1456
+ name,
1457
+ addressShort,
1458
+ displayName: name != null ? name : addressShort,
1459
+ ensName: wallet.ensName,
1460
+ ensAvatar: wallet.ensAvatar
1091
1461
  };
1092
1462
  }).filter((obj) => obj !== null),
1093
- ...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
+ })
1094
1469
  ];
1095
1470
  }
1096
1471
  /**
@@ -1136,8 +1511,15 @@ const _ParaCore = class _ParaCore {
1136
1511
  }
1137
1512
  getPartnerURL() {
1138
1513
  return __async(this, null, function* () {
1139
- const { portalUrl } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
1140
- return portalUrl;
1514
+ try {
1515
+ const { portalUrl } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
1516
+ return portalUrl;
1517
+ } catch (e) {
1518
+ if (this.isPartnerOptional) {
1519
+ return void 0;
1520
+ }
1521
+ throw e;
1522
+ }
1141
1523
  });
1142
1524
  }
1143
1525
  /**
@@ -1182,13 +1564,13 @@ const _ParaCore = class _ParaCore {
1182
1564
  return __async(this, null, function* () {
1183
1565
  const res = yield this.isPortal() || this.isParaConnect() ? this.ctx.client.getAllWallets(this.userId) : this.ctx.client.getWallets(this.userId, true);
1184
1566
  return res.data.wallets.filter(
1185
- (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)))
1186
1568
  );
1187
1569
  });
1188
1570
  }
1189
1571
  populateWalletAddresses() {
1190
1572
  return __async(this, null, function* () {
1191
- 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);
1192
1574
  const wallets = res.data.wallets;
1193
1575
  wallets.forEach((entity) => {
1194
1576
  if (this.wallets[entity.id]) {
@@ -1219,65 +1601,143 @@ const _ParaCore = class _ParaCore {
1219
1601
  loginExternalWallet(_a) {
1220
1602
  return __async(this, null, function* () {
1221
1603
  var _b = _a, {
1222
- externalWallet
1604
+ externalWallet,
1605
+ chainId,
1606
+ uri
1223
1607
  } = _b, urlOptions = __objRest(_b, [
1224
- "externalWallet"
1608
+ "externalWallet",
1609
+ "chainId",
1610
+ "uri"
1225
1611
  ]);
1226
- if (this.externalWalletConnectionOnly) {
1227
- externalWallet.withFullParaAuth = false;
1228
- yield this.setExternalWallet(externalWallet);
1612
+ const externalWallets = Array.isArray(externalWallet) ? externalWallet : [externalWallet];
1613
+ if (this.externalWalletConnectionOnly || externalWallets.every((wallet) => wallet.isConnectionOnly)) {
1614
+ yield this.addExternalWallets(
1615
+ externalWallets.map((wallet) => __spreadProps(__spreadValues({}, wallet), {
1616
+ withFullParaAuth: false
1617
+ }))
1618
+ );
1229
1619
  return Promise.resolve({
1230
1620
  userId: constants.EXTERNAL_WALLET_CONNECTION_ONLY_USER_ID
1231
1621
  });
1232
1622
  }
1623
+ if (Array.isArray(externalWallet)) {
1624
+ throw new Error(
1625
+ "Cannot authenticate multiple external wallets at once. To connect multiple wallets at once, use CONNECTION_ONLY mode."
1626
+ );
1627
+ }
1233
1628
  this.requireApiKey();
1234
- const serverAuthState = yield this.ctx.client.loginExternalWallet({ externalWallet });
1629
+ const serverAuthState = yield this.ctx.client.loginExternalWallet({ externalWallet, chainId, uri });
1630
+ if (!externalWallet.withFullParaAuth && externalWallet.withVerification) {
1631
+ yield this.touchSession(true);
1632
+ }
1633
+ if (externalWallet.withFullParaAuth) {
1634
+ yield this.ctx.client.sessionAddPortalVerification();
1635
+ }
1235
1636
  return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
1236
1637
  });
1237
1638
  }
1238
- verifyExternalWallet(_c) {
1639
+ verifyExternalWallet(params) {
1239
1640
  return __async(this, null, function* () {
1240
- var _d = _c, {
1241
- externalWallet,
1242
- signedMessage,
1243
- cosmosPublicKeyHex,
1244
- cosmosSigner
1245
- } = _d, urlOptions = __objRest(_d, [
1246
- "externalWallet",
1247
- "signedMessage",
1248
- "cosmosPublicKeyHex",
1249
- "cosmosSigner"
1250
- ]);
1251
- const serverAuthState = yield this.ctx.client.verifyExternalWallet(this.userId, {
1252
- externalWallet,
1253
- signedMessage,
1254
- cosmosPublicKeyHex,
1255
- cosmosSigner
1256
- });
1257
- return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
1641
+ var _c;
1642
+ let serverAuthState;
1643
+ let urlOptions;
1644
+ if ("serverAuthState" in params && params.serverAuthState !== void 0) {
1645
+ const _a = params, { serverAuthState: optsServerAuthState } = _a, rest = __objRest(_a, ["serverAuthState"]);
1646
+ serverAuthState = optsServerAuthState;
1647
+ urlOptions = rest;
1648
+ } else if ("externalWallet" in params) {
1649
+ const _b = params, { externalWallet, signedMessage, cosmosPublicKeyHex, cosmosSigner } = _b, rest = __objRest(_b, ["externalWallet", "signedMessage", "cosmosPublicKeyHex", "cosmosSigner"]);
1650
+ const _serverAuthState = yield this.ctx.client.verifyExternalWallet(this.userId, {
1651
+ externalWallet,
1652
+ signedMessage,
1653
+ cosmosPublicKeyHex,
1654
+ cosmosSigner
1655
+ });
1656
+ serverAuthState = _serverAuthState;
1657
+ urlOptions = rest;
1658
+ }
1659
+ if (serverAuthState.stage === "login" && ((_c = serverAuthState.loginAuthMethods) == null ? void 0 : _c.includes(AuthMethod.PIN))) {
1660
+ const { sessionLookupId } = yield this.touchSession();
1661
+ return yield __privateMethod(this, _ParaCore_instances, prepareLoginState_fn).call(this, serverAuthState, __spreadProps(__spreadValues({}, urlOptions), { sessionLookupId }));
1662
+ }
1663
+ let state;
1664
+ try {
1665
+ state = yield __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
1666
+ } catch (err) {
1667
+ console.error("Error prepping state:", err);
1668
+ }
1669
+ return state;
1670
+ });
1671
+ }
1672
+ verifyExternalWalletLink(opts) {
1673
+ return __async(this, null, function* () {
1674
+ const accountLinkInProgress = yield __privateMethod(this, _ParaCore_instances, assertIsLinkingAccount_fn).call(this, ["EXTERNAL_WALLET"]);
1675
+ if (!accountLinkInProgress.externalWallet) {
1676
+ throw new Error("no external wallet account link in progress");
1677
+ }
1678
+ const accounts = yield this.verifyLink(__spreadValues({
1679
+ accountLinkInProgress,
1680
+ externalWallet: accountLinkInProgress.externalWallet
1681
+ }, opts));
1682
+ return accounts;
1258
1683
  });
1259
1684
  }
1685
+ // TELEGRAM
1260
1686
  /**
1261
1687
  * Validates the response received from an attempted Telegram login for authenticity, then
1262
1688
  * creates or retrieves the corresponding Para user and prepares the Para instance to sign in with that user.
1263
1689
  * @param authResponse - the response JSON object received from the Telegram widget.
1264
1690
  * @returns `{ isValid: boolean; telegramUserId?: string; userId?: string; isNewUser?: boolean; supportedAuthMethods?: AuthMethod[]; biometricHints?: BiometricLocationHint[] }`
1265
1691
  */
1266
- verifyTelegram(_e) {
1692
+ verifyTelegramProcess(_c) {
1267
1693
  return __async(this, null, function* () {
1268
- var _f = _e, {
1269
- telegramAuthResponse
1270
- } = _f, urlOptions = __objRest(_f, [
1271
- "telegramAuthResponse"
1694
+ var _d = _c, {
1695
+ serverAuthState: optsServerAuthState,
1696
+ telegramAuthResponse,
1697
+ isLinkAccount
1698
+ } = _d, urlOptions = __objRest(_d, [
1699
+ "serverAuthState",
1700
+ "telegramAuthResponse",
1701
+ "isLinkAccount"
1272
1702
  ]);
1273
1703
  try {
1274
- const serverAuthState = yield this.ctx.client.verifyTelegram(telegramAuthResponse);
1275
- return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
1704
+ switch (isLinkAccount) {
1705
+ case false: {
1706
+ if (!optsServerAuthState && !telegramAuthResponse) {
1707
+ throw new Error("one of serverAuthState or telegramAuthResponse are required for verifying telegram");
1708
+ }
1709
+ const serverAuthState = optsServerAuthState != null ? optsServerAuthState : yield this.ctx.client.verifyTelegram({ authObject: telegramAuthResponse });
1710
+ const { sessionLookupId } = yield this.touchSession();
1711
+ return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, __spreadProps(__spreadValues({}, urlOptions), { sessionLookupId }));
1712
+ }
1713
+ case true: {
1714
+ if (!telegramAuthResponse) {
1715
+ throw new Error("telegramAuthResponse is required for verifying telegram link");
1716
+ }
1717
+ const accountLinkInProgress = yield __privateMethod(this, _ParaCore_instances, assertIsLinkingAccountOrStart_fn).call(this, "TELEGRAM");
1718
+ const accounts = yield this.verifyLink({
1719
+ accountLinkInProgress,
1720
+ telegramAuthResponse
1721
+ });
1722
+ return accounts;
1723
+ }
1724
+ }
1276
1725
  } catch (e) {
1277
- throw new Error(e.message);
1726
+ const errorMessage = e instanceof Error ? e.message : e ? String(e) : "Unknown error occurred";
1727
+ throw new Error(errorMessage);
1278
1728
  }
1279
1729
  });
1280
1730
  }
1731
+ verifyTelegram(opts) {
1732
+ return __async(this, null, function* () {
1733
+ return yield this.verifyTelegramProcess(__spreadProps(__spreadValues({}, opts), { isLinkAccount: false }));
1734
+ });
1735
+ }
1736
+ verifyTelegramLink(opts) {
1737
+ return __async(this, null, function* () {
1738
+ return yield this.verifyTelegramProcess(__spreadProps(__spreadValues({}, opts), { isLinkAccount: true }));
1739
+ });
1740
+ }
1281
1741
  /**
1282
1742
  * Performs 2FA verification.
1283
1743
  * @param {Object} opts the options object
@@ -1321,10 +1781,35 @@ const _ParaCore = class _ParaCore {
1321
1781
  /**
1322
1782
  * Resend a verification email for the current user.
1323
1783
  */
1324
- resendVerificationCode() {
1325
- return __async(this, null, function* () {
1784
+ resendVerificationCode(_0) {
1785
+ return __async(this, arguments, function* ({
1786
+ type: reason = "SIGNUP"
1787
+ }) {
1788
+ let type, linkedAccountId;
1789
+ switch (reason) {
1790
+ case "SIGNUP":
1791
+ case "LOGIN":
1792
+ {
1793
+ const authInfo = this.assertIsAuthSet(["email", "phone"]);
1794
+ type = authInfo.authType.toUpperCase();
1795
+ }
1796
+ break;
1797
+ case "LINK_ACCOUNT":
1798
+ {
1799
+ const accountLinkInProgress = __privateMethod(this, _ParaCore_instances, assertIsLinkingAccount_fn).call(this, ["EMAIL", "PHONE"]);
1800
+ linkedAccountId = accountLinkInProgress.id;
1801
+ type = accountLinkInProgress.type;
1802
+ }
1803
+ break;
1804
+ }
1805
+ const userId = this.assertUserId({ allowGuestMode: true });
1806
+ if (type !== "EMAIL" && type !== "PHONE") {
1807
+ throw new Error("invalid auth type for verification code");
1808
+ }
1326
1809
  yield this.ctx.client.resendVerificationCode(__spreadValues({
1327
- userId: this.userId
1810
+ userId,
1811
+ type,
1812
+ linkedAccountId
1328
1813
  }, this.getVerificationEmailProps()));
1329
1814
  });
1330
1815
  }
@@ -1337,7 +1822,14 @@ const _ParaCore = class _ParaCore {
1337
1822
  if (this.externalWalletConnectionType === "CONNECTION_ONLY") {
1338
1823
  return true;
1339
1824
  }
1340
- const { isAuthenticated } = yield this.touchSession();
1825
+ const { isAuthenticated, verifiedExternalWalletAddresses } = yield this.touchSession();
1826
+ if (this.externalWalletConnectionType === "VERIFICATION") {
1827
+ if (!verifiedExternalWalletAddresses) {
1828
+ return false;
1829
+ }
1830
+ const externalAddresses = Object.values(this.externalWallets).map((w) => w.id);
1831
+ return externalAddresses.every((address) => verifiedExternalWalletAddresses.includes(address));
1832
+ }
1341
1833
  return !!isAuthenticated;
1342
1834
  });
1343
1835
  }
@@ -1348,23 +1840,57 @@ const _ParaCore = class _ParaCore {
1348
1840
  isFullyLoggedIn() {
1349
1841
  return __async(this, null, function* () {
1350
1842
  if (this.externalWalletConnectionType === "CONNECTION_ONLY") {
1843
+ if (!this.isReady) {
1844
+ yield this.ready();
1845
+ }
1351
1846
  return true;
1352
1847
  }
1353
1848
  if (this.isGuestMode) {
1354
1849
  return true;
1355
1850
  }
1356
1851
  const isSessionActive = yield this.isSessionActive();
1357
- return isSessionActive && (this.isNoWalletConfig || this.currentWalletIdsArray.length > 0 && this.currentWalletIdsArray.reduce((acc, [id]) => acc && !!this.wallets[id], true));
1852
+ if (this.externalWalletConnectionType === "VERIFICATION") {
1853
+ return isSessionActive;
1854
+ }
1855
+ if (this.isSwitchingWallets) {
1856
+ return isSessionActive;
1857
+ }
1858
+ if (!isSessionActive) {
1859
+ return false;
1860
+ }
1861
+ if (this.isNoWalletConfig) {
1862
+ return true;
1863
+ }
1864
+ const { supportedWalletTypes } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
1865
+ const requiredWalletTypes = supportedWalletTypes.filter(({ optional }) => !optional);
1866
+ for (const { type } of requiredWalletTypes) {
1867
+ const hasWalletForType = this.currentWalletIdsArray.some(([walletId, walletType]) => {
1868
+ try {
1869
+ const wallet = this.wallets[walletId];
1870
+ return wallet && walletType === type && typeof wallet.address === "string";
1871
+ } catch (e) {
1872
+ return false;
1873
+ }
1874
+ });
1875
+ if (!hasWalletForType) {
1876
+ return false;
1877
+ }
1878
+ }
1879
+ return true;
1358
1880
  });
1359
1881
  }
1360
1882
  get isGuestMode() {
1361
1883
  return __privateGet(this, _ParaCore_instances, guestWalletIdsArray_get).length > 0 && Object.values(this.wallets).every(
1362
1884
  ({ userId, partnerId }) => {
1363
1885
  var _a;
1364
- return partnerId === ((_a = __privateGet(this, _partner)) == null ? void 0 : _a.id) && (!userId || userId !== this.userId);
1886
+ return partnerId === ((_a = this.partner) == null ? void 0 : _a.id) && (!userId || userId !== this.userId);
1365
1887
  }
1366
1888
  );
1367
1889
  }
1890
+ /**
1891
+ * Get the auth methods available to an existing user
1892
+ * @deprecated Use supportedUserAuthMethods instead
1893
+ */
1368
1894
  supportedAuthMethods(auth) {
1369
1895
  return __async(this, null, function* () {
1370
1896
  const { supportedAuthMethods } = yield this.ctx.client.getSupportedAuthMethods(auth);
@@ -1382,6 +1908,37 @@ const _ParaCore = class _ParaCore {
1382
1908
  return authMethods;
1383
1909
  });
1384
1910
  }
1911
+ /**
1912
+ * Get the auth methods available to an existing user
1913
+ */
1914
+ supportedUserAuthMethods() {
1915
+ return __async(this, null, function* () {
1916
+ yield this.assertIsAuthSet();
1917
+ const { supportedAuthMethods, hasPasswordWithoutPIN } = yield this.ctx.client.getSupportedAuthMethodsV2(
1918
+ this.authInfo.auth
1919
+ );
1920
+ const authMethods = /* @__PURE__ */ new Set();
1921
+ for (const type of supportedAuthMethods) {
1922
+ switch (type) {
1923
+ case "PASSWORD":
1924
+ if (hasPasswordWithoutPIN) {
1925
+ authMethods.add(AuthMethod.PASSWORD);
1926
+ }
1927
+ break;
1928
+ case "PASSKEY":
1929
+ authMethods.add(AuthMethod.PASSKEY);
1930
+ break;
1931
+ case "PIN":
1932
+ authMethods.add(AuthMethod.PIN);
1933
+ break;
1934
+ case "BASIC_LOGIN":
1935
+ authMethods.add(AuthMethod.BASIC_LOGIN);
1936
+ break;
1937
+ }
1938
+ }
1939
+ return authMethods;
1940
+ });
1941
+ }
1385
1942
  /**
1386
1943
  * Get hints associated with the users stored biometrics.
1387
1944
  * @deprecated
@@ -1458,36 +2015,47 @@ const _ParaCore = class _ParaCore {
1458
2015
  });
1459
2016
  }
1460
2017
  /**
1461
- * Initiates a Farcaster login attempt and return the URI for the user to connect.
2018
+ * Initiates a Farcaster login attempt and returns the URL for the user to connect.
1462
2019
  * You can create a QR code with this URI that works with Farcaster's mobile app.
1463
2020
  * @return {string} the Farcaster connect URI
1464
2021
  */
1465
2022
  getFarcasterConnectUri() {
1466
- return __async(this, null, function* () {
1467
- const {
1468
- data: { connect_uri: connectUri }
1469
- } = yield this.ctx.client.initializeFarcasterLogin();
2023
+ return __async(this, arguments, function* ({ appScheme } = {}) {
2024
+ const { connect_uri: connectUri } = yield this.ctx.client.initializeFarcasterLogin({ appScheme });
1470
2025
  return connectUri;
1471
2026
  });
1472
2027
  }
2028
+ // FARCASTER
1473
2029
  /**
1474
2030
  * Awaits the response from a user's attempt to log in with Farcaster.
1475
2031
  * If successful, this returns the user's Farcaster username and profile picture and indicates whether the user already exists.
1476
2032
  * @return {Object} `{userExists: boolean; username: string; pfpUrl?: string | null }` - the user's information and whether the user already exists.
1477
2033
  */
1478
- verifyFarcaster(_g) {
2034
+ verifyFarcasterProcess(_e) {
1479
2035
  return __async(this, null, function* () {
1480
- var _h = _g, {
2036
+ var _f = _e, {
1481
2037
  isCanceled = () => false,
1482
2038
  onConnectUri,
1483
2039
  onCancel,
1484
- onPoll
1485
- } = _h, urlOptions = __objRest(_h, [
2040
+ onPoll,
2041
+ isLinkAccount,
2042
+ serverAuthState: optsServerAuthState
2043
+ } = _f, urlOptions = __objRest(_f, [
1486
2044
  "isCanceled",
1487
2045
  "onConnectUri",
1488
2046
  "onCancel",
1489
- "onPoll"
2047
+ "onPoll",
2048
+ "isLinkAccount",
2049
+ "serverAuthState"
1490
2050
  ]);
2051
+ if (optsServerAuthState) {
2052
+ const authState = yield __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, optsServerAuthState, urlOptions);
2053
+ return authState;
2054
+ }
2055
+ let accountLinkInProgress;
2056
+ if (isLinkAccount) {
2057
+ accountLinkInProgress = yield __privateMethod(this, _ParaCore_instances, assertIsLinkingAccountOrStart_fn).call(this, "FARCASTER");
2058
+ }
1491
2059
  if (onConnectUri) {
1492
2060
  const connectUri = yield this.getFarcasterConnectUri();
1493
2061
  onConnectUri(connectUri);
@@ -1499,85 +2067,113 @@ const _ParaCore = class _ParaCore {
1499
2067
  try {
1500
2068
  if (isCanceled() || Date.now() - startedAt > constants.POLLING_TIMEOUT_MS) {
1501
2069
  onCancel == null ? void 0 : onCancel();
1502
- return reject("canceled");
2070
+ return reject("CANCELED");
1503
2071
  }
1504
2072
  yield new Promise((_resolve) => setTimeout(_resolve, constants.POLLING_INTERVAL_MS));
1505
- const serverAuthState = yield this.ctx.client.getFarcasterAuthStatus();
1506
- if (isServerAuthState(serverAuthState)) {
1507
- const authState = yield __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
1508
- return resolve(authState);
2073
+ switch (isLinkAccount) {
2074
+ case false:
2075
+ {
2076
+ const serverAuthState = yield this.ctx.client.getFarcasterAuthStatus();
2077
+ if (isServerAuthState(serverAuthState)) {
2078
+ const authState = yield __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
2079
+ return resolve(authState);
2080
+ }
2081
+ }
2082
+ break;
2083
+ case true: {
2084
+ const result = yield this.verifyLink({
2085
+ accountLinkInProgress
2086
+ });
2087
+ if ("isConflict" in result) {
2088
+ throw new Error(AccountLinkError.Conflict);
2089
+ }
2090
+ return resolve(result);
2091
+ }
1509
2092
  }
1510
2093
  onPoll == null ? void 0 : onPoll();
1511
2094
  } catch (e) {
1512
- console.error(e);
1513
- return reject(e);
2095
+ if (!isLinkAccount || e.message === AccountLinkError.Conflict) {
2096
+ return reject(e.message);
2097
+ }
1514
2098
  }
1515
2099
  }
1516
2100
  }))();
1517
2101
  });
1518
2102
  });
1519
2103
  }
1520
- /**
1521
- * Generates a URL for the user to log in with OAuth using a desire method.
1522
- *
1523
- * @param {Object} opts the options object
1524
- * @param {TOAuthMethod} opts.method the third-party service to use for OAuth.
1525
- * @param {string} [opts.deeplinkUrl] the deeplink to redirect to after the OAuth flow. This is for mobile only.
1526
- * @returns {string} the URL for the user to log in with OAuth.
1527
- */
1528
- getOAuthUrl(_i) {
2104
+ verifyFarcaster(opts) {
1529
2105
  return __async(this, null, function* () {
1530
- var _j = _i, { method, deeplinkUrl } = _j, params = __objRest(_j, ["method", "deeplinkUrl"]);
1531
- var _a;
1532
- if (deeplinkUrl) {
1533
- try {
1534
- new URL(deeplinkUrl);
1535
- } catch (e) {
1536
- throw new Error("Invalid deeplink URL");
1537
- }
1538
- }
1539
- const sessionLookupId = (_a = params.sessionLookupId) != null ? _a : yield __privateMethod(this, _ParaCore_instances, prepareLogin_fn).call(this);
1540
- return constructUrl({
1541
- base: getBaseOAuthUrl(this.ctx.env),
1542
- path: `/auth/${method}`,
1543
- params: {
1544
- apiKey: this.ctx.apiKey,
1545
- sessionLookupId,
1546
- deeplinkUrl
1547
- }
1548
- });
2106
+ return yield this.verifyFarcasterProcess(__spreadProps(__spreadValues({}, opts), { isLinkAccount: false }));
1549
2107
  });
1550
2108
  }
1551
- /**
1552
- * Awaits the response from a user's attempt to log in with OAuth.
2109
+ verifyFarcasterLink(opts) {
2110
+ return __async(this, null, function* () {
2111
+ return yield this.verifyFarcasterProcess(__spreadProps(__spreadValues({}, opts), { isLinkAccount: true }));
2112
+ });
2113
+ }
2114
+ getOAuthUrl(opts) {
2115
+ return __async(this, null, function* () {
2116
+ var _a;
2117
+ const sessionLookupId = (_a = opts.sessionLookupId) != null ? _a : yield this.prepareLogin();
2118
+ return __privateMethod(this, _ParaCore_instances, getOAuthUrl_fn).call(this, __spreadProps(__spreadValues({}, opts), { sessionLookupId }));
2119
+ });
2120
+ }
2121
+ /**
2122
+ * Awaits the response from a user's attempt to log in with OAuth.
1553
2123
  * If successful, this returns the user's email address and indicates whether the user already exists.
1554
2124
  *
1555
2125
  * @param {Object} opts the options object.
1556
2126
  * @param {Window} [opts.popupWindow] the popup window being used for login.
1557
2127
  * @return {Object} `{ email?: string; isError?: boolean; userExists: boolean; }` the result data
1558
2128
  */
1559
- verifyOAuth(_k) {
2129
+ verifyOAuthProcess(_g) {
1560
2130
  return __async(this, null, function* () {
1561
- var _l = _k, {
2131
+ var _h = _g, {
1562
2132
  method,
1563
- deeplinkUrl,
2133
+ appScheme,
1564
2134
  isCanceled = () => false,
1565
2135
  onCancel,
1566
2136
  onPoll,
1567
- onOAuthUrl
1568
- } = _l, urlOptions = __objRest(_l, [
2137
+ onOAuthUrl,
2138
+ onOAuthPopup,
2139
+ isLinkAccount
2140
+ } = _h, urlOptions = __objRest(_h, [
1569
2141
  "method",
1570
- "deeplinkUrl",
2142
+ "appScheme",
1571
2143
  "isCanceled",
1572
2144
  "onCancel",
1573
2145
  "onPoll",
1574
- "onOAuthUrl"
2146
+ "onOAuthUrl",
2147
+ "onOAuthPopup",
2148
+ "isLinkAccount"
1575
2149
  ]);
1576
- let sessionLookupId;
1577
- if (onOAuthUrl) {
1578
- sessionLookupId = yield __privateMethod(this, _ParaCore_instances, prepareLogin_fn).call(this);
1579
- const oAuthUrl = yield this.getOAuthUrl({ method, deeplinkUrl, sessionLookupId });
1580
- onOAuthUrl(oAuthUrl);
2150
+ if (onOAuthPopup) {
2151
+ try {
2152
+ this.popupWindow = yield this.platformUtils.openPopup("about:blank", { type: PopupType.OAUTH });
2153
+ } catch (error) {
2154
+ throw new Error(`Failed to open OAuth popup: ${error}`);
2155
+ }
2156
+ }
2157
+ let sessionLookupId, accountLinkInProgress;
2158
+ if (onOAuthUrl || onOAuthPopup) {
2159
+ if (isLinkAccount) {
2160
+ accountLinkInProgress = yield __privateMethod(this, _ParaCore_instances, assertIsLinkingAccountOrStart_fn).call(this, method);
2161
+ sessionLookupId = (yield this.touchSession()).sessionLookupId;
2162
+ } else {
2163
+ sessionLookupId = yield this.prepareLogin();
2164
+ }
2165
+ const oAuthUrl = yield __privateMethod(this, _ParaCore_instances, getOAuthUrl_fn).call(this, { method, appScheme, sessionLookupId, accountLinkInProgress });
2166
+ switch (true) {
2167
+ case !!onOAuthUrl: {
2168
+ onOAuthUrl(oAuthUrl);
2169
+ break;
2170
+ }
2171
+ case (!!onOAuthPopup && !!this.popupWindow): {
2172
+ this.popupWindow.location.href = oAuthUrl;
2173
+ onOAuthPopup(this.popupWindow);
2174
+ break;
2175
+ }
2176
+ }
1581
2177
  } else {
1582
2178
  ({ sessionLookupId } = yield this.touchSession());
1583
2179
  }
@@ -1588,17 +2184,29 @@ const _ParaCore = class _ParaCore {
1588
2184
  try {
1589
2185
  if (isCanceled() || Date.now() - startedAt > constants.POLLING_TIMEOUT_MS) {
1590
2186
  onCancel == null ? void 0 : onCancel();
1591
- return reject("canceled");
2187
+ return reject(AccountLinkError.Canceled);
1592
2188
  }
1593
2189
  yield new Promise((_resolve) => setTimeout(_resolve, constants.POLLING_INTERVAL_MS));
1594
- const serverAuthState = yield this.ctx.client.verifyOAuth();
1595
- if (isServerAuthState(serverAuthState)) {
1596
- const authState = yield __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, __spreadProps(__spreadValues({}, urlOptions), { sessionLookupId }));
1597
- return resolve(authState);
2190
+ switch (isLinkAccount) {
2191
+ case false:
2192
+ {
2193
+ const serverAuthState = yield this.ctx.client.verifyOAuth();
2194
+ if (isServerAuthState(serverAuthState)) {
2195
+ const authState = yield __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, __spreadProps(__spreadValues({}, urlOptions), { sessionLookupId }));
2196
+ return resolve(authState);
2197
+ }
2198
+ }
2199
+ break;
2200
+ case true: {
2201
+ const accounts = yield this.verifyLink({ accountLinkInProgress });
2202
+ return resolve(accounts);
2203
+ }
1598
2204
  }
1599
2205
  onPoll == null ? void 0 : onPoll();
1600
2206
  } catch (err) {
1601
- console.error(err);
2207
+ if (isLinkAccount && err.message === AccountLinkError.Conflict) {
2208
+ return reject(err.message);
2209
+ }
1602
2210
  onPoll == null ? void 0 : onPoll();
1603
2211
  }
1604
2212
  }
@@ -1606,6 +2214,16 @@ const _ParaCore = class _ParaCore {
1606
2214
  });
1607
2215
  });
1608
2216
  }
2217
+ verifyOAuth(opts) {
2218
+ return __async(this, null, function* () {
2219
+ return yield this.verifyOAuthProcess(__spreadProps(__spreadValues({}, opts), { isLinkAccount: false }));
2220
+ });
2221
+ }
2222
+ verifyOAuthLink(opts) {
2223
+ return __async(this, null, function* () {
2224
+ return yield this.verifyOAuthProcess(__spreadProps(__spreadValues({}, opts), { isLinkAccount: true }));
2225
+ });
2226
+ }
1609
2227
  /**
1610
2228
  * Waits for the session to be active and sets up the user.
1611
2229
  *
@@ -1614,61 +2232,26 @@ const _ParaCore = class _ParaCore {
1614
2232
  * @param {boolean} [opts.skipSessionRefresh] whether to skip refreshing the session.
1615
2233
  * @returns {Object} `{ isComplete: boolean; isError: boolean; needsWallet: boolean; partnerId: string; }` the result data
1616
2234
  **/
1617
- waitForLogin() {
1618
- return __async(this, arguments, function* ({
1619
- isCanceled = () => false,
1620
- onCancel,
1621
- onPoll,
1622
- skipSessionRefresh = false
1623
- } = {}) {
1624
- const startedAt = Date.now();
1625
- return new Promise((resolve, reject) => {
1626
- (() => __async(this, null, function* () {
1627
- var _a;
1628
- if (!this.isExternalWalletAuth) {
1629
- this.externalWallets = {};
1630
- }
1631
- while (true) {
1632
- if (isCanceled() || Date.now() - startedAt > constants.POLLING_TIMEOUT_MS) {
1633
- dispatchEvent(ParaEvent.LOGIN_EVENT, { isComplete: false }, "failed to setup user");
1634
- onCancel == null ? void 0 : onCancel();
1635
- return reject("canceled");
1636
- }
1637
- yield new Promise((resolve2) => setTimeout(resolve2, constants.POLLING_INTERVAL_MS));
1638
- try {
1639
- let session = yield this.touchSession();
1640
- if (!session.isAuthenticated) {
1641
- onPoll == null ? void 0 : onPoll();
1642
- continue;
1643
- }
1644
- session = yield this.userSetupAfterLogin();
1645
- const needsWallet = (_a = session.needsWallet) != null ? _a : false;
1646
- if (!needsWallet) {
1647
- if (this.currentWalletIdsArray.length === 0) {
1648
- onPoll == null ? void 0 : onPoll();
1649
- continue;
1650
- }
1651
- }
1652
- const fetchedWallets = yield this.fetchWallets();
1653
- const tempSharesRes = yield this.getTransmissionKeyShares();
1654
- if (tempSharesRes.data.temporaryShares.length === fetchedWallets.length) {
1655
- yield this.setupAfterLogin({ temporaryShares: tempSharesRes.data.temporaryShares, skipSessionRefresh });
1656
- yield this.claimPregenWallets();
1657
- const resp = {
1658
- needsWallet: needsWallet || Object.values(this.wallets).length === 0,
1659
- partnerId: session.partnerId
1660
- };
1661
- dispatchEvent(ParaEvent.LOGIN_EVENT, resp);
1662
- return resolve(resp);
1663
- }
1664
- onPoll == null ? void 0 : onPoll();
1665
- } catch (err) {
1666
- console.error(err);
1667
- onPoll == null ? void 0 : onPoll();
1668
- }
1669
- }
1670
- }))();
1671
- });
2235
+ waitForLogin(args) {
2236
+ return __async(this, null, function* () {
2237
+ return yield __privateMethod(this, _ParaCore_instances, waitForLoginProcess_fn).call(this, args);
2238
+ });
2239
+ }
2240
+ waitForWalletSwitching(args) {
2241
+ return __async(this, null, function* () {
2242
+ return yield __privateMethod(this, _ParaCore_instances, waitForLoginProcess_fn).call(this, __spreadProps(__spreadValues({}, args), { isSwitchingWallets: true }));
2243
+ });
2244
+ }
2245
+ /**
2246
+ * Gets the switch wallets URL for wallet selection.
2247
+ * The authMethod is automatically included in the URL if available.
2248
+ *
2249
+ * @returns {Promise<{ url: string; authMethod: TAuthMethod }>} The switch wallets URL and authMethod
2250
+ */
2251
+ getSwitchWalletsUrl() {
2252
+ return __async(this, null, function* () {
2253
+ const url = yield this.constructPortalUrl("switchWallets");
2254
+ return url;
1672
2255
  });
1673
2256
  }
1674
2257
  /**
@@ -1691,7 +2274,7 @@ const _ParaCore = class _ParaCore {
1691
2274
  sessionId
1692
2275
  });
1693
2276
  if (shouldOpenPopup) {
1694
- this.platformUtils.openPopup(link);
2277
+ yield this.platformUtils.openPopup(link);
1695
2278
  }
1696
2279
  return link;
1697
2280
  });
@@ -1782,7 +2365,9 @@ const _ParaCore = class _ParaCore {
1782
2365
  userId: this.userId,
1783
2366
  walletId,
1784
2367
  userShare: userSigner,
1785
- emailProps: this.getBackupKitEmailProps()
2368
+ emailProps: this.getBackupKitEmailProps(),
2369
+ isEnclaveUser: this.isEnclaveUser,
2370
+ walletScheme: this.wallets[walletId].scheme
1786
2371
  });
1787
2372
  return recoveryShare;
1788
2373
  });
@@ -1796,7 +2381,7 @@ const _ParaCore = class _ParaCore {
1796
2381
  break;
1797
2382
  }
1798
2383
  ++maxPolls;
1799
- const res = yield this.ctx.client.getWallets(this.userId);
2384
+ const res = yield (this.isPortal() ? this.ctx.client.getAllWallets : this.ctx.client.getWallets)(this.userId);
1800
2385
  const wallet = res.data.wallets.find((w) => w.id === walletId);
1801
2386
  if (wallet && wallet.address) {
1802
2387
  return;
@@ -1910,7 +2495,9 @@ const _ParaCore = class _ParaCore {
1910
2495
  ignoreRedistributingBackupEncryptedShare: !redistributeBackupEncryptedShares,
1911
2496
  emailProps: this.getBackupKitEmailProps(),
1912
2497
  partnerId: newPartnerId,
1913
- protocolId
2498
+ protocolId,
2499
+ isEnclaveUser: this.isEnclaveUser,
2500
+ walletScheme: this.wallets[walletId].scheme
1914
2501
  });
1915
2502
  return { signer, recoverySecret, protocolId };
1916
2503
  });
@@ -1959,26 +2546,29 @@ const _ParaCore = class _ParaCore {
1959
2546
  }
1960
2547
  }
1961
2548
  const walletId = keygenRes.walletId;
2549
+ const walletScheme = walletType === "SOLANA" ? "ED25519" : "DKLS";
1962
2550
  signer = keygenRes.signer;
1963
- this.wallets[walletId] = {
1964
- id: walletId,
1965
- signer,
1966
- scheme: walletType === "SOLANA" ? "ED25519" : "DKLS",
1967
- type: walletType
1968
- };
1969
- wallet = this.wallets[walletId];
1970
- yield this.waitForWalletAddress(wallet.id);
1971
- yield this.populateWalletAddresses();
2551
+ yield this.waitForWalletAddress(walletId);
1972
2552
  let recoveryShare = null;
1973
2553
  if (!skipDistribute) {
1974
2554
  recoveryShare = yield distributeNewShare({
1975
2555
  ctx: this.ctx,
1976
2556
  userId: this.userId,
1977
- walletId: wallet.id,
2557
+ walletId,
1978
2558
  userShare: signer,
1979
- emailProps: this.getBackupKitEmailProps()
2559
+ emailProps: this.getBackupKitEmailProps(),
2560
+ isEnclaveUser: this.isEnclaveUser,
2561
+ walletScheme
1980
2562
  });
1981
2563
  }
2564
+ this.wallets[walletId] = {
2565
+ id: walletId,
2566
+ signer,
2567
+ scheme: walletScheme,
2568
+ type: walletType
2569
+ };
2570
+ wallet = this.wallets[walletId];
2571
+ yield this.populateWalletAddresses();
1982
2572
  yield this.setCurrentWalletIds(__spreadProps(__spreadValues({}, this.currentWalletIds), {
1983
2573
  [walletType]: [.../* @__PURE__ */ new Set([...(_b = this.currentWalletIds[walletType]) != null ? _b : [], walletId])]
1984
2574
  }));
@@ -2057,7 +2647,9 @@ const _ParaCore = class _ParaCore {
2057
2647
  walletId: wallet.id,
2058
2648
  userShare: this.wallets[wallet.id].signer,
2059
2649
  emailProps: this.getBackupKitEmailProps(),
2060
- partnerId: wallet.partnerId
2650
+ partnerId: wallet.partnerId,
2651
+ isEnclaveUser: this.isEnclaveUser,
2652
+ walletScheme: wallet.scheme
2061
2653
  });
2062
2654
  if (distributeRes.length > 0) {
2063
2655
  newRecoverySecret = distributeRes;
@@ -2184,10 +2776,10 @@ const _ParaCore = class _ParaCore {
2184
2776
  dispatchEvent(ParaEvent.GUEST_WALLETS_CREATED, wallets);
2185
2777
  __privateSet(this, _isCreateGuestWalletsPending, false);
2186
2778
  return wallets;
2187
- } catch (e) {
2188
- dispatchEvent(ParaEvent.GUEST_WALLETS_CREATED, null, error == null ? void 0 : error.message);
2779
+ } catch (error2) {
2780
+ dispatchEvent(ParaEvent.GUEST_WALLETS_CREATED, null, error2 == null ? void 0 : error2.message);
2189
2781
  __privateSet(this, _isCreateGuestWalletsPending, false);
2190
- throw error;
2782
+ throw error2;
2191
2783
  }
2192
2784
  });
2193
2785
  }
@@ -2235,25 +2827,12 @@ const _ParaCore = class _ParaCore {
2235
2827
  });
2236
2828
  });
2237
2829
  }
2238
- getOnRampTransactionUrl(_m) {
2239
- return __async(this, null, function* () {
2240
- var _n = _m, {
2241
- purchaseId,
2242
- providerKey
2243
- } = _n, walletParams = __objRest(_n, [
2244
- "purchaseId",
2245
- "providerKey"
2246
- ]);
2247
- const { sessionId } = yield this.touchSession();
2248
- const [key, identifier] = extractWalletRef(walletParams);
2830
+ getOnRampTransactionUrl(_0) {
2831
+ return __async(this, arguments, function* ({
2832
+ purchaseId
2833
+ }) {
2249
2834
  return this.constructPortalUrl("onRamp", {
2250
- pathId: purchaseId,
2251
- sessionId,
2252
- params: {
2253
- [key]: identifier,
2254
- providerKey,
2255
- currentWalletIds: JSON.stringify(this.currentWalletIds)
2256
- }
2835
+ pathId: purchaseId
2257
2836
  });
2258
2837
  });
2259
2838
  }
@@ -2278,6 +2857,7 @@ const _ParaCore = class _ParaCore {
2278
2857
  onCancel,
2279
2858
  onPoll
2280
2859
  }) {
2860
+ var _a;
2281
2861
  this.assertIsValidWalletId(walletId);
2282
2862
  const wallet = this.wallets[walletId];
2283
2863
  let signerId = this.userId;
@@ -2287,7 +2867,7 @@ const _ParaCore = class _ParaCore {
2287
2867
  let signRes = yield this.signMessageInner({ wallet, signerId, messageBase64, cosmosSignDocBase64 });
2288
2868
  let timeStart = Date.now();
2289
2869
  if (signRes.pendingTransactionId) {
2290
- this.platformUtils.openPopup(
2870
+ yield this.platformUtils.openPopup(
2291
2871
  yield this.getTransactionReviewUrl(signRes.pendingTransactionId, timeoutMs),
2292
2872
  { type: cosmosSignDocBase64 ? PopupType.SIGN_TRANSACTION_REVIEW : PopupType.SIGN_MESSAGE_REVIEW }
2293
2873
  );
@@ -2301,18 +2881,19 @@ const _ParaCore = class _ParaCore {
2301
2881
  break;
2302
2882
  }
2303
2883
  yield new Promise((resolve) => setTimeout(resolve, constants.POLLING_INTERVAL_MS));
2884
+ let pendingTransaction;
2304
2885
  try {
2305
- yield this.ctx.client.getPendingTransaction(this.userId, signRes.pendingTransactionId);
2306
- } catch (err) {
2886
+ pendingTransaction = (_a = (yield this.ctx.client.getPendingTransaction(this.userId, signRes.pendingTransactionId)).data) == null ? void 0 : _a.pendingTransaction;
2887
+ } catch (e) {
2307
2888
  const error = new TransactionReviewDenied();
2308
2889
  dispatchEvent(ParaEvent.SIGN_MESSAGE_EVENT, signRes, error.message);
2309
2890
  throw error;
2310
2891
  }
2311
- signRes = yield this.signMessageInner({ wallet, signerId, messageBase64, cosmosSignDocBase64 });
2312
- if (signRes.pendingTransactionId) {
2892
+ if (!(pendingTransaction == null ? void 0 : pendingTransaction.approvedAt)) {
2313
2893
  onPoll == null ? void 0 : onPoll();
2314
2894
  continue;
2315
2895
  } else {
2896
+ signRes = yield this.signMessageInner({ wallet, signerId, messageBase64, cosmosSignDocBase64 });
2316
2897
  break;
2317
2898
  }
2318
2899
  }
@@ -2381,6 +2962,7 @@ const _ParaCore = class _ParaCore {
2381
2962
  onCancel,
2382
2963
  onPoll
2383
2964
  }) {
2965
+ var _a;
2384
2966
  this.assertIsValidWalletId(walletId);
2385
2967
  const wallet = this.wallets[walletId];
2386
2968
  let signerId = this.userId;
@@ -2399,7 +2981,7 @@ const _ParaCore = class _ParaCore {
2399
2981
  );
2400
2982
  let timeStart = Date.now();
2401
2983
  if (signRes.pendingTransactionId) {
2402
- this.platformUtils.openPopup(
2984
+ yield this.platformUtils.openPopup(
2403
2985
  yield this.getTransactionReviewUrl(signRes.pendingTransactionId, timeoutMs),
2404
2986
  { type: PopupType.SIGN_TRANSACTION_REVIEW }
2405
2987
  );
@@ -2413,27 +2995,28 @@ const _ParaCore = class _ParaCore {
2413
2995
  break;
2414
2996
  }
2415
2997
  yield new Promise((resolve) => setTimeout(resolve, constants.POLLING_INTERVAL_MS));
2998
+ let pendingTransaction;
2416
2999
  try {
2417
- yield this.ctx.client.getPendingTransaction(this.userId, signRes.pendingTransactionId);
2418
- } catch (err) {
3000
+ pendingTransaction = (_a = (yield this.ctx.client.getPendingTransaction(this.userId, signRes.pendingTransactionId)).data) == null ? void 0 : _a.pendingTransaction;
3001
+ } catch (e) {
2419
3002
  const error = new TransactionReviewDenied();
2420
3003
  dispatchEvent(ParaEvent.SIGN_TRANSACTION_EVENT, signRes, error.message);
2421
3004
  throw error;
2422
3005
  }
2423
- signRes = yield this.platformUtils.signTransaction(
2424
- this.ctx,
2425
- signerId,
2426
- walletId,
2427
- this.wallets[walletId].signer,
2428
- rlpEncodedTxBase64,
2429
- chainId,
2430
- this.retrieveSessionCookie(),
2431
- wallet.scheme === "DKLS"
2432
- );
2433
- if (signRes.pendingTransactionId) {
3006
+ if (!(pendingTransaction == null ? void 0 : pendingTransaction.approvedAt)) {
2434
3007
  onPoll == null ? void 0 : onPoll();
2435
3008
  continue;
2436
3009
  } else {
3010
+ signRes = yield this.platformUtils.signTransaction(
3011
+ this.ctx,
3012
+ signerId,
3013
+ walletId,
3014
+ this.wallets[walletId].signer,
3015
+ rlpEncodedTxBase64,
3016
+ chainId,
3017
+ this.retrieveSessionCookie(),
3018
+ wallet.scheme === "DKLS"
3019
+ );
2437
3020
  break;
2438
3021
  }
2439
3022
  }
@@ -2475,7 +3058,8 @@ const _ParaCore = class _ParaCore {
2475
3058
  providerKey: onRampPurchase.providerKey
2476
3059
  }, walletParams));
2477
3060
  if (shouldOpenPopup) {
2478
- this.platformUtils.openPopup(portalUrl, { type: PopupType.ON_RAMP_TRANSACTION });
3061
+ const onRampWindow = yield this.platformUtils.openPopup(portalUrl, { type: PopupType.ON_RAMP_TRANSACTION });
3062
+ this.onRampPopup = { window: onRampWindow, onRampPurchase };
2479
3063
  }
2480
3064
  return { onRampPurchase, portalUrl };
2481
3065
  });
@@ -2488,7 +3072,7 @@ const _ParaCore = class _ParaCore {
2488
3072
  try {
2489
3073
  yield this.ctx.client.keepSessionAlive(this.userId);
2490
3074
  return true;
2491
- } catch (err) {
3075
+ } catch (e) {
2492
3076
  return false;
2493
3077
  }
2494
3078
  });
@@ -2558,6 +3142,20 @@ const _ParaCore = class _ParaCore {
2558
3142
  return sessionLookupId;
2559
3143
  });
2560
3144
  }
3145
+ issueJwt() {
3146
+ return __async(this, arguments, function* ({ keyIndex = 0 } = {}) {
3147
+ try {
3148
+ return yield this.ctx.client.issueJwt({ keyIndex });
3149
+ } catch (error) {
3150
+ if (error.status === 403 || error.status === 401) {
3151
+ const errorMessage = "The user needs to be logged in to issue a JWT. Please log in and try again.";
3152
+ this.displayModalError(errorMessage);
3153
+ console.warn(errorMessage);
3154
+ }
3155
+ throw error;
3156
+ }
3157
+ });
3158
+ }
2561
3159
  /**
2562
3160
  * Logs the user out.
2563
3161
  * @param {Object} opts the options object.
@@ -2565,6 +3163,7 @@ const _ParaCore = class _ParaCore {
2565
3163
  **/
2566
3164
  logout() {
2567
3165
  return __async(this, arguments, function* ({ clearPregenWallets = false } = {}) {
3166
+ const shouldDispatchLogoutEvent = yield this.isSessionActive();
2568
3167
  yield this.ctx.client.logout();
2569
3168
  yield this.clearStorage();
2570
3169
  if (!clearPregenWallets) {
@@ -2581,22 +3180,17 @@ const _ParaCore = class _ParaCore {
2581
3180
  this.externalWallets = {};
2582
3181
  this.loginEncryptionKeyPair = void 0;
2583
3182
  __privateSet(this, _authInfo, void 0);
3183
+ this.accountLinkInProgress = void 0;
2584
3184
  this.userId = void 0;
2585
3185
  this.sessionCookie = void 0;
2586
- dispatchEvent(ParaEvent.LOGOUT_EVENT, null);
2587
- });
2588
- }
2589
- /** @deprecated */
2590
- getSupportedCreateAuthMethods() {
2591
- return __async(this, null, function* () {
2592
- const partner = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
2593
- let supportedAuthMethods = /* @__PURE__ */ new Set();
2594
- for (const authMethod of partner.supportedAuthMethods) {
2595
- supportedAuthMethods.add(AuthMethod[authMethod]);
3186
+ if (shouldDispatchLogoutEvent) {
3187
+ dispatchEvent(ParaEvent.LOGOUT_EVENT, null);
2596
3188
  }
2597
- return supportedAuthMethods;
2598
3189
  });
2599
3190
  }
3191
+ get toStringAdditions() {
3192
+ return {};
3193
+ }
2600
3194
  /**
2601
3195
  * Converts to a string, removing sensitive data when logging this class.
2602
3196
  *
@@ -2620,10 +3214,10 @@ const _ParaCore = class _ParaCore {
2620
3214
  }),
2621
3215
  {}
2622
3216
  );
2623
- const obj = {
2624
- partnerId: (_a = __privateGet(this, _partner)) == null ? void 0 : _a.id,
2625
- supportedWalletTypes: (_b = __privateGet(this, _partner)) == null ? void 0 : _b.supportedWalletTypes,
2626
- cosmosPrefix: (_c = __privateGet(this, _partner)) == null ? void 0 : _c.cosmosPrefix,
3217
+ const obj = __spreadProps(__spreadValues({
3218
+ partnerId: (_a = this.partner) == null ? void 0 : _a.id,
3219
+ supportedWalletTypes: (_b = this.partner) == null ? void 0 : _b.supportedWalletTypes,
3220
+ cosmosPrefix: (_c = this.partner) == null ? void 0 : _c.cosmosPrefix,
2627
3221
  authInfo: __privateGet(this, _authInfo),
2628
3222
  isGuestMode: this.isGuestMode,
2629
3223
  userId: this.userId,
@@ -2633,6 +3227,8 @@ const _ParaCore = class _ParaCore {
2633
3227
  wallets: redactedWallets,
2634
3228
  externalWallets: redactedExternalWallets,
2635
3229
  loginEncryptionKeyPair: this.loginEncryptionKeyPair ? "[REDACTED]" : void 0,
3230
+ isReady: this.isReady
3231
+ }, this.toStringAdditions), {
2636
3232
  ctx: {
2637
3233
  apiKey: this.ctx.apiKey,
2638
3234
  disableWorkers: this.ctx.disableWorkers,
@@ -2643,48 +3239,98 @@ const _ParaCore = class _ParaCore {
2643
3239
  useDKLS: this.ctx.useDKLS,
2644
3240
  cosmosPrefix: this.ctx.cosmosPrefix
2645
3241
  }
2646
- };
3242
+ });
2647
3243
  return `Para ${JSON.stringify(obj, null, 2)}`;
2648
3244
  }
3245
+ devLog(...s) {
3246
+ if (this.ctx.env === Environment.DEV || this.ctx.env === Environment.SANDBOX) {
3247
+ console.log(...s);
3248
+ }
3249
+ }
2649
3250
  getNewCredentialAndUrl() {
2650
3251
  return __async(this, arguments, function* ({
2651
- authMethod = "PASSKEY",
3252
+ authMethod: optsAuthMethod,
2652
3253
  isForNewDevice = false,
2653
3254
  portalTheme,
2654
3255
  shorten = false
2655
3256
  } = {}) {
3257
+ const userAuthMethods = yield this.supportedUserAuthMethods();
3258
+ const isEnclaveUser = userAuthMethods.has(AuthMethod.BASIC_LOGIN);
3259
+ const isAddingBasicLogin = optsAuthMethod === "BASIC_LOGIN";
3260
+ if (isEnclaveUser && isAddingBasicLogin) {
3261
+ throw new Error("That user is already using basic login");
3262
+ }
3263
+ if (isEnclaveUser || isAddingBasicLogin) {
3264
+ isForNewDevice = true;
3265
+ }
3266
+ const authMethods = optsAuthMethod ? [optsAuthMethod] : isForNewDevice ? ["PASSKEY", "PIN", "PASSWORD"] : ["PASSKEY"];
2656
3267
  this.assertIsAuthSet();
2657
- let credentialId, urlType;
2658
- switch (authMethod) {
2659
- case "PASSKEY":
3268
+ let passkeyId, passwordId, urlType, credentialId;
3269
+ if (!isAddingBasicLogin) {
3270
+ const canAddPasswordOrPIN = !userAuthMethods.has(AuthMethod.PASSWORD) && !userAuthMethods.has(AuthMethod.PIN);
3271
+ if (authMethods.includes("PASSKEY") && (yield this.isPasskeySupported())) {
2660
3272
  ({
2661
- data: { id: credentialId }
3273
+ data: { id: passkeyId }
2662
3274
  } = yield this.ctx.client.addSessionPublicKey(this.userId, {
2663
- status: PublicKeyStatus.PENDING,
3275
+ status: AuthMethodStatus.PENDING,
2664
3276
  type: PublicKeyType.WEB
2665
3277
  }));
2666
3278
  urlType = "createAuth";
2667
- break;
2668
- case "PASSWORD":
2669
- ({
2670
- data: { id: credentialId }
2671
- } = yield this.ctx.client.addSessionPasswordPublicKey(this.userId, {
2672
- status: PasswordStatus.PENDING
2673
- }));
2674
- urlType = "createPassword";
2675
- break;
3279
+ }
3280
+ if (authMethods.includes("PASSWORD")) {
3281
+ if (!canAddPasswordOrPIN) {
3282
+ if (optsAuthMethod === "PASSWORD") throw new Error("A user cannot have more than one password or PIN.");
3283
+ } else {
3284
+ ({
3285
+ data: { id: passwordId }
3286
+ } = yield this.ctx.client.addSessionPasswordPublicKey(this.userId, {
3287
+ status: AuthMethodStatus.PENDING
3288
+ }));
3289
+ urlType = "createPassword";
3290
+ }
3291
+ }
3292
+ if (authMethods.includes("PIN")) {
3293
+ if (!canAddPasswordOrPIN) {
3294
+ if (optsAuthMethod === "PIN") throw new Error("A user cannot have more than one password or PIN.");
3295
+ } else {
3296
+ ({
3297
+ data: { id: passwordId }
3298
+ } = yield this.ctx.client.addSessionPasswordPublicKey(this.userId, {
3299
+ status: AuthMethodStatus.PENDING
3300
+ }));
3301
+ urlType = "createPIN";
3302
+ }
3303
+ }
3304
+ credentialId = passkeyId != null ? passkeyId : passwordId;
3305
+ if (this.isNativePasskey && authMethods.includes("PASSKEY")) {
3306
+ return { credentialId };
3307
+ }
2676
3308
  }
2677
- const url = this.isNativePasskey && urlType === "createAuth" ? void 0 : yield this.constructPortalUrl(urlType, {
3309
+ const { sessionId } = yield this.touchSession();
3310
+ const url = (isForNewDevice || urlType) && (yield this.constructPortalUrl(isForNewDevice ? "addNewCredential" : urlType, {
2678
3311
  isForNewDevice,
2679
3312
  pathId: credentialId,
2680
3313
  portalTheme,
2681
- shorten
2682
- });
3314
+ shorten,
3315
+ sessionId: isForNewDevice ? sessionId : void 0,
3316
+ addNewCredentialType: optsAuthMethod,
3317
+ addNewCredentialPasskeyId: passkeyId,
3318
+ addNewCredentialPasswordId: passwordId
3319
+ }));
2683
3320
  return __spreadValues({ credentialId }, url ? { url } : {});
2684
3321
  });
2685
3322
  }
3323
+ addCredential(_0) {
3324
+ return __async(this, arguments, function* ({ authMethod }) {
3325
+ if (authMethod === "PASSKEY" && !(yield this.isPasskeySupported())) {
3326
+ throw new Error("Passkeys are not supported.");
3327
+ }
3328
+ const { url } = yield this.getNewCredentialAndUrl({ isForNewDevice: true, authMethod });
3329
+ return url;
3330
+ });
3331
+ }
2686
3332
  /**
2687
- * Returns a Para Portal URL for logging in with a WebAuth passkey or a password.
3333
+ * Returns a Para Portal URL for logging in with a WebAuth passkey, password, PIN or OTP.
2688
3334
  * @param {Object} opts the options object
2689
3335
  * @param {String} opts.auth - the user auth to sign up or log in with, in the form ` { email: string } | { phone: `+${number}` } `
2690
3336
  * @param {boolean} opts.useShortUrls - whether to shorten the generated portal URLs
@@ -2710,6 +3356,12 @@ const _ParaCore = class _ParaCore {
2710
3356
  case "PASSWORD":
2711
3357
  urlType = "loginPassword";
2712
3358
  break;
3359
+ case "PIN":
3360
+ urlType = "loginPIN";
3361
+ break;
3362
+ case "BASIC_LOGIN":
3363
+ urlType = this.authInfo.authType === "externalWallet" ? "loginExternalWallet" : "loginOTP";
3364
+ break;
2713
3365
  default:
2714
3366
  throw new Error(`invalid authentication method: '${authMethod}'`);
2715
3367
  }
@@ -2720,53 +3372,248 @@ const _ParaCore = class _ParaCore {
2720
3372
  });
2721
3373
  });
2722
3374
  }
2723
- signUpOrLogIn(_o) {
3375
+ prepareLogin() {
2724
3376
  return __async(this, null, function* () {
2725
- var _p = _o, { auth } = _p, urlOptions = __objRest(_p, ["auth"]);
2726
- const serverAuthState = yield this.ctx.client.signUpOrLogIn(__spreadValues(__spreadValues({}, auth), this.getVerificationEmailProps()));
2727
- return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
3377
+ yield this.logout();
3378
+ const { sessionLookupId } = yield this.touchSession(true);
3379
+ if (!this.loginEncryptionKeyPair) {
3380
+ yield this.setLoginEncryptionKeyPair();
3381
+ }
3382
+ return sessionLookupId;
3383
+ });
3384
+ }
3385
+ signUpOrLogIn(_i) {
3386
+ return __async(this, null, function* () {
3387
+ var _j = _i, { auth } = _j, urlOptions = __objRest(_j, ["auth"]);
3388
+ let serverAuthState;
3389
+ try {
3390
+ serverAuthState = yield this.ctx.client.signUpOrLogIn(__spreadValues(__spreadValues({}, auth), this.getVerificationEmailProps()));
3391
+ } catch (error) {
3392
+ if (error.message.includes("max beta users reached")) {
3393
+ this.displayModalError(
3394
+ `50 user limit reached. [Go to Production.](https://docs.getpara.com/v2/general/checklist#go-live-checklist)`
3395
+ );
3396
+ }
3397
+ throw error;
3398
+ }
3399
+ const authInfo = serverAuthState.auth;
3400
+ if (this.fetchPregenWalletsOverride && isPregenAuth(authInfo)) {
3401
+ const { userShare } = yield this.fetchPregenWalletsOverride({ pregenId: authInfo });
3402
+ if (userShare) {
3403
+ yield this.setUserShare(userShare);
3404
+ }
3405
+ }
3406
+ return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, __spreadValues({}, urlOptions));
2728
3407
  });
2729
3408
  }
2730
- verifyNewAccount(_q) {
3409
+ verifyNewAccount(_k) {
2731
3410
  return __async(this, null, function* () {
2732
- var _r = _q, {
3411
+ var _l = _k, {
2733
3412
  verificationCode
2734
- } = _r, urlOptions = __objRest(_r, [
3413
+ } = _l, urlOptions = __objRest(_l, [
2735
3414
  "verificationCode"
2736
3415
  ]);
2737
3416
  this.assertIsAuthSet(["email", "phone"]);
2738
- const userId = this.assertUserId();
2739
- const serverAuthState = yield this.ctx.client.verifyNewAccount(userId, {
3417
+ const userId = this.assertUserId({ allowGuestMode: true });
3418
+ const serverAuthState = yield this.ctx.client.verifyAccount(userId, {
2740
3419
  verificationCode
2741
3420
  });
3421
+ if (serverAuthState.stage === "login" || serverAuthState.stage === "done") {
3422
+ throw new Error("Account already exists.");
3423
+ }
3424
+ yield this.touchSession(true);
2742
3425
  return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
2743
3426
  });
2744
3427
  }
3428
+ getLinkedAccounts() {
3429
+ return __async(this, arguments, function* ({
3430
+ withMetadata = false
3431
+ } = {}) {
3432
+ const userId = this.assertUserId();
3433
+ const { accounts } = yield this.ctx.client.getLinkedAccounts({ userId, withMetadata });
3434
+ return __spreadValues({
3435
+ userId
3436
+ }, accounts);
3437
+ });
3438
+ }
3439
+ linkAccount(opts) {
3440
+ return __async(this, null, function* () {
3441
+ const { supportedAccountLinks = [...LINKED_ACCOUNT_TYPES] } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
3442
+ let type, identifier, externalWallet, isPermitted;
3443
+ switch (true) {
3444
+ case "auth" in opts:
3445
+ {
3446
+ const authInfo = extractAuthInfo(opts.auth, { isRequired: true });
3447
+ if (authInfo.auth === this.authInfo.auth) {
3448
+ throw new Error(AccountLinkError.Conflict);
3449
+ }
3450
+ type = authInfo.authType.toUpperCase();
3451
+ identifier = authInfo.identifier;
3452
+ isPermitted = supportedAccountLinks.includes(type);
3453
+ }
3454
+ break;
3455
+ case "externalWallet" in opts:
3456
+ {
3457
+ externalWallet = opts.externalWallet;
3458
+ type = "EXTERNAL_WALLET";
3459
+ isPermitted = supportedAccountLinks.includes("EXTERNAL_WALLET") || supportedAccountLinks.includes(externalWallet.providerId);
3460
+ }
3461
+ break;
3462
+ case "type" in opts:
3463
+ {
3464
+ type = opts.type;
3465
+ if (type === "X") {
3466
+ type = "TWITTER";
3467
+ }
3468
+ isPermitted = supportedAccountLinks.includes(type);
3469
+ }
3470
+ break;
3471
+ default:
3472
+ throw new Error("Invalid parameters for linking account, must pass `auth` or `type` or `externalWallet`");
3473
+ }
3474
+ if (!isPermitted) {
3475
+ throw new Error(`Account linking for type '${type}' is not supported by the current API key configuration`);
3476
+ }
3477
+ const userId = this.assertUserId();
3478
+ const result = yield this.ctx.client.linkAccount(__spreadValues(__spreadValues({
3479
+ userId,
3480
+ type
3481
+ }, identifier ? { identifier } : {}), externalWallet ? { externalWallet } : {}));
3482
+ if ("isConflict" in result) {
3483
+ throw new Error(AccountLinkError.Conflict);
3484
+ }
3485
+ const { linkedAccountId, signatureVerificationMessage } = result;
3486
+ this.accountLinkInProgress = __spreadValues(__spreadValues({
3487
+ id: linkedAccountId,
3488
+ type,
3489
+ isComplete: false
3490
+ }, identifier ? { identifier } : {}), signatureVerificationMessage && externalWallet ? {
3491
+ externalWallet: __spreadProps(__spreadValues({}, externalWallet), {
3492
+ signatureVerificationMessage
3493
+ })
3494
+ } : {});
3495
+ return this.accountLinkInProgress;
3496
+ });
3497
+ }
3498
+ unlinkAccount(_0) {
3499
+ return __async(this, arguments, function* ({
3500
+ linkedAccountId
3501
+ }) {
3502
+ if (!linkedAccountId) {
3503
+ throw new Error("No linked account ID provided");
3504
+ }
3505
+ const userId = this.assertUserId();
3506
+ const accounts = yield this.ctx.client.unlinkAccount({ linkedAccountId, userId });
3507
+ return accounts;
3508
+ });
3509
+ }
3510
+ verifyLink() {
3511
+ return __async(this, arguments, function* (_m = {}) {
3512
+ var _n = _m, {
3513
+ accountLinkInProgress = __privateMethod(this, _ParaCore_instances, assertIsLinkingAccount_fn).call(this)
3514
+ } = _n, opts = __objRest(_n, [
3515
+ "accountLinkInProgress"
3516
+ ]);
3517
+ try {
3518
+ const userId = this.assertUserId(), result = yield this.ctx.client.verifyLink(__spreadValues({
3519
+ linkedAccountId: accountLinkInProgress.id,
3520
+ userId
3521
+ }, opts));
3522
+ if ("isConflict" in result) {
3523
+ throw new Error(AccountLinkError.Conflict);
3524
+ }
3525
+ this.accountLinkInProgress = void 0;
3526
+ return result.accounts;
3527
+ } catch (e) {
3528
+ throw new Error(e.message === AccountLinkError.Conflict ? AccountLinkError.Conflict : e.message);
3529
+ }
3530
+ });
3531
+ }
3532
+ verifyEmailOrPhoneLink(_0) {
3533
+ return __async(this, arguments, function* ({
3534
+ verificationCode
3535
+ }) {
3536
+ const accounts = yield this.verifyLink({
3537
+ accountLinkInProgress: __privateMethod(this, _ParaCore_instances, assertIsLinkingAccount_fn).call(this, ["EMAIL", "PHONE"]),
3538
+ verificationCode
3539
+ });
3540
+ return accounts;
3541
+ });
3542
+ }
3543
+ getProfileBalance() {
3544
+ return __async(this, arguments, function* ({ config, refetch = false } = {}) {
3545
+ const { balance } = yield this.ctx.client.getProfileBalance({
3546
+ config,
3547
+ wallets: this.availableWallets.map(({ type, address }) => ({ type, address })),
3548
+ refetch
3549
+ });
3550
+ return balance;
3551
+ });
3552
+ }
3553
+ sendLoginCode() {
3554
+ return __async(this, null, function* () {
3555
+ const { userId } = yield this.ctx.client.sendLoginVerificationCode(this.authInfo);
3556
+ this.setUserId(userId);
3557
+ });
3558
+ }
3559
+ exportPrivateKey() {
3560
+ return __async(this, arguments, function* (args = {}) {
3561
+ let walletId = args == null ? void 0 : args.walletId;
3562
+ if (!(args == null ? void 0 : args.walletId)) {
3563
+ walletId = this.findWalletId(void 0, { forbidPregen: true, scheme: ["DKLS"] });
3564
+ }
3565
+ const wallet = this.wallets[walletId];
3566
+ if (this.externalWallets[walletId]) {
3567
+ throw new Error("Cannot export private key for an external wallet");
3568
+ }
3569
+ if (!wallet || !wallet.signer) {
3570
+ throw new Error("Wallet not found with id: " + walletId);
3571
+ }
3572
+ if (wallet.scheme !== "DKLS") {
3573
+ throw new Error("Cannot export private key for a Solana wallet");
3574
+ }
3575
+ if (wallet.isPregen && !!wallet.pregenIdentifier && wallet.pregenIdentifierType !== "GUEST_ID") {
3576
+ throw new Error("Cannot export private key for a pregenerated wallet");
3577
+ }
3578
+ if (args.shouldOpenPopup) {
3579
+ this.popupWindow = yield this.platformUtils.openPopup("about:blank", { type: PopupType.EXPORT_PRIVATE_KEY });
3580
+ }
3581
+ const exportPrivateKeyUrl = yield this.constructPortalUrl("exportPrivateKey", {
3582
+ pathId: walletId
3583
+ });
3584
+ if (args.shouldOpenPopup) {
3585
+ this.popupWindow.location.href = exportPrivateKeyUrl;
3586
+ }
3587
+ return {
3588
+ url: exportPrivateKeyUrl,
3589
+ popupWindow: this.popupWindow
3590
+ };
3591
+ });
3592
+ }
2745
3593
  };
2746
3594
  _authInfo = new WeakMap();
2747
- _partner = new WeakMap();
2748
3595
  _ParaCore_instances = new WeakSet();
2749
3596
  assertPartner_fn = function() {
2750
3597
  return __async(this, null, function* () {
2751
3598
  var _a, _b;
2752
- if (!__privateGet(this, _partner)) {
3599
+ if (!this.partner) {
2753
3600
  yield this.touchSession();
2754
3601
  }
2755
- if (((_a = __privateGet(this, _partner)) == null ? void 0 : _a.cosmosPrefix) && this.ctx.cosmosPrefix !== __privateGet(this, _partner).cosmosPrefix) {
2756
- this.ctx.cosmosPrefix = (_b = __privateGet(this, _partner)) == null ? void 0 : _b.cosmosPrefix;
3602
+ if (((_a = this.partner) == null ? void 0 : _a.cosmosPrefix) && this.ctx.cosmosPrefix !== this.partner.cosmosPrefix) {
3603
+ this.ctx.cosmosPrefix = (_b = this.partner) == null ? void 0 : _b.cosmosPrefix;
2757
3604
  }
2758
- return __privateGet(this, _partner);
3605
+ return this.partner;
2759
3606
  });
2760
3607
  };
2761
3608
  guestWalletIds_get = function() {
2762
3609
  var _a, _b, _c;
2763
- if (!((_a = __privateGet(this, _partner)) == null ? void 0 : _a.supportedWalletTypes)) {
3610
+ if (!((_a = this.partner) == null ? void 0 : _a.supportedWalletTypes)) {
2764
3611
  return {};
2765
3612
  }
2766
3613
  const guestId = (_c = (_b = this.pregenIds) == null ? void 0 : _b.GUEST_ID) == null ? void 0 : _c[0];
2767
3614
  return !!guestId ? Object.entries(this.wallets).reduce((acc, [id, wallet]) => {
2768
3615
  if (wallet.isPregen && !wallet.userId && wallet.pregenIdentifierType === "GUEST_ID" && wallet.pregenIdentifier === guestId) {
2769
- return __spreadValues(__spreadValues({}, acc), getEquivalentTypes(wallet.type).filter((type) => __privateGet(this, _partner).supportedWalletTypes.some((entry) => entry.type === type)).reduce((acc2, eqType) => {
3616
+ return __spreadValues(__spreadValues({}, acc), getEquivalentTypes(wallet.type).filter((type) => this.partner.supportedWalletTypes.some((entry) => entry.type === type)).reduce((acc2, eqType) => {
2770
3617
  var _a2;
2771
3618
  return __spreadProps(__spreadValues({}, acc2), { [eqType]: [.../* @__PURE__ */ new Set([...(_a2 = acc2[eqType]) != null ? _a2 : [], id])] });
2772
3619
  }, {}));
@@ -2823,9 +3670,236 @@ setAuthInfo_fn = function(authInfo) {
2823
3670
  };
2824
3671
  getPartner_fn = function(partnerId) {
2825
3672
  return __async(this, null, function* () {
3673
+ if (this.isPartnerOptional && !partnerId) {
3674
+ return void 0;
3675
+ }
2826
3676
  const res = yield this.ctx.client.getPartner(partnerId);
2827
- __privateSet(this, _partner, res.data.partner);
2828
- return __privateGet(this, _partner);
3677
+ this.partner = res.data.partner;
3678
+ return this.partner;
3679
+ });
3680
+ };
3681
+ assertIsLinkingAccount_fn = function(types) {
3682
+ if (!this.accountLinkInProgress || this.accountLinkInProgress.isComplete) {
3683
+ throw new Error("no account linking in progress");
3684
+ }
3685
+ if (types && !types.includes(this.accountLinkInProgress.type)) {
3686
+ throw new Error(
3687
+ `account linking in progress for type ${this.accountLinkInProgress.type}, expected one of ${types.join(", ")}`
3688
+ );
3689
+ }
3690
+ return this.accountLinkInProgress;
3691
+ };
3692
+ assertIsLinkingAccountOrStart_fn = function(type) {
3693
+ return __async(this, null, function* () {
3694
+ if (this.accountLinkInProgress && !this.accountLinkInProgress.isComplete) {
3695
+ return __privateMethod(this, _ParaCore_instances, assertIsLinkingAccount_fn).call(this, [type]);
3696
+ }
3697
+ return yield this.linkAccount({ type });
3698
+ });
3699
+ };
3700
+ getOAuthUrl_fn = function(_0) {
3701
+ return __async(this, arguments, function* ({
3702
+ method,
3703
+ appScheme,
3704
+ accountLinkInProgress,
3705
+ sessionLookupId,
3706
+ encryptionKey,
3707
+ portalCallbackParams
3708
+ }) {
3709
+ if (!accountLinkInProgress && !this.isPortal()) {
3710
+ return yield this.constructPortalUrl("oAuth", { sessionId: sessionLookupId, oAuthMethod: method, appScheme });
3711
+ }
3712
+ let portalSessionLookupId;
3713
+ if (this.isPortal()) {
3714
+ portalSessionLookupId = (yield this.touchSession(true)).sessionLookupId;
3715
+ }
3716
+ return constructUrl({
3717
+ base: getBaseOAuthUrl(this.ctx.env),
3718
+ path: `/auth/${method.toLowerCase()}`,
3719
+ params: __spreadProps(__spreadValues({
3720
+ apiKey: this.ctx.apiKey,
3721
+ origin: typeof window !== "undefined" ? window.location.origin : void 0,
3722
+ sessionLookupId,
3723
+ portalSessionLookupId,
3724
+ appScheme
3725
+ }, accountLinkInProgress ? {
3726
+ linkedAccountId: this.accountLinkInProgress.id
3727
+ } : {}), {
3728
+ callback: !accountLinkInProgress && (yield this.constructPortalUrl("oAuthCallback", __spreadValues({
3729
+ sessionId: sessionLookupId,
3730
+ oAuthMethod: method,
3731
+ appScheme,
3732
+ thisDevice: {
3733
+ sessionId: sessionLookupId,
3734
+ encryptionKey
3735
+ }
3736
+ }, this.isPortal() && { params: portalCallbackParams })))
3737
+ })
3738
+ });
3739
+ });
3740
+ };
3741
+ waitForLoginProcess_fn = function() {
3742
+ return __async(this, arguments, function* ({
3743
+ isCanceled = () => false,
3744
+ onCancel,
3745
+ onPoll,
3746
+ skipSessionRefresh = false,
3747
+ isSwitchingWallets = false
3748
+ } = {}) {
3749
+ this.devLog("[waitForLoginProcess] Starting", {
3750
+ isSwitchingWallets,
3751
+ skipSessionRefresh,
3752
+ isExternalWalletAuth: this.isExternalWalletAuth
3753
+ });
3754
+ const startedAt = Date.now();
3755
+ let originalCurrentWalletIdsHash;
3756
+ if (isSwitchingWallets) {
3757
+ this.devLog("[waitForLoginProcess] Wallet switching mode enabled");
3758
+ this.isSwitchingWallets = true;
3759
+ const session = yield this.touchSession();
3760
+ originalCurrentWalletIdsHash = session.currentWalletIdsHash;
3761
+ this.devLog("[waitForLoginProcess] Original wallet IDs hash", { originalCurrentWalletIdsHash });
3762
+ }
3763
+ return new Promise((resolve, reject) => {
3764
+ (() => __async(this, null, function* () {
3765
+ var _a;
3766
+ if (!this.isExternalWalletAuth && !isSwitchingWallets) {
3767
+ this.devLog("[waitForLoginProcess] Clearing external wallets");
3768
+ this.externalWallets = {};
3769
+ }
3770
+ let pollCount = 0;
3771
+ while (true) {
3772
+ pollCount++;
3773
+ this.devLog("[waitForLoginProcess] Poll iteration", {
3774
+ pollCount,
3775
+ elapsedMs: Date.now() - startedAt
3776
+ });
3777
+ if (isCanceled() || Date.now() - startedAt > constants.POLLING_TIMEOUT_MS) {
3778
+ this.devLog("[waitForLoginProcess] Canceled or timed out", {
3779
+ wasCanceled: isCanceled(),
3780
+ timedOut: Date.now() - startedAt > constants.POLLING_TIMEOUT_MS,
3781
+ elapsedMs: Date.now() - startedAt
3782
+ });
3783
+ if (isSwitchingWallets) {
3784
+ this.isSwitchingWallets = false;
3785
+ } else {
3786
+ dispatchEvent(ParaEvent.LOGIN_EVENT, { isComplete: false }, "failed to setup user");
3787
+ }
3788
+ onCancel == null ? void 0 : onCancel();
3789
+ return reject("canceled");
3790
+ }
3791
+ yield new Promise((resolve2) => setTimeout(resolve2, constants.POLLING_INTERVAL_MS));
3792
+ try {
3793
+ this.devLog("[waitForLoginProcess] Touching session");
3794
+ let session = yield this.touchSession();
3795
+ this.devLog("[waitForLoginProcess] Session state", {
3796
+ isAuthenticated: session.isAuthenticated,
3797
+ currentWalletIdsHash: session.currentWalletIdsHash,
3798
+ needsWallet: session.needsWallet
3799
+ });
3800
+ const shouldContinuePolling = isSwitchingWallets ? originalCurrentWalletIdsHash === session.currentWalletIdsHash : !session.isAuthenticated;
3801
+ this.devLog("[waitForLoginProcess] Should continue polling", {
3802
+ shouldContinuePolling,
3803
+ isSwitchingWallets,
3804
+ originalCurrentWalletIdsHash,
3805
+ sessionCurrentWalletIdsHash: session.currentWalletIdsHash,
3806
+ isAuthenticated: session.isAuthenticated
3807
+ });
3808
+ if (shouldContinuePolling) {
3809
+ onPoll == null ? void 0 : onPoll();
3810
+ continue;
3811
+ }
3812
+ this.devLog("[waitForLoginProcess] Authentication check passed, setting up user");
3813
+ session = yield this.userSetupAfterLogin();
3814
+ const needsWallet = (_a = session.needsWallet) != null ? _a : false;
3815
+ this.devLog("[waitForLoginProcess] User setup complete", { needsWallet });
3816
+ if (isSwitchingWallets) {
3817
+ const isWalletSwitchingComplete = originalCurrentWalletIdsHash !== session.currentWalletIdsHash;
3818
+ this.devLog("[waitForLoginProcess] Wallet switching check", {
3819
+ isWalletSwitchingComplete,
3820
+ originalHash: originalCurrentWalletIdsHash,
3821
+ sessionHash: session.currentWalletIdsHash
3822
+ });
3823
+ if (!isWalletSwitchingComplete) {
3824
+ onPoll == null ? void 0 : onPoll();
3825
+ continue;
3826
+ }
3827
+ } else if (!needsWallet) {
3828
+ this.devLog("[waitForLoginProcess] Checking wallet IDs", {
3829
+ currentWalletIdsArrayLength: this.currentWalletIdsArray.length
3830
+ });
3831
+ if (this.currentWalletIdsArray.length === 0) {
3832
+ this.devLog("[waitForLoginProcess] No wallet IDs yet, continuing to poll");
3833
+ onPoll == null ? void 0 : onPoll();
3834
+ continue;
3835
+ }
3836
+ }
3837
+ this.devLog("[waitForLoginProcess] Getting transmission key shares");
3838
+ const tempSharesRes = yield this.getTransmissionKeyShares();
3839
+ this.devLog("[waitForLoginProcess] Transmission shares received", {
3840
+ shareCount: tempSharesRes.data.temporaryShares.length,
3841
+ shares: tempSharesRes.data.temporaryShares.map((s) => ({
3842
+ walletId: s.walletId,
3843
+ walletScheme: s.walletScheme
3844
+ }))
3845
+ });
3846
+ let hasSharesForCurrentWallets;
3847
+ if (!isSwitchingWallets && !this.isPortal()) {
3848
+ this.devLog("[waitForLoginProcess] Fetching wallets");
3849
+ const fetchedWallets = yield this.fetchWallets();
3850
+ this.devLog("[waitForLoginProcess] Wallets fetched", {
3851
+ walletCount: fetchedWallets.length,
3852
+ wallets: fetchedWallets.map((w) => ({ id: w.id, type: w.type, scheme: w.scheme }))
3853
+ });
3854
+ hasSharesForCurrentWallets = tempSharesRes.data.temporaryShares.length === fetchedWallets.length;
3855
+ } else {
3856
+ hasSharesForCurrentWallets = this.currentWalletIdsArray.every(([walletId]) => {
3857
+ return tempSharesRes.data.temporaryShares.some((share) => share.walletId === walletId);
3858
+ });
3859
+ }
3860
+ this.devLog("[waitForLoginProcess] Checking shares for current wallets", {
3861
+ hasSharesForCurrentWallets,
3862
+ currentWalletIdsArray: this.currentWalletIdsArray,
3863
+ shares: tempSharesRes.data.temporaryShares.map((s) => ({
3864
+ walletId: s.walletId,
3865
+ walletScheme: s.walletScheme
3866
+ }))
3867
+ });
3868
+ if (hasSharesForCurrentWallets) {
3869
+ this.devLog("[waitForLoginProcess] Setting up after login");
3870
+ yield this.setupAfterLogin({ temporaryShares: tempSharesRes.data.temporaryShares, skipSessionRefresh });
3871
+ this.devLog("[waitForLoginProcess] Setup after login complete");
3872
+ this.devLog("[waitForLoginProcess] Claiming pregen wallets");
3873
+ yield this.claimPregenWallets();
3874
+ this.devLog("[waitForLoginProcess] Pregen wallets claimed");
3875
+ const resp = {
3876
+ needsWallet: needsWallet || Object.values(this.wallets).length === 0,
3877
+ partnerId: session.partnerId
3878
+ };
3879
+ this.devLog("[waitForLoginProcess] Login process complete", {
3880
+ needsWallet: resp.needsWallet,
3881
+ partnerId: resp.partnerId,
3882
+ walletCount: Object.values(this.wallets).length,
3883
+ isSwitchingWallets
3884
+ });
3885
+ if (isSwitchingWallets) {
3886
+ this.devLog("[waitForLoginProcess] Clearing wallet switching state");
3887
+ this.isSwitchingWallets = false;
3888
+ } else {
3889
+ this.devLog("[waitForLoginProcess] Dispatching LOGIN_EVENT");
3890
+ dispatchEvent(ParaEvent.LOGIN_EVENT, resp);
3891
+ }
3892
+ return resolve(resp);
3893
+ }
3894
+ this.devLog("[waitForLoginProcess] Not all shares available yet, continuing to poll");
3895
+ onPoll == null ? void 0 : onPoll();
3896
+ } catch (err) {
3897
+ console.error("[waitForLoginProcess] Error during polling iteration", err);
3898
+ onPoll == null ? void 0 : onPoll();
3899
+ }
3900
+ }
3901
+ }))();
3902
+ });
2829
3903
  });
2830
3904
  };
2831
3905
  createPregenWallet_fn = function(opts) {
@@ -2878,8 +3952,9 @@ createPregenWallet_fn = function(opts) {
2878
3952
  _isCreateGuestWalletsPending = new WeakMap();
2879
3953
  prepareAuthState_fn = function(_0) {
2880
3954
  return __async(this, arguments, function* (serverAuthState, opts = {}) {
2881
- if (!opts.sessionLookupId && serverAuthState.stage === "login") {
2882
- opts.sessionLookupId = yield __privateMethod(this, _ParaCore_instances, prepareLogin_fn).call(this);
3955
+ var _a, _b;
3956
+ 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))))) {
3957
+ opts.sessionLookupId = yield this.prepareLogin();
2883
3958
  }
2884
3959
  const { auth, externalWallet, userId, displayName, pfpUrl, username } = serverAuthState;
2885
3960
  const authInfo = __spreadValues(__spreadValues({}, extractAuthInfo(auth, { isRequired: true })), Object.fromEntries(
@@ -2893,34 +3968,70 @@ prepareAuthState_fn = function(_0) {
2893
3968
  yield __privateMethod(this, _ParaCore_instances, setAuthInfo_fn).call(this, authInfo);
2894
3969
  yield this.assertIsAuthSet();
2895
3970
  if (!!externalWallet) {
2896
- yield this.setExternalWallet(externalWallet);
3971
+ yield this.setExternalWallet([externalWallet]);
2897
3972
  }
2898
3973
  if (!!userId) {
2899
3974
  yield this.setUserId(userId);
2900
3975
  }
2901
3976
  let authState;
2902
3977
  switch (serverAuthState.stage) {
3978
+ case "done": {
3979
+ authState = yield __privateMethod(this, _ParaCore_instances, prepareDoneState_fn).call(this, serverAuthState);
3980
+ break;
3981
+ }
2903
3982
  case "verify":
2904
- authState = serverAuthState;
3983
+ authState = yield __privateMethod(this, _ParaCore_instances, prepareVerificationState_fn).call(this, serverAuthState, __spreadProps(__spreadValues({}, opts), {
3984
+ sessionLookupId: opts.sessionLookupId
3985
+ }));
2905
3986
  break;
2906
3987
  case "login":
3988
+ if (externalWallet && !(externalWallet == null ? void 0 : externalWallet.withFullParaAuth)) {
3989
+ authState = serverAuthState;
3990
+ break;
3991
+ }
2907
3992
  authState = yield __privateMethod(this, _ParaCore_instances, prepareLoginState_fn).call(this, serverAuthState, __spreadProps(__spreadValues({}, opts), { sessionLookupId: opts.sessionLookupId }));
2908
3993
  break;
2909
3994
  case "signup":
3995
+ if (externalWallet && !(externalWallet == null ? void 0 : externalWallet.withFullParaAuth)) {
3996
+ authState = serverAuthState;
3997
+ break;
3998
+ }
2910
3999
  authState = yield __privateMethod(this, _ParaCore_instances, prepareSignUpState_fn).call(this, serverAuthState, opts);
2911
4000
  break;
2912
4001
  }
2913
4002
  return authState;
2914
4003
  });
2915
4004
  };
2916
- prepareLogin_fn = function() {
4005
+ prepareDoneState_fn = function(doneState) {
2917
4006
  return __async(this, null, function* () {
2918
- yield this.logout();
2919
- const { sessionLookupId } = yield this.touchSession(true);
2920
- if (!this.loginEncryptionKeyPair) {
2921
- yield this.setLoginEncryptionKeyPair();
4007
+ let isSLOPossible = doneState.authMethods.includes(AuthMethod.BASIC_LOGIN);
4008
+ this.isEnclaveUser = isSLOPossible;
4009
+ return doneState;
4010
+ });
4011
+ };
4012
+ prepareVerificationState_fn = function(_0, _1) {
4013
+ return __async(this, arguments, function* (verifyState, {
4014
+ useShortUrls: shorten = false,
4015
+ portalTheme,
4016
+ sessionLookupId
4017
+ }) {
4018
+ var _a;
4019
+ let isSLOPossible = false;
4020
+ if (verifyState.nextStage === "login") {
4021
+ isSLOPossible = verifyState.loginAuthMethods.includes(AuthMethod.BASIC_LOGIN);
4022
+ } else if (verifyState.nextStage === "signup") {
4023
+ isSLOPossible = verifyState.signupAuthMethods.includes(AuthMethod.BASIC_LOGIN);
2922
4024
  }
2923
- return sessionLookupId;
4025
+ this.isEnclaveUser = isSLOPossible;
4026
+ const isExternalWalletFullAuth = (_a = verifyState.externalWallet) == null ? void 0 : _a.withFullParaAuth;
4027
+ return __spreadValues(__spreadValues({}, verifyState), isSLOPossible || isExternalWalletFullAuth ? {
4028
+ loginUrl: yield this.getLoginUrl({
4029
+ authMethod: AuthMethod.BASIC_LOGIN,
4030
+ sessionId: sessionLookupId,
4031
+ shorten,
4032
+ portalTheme
4033
+ })
4034
+ } : {});
2924
4035
  });
2925
4036
  };
2926
4037
  prepareLoginState_fn = function(_0, _1) {
@@ -2929,8 +4040,12 @@ prepareLoginState_fn = function(_0, _1) {
2929
4040
  portalTheme,
2930
4041
  sessionLookupId
2931
4042
  }) {
2932
- const _a = loginState, { loginAuthMethods } = _a, authState = __objRest(_a, ["loginAuthMethods"]);
2933
- return __spreadValues(__spreadValues(__spreadValues({}, authState), !this.isNativePasskey && loginAuthMethods.includes(AuthMethod.PASSKEY) ? {
4043
+ const _a = loginState, { loginAuthMethods = [], hasPasswordWithoutPIN } = _a, authState = __objRest(_a, ["loginAuthMethods", "hasPasswordWithoutPIN"]);
4044
+ const isPasskeySupported = yield this.isPasskeySupported(), isPasskeyPossible = loginAuthMethods.includes(AuthMethod.PASSKEY) && !this.isNativePasskey, isPasswordPossible = loginAuthMethods.includes(AuthMethod.PASSWORD) && hasPasswordWithoutPIN, isPINPossible = loginAuthMethods.includes(AuthMethod.PIN);
4045
+ return __spreadValues(__spreadValues(__spreadValues(__spreadProps(__spreadValues({}, authState), {
4046
+ isPasskeySupported,
4047
+ loginAuthMethods
4048
+ }), isPasskeyPossible ? {
2934
4049
  passkeyUrl: yield this.getLoginUrl({ sessionId: sessionLookupId, shorten, portalTheme }),
2935
4050
  passkeyKnownDeviceUrl: yield this.constructPortalUrl("loginAuth", {
2936
4051
  sessionId: sessionLookupId,
@@ -2941,28 +4056,41 @@ prepareLoginState_fn = function(_0, _1) {
2941
4056
  shorten,
2942
4057
  portalTheme
2943
4058
  })
2944
- } : {}), loginAuthMethods.includes(AuthMethod.PASSWORD) ? {
4059
+ } : {}), isPasswordPossible ? {
2945
4060
  passwordUrl: yield this.constructPortalUrl("loginPassword", {
2946
4061
  sessionId: sessionLookupId,
2947
4062
  shorten,
2948
- portalTheme
4063
+ portalTheme,
4064
+ params: { isEmbedded: `${!loginState.isWalletSelectionNeeded}` }
4065
+ })
4066
+ } : {}), isPINPossible ? {
4067
+ pinUrl: yield this.constructPortalUrl("loginPIN", {
4068
+ sessionId: sessionLookupId,
4069
+ shorten,
4070
+ portalTheme,
4071
+ params: { isEmbedded: `${!loginState.isWalletSelectionNeeded}` }
2949
4072
  })
2950
4073
  } : {});
2951
4074
  });
2952
4075
  };
2953
4076
  prepareSignUpState_fn = function(_0, _1) {
2954
4077
  return __async(this, arguments, function* (serverSignupState, { useShortUrls: shorten = false, portalTheme }) {
2955
- const _a = serverSignupState, { signupAuthMethods } = _a, authState = __objRest(_a, ["signupAuthMethods"]);
2956
- const [isPasskey, isPassword] = [
4078
+ const _a = serverSignupState, { signupAuthMethods = [] } = _a, authState = __objRest(_a, ["signupAuthMethods"]);
4079
+ const isPasskeySupported = yield this.isPasskeySupported();
4080
+ const [isPasskey, isPassword, isPIN] = [
2957
4081
  signupAuthMethods.includes(AuthMethod.PASSKEY),
2958
- signupAuthMethods.includes(AuthMethod.PASSWORD)
4082
+ signupAuthMethods.includes(AuthMethod.PASSWORD) || !isPasskeySupported,
4083
+ signupAuthMethods.includes(AuthMethod.PIN)
2959
4084
  ];
2960
- if (!isPasskey && !isPassword) {
4085
+ if (!isPasskey && !isPassword && !isPIN) {
2961
4086
  throw new Error(
2962
- "No supported authentication methods found. Please ensure you have enabled either WebAuth passkeys or passwords in your Developer Portal settings."
4087
+ "No supported authentication methods found. Please ensure you have enabled either WebAuth passkeys, passwords or PINs in your Developer Portal settings."
2963
4088
  );
2964
4089
  }
2965
- const signupState = authState;
4090
+ const signupState = __spreadProps(__spreadValues({}, authState), {
4091
+ isPasskeySupported,
4092
+ signupAuthMethods
4093
+ });
2966
4094
  if (isPasskey) {
2967
4095
  const { url: passkeyUrl, credentialId: passkeyId } = yield this.getNewCredentialAndUrl({
2968
4096
  authMethod: "PASSKEY",
@@ -2980,6 +4108,15 @@ prepareSignUpState_fn = function(_0, _1) {
2980
4108
  signupState.passwordUrl = passwordUrl;
2981
4109
  signupState.passwordId = passwordId;
2982
4110
  }
4111
+ if (isPIN) {
4112
+ const { url: pinUrl, credentialId: pinId } = yield this.getNewCredentialAndUrl({
4113
+ authMethod: "PIN",
4114
+ portalTheme,
4115
+ shorten
4116
+ });
4117
+ signupState.pinUrl = pinUrl;
4118
+ signupState.pinId = pinId;
4119
+ }
2983
4120
  return signupState;
2984
4121
  });
2985
4122
  };