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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/dist/cjs/ParaCore.js +1038 -248
  2. package/dist/cjs/constants.js +13 -1
  3. package/dist/cjs/index.js +31 -3
  4. package/dist/cjs/shares/enclave.js +266 -0
  5. package/dist/cjs/shares/shareDistribution.js +16 -1
  6. package/dist/cjs/types/{theme.js → assets.js} +2 -2
  7. package/dist/cjs/types/{onRamps.js → auth.js} +12 -12
  8. package/dist/cjs/types/coreApi.js +20 -3
  9. package/dist/cjs/types/events.js +2 -0
  10. package/dist/cjs/types/index.js +2 -21
  11. package/dist/cjs/utils/config.js +108 -0
  12. package/dist/cjs/utils/formatting.js +46 -0
  13. package/dist/cjs/utils/index.js +2 -0
  14. package/dist/cjs/utils/onRamps.js +2 -3
  15. package/dist/cjs/utils/wallet.js +3 -0
  16. package/dist/esm/ParaCore.js +1045 -254
  17. package/dist/esm/{chunk-7B52C2XE.js → chunk-W5CT3TVS.js} +2 -0
  18. package/dist/esm/constants.js +10 -2
  19. package/dist/esm/cryptography/utils.js +1 -1
  20. package/dist/esm/errors.js +1 -1
  21. package/dist/esm/external/mpcComputationClient.js +1 -1
  22. package/dist/esm/external/userManagementClient.js +1 -1
  23. package/dist/esm/index.js +31 -6
  24. package/dist/esm/shares/KeyContainer.js +1 -1
  25. package/dist/esm/shares/enclave.js +226 -0
  26. package/dist/esm/shares/recovery.js +1 -1
  27. package/dist/esm/shares/shareDistribution.js +17 -2
  28. package/dist/esm/transmission/transmissionUtils.js +1 -1
  29. package/dist/esm/types/auth.js +11 -0
  30. package/dist/esm/types/config.js +1 -1
  31. package/dist/esm/types/coreApi.js +19 -3
  32. package/dist/esm/types/events.js +3 -1
  33. package/dist/esm/types/index.js +1 -16
  34. package/dist/esm/types/popup.js +1 -1
  35. package/dist/esm/types/wallet.js +1 -1
  36. package/dist/esm/utils/autobind.js +1 -1
  37. package/dist/esm/utils/config.js +86 -0
  38. package/dist/esm/utils/events.js +1 -1
  39. package/dist/esm/utils/formatting.js +44 -1
  40. package/dist/esm/utils/index.js +1 -0
  41. package/dist/esm/utils/json.js +1 -1
  42. package/dist/esm/utils/listeners.js +1 -1
  43. package/dist/esm/utils/onRamps.js +3 -4
  44. package/dist/esm/utils/phone.js +1 -1
  45. package/dist/esm/utils/polling.js +1 -1
  46. package/dist/esm/utils/types.js +1 -1
  47. package/dist/esm/utils/url.js +1 -1
  48. package/dist/esm/utils/wallet.js +4 -1
  49. package/dist/types/ParaCore.d.ts +115 -52
  50. package/dist/types/PlatformUtils.d.ts +2 -3
  51. package/dist/types/constants.d.ts +18 -14
  52. package/dist/types/index.d.ts +6 -4
  53. package/dist/types/shares/KeyContainer.d.ts +0 -2
  54. package/dist/types/shares/enclave.d.ts +81 -0
  55. package/dist/types/shares/shareDistribution.d.ts +4 -2
  56. package/dist/types/types/assets.d.ts +14 -0
  57. package/dist/types/types/auth.d.ts +16 -0
  58. package/dist/types/types/config.d.ts +11 -2
  59. package/dist/types/types/coreApi.d.ts +101 -36
  60. package/dist/types/types/events.d.ts +7 -2
  61. package/dist/types/types/index.d.ts +1 -4
  62. package/dist/types/types/methods.d.ts +85 -13
  63. package/dist/types/types/wallet.d.ts +7 -4
  64. package/dist/types/utils/config.d.ts +7 -0
  65. package/dist/types/utils/formatting.d.ts +12 -1
  66. package/dist/types/utils/index.d.ts +1 -0
  67. package/dist/types/utils/onRamps.d.ts +9 -10
  68. package/package.json +23 -23
  69. package/dist/cjs/types/recovery.js +0 -34
  70. package/dist/esm/types/onRamps.js +0 -11
  71. package/dist/esm/types/recovery.js +0 -12
  72. package/dist/types/types/onRamps.d.ts +0 -10
  73. package/dist/types/types/recovery.d.ts +0 -7
  74. package/dist/types/types/theme.d.ts +0 -12
  75. /package/dist/esm/types/{theme.js → assets.js} +0 -0
@@ -7,8 +7,8 @@ import {
7
7
  __privateSet,
8
8
  __spreadProps,
9
9
  __spreadValues
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;
10
+ } from "./chunk-W5CT3TVS.js";
11
+ var _authInfo, _ParaCore_instances, assertPartner_fn, guestWalletIds_get, guestWalletIdsArray_get, toAuthInfo_fn, setAuthInfo_fn, getPartner_fn, assertIsLinkingAccount_fn, assertIsLinkingAccountOrStart_fn, getOAuthUrl_fn, createPregenWallet_fn, _isCreateGuestWalletsPending, prepareAuthState_fn, prepareDoneState_fn, prepareVerificationState_fn, prepareLoginState_fn, prepareSignUpState_fn;
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 {
@@ -73,23 +74,21 @@ import {
73
74
  } from "./utils/index.js";
74
75
  import { TransactionReviewDenied, TransactionReviewTimeout } from "./errors.js";
75
76
  import * as constants from "./constants.js";
77
+ import { EnclaveClient } from "./shares/enclave.js";
76
78
  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) {
79
+ constructor(envOrApiKey, apiKeyOrOpts, opts) {
85
80
  __privateAdd(this, _ParaCore_instances);
81
+ this.popupWindow = null;
86
82
  __privateAdd(this, _authInfo);
87
83
  this.isNativePasskey = false;
88
- __privateAdd(this, _partner);
84
+ this.isReady = false;
85
+ this.accountLinkInProgress = void 0;
86
+ this.isEnclaveUser = false;
89
87
  this.isAwaitingAccountCreation = false;
90
88
  this.isAwaitingLogin = false;
91
89
  this.isAwaitingFarcaster = false;
92
90
  this.isAwaitingOAuth = false;
91
+ this.isWorkerInitialized = false;
93
92
  /**
94
93
  * 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
94
  */
@@ -98,6 +97,7 @@ const _ParaCore = class _ParaCore {
98
97
  * Wallets associated with the `ParaCore` instance.
99
98
  */
100
99
  this.externalWallets = {};
100
+ this.onRampPopup = void 0;
101
101
  this.localStorageGetItem = (key) => {
102
102
  return this.platformUtils.localStorage.get(key);
103
103
  };
@@ -119,16 +119,29 @@ const _ParaCore = class _ParaCore {
119
119
  this.retrieveSessionCookie = () => {
120
120
  return this.sessionCookie;
121
121
  };
122
+ this.retrieveEnclaveJwt = () => {
123
+ return this.enclaveJwt;
124
+ };
125
+ this.retrieveEnclaveRefreshJwt = () => {
126
+ return this.enclaveRefreshJwt;
127
+ };
122
128
  /**
123
129
  * Remove all local storage and prefixed session storage.
124
130
  * @param {'local' | 'session' | 'secure' | 'all'} type - Type of storage to clear. Defaults to 'all'.
125
131
  */
126
132
  this.clearStorage = (type = "all") => __async(this, null, function* () {
127
133
  const isAll = type === "all";
128
- (isAll || type === "local") && this.platformUtils.localStorage.clear(constants.PREFIX);
129
- (isAll || type === "session") && this.platformUtils.sessionStorage.clear(constants.PREFIX);
134
+ if (isAll || type === "local") {
135
+ this.platformUtils.localStorage.clear(constants.PREFIX);
136
+ this.platformUtils.localStorage.clear(constants.PARA_PREFIX);
137
+ }
138
+ if (isAll || type === "session") {
139
+ this.platformUtils.sessionStorage.clear(constants.PREFIX);
140
+ this.platformUtils.sessionStorage.clear(constants.PARA_PREFIX);
141
+ }
130
142
  if ((isAll || type === "secure") && this.platformUtils.secureStorage) {
131
143
  this.platformUtils.secureStorage.clear(constants.PREFIX);
144
+ this.platformUtils.secureStorage.clear(constants.PARA_PREFIX);
132
145
  }
133
146
  });
134
147
  this.trackError = (methodName, err) => __async(this, null, function* () {
@@ -170,6 +183,7 @@ const _ParaCore = class _ParaCore {
170
183
  this.updateWalletIdsFromStorage();
171
184
  this.updateSessionCookieFromStorage();
172
185
  this.updateLoginEncryptionKeyPairFromStorage();
186
+ this.updateEnclaveJwtFromStorage();
173
187
  };
174
188
  this.updateAuthInfoFromStorage = () => {
175
189
  var _a;
@@ -189,6 +203,10 @@ const _ParaCore = class _ParaCore {
189
203
  }
190
204
  __privateSet(this, _authInfo, authInfo);
191
205
  };
206
+ this.updateEnclaveJwtFromStorage = () => {
207
+ this.enclaveJwt = this.localStorageGetItem(constants.LOCAL_STORAGE_ENCLAVE_JWT) || this.sessionStorageGetItem(constants.LOCAL_STORAGE_ENCLAVE_JWT) || void 0;
208
+ this.enclaveRefreshJwt = this.localStorageGetItem(constants.LOCAL_STORAGE_ENCLAVE_REFRESH_JWT) || this.sessionStorageGetItem(constants.LOCAL_STORAGE_ENCLAVE_REFRESH_JWT) || void 0;
209
+ };
192
210
  this.updateUserIdFromStorage = () => {
193
211
  this.userId = this.localStorageGetItem(constants.LOCAL_STORAGE_USER_ID) || void 0;
194
212
  };
@@ -249,6 +267,16 @@ const _ParaCore = class _ParaCore {
249
267
  const _externalWallets = JSON.parse(stringExternalWallets || "{}");
250
268
  this.setExternalWallets(_externalWallets);
251
269
  };
270
+ this.initializeWorker = () => __async(this, null, function* () {
271
+ if (!this.isWorkerInitialized && !this.ctx.disableWebSockets && !this.ctx.disableWorkers) {
272
+ try {
273
+ this.isWorkerInitialized = true;
274
+ yield this.platformUtils.initializeWorker(this.ctx);
275
+ } catch (e) {
276
+ this.devLog("error initializing worker:", e);
277
+ }
278
+ }
279
+ });
252
280
  /**
253
281
  * Creates several new wallets with the desired types. If no types are provided, this method
254
282
  * will create one for each of the non-optional types specified in the instance's `supportedWalletTypes`
@@ -265,8 +293,29 @@ const _ParaCore = class _ParaCore {
265
293
  }) {
266
294
  return (yield this.ctx.client.getWalletBalance({ walletId, rpcUrl })).balance;
267
295
  });
268
- if (!apiKey) {
269
- throw new Error("A Para API key is required.");
296
+ let env, apiKey;
297
+ const actualArgs = Array.from(arguments).filter((arg) => arg !== void 0);
298
+ const actualArgumentCount = actualArgs.length;
299
+ if (actualArgumentCount === 1) {
300
+ if (Object.values(Environment).includes(envOrApiKey)) {
301
+ throw new Error("A Para API key is required.");
302
+ }
303
+ env = _ParaCore.resolveEnvironment(void 0, actualArgs[0]);
304
+ apiKey = actualArgs[0];
305
+ opts = void 0;
306
+ } else if (actualArgumentCount === 2) {
307
+ if (typeof apiKeyOrOpts === "object" && apiKeyOrOpts !== null) {
308
+ env = _ParaCore.resolveEnvironment(void 0, envOrApiKey);
309
+ apiKey = envOrApiKey;
310
+ opts = apiKeyOrOpts;
311
+ } else {
312
+ env = _ParaCore.resolveEnvironment(envOrApiKey, apiKeyOrOpts);
313
+ apiKey = apiKeyOrOpts;
314
+ opts = void 0;
315
+ }
316
+ } else {
317
+ env = _ParaCore.resolveEnvironment(envOrApiKey, apiKeyOrOpts);
318
+ apiKey = apiKeyOrOpts;
270
319
  }
271
320
  if (!opts) opts = {};
272
321
  let isE2E = false;
@@ -289,6 +338,7 @@ const _ParaCore = class _ParaCore {
289
338
  this.portalTheme = opts.portalTheme;
290
339
  this.platformUtils = this.getPlatformUtils();
291
340
  this.disableProviderModal = this.platformUtils.disableProviderModal;
341
+ this.fetchPregenWalletsOverride = opts.fetchPregenWalletsOverride;
292
342
  if (opts.useStorageOverrides) {
293
343
  this.localStorageGetItem = opts.localStorageGetItemOverride;
294
344
  this.localStorageSetItem = opts.localStorageSetItemOverride;
@@ -308,18 +358,41 @@ const _ParaCore = class _ParaCore {
308
358
  cookie
309
359
  );
310
360
  };
361
+ this.persistEnclaveJwt = (jwt) => {
362
+ this.enclaveJwt = jwt;
363
+ (opts.useSessionStorage ? this.sessionStorageSetItem : this.localStorageSetItem)(
364
+ constants.LOCAL_STORAGE_ENCLAVE_JWT,
365
+ jwt
366
+ );
367
+ };
368
+ this.persistEnclaveRefreshJwt = (refreshJwt) => {
369
+ this.enclaveRefreshJwt = refreshJwt;
370
+ (opts.useSessionStorage ? this.sessionStorageSetItem : this.localStorageSetItem)(
371
+ constants.LOCAL_STORAGE_ENCLAVE_REFRESH_JWT,
372
+ refreshJwt
373
+ );
374
+ };
375
+ const client = initClient({
376
+ env,
377
+ version: _ParaCore.version,
378
+ apiKey,
379
+ partnerId: this.isPortal(env) ? opts.portalPartnerId : void 0,
380
+ useFetchAdapter: !!opts.disableWorkers,
381
+ retrieveSessionCookie: this.retrieveSessionCookie,
382
+ persistSessionCookie: this.persistSessionCookie
383
+ });
384
+ const enclaveClient = new EnclaveClient({
385
+ userManagementClient: client,
386
+ retrieveJwt: this.retrieveEnclaveJwt,
387
+ persistJwt: this.persistEnclaveJwt,
388
+ retrieveRefreshJwt: this.retrieveEnclaveRefreshJwt,
389
+ persistRefreshJwt: this.persistEnclaveRefreshJwt
390
+ });
311
391
  this.ctx = {
312
392
  env,
313
393
  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
- }),
394
+ client,
395
+ enclaveClient,
323
396
  disableWorkers: opts.disableWorkers,
324
397
  offloadMPCComputationURL: opts.offloadMPCComputationURL,
325
398
  useLocalFiles: opts.useLocalFiles,
@@ -354,6 +427,9 @@ const _ParaCore = class _ParaCore {
354
427
  ]);
355
428
  }
356
429
  }
430
+ setModalError(_error) {
431
+ return;
432
+ }
357
433
  get authInfo() {
358
434
  return __privateGet(this, _authInfo);
359
435
  }
@@ -380,8 +456,15 @@ const _ParaCore = class _ParaCore {
380
456
  get externalWalletConnectionType() {
381
457
  if (this.isExternalWalletAuth) {
382
458
  return "AUTHENTICATED";
459
+ } else if (this.isExternalWalletWithVerification) {
460
+ return "VERIFICATION";
383
461
  } else if (!!Object.keys(this.externalWallets).length) {
384
- return "CONNECTION_ONLY";
462
+ const hasEmbeddedWallets = Object.keys(this.wallets).some((id) => !this.wallets[id].isExternal);
463
+ if (hasEmbeddedWallets) {
464
+ return "NONE";
465
+ } else {
466
+ return "CONNECTION_ONLY";
467
+ }
385
468
  }
386
469
  return "NONE";
387
470
  }
@@ -402,16 +485,28 @@ const _ParaCore = class _ParaCore {
402
485
  return isTelegram((_a = this.authInfo) == null ? void 0 : _a.auth);
403
486
  }
404
487
  get isExternalWalletAuth() {
405
- var _a;
406
- return isExternalWallet((_a = __privateGet(this, _authInfo)) == null ? void 0 : _a.auth);
488
+ var _a, _b, _c;
489
+ 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);
490
+ }
491
+ get isExternalWalletWithVerification() {
492
+ var _a, _b, _c;
493
+ 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
494
  }
408
495
  get partnerId() {
409
496
  var _a;
410
- return (_a = __privateGet(this, _partner)) == null ? void 0 : _a.id;
497
+ return (_a = this.partner) == null ? void 0 : _a.id;
498
+ }
499
+ get partnerName() {
500
+ var _a;
501
+ return (_a = this.partner) == null ? void 0 : _a.displayName;
502
+ }
503
+ get partnerLogo() {
504
+ var _a;
505
+ return (_a = this.partner) == null ? void 0 : _a.logoUrl;
411
506
  }
412
507
  get currentWalletIdsArray() {
413
508
  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(
509
+ return ((_b = (_a = this.partner) == null ? void 0 : _a.supportedWalletTypes) != null ? _b : Object.keys(this.currentWalletIds).map((type) => ({ type }))).reduce(
415
510
  (acc, { type }) => {
416
511
  var _a2;
417
512
  return [
@@ -451,19 +546,23 @@ const _ParaCore = class _ParaCore {
451
546
  }
452
547
  get isNoWalletConfig() {
453
548
  var _a;
454
- return !!((_a = __privateGet(this, _partner)) == null ? void 0 : _a.supportedWalletTypes) && __privateGet(this, _partner).supportedWalletTypes.length === 0;
549
+ return !!((_a = this.partner) == null ? void 0 : _a.supportedWalletTypes) && this.partner.supportedWalletTypes.length === 0;
455
550
  }
456
551
  get supportedWalletTypes() {
457
552
  var _a, _b;
458
- return (_b = (_a = __privateGet(this, _partner)) == null ? void 0 : _a.supportedWalletTypes) != null ? _b : [];
553
+ return (_b = (_a = this.partner) == null ? void 0 : _a.supportedWalletTypes) != null ? _b : [];
459
554
  }
460
555
  get cosmosPrefix() {
461
556
  var _a;
462
- return (_a = __privateGet(this, _partner)) == null ? void 0 : _a.cosmosPrefix;
557
+ return (_a = this.partner) == null ? void 0 : _a.cosmosPrefix;
558
+ }
559
+ get supportedAccountLinks() {
560
+ var _a, _b;
561
+ return (_b = (_a = this.partner) == null ? void 0 : _a.supportedAccountLinks) != null ? _b : [...LINKED_ACCOUNT_TYPES];
463
562
  }
464
563
  get isWalletTypeEnabled() {
465
564
  var _a;
466
- return (((_a = __privateGet(this, _partner)) == null ? void 0 : _a.supportedWalletTypes) || []).reduce((acc, { type }) => {
565
+ return (((_a = this.partner) == null ? void 0 : _a.supportedWalletTypes) || []).reduce((acc, { type }) => {
467
566
  return __spreadProps(__spreadValues({}, acc), { [type]: true });
468
567
  }, {});
469
568
  }
@@ -497,6 +596,12 @@ const _ParaCore = class _ParaCore {
497
596
  if (typeof window === "undefined") return false;
498
597
  return !!((_a = window.location) == null ? void 0 : _a.host) && getPortalBaseURL(envOverride ? { env: envOverride } : this.ctx).includes(window.location.host);
499
598
  }
599
+ isRecoveryPortal(envOverride) {
600
+ var _a, _b;
601
+ if (typeof window === "undefined") return false;
602
+ const normalizedUrl = (_b = (_a = window.location) == null ? void 0 : _a.host) == null ? void 0 : _b.replace("getpara", "usecapsule");
603
+ return !!normalizedUrl && getPortalBaseURL(envOverride ? { env: envOverride } : this.ctx).includes(normalizedUrl);
604
+ }
500
605
  isParaConnect() {
501
606
  var _a;
502
607
  if (typeof window === "undefined") return false;
@@ -512,7 +617,7 @@ const _ParaCore = class _ParaCore {
512
617
  }
513
618
  isWalletSupported(wallet) {
514
619
  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);
620
+ return !((_a = this.partner) == null ? void 0 : _a.supportedWalletTypes) || isWalletSupported((_b = this.partner.supportedWalletTypes.map(({ type }) => type)) != null ? _b : [], wallet);
516
621
  }
517
622
  isWalletOwned(wallet) {
518
623
  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 +643,12 @@ const _ParaCore = class _ParaCore {
538
643
  } else {
539
644
  const wallet = this.wallets[walletId];
540
645
  const [isUnclaimed, isOwned] = [this.isPregenWalletUnclaimed(wallet), this.isWalletOwned(wallet)];
541
- if (forbidPregen && isUnclaimed) {
646
+ if (forbidPregen && isUnclaimed && wallet.pregenIdentifierType !== "GUEST_ID") {
542
647
  error = `pre-generated wallet with id ${wallet == null ? void 0 : wallet.id} cannot be selected`;
543
648
  } else if (!isOwned && !isUnclaimed) {
544
649
  error = `wallet with id ${wallet == null ? void 0 : wallet.id} is not owned by the current user`;
545
650
  } 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(", ")}`;
651
+ 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
652
  } else if (types && (!getEquivalentTypes(types).includes(wallet == null ? void 0 : wallet.type) || isOwned && !types.some((type) => {
548
653
  var _a2, _b2;
549
654
  return (_b2 = (_a2 = this.currentWalletIds) == null ? void 0 : _a2[type]) == null ? void 0 : _b2.includes(walletId);
@@ -574,7 +679,7 @@ const _ParaCore = class _ParaCore {
574
679
  if (this.externalWallets[walletId]) {
575
680
  const wallet2 = this.externalWallets[walletId];
576
681
  return options.truncate ? truncateAddress(wallet2.address, wallet2.type, {
577
- prefix: (_a = __privateGet(this, _partner)) == null ? void 0 : _a.cosmosPrefix,
682
+ prefix: (_a = this.partner) == null ? void 0 : _a.cosmosPrefix,
578
683
  targetLength: options.targetLength
579
684
  }) : wallet2.address;
580
685
  }
@@ -586,7 +691,7 @@ const _ParaCore = class _ParaCore {
586
691
  let prefix;
587
692
  switch (wallet.type) {
588
693
  case "COSMOS":
589
- prefix = (_d = (_c = options.cosmosPrefix) != null ? _c : (_b = __privateGet(this, _partner)) == null ? void 0 : _b.cosmosPrefix) != null ? _d : "cosmos";
694
+ prefix = (_d = (_c = options.cosmosPrefix) != null ? _c : (_b = this.partner) == null ? void 0 : _b.cosmosPrefix) != null ? _d : "cosmos";
590
695
  str = getCosmosAddress(wallet.publicKey, prefix);
591
696
  break;
592
697
  default:
@@ -620,29 +725,40 @@ const _ParaCore = class _ParaCore {
620
725
  constructPortalUrl(_0) {
621
726
  return __async(this, arguments, function* (type, opts = {}) {
622
727
  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"
728
+ const [isCreate, isLogin, isOnRamp, isOAuth, isOAuthCallback, isTelegramLogin, isFarcasterLogin] = [
729
+ ["createAuth", "createPassword", "createPIN"].includes(type),
730
+ ["loginAuth", "loginPassword", "loginPIN", "loginOTP"].includes(type),
731
+ type === "onRamp",
732
+ type === "oAuth",
733
+ type === "oAuthCallback",
734
+ ["telegramLogin", "telegramLoginVerify"].includes(type),
735
+ type === "loginFarcaster"
627
736
  ];
737
+ if (isOAuth && !opts.oAuthMethod) {
738
+ throw new Error("oAuthMethod is required for oAuth portal URLs");
739
+ }
628
740
  if (isCreate || isLogin) {
629
741
  this.assertIsAuthSet();
630
742
  }
631
743
  let sessionId = opts.sessionId;
632
- if ((isLogin || isOnRamp) && !sessionId) {
744
+ if ((isLogin || isOnRamp || isTelegramLogin || isFarcasterLogin) && !sessionId) {
633
745
  const session = yield this.touchSession(true);
634
746
  sessionId = session.sessionId;
635
747
  }
636
748
  if (!this.loginEncryptionKeyPair) {
637
749
  yield this.setLoginEncryptionKeyPair();
638
750
  }
639
- const base = type === "onRamp" ? getPortalBaseURL(this.ctx) : yield this.getPortalURL();
751
+ const base = type === "onRamp" || isTelegramLogin ? getPortalBaseURL(this.ctx, isTelegramLogin) : yield this.getPortalURL();
640
752
  let path;
641
753
  switch (type) {
642
754
  case "createPassword": {
643
755
  path = `/web/users/${this.userId}/passwords/${opts.pathId}`;
644
756
  break;
645
757
  }
758
+ case "createPIN": {
759
+ path = `/web/users/${this.userId}/pin/${opts.pathId}`;
760
+ break;
761
+ }
646
762
  case "createAuth": {
647
763
  path = `/web/users/${this.userId}/biometrics/${opts.pathId}`;
648
764
  break;
@@ -655,32 +771,69 @@ const _ParaCore = class _ParaCore {
655
771
  path = "/web/biometrics/login";
656
772
  break;
657
773
  }
774
+ case "loginPIN": {
775
+ path = "/web/pin/login";
776
+ break;
777
+ }
658
778
  case "txReview": {
659
779
  path = `/web/users/${this.userId}/transaction-review/${opts.pathId}`;
660
780
  break;
661
781
  }
662
782
  case "onRamp": {
663
- path = `/web/users/${this.userId}/on-ramp-transaction/${opts.pathId}`;
783
+ path = `/web/users/${this.userId}/on-ramp-transaction/v2/${opts.pathId}`;
784
+ break;
785
+ }
786
+ case "telegramLoginVerify": {
787
+ path = `/auth/telegram/verify`;
788
+ break;
789
+ }
790
+ case "telegramLogin": {
791
+ path = `/auth/telegram`;
792
+ break;
793
+ }
794
+ case "oAuth": {
795
+ path = `/auth/${opts.oAuthMethod.toLowerCase()}`;
796
+ break;
797
+ }
798
+ case "oAuthCallback": {
799
+ path = `/auth/${opts.oAuthMethod.toLowerCase()}/callback`;
800
+ break;
801
+ }
802
+ case "loginOTP": {
803
+ path = "/auth/otp";
804
+ break;
805
+ }
806
+ case "loginFarcaster": {
807
+ path = "/auth/farcaster";
664
808
  break;
665
809
  }
666
810
  default: {
667
811
  throw new Error(`invalid URL type ${type}`);
668
812
  }
669
813
  }
670
- const partner = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
814
+ let partner = void 0;
815
+ try {
816
+ partner = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
817
+ } catch (e) {
818
+ if (this.isPartnerOptional) {
819
+ partner = void 0;
820
+ } else {
821
+ throw e;
822
+ }
823
+ }
671
824
  const thisDevice = (_a = opts.thisDevice) != null ? _a : {
672
825
  encryptionKey: getPublicKeyHex(this.loginEncryptionKeyPair),
673
826
  sessionId
674
827
  };
675
- const params = __spreadValues(__spreadValues(__spreadValues(__spreadValues({
828
+ const params = __spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues({
676
829
  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),
830
+ partnerId: partner == null ? void 0 : partner.id,
831
+ portalFont: ((_b = opts.portalTheme) == null ? void 0 : _b.font) || ((_c = this.portalTheme) == null ? void 0 : _c.font) || (partner == null ? void 0 : partner.font),
679
832
  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),
833
+ portalThemeMode: ((_f = opts.portalTheme) == null ? void 0 : _f.mode) || ((_g = this.portalTheme) == null ? void 0 : _g.mode) || (partner == null ? void 0 : partner.themeMode),
834
+ portalAccentColor: ((_h = opts.portalTheme) == null ? void 0 : _h.accentColor) || ((_i = this.portalTheme) == null ? void 0 : _i.accentColor) || (partner == null ? void 0 : partner.accentColor),
835
+ portalForegroundColor: ((_j = opts.portalTheme) == null ? void 0 : _j.foregroundColor) || ((_k = this.portalTheme) == null ? void 0 : _k.foregroundColor) || (partner == null ? void 0 : partner.foregroundColor),
836
+ portalBackgroundColor: ((_l = opts.portalTheme) == null ? void 0 : _l.backgroundColor) || ((_m = this.portalTheme) == null ? void 0 : _m.backgroundColor) || (partner == null ? void 0 : partner.backgroundColor) || this.portalBackgroundColor,
684
837
  portalPrimaryButtonColor: this.portalPrimaryButtonColor,
685
838
  portalTextColor: this.portalTextColor,
686
839
  portalPrimaryButtonTextColor: this.portalPrimaryButtonTextColor,
@@ -690,7 +843,7 @@ const _ParaCore = class _ParaCore {
690
843
  }, isPhone(this.authInfo.auth) ? splitPhoneNumber(this.authInfo.auth.phone) : this.authInfo.auth), {
691
844
  pfpUrl: this.authInfo.pfpUrl,
692
845
  displayName: this.authInfo.displayName
693
- }) : {}), isOnRamp ? { sessionId } : {}), isLogin ? __spreadProps(__spreadValues({
846
+ }) : {}), isOnRamp ? { origin: typeof window !== "undefined" ? window.location.origin : void 0, email: this.email } : {}), isLogin || isOAuth || isOAuthCallback || isTelegramLogin || isFarcasterLogin ? __spreadProps(__spreadValues({
694
847
  sessionId: thisDevice.sessionId,
695
848
  encryptionKey: thisDevice.encryptionKey
696
849
  }, opts.newDevice ? {
@@ -698,7 +851,9 @@ const _ParaCore = class _ParaCore {
698
851
  newDeviceEncryptionKey: opts.newDevice.encryptionKey
699
852
  } : {}), {
700
853
  pregenIds: JSON.stringify(this.pregenIds)
701
- }) : {}), opts.params || {});
854
+ }) : {}), isOAuth || isOAuthCallback || isFarcasterLogin ? {
855
+ appScheme: opts.appScheme
856
+ } : {}), isTelegramLogin ? { isEmbed: "true" } : {}), opts.params || {});
702
857
  const url = constructUrl({ base, path, params });
703
858
  if (opts.shorten) {
704
859
  return shortenUrl(this.ctx, url);
@@ -706,12 +861,72 @@ const _ParaCore = class _ParaCore {
706
861
  return url;
707
862
  });
708
863
  }
864
+ static resolveEnvironment(env, apiKey) {
865
+ var _a;
866
+ if (!apiKey) {
867
+ throw new Error("A Para API key is required.");
868
+ }
869
+ if (apiKey.includes("_")) {
870
+ const validEnvironmentPrefixes = Object.values(Environment);
871
+ const envPrefix = (_a = apiKey.split("_")[0]) == null ? void 0 : _a.toUpperCase();
872
+ const hasValidPrefix = validEnvironmentPrefixes.some((envValue) => envValue === envPrefix);
873
+ if (!hasValidPrefix) {
874
+ throw new Error(`Invalid API key environment prefix.`);
875
+ }
876
+ return envPrefix;
877
+ }
878
+ if (!env) {
879
+ throw new Error("Environment parameter is required.");
880
+ }
881
+ return env;
882
+ }
709
883
  touchSession(regenerate = false) {
710
884
  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);
885
+ var _a, _b, _c, _d, _e;
886
+ if (!this.isWorkerInitialized) {
887
+ this.initializeWorker();
888
+ }
889
+ if (!this.isReady) {
890
+ yield this.ready();
891
+ }
892
+ let session;
893
+ try {
894
+ session = yield this.ctx.client.touchSession(regenerate);
895
+ } catch (error) {
896
+ this.handleTouchSessionError(error);
897
+ throw error;
898
+ }
899
+ 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) {
900
+ if (!session.partnerId && !this.isRecoveryPortal()) {
901
+ this.displayModalError(
902
+ `Invalid API Key. Please ensure you have a valid API key for the current environment: ${(_d = this.ctx.env) == null ? void 0 : _d.toUpperCase()}.`
903
+ );
904
+ console.error(`
905
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
906
+ \u{1F6A8} PARA SDK CONFIGURATION ERROR \u{1F6A8}
907
+
908
+ INVALID API KEY FOR CONFIGURED ENVIRONMENT
909
+
910
+ Your API key does not match the configured environment. This usually means:
911
+
912
+ 1. You're using a production API key with a development environment
913
+ 2. You're using a development API key with a production environment
914
+ 3. Your API key is invalid or has been regenerated
915
+
916
+ SOLUTION:
917
+ \u2022 Verify your API key at: https://developer.getpara.com
918
+ \u2022 If your API key doesn't contain an environment prefix, ensure your API key is the correct key for your target environment
919
+
920
+ Current Environment: ${this.ctx.env}
921
+ API Key Prefix: ${((_e = this.ctx.apiKey) == null ? void 0 : _e.split("_")[0].toUpperCase()) || "None"}
922
+
923
+ Need help? Visit: https://docs.getpara.com or contact support
924
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
925
+ `);
926
+ throw new Error("Invalid API Key.");
927
+ } else {
928
+ yield __privateMethod(this, _ParaCore_instances, getPartner_fn).call(this, session.partnerId);
929
+ }
715
930
  }
716
931
  return session;
717
932
  });
@@ -810,8 +1025,35 @@ const _ParaCore = class _ParaCore {
810
1025
  return __privateGet(this, _authInfo);
811
1026
  });
812
1027
  }
813
- assertUserId() {
814
- if (!this.userId) {
1028
+ /**
1029
+ * Display an error message in the modal (if available)
1030
+ * @internal
1031
+ */
1032
+ displayModalError(error) {
1033
+ if (this.ctx.env !== Environment.PROD) {
1034
+ this.setModalError(error);
1035
+ }
1036
+ }
1037
+ /**
1038
+ * Handle specific touchSession errors with user-friendly messages
1039
+ * @private
1040
+ */
1041
+ handleTouchSessionError(error) {
1042
+ const errorStr = String(error);
1043
+ const errorMessage = error instanceof Error ? error.message : "";
1044
+ if (errorStr.includes("blocked by CORS policy") && errorStr.includes("Access-Control-Allow-Origin")) {
1045
+ this.displayModalError("Request rate limit reached. Please wait a couple of minutes and try again.");
1046
+ return;
1047
+ }
1048
+ if (error.status === 403 && errorMessage.includes("origin not authorized")) {
1049
+ this.displayModalError(
1050
+ "The current origin is not allowed. Update your allowed origins in the Para developer portal to allow the current origin."
1051
+ );
1052
+ return;
1053
+ }
1054
+ }
1055
+ assertUserId({ allowGuestMode = false } = {}) {
1056
+ if (!this.userId || !allowGuestMode && this.isGuestMode) {
815
1057
  throw new Error("no userId is set");
816
1058
  }
817
1059
  return this.userId;
@@ -867,19 +1109,75 @@ const _ParaCore = class _ParaCore {
867
1109
  * @param externalAddress - External wallet address to set.
868
1110
  * @param externalType - Type of external wallet to set.
869
1111
  */
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,
1112
+ setExternalWallet(externalWallet) {
1113
+ return __async(this, null, function* () {
1114
+ const { id: partnerId, supportedWalletTypes } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
1115
+ this.externalWallets = (Array.isArray(externalWallet) ? externalWallet : [externalWallet]).reduce(
1116
+ (acc, {
1117
+ partnerId: wPartnerId,
1118
+ address,
876
1119
  type,
877
- name: provider,
878
- isExternal: true,
879
- isExternalWithParaAuth: withFullParaAuth,
880
- signer: ""
1120
+ provider,
1121
+ providerId,
1122
+ addressBech32,
1123
+ withFullParaAuth,
1124
+ isConnectionOnly,
1125
+ withVerification
1126
+ }) => {
1127
+ if (partnerId === wPartnerId && supportedWalletTypes.some(({ type: supportedType }) => supportedType === type)) {
1128
+ return __spreadProps(__spreadValues({}, acc), {
1129
+ [address]: {
1130
+ id: address,
1131
+ partnerId,
1132
+ address: addressBech32 != null ? addressBech32 : address,
1133
+ type,
1134
+ name: provider,
1135
+ isExternal: true,
1136
+ isExternalWithParaAuth: withFullParaAuth,
1137
+ externalProviderId: providerId,
1138
+ signer: "",
1139
+ isExternalConnectionOnly: isConnectionOnly,
1140
+ isExternalWithVerification: withVerification
1141
+ }
1142
+ });
1143
+ }
1144
+ return acc;
1145
+ },
1146
+ {}
1147
+ ), this.setExternalWallets(this.externalWallets);
1148
+ dispatchEvent(ParaEvent.EXTERNAL_WALLET_CHANGE_EVENT, null);
1149
+ });
1150
+ }
1151
+ addExternalWallets(externalWallets) {
1152
+ return __async(this, null, function* () {
1153
+ const { id: partnerId, supportedWalletTypes } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
1154
+ this.externalWallets = __spreadValues(__spreadValues({}, Object.entries(this.externalWallets).reduce((acc, [address, wallet]) => {
1155
+ if (partnerId === wallet.partnerId && supportedWalletTypes.some(({ type }) => type === wallet.type)) {
1156
+ return __spreadProps(__spreadValues({}, acc), {
1157
+ [address]: wallet
1158
+ });
881
1159
  }
882
- };
1160
+ return acc;
1161
+ }, {})), externalWallets.reduce(
1162
+ (acc, { address, type, provider, providerId, addressBech32, withFullParaAuth, isConnectionOnly, withVerification }) => {
1163
+ return __spreadProps(__spreadValues({}, acc), {
1164
+ [address]: {
1165
+ id: address,
1166
+ partnerId,
1167
+ address: addressBech32 != null ? addressBech32 : address,
1168
+ type,
1169
+ name: provider,
1170
+ isExternal: true,
1171
+ isExternalWithParaAuth: withFullParaAuth,
1172
+ externalProviderId: providerId,
1173
+ signer: "",
1174
+ isExternalConnectionOnly: isConnectionOnly,
1175
+ isExternalWithVerification: withVerification
1176
+ }
1177
+ });
1178
+ },
1179
+ {}
1180
+ ));
883
1181
  this.setExternalWallets(this.externalWallets);
884
1182
  dispatchEvent(ParaEvent.EXTERNAL_WALLET_CHANGE_EVENT, null);
885
1183
  });
@@ -910,12 +1208,16 @@ const _ParaCore = class _ParaCore {
910
1208
  }
911
1209
  /**
912
1210
  * Sets the external wallets associated with the `ParaCore` instance.
913
- * @param externalWallets - External wallets to set.
1211
+ * @param externalWallets - External wallets to set, or a function that modifies the current wallets.
914
1212
  */
915
1213
  setExternalWallets(externalWallets) {
916
1214
  return __async(this, null, function* () {
917
- this.externalWallets = externalWallets;
918
- yield this.localStorageSetItem(constants.LOCAL_STORAGE_EXTERNAL_WALLETS, JSON.stringify(externalWallets));
1215
+ if (typeof externalWallets === "function") {
1216
+ this.externalWallets = externalWallets(this.externalWallets);
1217
+ } else {
1218
+ this.externalWallets = externalWallets;
1219
+ }
1220
+ yield this.localStorageSetItem(constants.LOCAL_STORAGE_EXTERNAL_WALLETS, JSON.stringify(this.externalWallets));
919
1221
  });
920
1222
  }
921
1223
  /**
@@ -991,6 +1293,7 @@ const _ParaCore = class _ParaCore {
991
1293
  /**
992
1294
  * Fetches the most recent OAuth account metadata for the signed-in user.
993
1295
  * 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.
1296
+ * @deprecated use `para.getLinkedAccounts({ withMetadata: true })` instead.
994
1297
  * @returns {Promise<AccountMetadata>} the user's account metadata.
995
1298
  */
996
1299
  getAccountMetadata() {
@@ -1136,8 +1439,15 @@ const _ParaCore = class _ParaCore {
1136
1439
  }
1137
1440
  getPartnerURL() {
1138
1441
  return __async(this, null, function* () {
1139
- const { portalUrl } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
1140
- return portalUrl;
1442
+ try {
1443
+ const { portalUrl } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
1444
+ return portalUrl;
1445
+ } catch (e) {
1446
+ if (this.isPartnerOptional) {
1447
+ return void 0;
1448
+ }
1449
+ throw e;
1450
+ }
1141
1451
  });
1142
1452
  }
1143
1453
  /**
@@ -1223,15 +1533,27 @@ const _ParaCore = class _ParaCore {
1223
1533
  } = _b, urlOptions = __objRest(_b, [
1224
1534
  "externalWallet"
1225
1535
  ]);
1226
- if (this.externalWalletConnectionOnly) {
1227
- externalWallet.withFullParaAuth = false;
1228
- yield this.setExternalWallet(externalWallet);
1536
+ const externalWallets = Array.isArray(externalWallet) ? externalWallet : [externalWallet];
1537
+ if (this.externalWalletConnectionOnly || externalWallets.every((wallet) => wallet.isConnectionOnly)) {
1538
+ yield this.addExternalWallets(
1539
+ externalWallets.map((wallet) => __spreadProps(__spreadValues({}, wallet), {
1540
+ withFullParaAuth: false
1541
+ }))
1542
+ );
1229
1543
  return Promise.resolve({
1230
1544
  userId: constants.EXTERNAL_WALLET_CONNECTION_ONLY_USER_ID
1231
1545
  });
1232
1546
  }
1547
+ if (Array.isArray(externalWallet)) {
1548
+ throw new Error(
1549
+ "Cannot authenticate multiple external wallets at once. To connect multiple wallets at once, use CONNECTION_ONLY mode."
1550
+ );
1551
+ }
1233
1552
  this.requireApiKey();
1234
1553
  const serverAuthState = yield this.ctx.client.loginExternalWallet({ externalWallet });
1554
+ if (!externalWallet.withFullParaAuth && externalWallet.withVerification) {
1555
+ yield this.touchSession(true);
1556
+ }
1235
1557
  return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
1236
1558
  });
1237
1559
  }
@@ -1248,36 +1570,89 @@ const _ParaCore = class _ParaCore {
1248
1570
  "cosmosPublicKeyHex",
1249
1571
  "cosmosSigner"
1250
1572
  ]);
1573
+ var _a;
1251
1574
  const serverAuthState = yield this.ctx.client.verifyExternalWallet(this.userId, {
1252
1575
  externalWallet,
1253
1576
  signedMessage,
1254
1577
  cosmosPublicKeyHex,
1255
1578
  cosmosSigner
1256
1579
  });
1580
+ if (serverAuthState.stage === "login" && ((_a = serverAuthState.loginAuthMethods) == null ? void 0 : _a.includes(AuthMethod.PIN))) {
1581
+ const { sessionLookupId } = yield this.touchSession();
1582
+ return __privateMethod(this, _ParaCore_instances, prepareLoginState_fn).call(this, serverAuthState, __spreadProps(__spreadValues({}, urlOptions), { sessionLookupId }));
1583
+ }
1257
1584
  return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
1258
1585
  });
1259
1586
  }
1587
+ verifyExternalWalletLink(opts) {
1588
+ return __async(this, null, function* () {
1589
+ const accountLinkInProgress = yield __privateMethod(this, _ParaCore_instances, assertIsLinkingAccount_fn).call(this, ["EXTERNAL_WALLET"]);
1590
+ if (!accountLinkInProgress.externalWallet) {
1591
+ throw new Error("no external wallet account link in progress");
1592
+ }
1593
+ const accounts = yield this.verifyLink(__spreadValues({
1594
+ accountLinkInProgress,
1595
+ externalWallet: accountLinkInProgress.externalWallet
1596
+ }, opts));
1597
+ return accounts;
1598
+ });
1599
+ }
1600
+ // TELEGRAM
1260
1601
  /**
1261
1602
  * Validates the response received from an attempted Telegram login for authenticity, then
1262
1603
  * creates or retrieves the corresponding Para user and prepares the Para instance to sign in with that user.
1263
1604
  * @param authResponse - the response JSON object received from the Telegram widget.
1264
1605
  * @returns `{ isValid: boolean; telegramUserId?: string; userId?: string; isNewUser?: boolean; supportedAuthMethods?: AuthMethod[]; biometricHints?: BiometricLocationHint[] }`
1265
1606
  */
1266
- verifyTelegram(_e) {
1607
+ verifyTelegramProcess(_e) {
1267
1608
  return __async(this, null, function* () {
1268
1609
  var _f = _e, {
1269
- telegramAuthResponse
1610
+ serverAuthState: optsServerAuthState,
1611
+ telegramAuthResponse,
1612
+ isLinkAccount
1270
1613
  } = _f, urlOptions = __objRest(_f, [
1271
- "telegramAuthResponse"
1614
+ "serverAuthState",
1615
+ "telegramAuthResponse",
1616
+ "isLinkAccount"
1272
1617
  ]);
1273
1618
  try {
1274
- const serverAuthState = yield this.ctx.client.verifyTelegram(telegramAuthResponse);
1275
- return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
1619
+ switch (isLinkAccount) {
1620
+ case false: {
1621
+ if (!optsServerAuthState && !telegramAuthResponse) {
1622
+ throw new Error("one of serverAuthState or telegramAuthResponse are required for verifying telegram");
1623
+ }
1624
+ const serverAuthState = optsServerAuthState != null ? optsServerAuthState : yield this.ctx.client.verifyTelegram({ authObject: telegramAuthResponse });
1625
+ const { sessionLookupId } = yield this.touchSession();
1626
+ return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, __spreadProps(__spreadValues({}, urlOptions), { sessionLookupId }));
1627
+ }
1628
+ case true: {
1629
+ if (!telegramAuthResponse) {
1630
+ throw new Error("telegramAuthResponse is required for verifying telegram link");
1631
+ }
1632
+ const accountLinkInProgress = yield __privateMethod(this, _ParaCore_instances, assertIsLinkingAccountOrStart_fn).call(this, "TELEGRAM");
1633
+ const accounts = yield this.verifyLink({
1634
+ accountLinkInProgress,
1635
+ telegramAuthResponse
1636
+ });
1637
+ return accounts;
1638
+ }
1639
+ }
1276
1640
  } catch (e) {
1277
- throw new Error(e.message);
1641
+ const errorMessage = e instanceof Error ? e.message : e ? String(e) : "Unknown error occurred";
1642
+ throw new Error(errorMessage);
1278
1643
  }
1279
1644
  });
1280
1645
  }
1646
+ verifyTelegram(opts) {
1647
+ return __async(this, null, function* () {
1648
+ return yield this.verifyTelegramProcess(__spreadProps(__spreadValues({}, opts), { isLinkAccount: false }));
1649
+ });
1650
+ }
1651
+ verifyTelegramLink(opts) {
1652
+ return __async(this, null, function* () {
1653
+ return yield this.verifyTelegramProcess(__spreadProps(__spreadValues({}, opts), { isLinkAccount: true }));
1654
+ });
1655
+ }
1281
1656
  /**
1282
1657
  * Performs 2FA verification.
1283
1658
  * @param {Object} opts the options object
@@ -1321,10 +1696,35 @@ const _ParaCore = class _ParaCore {
1321
1696
  /**
1322
1697
  * Resend a verification email for the current user.
1323
1698
  */
1324
- resendVerificationCode() {
1325
- return __async(this, null, function* () {
1699
+ resendVerificationCode(_0) {
1700
+ return __async(this, arguments, function* ({
1701
+ type: reason = "SIGNUP"
1702
+ }) {
1703
+ let type, linkedAccountId;
1704
+ switch (reason) {
1705
+ case "SIGNUP":
1706
+ case "LOGIN":
1707
+ {
1708
+ const authInfo = this.assertIsAuthSet(["email", "phone"]);
1709
+ type = authInfo.authType.toUpperCase();
1710
+ }
1711
+ break;
1712
+ case "LINK_ACCOUNT":
1713
+ {
1714
+ const accountLinkInProgress = __privateMethod(this, _ParaCore_instances, assertIsLinkingAccount_fn).call(this, ["EMAIL", "PHONE"]);
1715
+ linkedAccountId = accountLinkInProgress.id;
1716
+ type = accountLinkInProgress.type;
1717
+ }
1718
+ break;
1719
+ }
1720
+ const userId = this.assertUserId({ allowGuestMode: true });
1721
+ if (type !== "EMAIL" && type !== "PHONE") {
1722
+ throw new Error("invalid auth type for verification code");
1723
+ }
1326
1724
  yield this.ctx.client.resendVerificationCode(__spreadValues({
1327
- userId: this.userId
1725
+ userId,
1726
+ type,
1727
+ linkedAccountId
1328
1728
  }, this.getVerificationEmailProps()));
1329
1729
  });
1330
1730
  }
@@ -1337,7 +1737,14 @@ const _ParaCore = class _ParaCore {
1337
1737
  if (this.externalWalletConnectionType === "CONNECTION_ONLY") {
1338
1738
  return true;
1339
1739
  }
1340
- const { isAuthenticated } = yield this.touchSession();
1740
+ const { isAuthenticated, verifiedExternalWalletAddresses } = yield this.touchSession();
1741
+ if (this.externalWalletConnectionType === "VERIFICATION") {
1742
+ if (!verifiedExternalWalletAddresses) {
1743
+ return false;
1744
+ }
1745
+ const externalAddresses = Object.values(this.externalWallets).map((w) => w.id);
1746
+ return externalAddresses.every((address) => verifiedExternalWalletAddresses.includes(address));
1747
+ }
1341
1748
  return !!isAuthenticated;
1342
1749
  });
1343
1750
  }
@@ -1348,12 +1755,18 @@ const _ParaCore = class _ParaCore {
1348
1755
  isFullyLoggedIn() {
1349
1756
  return __async(this, null, function* () {
1350
1757
  if (this.externalWalletConnectionType === "CONNECTION_ONLY") {
1758
+ if (!this.isReady) {
1759
+ yield this.ready();
1760
+ }
1351
1761
  return true;
1352
1762
  }
1353
1763
  if (this.isGuestMode) {
1354
1764
  return true;
1355
1765
  }
1356
1766
  const isSessionActive = yield this.isSessionActive();
1767
+ if (this.externalWalletConnectionType === "VERIFICATION") {
1768
+ return isSessionActive;
1769
+ }
1357
1770
  return isSessionActive && (this.isNoWalletConfig || this.currentWalletIdsArray.length > 0 && this.currentWalletIdsArray.reduce((acc, [id]) => acc && !!this.wallets[id], true));
1358
1771
  });
1359
1772
  }
@@ -1361,10 +1774,13 @@ const _ParaCore = class _ParaCore {
1361
1774
  return __privateGet(this, _ParaCore_instances, guestWalletIdsArray_get).length > 0 && Object.values(this.wallets).every(
1362
1775
  ({ userId, partnerId }) => {
1363
1776
  var _a;
1364
- return partnerId === ((_a = __privateGet(this, _partner)) == null ? void 0 : _a.id) && (!userId || userId !== this.userId);
1777
+ return partnerId === ((_a = this.partner) == null ? void 0 : _a.id) && (!userId || userId !== this.userId);
1365
1778
  }
1366
1779
  );
1367
1780
  }
1781
+ /**
1782
+ * Get the auth methods available to an existing user
1783
+ */
1368
1784
  supportedAuthMethods(auth) {
1369
1785
  return __async(this, null, function* () {
1370
1786
  const { supportedAuthMethods } = yield this.ctx.client.getSupportedAuthMethods(auth);
@@ -1458,36 +1874,47 @@ const _ParaCore = class _ParaCore {
1458
1874
  });
1459
1875
  }
1460
1876
  /**
1461
- * Initiates a Farcaster login attempt and return the URI for the user to connect.
1877
+ * Initiates a Farcaster login attempt and returns the URL for the user to connect.
1462
1878
  * You can create a QR code with this URI that works with Farcaster's mobile app.
1463
1879
  * @return {string} the Farcaster connect URI
1464
1880
  */
1465
1881
  getFarcasterConnectUri() {
1466
- return __async(this, null, function* () {
1467
- const {
1468
- data: { connect_uri: connectUri }
1469
- } = yield this.ctx.client.initializeFarcasterLogin();
1882
+ return __async(this, arguments, function* ({ appScheme } = {}) {
1883
+ const { connect_uri: connectUri } = yield this.ctx.client.initializeFarcasterLogin({ appScheme });
1470
1884
  return connectUri;
1471
1885
  });
1472
1886
  }
1887
+ // FARCASTER
1473
1888
  /**
1474
1889
  * Awaits the response from a user's attempt to log in with Farcaster.
1475
1890
  * If successful, this returns the user's Farcaster username and profile picture and indicates whether the user already exists.
1476
1891
  * @return {Object} `{userExists: boolean; username: string; pfpUrl?: string | null }` - the user's information and whether the user already exists.
1477
1892
  */
1478
- verifyFarcaster(_g) {
1893
+ verifyFarcasterProcess(_g) {
1479
1894
  return __async(this, null, function* () {
1480
1895
  var _h = _g, {
1481
1896
  isCanceled = () => false,
1482
1897
  onConnectUri,
1483
1898
  onCancel,
1484
- onPoll
1899
+ onPoll,
1900
+ isLinkAccount,
1901
+ serverAuthState: optsServerAuthState
1485
1902
  } = _h, urlOptions = __objRest(_h, [
1486
1903
  "isCanceled",
1487
1904
  "onConnectUri",
1488
1905
  "onCancel",
1489
- "onPoll"
1906
+ "onPoll",
1907
+ "isLinkAccount",
1908
+ "serverAuthState"
1490
1909
  ]);
1910
+ if (optsServerAuthState) {
1911
+ const authState = yield __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, optsServerAuthState, urlOptions);
1912
+ return authState;
1913
+ }
1914
+ let accountLinkInProgress;
1915
+ if (isLinkAccount) {
1916
+ accountLinkInProgress = yield __privateMethod(this, _ParaCore_instances, assertIsLinkingAccountOrStart_fn).call(this, "FARCASTER");
1917
+ }
1491
1918
  if (onConnectUri) {
1492
1919
  const connectUri = yield this.getFarcasterConnectUri();
1493
1920
  onConnectUri(connectUri);
@@ -1499,53 +1926,55 @@ const _ParaCore = class _ParaCore {
1499
1926
  try {
1500
1927
  if (isCanceled() || Date.now() - startedAt > constants.POLLING_TIMEOUT_MS) {
1501
1928
  onCancel == null ? void 0 : onCancel();
1502
- return reject("canceled");
1929
+ return reject("CANCELED");
1503
1930
  }
1504
1931
  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);
1932
+ switch (isLinkAccount) {
1933
+ case false:
1934
+ {
1935
+ const serverAuthState = yield this.ctx.client.getFarcasterAuthStatus();
1936
+ if (isServerAuthState(serverAuthState)) {
1937
+ const authState = yield __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
1938
+ return resolve(authState);
1939
+ }
1940
+ }
1941
+ break;
1942
+ case true: {
1943
+ const result = yield this.verifyLink({
1944
+ accountLinkInProgress
1945
+ });
1946
+ if ("isConflict" in result) {
1947
+ throw new Error(AccountLinkError.Conflict);
1948
+ }
1949
+ return resolve(result);
1950
+ }
1509
1951
  }
1510
1952
  onPoll == null ? void 0 : onPoll();
1511
1953
  } catch (e) {
1512
- console.error(e);
1513
- return reject(e);
1954
+ if (!isLinkAccount || e.message === AccountLinkError.Conflict) {
1955
+ return reject(e.message);
1956
+ }
1514
1957
  }
1515
1958
  }
1516
1959
  }))();
1517
1960
  });
1518
1961
  });
1519
1962
  }
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) {
1963
+ verifyFarcaster(opts) {
1964
+ return __async(this, null, function* () {
1965
+ return yield this.verifyFarcasterProcess(__spreadProps(__spreadValues({}, opts), { isLinkAccount: false }));
1966
+ });
1967
+ }
1968
+ verifyFarcasterLink(opts) {
1969
+ return __async(this, null, function* () {
1970
+ return yield this.verifyFarcasterProcess(__spreadProps(__spreadValues({}, opts), { isLinkAccount: true }));
1971
+ });
1972
+ }
1973
+ getOAuthUrl(opts) {
1529
1974
  return __async(this, null, function* () {
1530
- var _j = _i, { method, deeplinkUrl } = _j, params = __objRest(_j, ["method", "deeplinkUrl"]);
1531
1975
  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
- });
1976
+ const sessionLookupId = (_a = opts.sessionLookupId) != null ? _a : yield this.prepareLogin();
1977
+ return __privateMethod(this, _ParaCore_instances, getOAuthUrl_fn).call(this, __spreadProps(__spreadValues({}, opts), { sessionLookupId }));
1549
1978
  });
1550
1979
  }
1551
1980
  /**
@@ -1556,28 +1985,54 @@ const _ParaCore = class _ParaCore {
1556
1985
  * @param {Window} [opts.popupWindow] the popup window being used for login.
1557
1986
  * @return {Object} `{ email?: string; isError?: boolean; userExists: boolean; }` the result data
1558
1987
  */
1559
- verifyOAuth(_k) {
1988
+ verifyOAuthProcess(_i) {
1560
1989
  return __async(this, null, function* () {
1561
- var _l = _k, {
1990
+ var _j = _i, {
1562
1991
  method,
1563
- deeplinkUrl,
1992
+ appScheme,
1564
1993
  isCanceled = () => false,
1565
1994
  onCancel,
1566
1995
  onPoll,
1567
- onOAuthUrl
1568
- } = _l, urlOptions = __objRest(_l, [
1996
+ onOAuthUrl,
1997
+ onOAuthPopup,
1998
+ isLinkAccount
1999
+ } = _j, urlOptions = __objRest(_j, [
1569
2000
  "method",
1570
- "deeplinkUrl",
2001
+ "appScheme",
1571
2002
  "isCanceled",
1572
2003
  "onCancel",
1573
2004
  "onPoll",
1574
- "onOAuthUrl"
2005
+ "onOAuthUrl",
2006
+ "onOAuthPopup",
2007
+ "isLinkAccount"
1575
2008
  ]);
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);
2009
+ if (onOAuthPopup) {
2010
+ try {
2011
+ this.popupWindow = yield this.platformUtils.openPopup("about:blank", { type: PopupType.OAUTH });
2012
+ } catch (error) {
2013
+ throw new Error(`Failed to open OAuth popup: ${error}`);
2014
+ }
2015
+ }
2016
+ let sessionLookupId, accountLinkInProgress;
2017
+ if (onOAuthUrl || onOAuthPopup) {
2018
+ if (isLinkAccount) {
2019
+ accountLinkInProgress = yield __privateMethod(this, _ParaCore_instances, assertIsLinkingAccountOrStart_fn).call(this, method);
2020
+ sessionLookupId = (yield this.touchSession()).sessionLookupId;
2021
+ } else {
2022
+ sessionLookupId = yield this.prepareLogin();
2023
+ }
2024
+ const oAuthUrl = yield __privateMethod(this, _ParaCore_instances, getOAuthUrl_fn).call(this, { method, appScheme, sessionLookupId, accountLinkInProgress });
2025
+ switch (true) {
2026
+ case !!onOAuthUrl: {
2027
+ onOAuthUrl(oAuthUrl);
2028
+ break;
2029
+ }
2030
+ case (!!onOAuthPopup && !!this.popupWindow): {
2031
+ this.popupWindow.location.href = oAuthUrl;
2032
+ onOAuthPopup(this.popupWindow);
2033
+ break;
2034
+ }
2035
+ }
1581
2036
  } else {
1582
2037
  ({ sessionLookupId } = yield this.touchSession());
1583
2038
  }
@@ -1588,17 +2043,29 @@ const _ParaCore = class _ParaCore {
1588
2043
  try {
1589
2044
  if (isCanceled() || Date.now() - startedAt > constants.POLLING_TIMEOUT_MS) {
1590
2045
  onCancel == null ? void 0 : onCancel();
1591
- return reject("canceled");
2046
+ return reject(AccountLinkError.Canceled);
1592
2047
  }
1593
2048
  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);
2049
+ switch (isLinkAccount) {
2050
+ case false:
2051
+ {
2052
+ const serverAuthState = yield this.ctx.client.verifyOAuth();
2053
+ if (isServerAuthState(serverAuthState)) {
2054
+ const authState = yield __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, __spreadProps(__spreadValues({}, urlOptions), { sessionLookupId }));
2055
+ return resolve(authState);
2056
+ }
2057
+ }
2058
+ break;
2059
+ case true: {
2060
+ const accounts = yield this.verifyLink({ accountLinkInProgress });
2061
+ return resolve(accounts);
2062
+ }
1598
2063
  }
1599
2064
  onPoll == null ? void 0 : onPoll();
1600
2065
  } catch (err) {
1601
- console.error(err);
2066
+ if (isLinkAccount && err.message === AccountLinkError.Conflict) {
2067
+ return reject(err.message);
2068
+ }
1602
2069
  onPoll == null ? void 0 : onPoll();
1603
2070
  }
1604
2071
  }
@@ -1606,6 +2073,16 @@ const _ParaCore = class _ParaCore {
1606
2073
  });
1607
2074
  });
1608
2075
  }
2076
+ verifyOAuth(opts) {
2077
+ return __async(this, null, function* () {
2078
+ return yield this.verifyOAuthProcess(__spreadProps(__spreadValues({}, opts), { isLinkAccount: false }));
2079
+ });
2080
+ }
2081
+ verifyOAuthLink(opts) {
2082
+ return __async(this, null, function* () {
2083
+ return yield this.verifyOAuthProcess(__spreadProps(__spreadValues({}, opts), { isLinkAccount: true }));
2084
+ });
2085
+ }
1609
2086
  /**
1610
2087
  * Waits for the session to be active and sets up the user.
1611
2088
  *
@@ -1691,7 +2168,7 @@ const _ParaCore = class _ParaCore {
1691
2168
  sessionId
1692
2169
  });
1693
2170
  if (shouldOpenPopup) {
1694
- this.platformUtils.openPopup(link);
2171
+ yield this.platformUtils.openPopup(link);
1695
2172
  }
1696
2173
  return link;
1697
2174
  });
@@ -1782,7 +2259,9 @@ const _ParaCore = class _ParaCore {
1782
2259
  userId: this.userId,
1783
2260
  walletId,
1784
2261
  userShare: userSigner,
1785
- emailProps: this.getBackupKitEmailProps()
2262
+ emailProps: this.getBackupKitEmailProps(),
2263
+ isEnclaveUser: this.isEnclaveUser,
2264
+ walletScheme: this.wallets[walletId].scheme
1786
2265
  });
1787
2266
  return recoveryShare;
1788
2267
  });
@@ -1910,7 +2389,9 @@ const _ParaCore = class _ParaCore {
1910
2389
  ignoreRedistributingBackupEncryptedShare: !redistributeBackupEncryptedShares,
1911
2390
  emailProps: this.getBackupKitEmailProps(),
1912
2391
  partnerId: newPartnerId,
1913
- protocolId
2392
+ protocolId,
2393
+ isEnclaveUser: this.isEnclaveUser,
2394
+ walletScheme: this.wallets[walletId].scheme
1914
2395
  });
1915
2396
  return { signer, recoverySecret, protocolId };
1916
2397
  });
@@ -1976,7 +2457,9 @@ const _ParaCore = class _ParaCore {
1976
2457
  userId: this.userId,
1977
2458
  walletId: wallet.id,
1978
2459
  userShare: signer,
1979
- emailProps: this.getBackupKitEmailProps()
2460
+ emailProps: this.getBackupKitEmailProps(),
2461
+ isEnclaveUser: this.isEnclaveUser,
2462
+ walletScheme: wallet.scheme
1980
2463
  });
1981
2464
  }
1982
2465
  yield this.setCurrentWalletIds(__spreadProps(__spreadValues({}, this.currentWalletIds), {
@@ -2057,7 +2540,9 @@ const _ParaCore = class _ParaCore {
2057
2540
  walletId: wallet.id,
2058
2541
  userShare: this.wallets[wallet.id].signer,
2059
2542
  emailProps: this.getBackupKitEmailProps(),
2060
- partnerId: wallet.partnerId
2543
+ partnerId: wallet.partnerId,
2544
+ isEnclaveUser: this.isEnclaveUser,
2545
+ walletScheme: wallet.scheme
2061
2546
  });
2062
2547
  if (distributeRes.length > 0) {
2063
2548
  newRecoverySecret = distributeRes;
@@ -2235,25 +2720,12 @@ const _ParaCore = class _ParaCore {
2235
2720
  });
2236
2721
  });
2237
2722
  }
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);
2723
+ getOnRampTransactionUrl(_0) {
2724
+ return __async(this, arguments, function* ({
2725
+ purchaseId
2726
+ }) {
2249
2727
  return this.constructPortalUrl("onRamp", {
2250
- pathId: purchaseId,
2251
- sessionId,
2252
- params: {
2253
- [key]: identifier,
2254
- providerKey,
2255
- currentWalletIds: JSON.stringify(this.currentWalletIds)
2256
- }
2728
+ pathId: purchaseId
2257
2729
  });
2258
2730
  });
2259
2731
  }
@@ -2278,6 +2750,7 @@ const _ParaCore = class _ParaCore {
2278
2750
  onCancel,
2279
2751
  onPoll
2280
2752
  }) {
2753
+ var _a;
2281
2754
  this.assertIsValidWalletId(walletId);
2282
2755
  const wallet = this.wallets[walletId];
2283
2756
  let signerId = this.userId;
@@ -2287,7 +2760,7 @@ const _ParaCore = class _ParaCore {
2287
2760
  let signRes = yield this.signMessageInner({ wallet, signerId, messageBase64, cosmosSignDocBase64 });
2288
2761
  let timeStart = Date.now();
2289
2762
  if (signRes.pendingTransactionId) {
2290
- this.platformUtils.openPopup(
2763
+ yield this.platformUtils.openPopup(
2291
2764
  yield this.getTransactionReviewUrl(signRes.pendingTransactionId, timeoutMs),
2292
2765
  { type: cosmosSignDocBase64 ? PopupType.SIGN_TRANSACTION_REVIEW : PopupType.SIGN_MESSAGE_REVIEW }
2293
2766
  );
@@ -2301,18 +2774,19 @@ const _ParaCore = class _ParaCore {
2301
2774
  break;
2302
2775
  }
2303
2776
  yield new Promise((resolve) => setTimeout(resolve, constants.POLLING_INTERVAL_MS));
2777
+ let pendingTransaction;
2304
2778
  try {
2305
- yield this.ctx.client.getPendingTransaction(this.userId, signRes.pendingTransactionId);
2779
+ pendingTransaction = (_a = (yield this.ctx.client.getPendingTransaction(this.userId, signRes.pendingTransactionId)).data) == null ? void 0 : _a.pendingTransaction;
2306
2780
  } catch (err) {
2307
2781
  const error = new TransactionReviewDenied();
2308
2782
  dispatchEvent(ParaEvent.SIGN_MESSAGE_EVENT, signRes, error.message);
2309
2783
  throw error;
2310
2784
  }
2311
- signRes = yield this.signMessageInner({ wallet, signerId, messageBase64, cosmosSignDocBase64 });
2312
- if (signRes.pendingTransactionId) {
2785
+ if (!(pendingTransaction == null ? void 0 : pendingTransaction.approvedAt)) {
2313
2786
  onPoll == null ? void 0 : onPoll();
2314
2787
  continue;
2315
2788
  } else {
2789
+ signRes = yield this.signMessageInner({ wallet, signerId, messageBase64, cosmosSignDocBase64 });
2316
2790
  break;
2317
2791
  }
2318
2792
  }
@@ -2381,6 +2855,7 @@ const _ParaCore = class _ParaCore {
2381
2855
  onCancel,
2382
2856
  onPoll
2383
2857
  }) {
2858
+ var _a;
2384
2859
  this.assertIsValidWalletId(walletId);
2385
2860
  const wallet = this.wallets[walletId];
2386
2861
  let signerId = this.userId;
@@ -2399,7 +2874,7 @@ const _ParaCore = class _ParaCore {
2399
2874
  );
2400
2875
  let timeStart = Date.now();
2401
2876
  if (signRes.pendingTransactionId) {
2402
- this.platformUtils.openPopup(
2877
+ yield this.platformUtils.openPopup(
2403
2878
  yield this.getTransactionReviewUrl(signRes.pendingTransactionId, timeoutMs),
2404
2879
  { type: PopupType.SIGN_TRANSACTION_REVIEW }
2405
2880
  );
@@ -2413,27 +2888,28 @@ const _ParaCore = class _ParaCore {
2413
2888
  break;
2414
2889
  }
2415
2890
  yield new Promise((resolve) => setTimeout(resolve, constants.POLLING_INTERVAL_MS));
2891
+ let pendingTransaction;
2416
2892
  try {
2417
- yield this.ctx.client.getPendingTransaction(this.userId, signRes.pendingTransactionId);
2893
+ pendingTransaction = (_a = (yield this.ctx.client.getPendingTransaction(this.userId, signRes.pendingTransactionId)).data) == null ? void 0 : _a.pendingTransaction;
2418
2894
  } catch (err) {
2419
2895
  const error = new TransactionReviewDenied();
2420
2896
  dispatchEvent(ParaEvent.SIGN_TRANSACTION_EVENT, signRes, error.message);
2421
2897
  throw error;
2422
2898
  }
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) {
2899
+ if (!(pendingTransaction == null ? void 0 : pendingTransaction.approvedAt)) {
2434
2900
  onPoll == null ? void 0 : onPoll();
2435
2901
  continue;
2436
2902
  } else {
2903
+ signRes = yield this.platformUtils.signTransaction(
2904
+ this.ctx,
2905
+ signerId,
2906
+ walletId,
2907
+ this.wallets[walletId].signer,
2908
+ rlpEncodedTxBase64,
2909
+ chainId,
2910
+ this.retrieveSessionCookie(),
2911
+ wallet.scheme === "DKLS"
2912
+ );
2437
2913
  break;
2438
2914
  }
2439
2915
  }
@@ -2475,7 +2951,8 @@ const _ParaCore = class _ParaCore {
2475
2951
  providerKey: onRampPurchase.providerKey
2476
2952
  }, walletParams));
2477
2953
  if (shouldOpenPopup) {
2478
- this.platformUtils.openPopup(portalUrl, { type: PopupType.ON_RAMP_TRANSACTION });
2954
+ const onRampWindow = yield this.platformUtils.openPopup(portalUrl, { type: PopupType.ON_RAMP_TRANSACTION });
2955
+ this.onRampPopup = { window: onRampWindow, onRampPurchase };
2479
2956
  }
2480
2957
  return { onRampPurchase, portalUrl };
2481
2958
  });
@@ -2558,6 +3035,20 @@ const _ParaCore = class _ParaCore {
2558
3035
  return sessionLookupId;
2559
3036
  });
2560
3037
  }
3038
+ issueJwt() {
3039
+ return __async(this, arguments, function* ({ keyIndex = 0 } = {}) {
3040
+ try {
3041
+ return yield this.ctx.client.issueJwt({ keyIndex });
3042
+ } catch (error) {
3043
+ if (error.status === 403 || error.status === 401) {
3044
+ const errorMessage = "The user needs to be logged in to issue a JWT. Please log in and try again.";
3045
+ this.displayModalError(errorMessage);
3046
+ console.warn(errorMessage);
3047
+ }
3048
+ throw error;
3049
+ }
3050
+ });
3051
+ }
2561
3052
  /**
2562
3053
  * Logs the user out.
2563
3054
  * @param {Object} opts the options object.
@@ -2565,6 +3056,7 @@ const _ParaCore = class _ParaCore {
2565
3056
  **/
2566
3057
  logout() {
2567
3058
  return __async(this, arguments, function* ({ clearPregenWallets = false } = {}) {
3059
+ const shouldDispatchLogoutEvent = yield this.isSessionActive();
2568
3060
  yield this.ctx.client.logout();
2569
3061
  yield this.clearStorage();
2570
3062
  if (!clearPregenWallets) {
@@ -2581,22 +3073,17 @@ const _ParaCore = class _ParaCore {
2581
3073
  this.externalWallets = {};
2582
3074
  this.loginEncryptionKeyPair = void 0;
2583
3075
  __privateSet(this, _authInfo, void 0);
3076
+ this.accountLinkInProgress = void 0;
2584
3077
  this.userId = void 0;
2585
3078
  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]);
3079
+ if (shouldDispatchLogoutEvent) {
3080
+ dispatchEvent(ParaEvent.LOGOUT_EVENT, null);
2596
3081
  }
2597
- return supportedAuthMethods;
2598
3082
  });
2599
3083
  }
3084
+ get toStringAdditions() {
3085
+ return {};
3086
+ }
2600
3087
  /**
2601
3088
  * Converts to a string, removing sensitive data when logging this class.
2602
3089
  *
@@ -2620,10 +3107,10 @@ const _ParaCore = class _ParaCore {
2620
3107
  }),
2621
3108
  {}
2622
3109
  );
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,
3110
+ const obj = __spreadProps(__spreadValues({
3111
+ partnerId: (_a = this.partner) == null ? void 0 : _a.id,
3112
+ supportedWalletTypes: (_b = this.partner) == null ? void 0 : _b.supportedWalletTypes,
3113
+ cosmosPrefix: (_c = this.partner) == null ? void 0 : _c.cosmosPrefix,
2627
3114
  authInfo: __privateGet(this, _authInfo),
2628
3115
  isGuestMode: this.isGuestMode,
2629
3116
  userId: this.userId,
@@ -2633,6 +3120,8 @@ const _ParaCore = class _ParaCore {
2633
3120
  wallets: redactedWallets,
2634
3121
  externalWallets: redactedExternalWallets,
2635
3122
  loginEncryptionKeyPair: this.loginEncryptionKeyPair ? "[REDACTED]" : void 0,
3123
+ isReady: this.isReady
3124
+ }, this.toStringAdditions), {
2636
3125
  ctx: {
2637
3126
  apiKey: this.ctx.apiKey,
2638
3127
  disableWorkers: this.ctx.disableWorkers,
@@ -2643,9 +3132,14 @@ const _ParaCore = class _ParaCore {
2643
3132
  useDKLS: this.ctx.useDKLS,
2644
3133
  cosmosPrefix: this.ctx.cosmosPrefix
2645
3134
  }
2646
- };
3135
+ });
2647
3136
  return `Para ${JSON.stringify(obj, null, 2)}`;
2648
3137
  }
3138
+ devLog(...s) {
3139
+ if (this.ctx.env === Environment.DEV || this.ctx.env === Environment.SANDBOX) {
3140
+ console.log(...s);
3141
+ }
3142
+ }
2649
3143
  getNewCredentialAndUrl() {
2650
3144
  return __async(this, arguments, function* ({
2651
3145
  authMethod = "PASSKEY",
@@ -2660,7 +3154,7 @@ const _ParaCore = class _ParaCore {
2660
3154
  ({
2661
3155
  data: { id: credentialId }
2662
3156
  } = yield this.ctx.client.addSessionPublicKey(this.userId, {
2663
- status: PublicKeyStatus.PENDING,
3157
+ status: AuthMethodStatus.PENDING,
2664
3158
  type: PublicKeyType.WEB
2665
3159
  }));
2666
3160
  urlType = "createAuth";
@@ -2669,10 +3163,18 @@ const _ParaCore = class _ParaCore {
2669
3163
  ({
2670
3164
  data: { id: credentialId }
2671
3165
  } = yield this.ctx.client.addSessionPasswordPublicKey(this.userId, {
2672
- status: PasswordStatus.PENDING
3166
+ status: AuthMethodStatus.PENDING
2673
3167
  }));
2674
3168
  urlType = "createPassword";
2675
3169
  break;
3170
+ case "PIN":
3171
+ ({
3172
+ data: { id: credentialId }
3173
+ } = yield this.ctx.client.addSessionPasswordPublicKey(this.userId, {
3174
+ status: AuthMethodStatus.PENDING
3175
+ }));
3176
+ urlType = "createPIN";
3177
+ break;
2676
3178
  }
2677
3179
  const url = this.isNativePasskey && urlType === "createAuth" ? void 0 : yield this.constructPortalUrl(urlType, {
2678
3180
  isForNewDevice,
@@ -2684,7 +3186,7 @@ const _ParaCore = class _ParaCore {
2684
3186
  });
2685
3187
  }
2686
3188
  /**
2687
- * Returns a Para Portal URL for logging in with a WebAuth passkey or a password.
3189
+ * Returns a Para Portal URL for logging in with a WebAuth passkey, password, PIN or OTP.
2688
3190
  * @param {Object} opts the options object
2689
3191
  * @param {String} opts.auth - the user auth to sign up or log in with, in the form ` { email: string } | { phone: `+${number}` } `
2690
3192
  * @param {boolean} opts.useShortUrls - whether to shorten the generated portal URLs
@@ -2710,6 +3212,12 @@ const _ParaCore = class _ParaCore {
2710
3212
  case "PASSWORD":
2711
3213
  urlType = "loginPassword";
2712
3214
  break;
3215
+ case "PIN":
3216
+ urlType = "loginPIN";
3217
+ break;
3218
+ case "BASIC_LOGIN":
3219
+ urlType = "loginOTP";
3220
+ break;
2713
3221
  default:
2714
3222
  throw new Error(`invalid authentication method: '${authMethod}'`);
2715
3223
  }
@@ -2720,53 +3228,214 @@ const _ParaCore = class _ParaCore {
2720
3228
  });
2721
3229
  });
2722
3230
  }
2723
- signUpOrLogIn(_o) {
3231
+ prepareLogin() {
2724
3232
  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);
3233
+ yield this.logout();
3234
+ const { sessionLookupId } = yield this.touchSession(true);
3235
+ if (!this.loginEncryptionKeyPair) {
3236
+ yield this.setLoginEncryptionKeyPair();
3237
+ }
3238
+ return sessionLookupId;
2728
3239
  });
2729
3240
  }
2730
- verifyNewAccount(_q) {
3241
+ signUpOrLogIn(_k) {
2731
3242
  return __async(this, null, function* () {
2732
- var _r = _q, {
3243
+ var _l = _k, { auth } = _l, urlOptions = __objRest(_l, ["auth"]);
3244
+ let serverAuthState;
3245
+ try {
3246
+ serverAuthState = yield this.ctx.client.signUpOrLogIn(__spreadValues(__spreadValues({}, auth), this.getVerificationEmailProps()));
3247
+ } catch (error) {
3248
+ if (error.message.includes("max beta users reached")) {
3249
+ this.displayModalError(
3250
+ `50 user limit reached. [Go to Production.](https://docs.getpara.com/v2/general/checklist#go-live-checklist)`
3251
+ );
3252
+ }
3253
+ throw error;
3254
+ }
3255
+ const authInfo = serverAuthState.auth;
3256
+ if (this.fetchPregenWalletsOverride && isPregenAuth(authInfo)) {
3257
+ const { userShare } = yield this.fetchPregenWalletsOverride({ pregenId: authInfo });
3258
+ if (userShare) {
3259
+ yield this.setUserShare(userShare);
3260
+ }
3261
+ }
3262
+ return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, __spreadValues({}, urlOptions));
3263
+ });
3264
+ }
3265
+ verifyNewAccount(_m) {
3266
+ return __async(this, null, function* () {
3267
+ var _n = _m, {
2733
3268
  verificationCode
2734
- } = _r, urlOptions = __objRest(_r, [
3269
+ } = _n, urlOptions = __objRest(_n, [
2735
3270
  "verificationCode"
2736
3271
  ]);
2737
3272
  this.assertIsAuthSet(["email", "phone"]);
2738
- const userId = this.assertUserId();
2739
- const serverAuthState = yield this.ctx.client.verifyNewAccount(userId, {
3273
+ const userId = this.assertUserId({ allowGuestMode: true });
3274
+ const serverAuthState = yield this.ctx.client.verifyAccount(userId, {
2740
3275
  verificationCode
2741
3276
  });
3277
+ if (serverAuthState.stage === "login" || serverAuthState.stage === "done") {
3278
+ throw new Error("Account already exists.");
3279
+ }
3280
+ yield this.touchSession(true);
2742
3281
  return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
2743
3282
  });
2744
3283
  }
3284
+ getLinkedAccounts() {
3285
+ return __async(this, arguments, function* ({
3286
+ withMetadata = false
3287
+ } = {}) {
3288
+ const userId = this.assertUserId();
3289
+ const { accounts } = yield this.ctx.client.getLinkedAccounts({ userId, withMetadata });
3290
+ return __spreadValues({
3291
+ userId
3292
+ }, accounts);
3293
+ });
3294
+ }
3295
+ linkAccount(opts) {
3296
+ return __async(this, null, function* () {
3297
+ const { supportedAccountLinks = [...LINKED_ACCOUNT_TYPES] } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
3298
+ let type, identifier, externalWallet, isPermitted;
3299
+ switch (true) {
3300
+ case "auth" in opts:
3301
+ {
3302
+ const authInfo = extractAuthInfo(opts.auth, { isRequired: true });
3303
+ if (authInfo.auth === this.authInfo.auth) {
3304
+ throw new Error(AccountLinkError.Conflict);
3305
+ }
3306
+ type = authInfo.authType.toUpperCase();
3307
+ identifier = authInfo.identifier;
3308
+ isPermitted = supportedAccountLinks.includes(type);
3309
+ }
3310
+ break;
3311
+ case "externalWallet" in opts:
3312
+ {
3313
+ externalWallet = opts.externalWallet;
3314
+ type = "EXTERNAL_WALLET";
3315
+ isPermitted = supportedAccountLinks.includes("EXTERNAL_WALLET") || supportedAccountLinks.includes(externalWallet.providerId);
3316
+ }
3317
+ break;
3318
+ case "type" in opts:
3319
+ {
3320
+ type = opts.type;
3321
+ if (type === "X") {
3322
+ type = "TWITTER";
3323
+ }
3324
+ isPermitted = supportedAccountLinks.includes(type);
3325
+ }
3326
+ break;
3327
+ default:
3328
+ throw new Error("Invalid parameters for linking account, must pass `auth` or `type` or `externalWallet`");
3329
+ }
3330
+ if (!isPermitted) {
3331
+ throw new Error(`Account linking for type '${type}' is not supported by the current API key configuration`);
3332
+ }
3333
+ const userId = this.assertUserId();
3334
+ const result = yield this.ctx.client.linkAccount(__spreadValues(__spreadValues({
3335
+ userId,
3336
+ type
3337
+ }, identifier ? { identifier } : {}), externalWallet ? { externalWallet } : {}));
3338
+ if ("isConflict" in result) {
3339
+ throw new Error(AccountLinkError.Conflict);
3340
+ }
3341
+ const { linkedAccountId, signatureVerificationMessage } = result;
3342
+ this.accountLinkInProgress = __spreadValues(__spreadValues({
3343
+ id: linkedAccountId,
3344
+ type,
3345
+ isComplete: false
3346
+ }, identifier ? { identifier } : {}), signatureVerificationMessage && externalWallet ? {
3347
+ externalWallet: __spreadProps(__spreadValues({}, externalWallet), {
3348
+ signatureVerificationMessage
3349
+ })
3350
+ } : {});
3351
+ return this.accountLinkInProgress;
3352
+ });
3353
+ }
3354
+ unlinkAccount(_0) {
3355
+ return __async(this, arguments, function* ({
3356
+ linkedAccountId
3357
+ }) {
3358
+ if (!linkedAccountId) {
3359
+ throw new Error("No linked account ID provided");
3360
+ }
3361
+ const userId = this.assertUserId();
3362
+ const accounts = yield this.ctx.client.unlinkAccount({ linkedAccountId, userId });
3363
+ return accounts;
3364
+ });
3365
+ }
3366
+ verifyLink() {
3367
+ return __async(this, arguments, function* (_o = {}) {
3368
+ var _p = _o, {
3369
+ accountLinkInProgress = __privateMethod(this, _ParaCore_instances, assertIsLinkingAccount_fn).call(this)
3370
+ } = _p, opts = __objRest(_p, [
3371
+ "accountLinkInProgress"
3372
+ ]);
3373
+ try {
3374
+ const userId = this.assertUserId(), result = yield this.ctx.client.verifyLink(__spreadValues({
3375
+ linkedAccountId: accountLinkInProgress.id,
3376
+ userId
3377
+ }, opts));
3378
+ if ("isConflict" in result) {
3379
+ throw new Error(AccountLinkError.Conflict);
3380
+ }
3381
+ this.accountLinkInProgress = void 0;
3382
+ return result.accounts;
3383
+ } catch (e) {
3384
+ throw new Error(e.message === AccountLinkError.Conflict ? AccountLinkError.Conflict : e.message);
3385
+ }
3386
+ });
3387
+ }
3388
+ verifyEmailOrPhoneLink(_0) {
3389
+ return __async(this, arguments, function* ({
3390
+ verificationCode
3391
+ }) {
3392
+ const accounts = yield this.verifyLink({
3393
+ accountLinkInProgress: __privateMethod(this, _ParaCore_instances, assertIsLinkingAccount_fn).call(this, ["EMAIL", "PHONE"]),
3394
+ verificationCode
3395
+ });
3396
+ return accounts;
3397
+ });
3398
+ }
3399
+ getProfileBalance() {
3400
+ return __async(this, arguments, function* ({ config, refetch = false } = {}) {
3401
+ const { balance } = yield this.ctx.client.getProfileBalance({
3402
+ config,
3403
+ wallets: this.availableWallets.map(({ type, address }) => ({ type, address })),
3404
+ refetch
3405
+ });
3406
+ return balance;
3407
+ });
3408
+ }
3409
+ sendLoginCode() {
3410
+ return __async(this, null, function* () {
3411
+ const { userId } = yield this.ctx.client.sendLoginVerificationCode(this.authInfo);
3412
+ this.setUserId(userId);
3413
+ });
3414
+ }
2745
3415
  };
2746
3416
  _authInfo = new WeakMap();
2747
- _partner = new WeakMap();
2748
3417
  _ParaCore_instances = new WeakSet();
2749
3418
  assertPartner_fn = function() {
2750
3419
  return __async(this, null, function* () {
2751
3420
  var _a, _b;
2752
- if (!__privateGet(this, _partner)) {
3421
+ if (!this.partner) {
2753
3422
  yield this.touchSession();
2754
3423
  }
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;
3424
+ if (((_a = this.partner) == null ? void 0 : _a.cosmosPrefix) && this.ctx.cosmosPrefix !== this.partner.cosmosPrefix) {
3425
+ this.ctx.cosmosPrefix = (_b = this.partner) == null ? void 0 : _b.cosmosPrefix;
2757
3426
  }
2758
- return __privateGet(this, _partner);
3427
+ return this.partner;
2759
3428
  });
2760
3429
  };
2761
3430
  guestWalletIds_get = function() {
2762
3431
  var _a, _b, _c;
2763
- if (!((_a = __privateGet(this, _partner)) == null ? void 0 : _a.supportedWalletTypes)) {
3432
+ if (!((_a = this.partner) == null ? void 0 : _a.supportedWalletTypes)) {
2764
3433
  return {};
2765
3434
  }
2766
3435
  const guestId = (_c = (_b = this.pregenIds) == null ? void 0 : _b.GUEST_ID) == null ? void 0 : _c[0];
2767
3436
  return !!guestId ? Object.entries(this.wallets).reduce((acc, [id, wallet]) => {
2768
3437
  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) => {
3438
+ return __spreadValues(__spreadValues({}, acc), getEquivalentTypes(wallet.type).filter((type) => this.partner.supportedWalletTypes.some((entry) => entry.type === type)).reduce((acc2, eqType) => {
2770
3439
  var _a2;
2771
3440
  return __spreadProps(__spreadValues({}, acc2), { [eqType]: [.../* @__PURE__ */ new Set([...(_a2 = acc2[eqType]) != null ? _a2 : [], id])] });
2772
3441
  }, {}));
@@ -2823,9 +3492,70 @@ setAuthInfo_fn = function(authInfo) {
2823
3492
  };
2824
3493
  getPartner_fn = function(partnerId) {
2825
3494
  return __async(this, null, function* () {
3495
+ if (this.isPartnerOptional && !partnerId) {
3496
+ return void 0;
3497
+ }
2826
3498
  const res = yield this.ctx.client.getPartner(partnerId);
2827
- __privateSet(this, _partner, res.data.partner);
2828
- return __privateGet(this, _partner);
3499
+ this.partner = res.data.partner;
3500
+ return this.partner;
3501
+ });
3502
+ };
3503
+ assertIsLinkingAccount_fn = function(types) {
3504
+ if (!this.accountLinkInProgress || this.accountLinkInProgress.isComplete) {
3505
+ throw new Error("no account linking in progress");
3506
+ }
3507
+ if (types && !types.includes(this.accountLinkInProgress.type)) {
3508
+ throw new Error(
3509
+ `account linking in progress for type ${this.accountLinkInProgress.type}, expected one of ${types.join(", ")}`
3510
+ );
3511
+ }
3512
+ return this.accountLinkInProgress;
3513
+ };
3514
+ assertIsLinkingAccountOrStart_fn = function(type) {
3515
+ return __async(this, null, function* () {
3516
+ if (this.accountLinkInProgress && !this.accountLinkInProgress.isComplete) {
3517
+ return __privateMethod(this, _ParaCore_instances, assertIsLinkingAccount_fn).call(this, [type]);
3518
+ }
3519
+ return yield this.linkAccount({ type });
3520
+ });
3521
+ };
3522
+ getOAuthUrl_fn = function(_0) {
3523
+ return __async(this, arguments, function* ({
3524
+ method,
3525
+ appScheme,
3526
+ accountLinkInProgress,
3527
+ sessionLookupId,
3528
+ encryptionKey
3529
+ }) {
3530
+ if (!accountLinkInProgress && !this.isPortal()) {
3531
+ return yield this.constructPortalUrl("oAuth", { sessionId: sessionLookupId, oAuthMethod: method, appScheme });
3532
+ }
3533
+ let portalSessionLookupId;
3534
+ if (this.isPortal()) {
3535
+ portalSessionLookupId = (yield this.touchSession(true)).sessionLookupId;
3536
+ }
3537
+ return constructUrl({
3538
+ base: getBaseOAuthUrl(this.ctx.env),
3539
+ path: `/auth/${method.toLowerCase()}`,
3540
+ params: __spreadProps(__spreadValues({
3541
+ apiKey: this.ctx.apiKey,
3542
+ sessionLookupId,
3543
+ portalSessionLookupId,
3544
+ appScheme
3545
+ }, accountLinkInProgress ? {
3546
+ linkedAccountId: this.accountLinkInProgress.id
3547
+ } : {}), {
3548
+ callback: !accountLinkInProgress && (yield this.constructPortalUrl("oAuthCallback", {
3549
+ sessionId: sessionLookupId,
3550
+ oAuthMethod: method,
3551
+ appScheme,
3552
+ thisDevice: {
3553
+ sessionId: sessionLookupId,
3554
+ encryptionKey
3555
+ }
3556
+ }))
3557
+ })
3558
+ });
2829
3559
  });
2830
3560
  };
2831
3561
  createPregenWallet_fn = function(opts) {
@@ -2878,8 +3608,9 @@ createPregenWallet_fn = function(opts) {
2878
3608
  _isCreateGuestWalletsPending = new WeakMap();
2879
3609
  prepareAuthState_fn = function(_0) {
2880
3610
  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);
3611
+ var _a, _b;
3612
+ 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))))) {
3613
+ opts.sessionLookupId = yield this.prepareLogin();
2883
3614
  }
2884
3615
  const { auth, externalWallet, userId, displayName, pfpUrl, username } = serverAuthState;
2885
3616
  const authInfo = __spreadValues(__spreadValues({}, extractAuthInfo(auth, { isRequired: true })), Object.fromEntries(
@@ -2893,34 +3624,68 @@ prepareAuthState_fn = function(_0) {
2893
3624
  yield __privateMethod(this, _ParaCore_instances, setAuthInfo_fn).call(this, authInfo);
2894
3625
  yield this.assertIsAuthSet();
2895
3626
  if (!!externalWallet) {
2896
- yield this.setExternalWallet(externalWallet);
3627
+ yield this.setExternalWallet([externalWallet]);
2897
3628
  }
2898
3629
  if (!!userId) {
2899
3630
  yield this.setUserId(userId);
2900
3631
  }
2901
3632
  let authState;
2902
3633
  switch (serverAuthState.stage) {
3634
+ case "done": {
3635
+ authState = yield __privateMethod(this, _ParaCore_instances, prepareDoneState_fn).call(this, serverAuthState);
3636
+ break;
3637
+ }
2903
3638
  case "verify":
2904
- authState = serverAuthState;
3639
+ authState = yield __privateMethod(this, _ParaCore_instances, prepareVerificationState_fn).call(this, serverAuthState, __spreadProps(__spreadValues({}, opts), {
3640
+ sessionLookupId: opts.sessionLookupId
3641
+ }));
2905
3642
  break;
2906
3643
  case "login":
3644
+ if (externalWallet && !(externalWallet == null ? void 0 : externalWallet.withFullParaAuth)) {
3645
+ authState = serverAuthState;
3646
+ break;
3647
+ }
2907
3648
  authState = yield __privateMethod(this, _ParaCore_instances, prepareLoginState_fn).call(this, serverAuthState, __spreadProps(__spreadValues({}, opts), { sessionLookupId: opts.sessionLookupId }));
2908
3649
  break;
2909
3650
  case "signup":
3651
+ if (externalWallet && !(externalWallet == null ? void 0 : externalWallet.withFullParaAuth)) {
3652
+ authState = serverAuthState;
3653
+ break;
3654
+ }
2910
3655
  authState = yield __privateMethod(this, _ParaCore_instances, prepareSignUpState_fn).call(this, serverAuthState, opts);
2911
3656
  break;
2912
3657
  }
2913
3658
  return authState;
2914
3659
  });
2915
3660
  };
2916
- prepareLogin_fn = function() {
3661
+ prepareDoneState_fn = function(doneState) {
2917
3662
  return __async(this, null, function* () {
2918
- yield this.logout();
2919
- const { sessionLookupId } = yield this.touchSession(true);
2920
- if (!this.loginEncryptionKeyPair) {
2921
- yield this.setLoginEncryptionKeyPair();
3663
+ let isSLOPossible = doneState.authMethods.includes(AuthMethod.BASIC_LOGIN);
3664
+ this.isEnclaveUser = isSLOPossible;
3665
+ return doneState;
3666
+ });
3667
+ };
3668
+ prepareVerificationState_fn = function(_0, _1) {
3669
+ return __async(this, arguments, function* (verifyState, {
3670
+ useShortUrls: shorten = false,
3671
+ portalTheme,
3672
+ sessionLookupId
3673
+ }) {
3674
+ let isSLOPossible = false;
3675
+ if (verifyState.nextStage === "login") {
3676
+ isSLOPossible = verifyState.loginAuthMethods.includes(AuthMethod.BASIC_LOGIN);
3677
+ } else if (verifyState.nextStage === "signup") {
3678
+ isSLOPossible = verifyState.signupAuthMethods.includes(AuthMethod.BASIC_LOGIN);
2922
3679
  }
2923
- return sessionLookupId;
3680
+ this.isEnclaveUser = isSLOPossible;
3681
+ return __spreadValues(__spreadValues({}, verifyState), isSLOPossible ? {
3682
+ loginUrl: yield this.getLoginUrl({
3683
+ authMethod: AuthMethod.BASIC_LOGIN,
3684
+ sessionId: sessionLookupId,
3685
+ shorten,
3686
+ portalTheme
3687
+ })
3688
+ } : {});
2924
3689
  });
2925
3690
  };
2926
3691
  prepareLoginState_fn = function(_0, _1) {
@@ -2929,8 +3694,12 @@ prepareLoginState_fn = function(_0, _1) {
2929
3694
  portalTheme,
2930
3695
  sessionLookupId
2931
3696
  }) {
2932
- const _a = loginState, { loginAuthMethods } = _a, authState = __objRest(_a, ["loginAuthMethods"]);
2933
- return __spreadValues(__spreadValues(__spreadValues({}, authState), !this.isNativePasskey && loginAuthMethods.includes(AuthMethod.PASSKEY) ? {
3697
+ const _a = loginState, { loginAuthMethods = [], hasPasswordWithoutPIN } = _a, authState = __objRest(_a, ["loginAuthMethods", "hasPasswordWithoutPIN"]);
3698
+ const isPasskeySupported = yield this.isPasskeySupported(), isPasskeyPossible = loginAuthMethods.includes(AuthMethod.PASSKEY) && !this.isNativePasskey, isPasswordPossible = loginAuthMethods.includes(AuthMethod.PASSWORD) && hasPasswordWithoutPIN, isPINPossible = loginAuthMethods.includes(AuthMethod.PIN);
3699
+ return __spreadValues(__spreadValues(__spreadValues(__spreadProps(__spreadValues({}, authState), {
3700
+ isPasskeySupported,
3701
+ loginAuthMethods
3702
+ }), isPasskeyPossible ? {
2934
3703
  passkeyUrl: yield this.getLoginUrl({ sessionId: sessionLookupId, shorten, portalTheme }),
2935
3704
  passkeyKnownDeviceUrl: yield this.constructPortalUrl("loginAuth", {
2936
3705
  sessionId: sessionLookupId,
@@ -2941,28 +3710,41 @@ prepareLoginState_fn = function(_0, _1) {
2941
3710
  shorten,
2942
3711
  portalTheme
2943
3712
  })
2944
- } : {}), loginAuthMethods.includes(AuthMethod.PASSWORD) ? {
3713
+ } : {}), isPasswordPossible ? {
2945
3714
  passwordUrl: yield this.constructPortalUrl("loginPassword", {
2946
3715
  sessionId: sessionLookupId,
2947
3716
  shorten,
2948
- portalTheme
3717
+ portalTheme,
3718
+ params: { isEmbedded: `${!loginState.isWalletSelectionNeeded}` }
3719
+ })
3720
+ } : {}), isPINPossible ? {
3721
+ pinUrl: yield this.constructPortalUrl("loginPIN", {
3722
+ sessionId: sessionLookupId,
3723
+ shorten,
3724
+ portalTheme,
3725
+ params: { isEmbedded: `${!loginState.isWalletSelectionNeeded}` }
2949
3726
  })
2950
3727
  } : {});
2951
3728
  });
2952
3729
  };
2953
3730
  prepareSignUpState_fn = function(_0, _1) {
2954
3731
  return __async(this, arguments, function* (serverSignupState, { useShortUrls: shorten = false, portalTheme }) {
2955
- const _a = serverSignupState, { signupAuthMethods } = _a, authState = __objRest(_a, ["signupAuthMethods"]);
2956
- const [isPasskey, isPassword] = [
3732
+ const _a = serverSignupState, { signupAuthMethods = [] } = _a, authState = __objRest(_a, ["signupAuthMethods"]);
3733
+ const isPasskeySupported = yield this.isPasskeySupported();
3734
+ const [isPasskey, isPassword, isPIN] = [
2957
3735
  signupAuthMethods.includes(AuthMethod.PASSKEY),
2958
- signupAuthMethods.includes(AuthMethod.PASSWORD)
3736
+ signupAuthMethods.includes(AuthMethod.PASSWORD) || !isPasskeySupported,
3737
+ signupAuthMethods.includes(AuthMethod.PIN)
2959
3738
  ];
2960
- if (!isPasskey && !isPassword) {
3739
+ if (!isPasskey && !isPassword && !isPIN) {
2961
3740
  throw new Error(
2962
- "No supported authentication methods found. Please ensure you have enabled either WebAuth passkeys or passwords in your Developer Portal settings."
3741
+ "No supported authentication methods found. Please ensure you have enabled either WebAuth passkeys, passwords or PINs in your Developer Portal settings."
2963
3742
  );
2964
3743
  }
2965
- const signupState = authState;
3744
+ const signupState = __spreadProps(__spreadValues({}, authState), {
3745
+ isPasskeySupported,
3746
+ signupAuthMethods
3747
+ });
2966
3748
  if (isPasskey) {
2967
3749
  const { url: passkeyUrl, credentialId: passkeyId } = yield this.getNewCredentialAndUrl({
2968
3750
  authMethod: "PASSKEY",
@@ -2980,6 +3762,15 @@ prepareSignUpState_fn = function(_0, _1) {
2980
3762
  signupState.passwordUrl = passwordUrl;
2981
3763
  signupState.passwordId = passwordId;
2982
3764
  }
3765
+ if (isPIN) {
3766
+ const { url: pinUrl, credentialId: pinId } = yield this.getNewCredentialAndUrl({
3767
+ authMethod: "PIN",
3768
+ portalTheme,
3769
+ shorten
3770
+ });
3771
+ signupState.pinUrl = pinUrl;
3772
+ signupState.pinId = pinId;
3773
+ }
2983
3774
  return signupState;
2984
3775
  });
2985
3776
  };