@getpara/core-sdk 2.12.0 → 2.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (197) hide show
  1. package/dist/cjs/ParaCore.js +805 -1999
  2. package/dist/cjs/constants.js +4 -1
  3. package/dist/cjs/services/AuthService.js +787 -0
  4. package/dist/cjs/services/BaseAuthFlowService.js +78 -0
  5. package/dist/cjs/services/ExternalWalletService.js +386 -0
  6. package/dist/cjs/services/LoginFlowService.js +163 -0
  7. package/dist/cjs/services/PollingService.js +448 -0
  8. package/dist/cjs/services/PortalUrlService.js +379 -0
  9. package/dist/cjs/services/PregenWalletService.js +442 -0
  10. package/dist/cjs/services/SessionManagementService.js +280 -0
  11. package/dist/cjs/services/SignupFlowService.js +185 -0
  12. package/dist/cjs/services/VerificationFlowService.js +242 -0
  13. package/dist/cjs/services/WalletService.js +577 -0
  14. package/dist/cjs/services/types/AuthServiceTypes.js +15 -0
  15. package/dist/cjs/services/types/BaseAuthFlowServiceTypes.js +15 -0
  16. package/dist/cjs/services/types/ExternalWalletServiceTypes.js +15 -0
  17. package/dist/cjs/services/types/LoginFlowServiceTypes.js +15 -0
  18. package/dist/cjs/services/types/PollingServiceTypes.js +15 -0
  19. package/dist/cjs/services/types/PortalUrlServiceTypes.js +15 -0
  20. package/dist/cjs/services/types/PregenWalletServiceTypes.js +15 -0
  21. package/dist/cjs/services/types/SessionManagementServiceTypes.js +15 -0
  22. package/dist/cjs/services/types/SignupFlowServiceTypes.js +15 -0
  23. package/dist/cjs/services/types/VerificationFlowServiceTypes.js +15 -0
  24. package/dist/cjs/services/types/WalletServiceTypes.js +15 -0
  25. package/dist/cjs/services/types/index.js +15 -0
  26. package/dist/cjs/state/CoreStateManager.js +301 -0
  27. package/dist/cjs/state/actors/authenticateWithEmailOrPhone.js +50 -0
  28. package/dist/cjs/state/actors/authenticateWithExternalWallet.js +50 -0
  29. package/dist/cjs/state/actors/authenticateWithFarcaster.js +50 -0
  30. package/dist/cjs/state/actors/authenticateWithFarcasterLegacy.js +50 -0
  31. package/dist/cjs/state/actors/authenticateWithTelegram.js +50 -0
  32. package/dist/cjs/state/actors/authenticateWithTelegramLegacy.js +50 -0
  33. package/dist/cjs/state/actors/checkUserState.js +53 -0
  34. package/dist/cjs/state/actors/claimWallets.js +56 -0
  35. package/dist/cjs/state/actors/connectExternalConnectors.js +54 -0
  36. package/dist/cjs/state/actors/connectExternalWallet.js +50 -0
  37. package/dist/cjs/state/actors/createGuestWallets.js +50 -0
  38. package/dist/cjs/state/actors/createWallets.js +73 -0
  39. package/dist/cjs/state/actors/polling.js +91 -0
  40. package/dist/cjs/state/actors/processAuthentication.js +50 -0
  41. package/dist/cjs/state/actors/setupAfterLogin.js +52 -0
  42. package/dist/cjs/state/actors/setupPara.js +50 -0
  43. package/dist/cjs/state/actors/signExternalWalletVerification.js +79 -0
  44. package/dist/cjs/state/actors/switchExternalWallet.js +50 -0
  45. package/dist/cjs/state/actors/verifyExternalWallet.js +50 -0
  46. package/dist/cjs/state/actors/verifyNewAccount.js +50 -0
  47. package/dist/cjs/state/actors/waitForExternalWalletProviders.js +54 -0
  48. package/dist/cjs/state/machines/authStateMachine.helpers.js +137 -0
  49. package/dist/cjs/state/machines/authStateMachine.js +1084 -0
  50. package/dist/cjs/state/machines/coreStateMachine.js +383 -0
  51. package/dist/cjs/state/machines/walletStateMachine.js +456 -0
  52. package/dist/cjs/state/types/auth.js +15 -0
  53. package/dist/cjs/state/types/core.js +15 -0
  54. package/dist/cjs/state/types/wallet.js +15 -0
  55. package/dist/cjs/types/{auth.js → accountLinking.js} +3 -3
  56. package/dist/cjs/types/authState.js +15 -0
  57. package/dist/cjs/types/coreApi.js +3 -1
  58. package/dist/cjs/types/index.js +2 -2
  59. package/dist/cjs/types/serviceInterfaces.js +15 -0
  60. package/dist/cjs/types/util.js +15 -0
  61. package/dist/cjs/utils/formatting.js +6 -0
  62. package/dist/cjs/utils/retryBackoff.js +30 -0
  63. package/dist/cjs/utils/stateErrorHelpers.js +60 -0
  64. package/dist/cjs/utils/stateListener.js +129 -0
  65. package/dist/esm/ParaCore.js +808 -2026
  66. package/dist/esm/constants.js +3 -1
  67. package/dist/esm/services/AuthService.js +717 -0
  68. package/dist/esm/services/BaseAuthFlowService.js +25 -0
  69. package/dist/esm/services/ExternalWalletService.js +327 -0
  70. package/dist/esm/services/LoginFlowService.js +97 -0
  71. package/dist/esm/services/PollingService.js +389 -0
  72. package/dist/esm/services/PortalUrlService.js +320 -0
  73. package/dist/esm/services/PregenWalletService.js +393 -0
  74. package/dist/esm/services/SessionManagementService.js +236 -0
  75. package/dist/esm/services/SignupFlowService.js +119 -0
  76. package/dist/esm/services/VerificationFlowService.js +178 -0
  77. package/dist/esm/services/WalletService.js +514 -0
  78. package/dist/esm/services/types/AuthServiceTypes.js +0 -0
  79. package/dist/esm/services/types/BaseAuthFlowServiceTypes.js +0 -0
  80. package/dist/esm/services/types/ExternalWalletServiceTypes.js +0 -0
  81. package/dist/esm/services/types/LoginFlowServiceTypes.js +0 -0
  82. package/dist/esm/services/types/PollingServiceTypes.js +0 -0
  83. package/dist/esm/services/types/PortalUrlServiceTypes.js +0 -0
  84. package/dist/esm/services/types/PregenWalletServiceTypes.js +0 -0
  85. package/dist/esm/services/types/SessionManagementServiceTypes.js +0 -0
  86. package/dist/esm/services/types/SignupFlowServiceTypes.js +0 -0
  87. package/dist/esm/services/types/VerificationFlowServiceTypes.js +0 -0
  88. package/dist/esm/services/types/WalletServiceTypes.js +0 -0
  89. package/dist/esm/services/types/index.js +0 -0
  90. package/dist/esm/state/CoreStateManager.js +265 -0
  91. package/dist/esm/state/actors/authenticateWithEmailOrPhone.js +10 -0
  92. package/dist/esm/state/actors/authenticateWithExternalWallet.js +10 -0
  93. package/dist/esm/state/actors/authenticateWithFarcaster.js +10 -0
  94. package/dist/esm/state/actors/authenticateWithFarcasterLegacy.js +10 -0
  95. package/dist/esm/state/actors/authenticateWithTelegram.js +10 -0
  96. package/dist/esm/state/actors/authenticateWithTelegramLegacy.js +10 -0
  97. package/dist/esm/state/actors/checkUserState.js +13 -0
  98. package/dist/esm/state/actors/claimWallets.js +16 -0
  99. package/dist/esm/state/actors/connectExternalConnectors.js +14 -0
  100. package/dist/esm/state/actors/connectExternalWallet.js +10 -0
  101. package/dist/esm/state/actors/createGuestWallets.js +10 -0
  102. package/dist/esm/state/actors/createWallets.js +20 -0
  103. package/dist/esm/state/actors/polling.js +55 -0
  104. package/dist/esm/state/actors/processAuthentication.js +10 -0
  105. package/dist/esm/state/actors/setupAfterLogin.js +12 -0
  106. package/dist/esm/state/actors/setupPara.js +10 -0
  107. package/dist/esm/state/actors/signExternalWalletVerification.js +15 -0
  108. package/dist/esm/state/actors/switchExternalWallet.js +10 -0
  109. package/dist/esm/state/actors/verifyExternalWallet.js +10 -0
  110. package/dist/esm/state/actors/verifyNewAccount.js +10 -0
  111. package/dist/esm/state/actors/waitForExternalWalletProviders.js +14 -0
  112. package/dist/esm/state/machines/authStateMachine.helpers.js +92 -0
  113. package/dist/esm/state/machines/authStateMachine.js +1039 -0
  114. package/dist/esm/state/machines/coreStateMachine.js +343 -0
  115. package/dist/esm/state/machines/walletStateMachine.js +401 -0
  116. package/dist/esm/state/types/auth.js +0 -0
  117. package/dist/esm/state/types/core.js +0 -0
  118. package/dist/esm/state/types/wallet.js +0 -0
  119. package/dist/esm/types/authState.js +0 -0
  120. package/dist/esm/types/coreApi.js +3 -1
  121. package/dist/esm/types/index.js +1 -1
  122. package/dist/esm/types/serviceInterfaces.js +0 -0
  123. package/dist/esm/types/util.js +0 -0
  124. package/dist/esm/utils/formatting.js +6 -0
  125. package/dist/esm/utils/retryBackoff.js +7 -0
  126. package/dist/esm/utils/stateErrorHelpers.js +37 -0
  127. package/dist/esm/utils/stateListener.js +106 -0
  128. package/dist/types/ParaCore.d.ts +191 -119
  129. package/dist/types/PlatformUtils.d.ts +23 -0
  130. package/dist/types/constants.d.ts +1 -0
  131. package/dist/types/index.d.ts +4 -2
  132. package/dist/types/services/AuthService.d.ts +72 -0
  133. package/dist/types/services/BaseAuthFlowService.d.ts +28 -0
  134. package/dist/types/services/ExternalWalletService.d.ts +44 -0
  135. package/dist/types/services/LoginFlowService.d.ts +9 -0
  136. package/dist/types/services/PollingService.d.ts +35 -0
  137. package/dist/types/services/PortalUrlService.d.ts +26 -0
  138. package/dist/types/services/PregenWalletService.d.ts +38 -0
  139. package/dist/types/services/SessionManagementService.d.ts +28 -0
  140. package/dist/types/services/SignupFlowService.d.ts +10 -0
  141. package/dist/types/services/VerificationFlowService.d.ts +17 -0
  142. package/dist/types/services/WalletService.d.ts +54 -0
  143. package/dist/types/services/types/AuthServiceTypes.d.ts +147 -0
  144. package/dist/types/services/types/BaseAuthFlowServiceTypes.d.ts +4 -0
  145. package/dist/types/services/types/ExternalWalletServiceTypes.d.ts +67 -0
  146. package/dist/types/services/types/LoginFlowServiceTypes.d.ts +19 -0
  147. package/dist/types/services/types/PollingServiceTypes.d.ts +82 -0
  148. package/dist/types/services/types/PortalUrlServiceTypes.d.ts +46 -0
  149. package/dist/types/services/types/PregenWalletServiceTypes.d.ts +73 -0
  150. package/dist/types/services/types/SessionManagementServiceTypes.d.ts +27 -0
  151. package/dist/types/services/types/SignupFlowServiceTypes.d.ts +18 -0
  152. package/dist/types/services/types/VerificationFlowServiceTypes.d.ts +90 -0
  153. package/dist/types/services/types/WalletServiceTypes.d.ts +109 -0
  154. package/dist/types/services/types/index.d.ts +11 -0
  155. package/dist/types/state/CoreStateManager.d.ts +36 -0
  156. package/dist/types/state/actors/authenticateWithEmailOrPhone.d.ts +8 -0
  157. package/dist/types/state/actors/authenticateWithExternalWallet.d.ts +8 -0
  158. package/dist/types/state/actors/authenticateWithFarcaster.d.ts +3 -0
  159. package/dist/types/state/actors/authenticateWithFarcasterLegacy.d.ts +3 -0
  160. package/dist/types/state/actors/authenticateWithTelegram.d.ts +3 -0
  161. package/dist/types/state/actors/authenticateWithTelegramLegacy.d.ts +8 -0
  162. package/dist/types/state/actors/checkUserState.d.ts +6 -0
  163. package/dist/types/state/actors/claimWallets.d.ts +8 -0
  164. package/dist/types/state/actors/connectExternalConnectors.d.ts +4 -0
  165. package/dist/types/state/actors/connectExternalWallet.d.ts +3 -0
  166. package/dist/types/state/actors/createGuestWallets.d.ts +3 -0
  167. package/dist/types/state/actors/createWallets.d.ts +10 -0
  168. package/dist/types/state/actors/polling.d.ts +3 -0
  169. package/dist/types/state/actors/processAuthentication.d.ts +10 -0
  170. package/dist/types/state/actors/setupAfterLogin.d.ts +5 -0
  171. package/dist/types/state/actors/setupPara.d.ts +2 -0
  172. package/dist/types/state/actors/signExternalWalletVerification.d.ts +7 -0
  173. package/dist/types/state/actors/switchExternalWallet.d.ts +3 -0
  174. package/dist/types/state/actors/verifyExternalWallet.d.ts +8 -0
  175. package/dist/types/state/actors/verifyNewAccount.d.ts +8 -0
  176. package/dist/types/state/actors/waitForExternalWalletProviders.d.ts +2 -0
  177. package/dist/types/state/machines/authStateMachine.d.ts +2570 -0
  178. package/dist/types/state/machines/authStateMachine.helpers.d.ts +57 -0
  179. package/dist/types/state/machines/coreStateMachine.d.ts +22075 -0
  180. package/dist/types/state/machines/walletStateMachine.d.ts +1056 -0
  181. package/dist/types/state/types/auth.d.ts +113 -0
  182. package/dist/types/state/types/core.d.ts +116 -0
  183. package/dist/types/state/types/wallet.d.ts +76 -0
  184. package/dist/types/types/authState.d.ts +66 -0
  185. package/dist/types/types/config.d.ts +5 -0
  186. package/dist/types/types/coreApi.d.ts +148 -298
  187. package/dist/types/types/index.d.ts +3 -1
  188. package/dist/types/types/methods.d.ts +1 -191
  189. package/dist/types/types/serviceInterfaces.d.ts +125 -0
  190. package/dist/types/types/util.d.ts +43 -0
  191. package/dist/types/types/wallet.d.ts +3 -1
  192. package/dist/types/utils/retryBackoff.d.ts +2 -0
  193. package/dist/types/utils/stateErrorHelpers.d.ts +2 -0
  194. package/dist/types/utils/stateListener.d.ts +47 -0
  195. package/package.json +5 -4
  196. /package/dist/esm/types/{auth.js → accountLinking.js} +0 -0
  197. /package/dist/types/types/{auth.d.ts → accountLinking.d.ts} +0 -0
@@ -8,7 +8,7 @@ import {
8
8
  __spreadProps,
9
9
  __spreadValues
10
10
  } from "./chunk-7B52C2XE.js";
11
- var _authInfo, _ParaCore_instances, assertPartner_fn, guestWalletIds_get, guestWalletIdsArray_get, toAuthInfo_fn, setAuthInfo_fn, getPartner_fn, assertIsLinkingAccount_fn, assertIsLinkingAccountOrStart_fn, getOAuthUrl_fn, waitForLoginProcess_fn, createPregenWallet_fn, _isCreateGuestWalletsPending, prepareAuthState_fn, prepareDoneState_fn, prepareVerificationState_fn, prepareLoginState_fn, prepareSignUpState_fn;
11
+ var _stateManager, _authService, _walletService, _externalWalletService, _pregenWalletService, _pollingService, _portalUrlService, _sessionManagementService, _debugLogsEnabled, _ParaCore_instances, assertPartner_fn, toAuthInfo_fn, _servicesInitialized, assertIsLinkingAccount_fn, assertIsLinkingAccountOrStart_fn, waitForLoginProcess_fn, logout_fn;
12
12
  import { Buffer as NodeBuffer } from "buffer";
13
13
  if (typeof global !== "undefined") {
14
14
  global.Buffer = global.Buffer || NodeBuffer;
@@ -21,85 +21,63 @@ if (typeof global !== "undefined") {
21
21
  }
22
22
  import {
23
23
  AuthMethod,
24
- AuthMethodStatus,
25
- PublicKeyType,
26
24
  extractAuthInfo,
27
- isEmail,
28
- isPhone,
29
- isFarcaster,
30
- isTelegram,
31
- toPregenTypeAndId,
32
- toPregenIds,
33
- isExternalWallet,
34
25
  WALLET_TYPES,
35
26
  LINKED_ACCOUNT_TYPES,
36
- isPregenAuth
27
+ OnRampProvider
37
28
  } from "@getpara/user-management-client";
38
29
  import forge from "node-forge";
39
30
  const { pki, jsbn } = forge;
40
- import { decryptWithPrivateKey, getAsymmetricKeyPair, getPublicKeyHex } from "./cryptography/utils.js";
41
- import { getBaseOAuthUrl, initClient } from "./external/userManagementClient.js";
31
+ import { decryptWithPrivateKey, getAsymmetricKeyPair } from "./cryptography/utils.js";
32
+ import { initClient } from "./external/userManagementClient.js";
42
33
  import * as mpcComputationClient from "./external/mpcComputationClient.js";
43
- import { distributeNewShare } from "./shares/shareDistribution.js";
44
34
  import {
45
35
  Environment,
46
36
  PopupType,
47
37
  ParaEvent,
48
38
  AccountLinkError
49
39
  } from "./types/index.js";
50
- import { sendRecoveryForShare } from "./shares/recovery.js";
51
40
  import {
52
41
  autoBind,
53
42
  formatPhoneNumber,
54
- constructUrl,
55
43
  dispatchEvent,
56
- entityToWallet,
57
- getCosmosAddress,
58
- getEquivalentTypes,
59
44
  getParaConnectBaseUrl,
60
- getPortalBaseURL,
61
- getSchemes,
62
- isPregenIdentifierMatch,
63
- isWalletSupported,
64
45
  jsonParse,
65
46
  migrateWallet,
66
- newUuid,
67
47
  setupListeners,
68
- supportedWalletTypesEq,
69
- truncateAddress,
70
48
  WalletSchemeTypeMap,
71
- shortenUrl,
72
- isServerAuthState,
73
- splitPhoneNumber,
74
- currentWalletIdsEq,
75
49
  isPortal
76
50
  } from "./utils/index.js";
51
+ import { waitForAuthStateChange } from "./utils/stateListener.js";
77
52
  import { TransactionReviewDenied, TransactionReviewTimeout } from "./errors.js";
78
53
  import * as constants from "./constants.js";
79
54
  import { EnclaveClient } from "./shares/enclave.js";
55
+ import { AuthService } from "./services/AuthService.js";
56
+ import { PollingService } from "./services/PollingService.js";
57
+ import { CoreStateManager } from "./state/CoreStateManager.js";
58
+ import { WalletService } from "./services/WalletService.js";
59
+ import { PregenWalletService } from "./services/PregenWalletService.js";
60
+ import { PortalUrlService } from "./services/PortalUrlService.js";
61
+ import { SessionManagementService } from "./services/SessionManagementService.js";
62
+ import { ExternalWalletService } from "./services/ExternalWalletService.js";
80
63
  const _ParaCore = class _ParaCore {
81
64
  constructor(envOrApiKey, apiKeyOrOpts, opts) {
82
65
  __privateAdd(this, _ParaCore_instances);
66
+ __privateAdd(this, _stateManager);
67
+ __privateAdd(this, _authService);
68
+ __privateAdd(this, _walletService);
69
+ __privateAdd(this, _externalWalletService);
70
+ __privateAdd(this, _pregenWalletService);
71
+ __privateAdd(this, _pollingService);
72
+ __privateAdd(this, _portalUrlService);
73
+ __privateAdd(this, _sessionManagementService);
74
+ __privateAdd(this, _debugLogsEnabled);
83
75
  this.popupWindow = null;
84
- __privateAdd(this, _authInfo);
85
76
  this.isSwitchingWallets = false;
86
77
  this.isNativePasskey = false;
87
- this.isReady = false;
78
+ this.isSetup = false;
88
79
  this.accountLinkInProgress = void 0;
89
- this.isEnclaveUser = false;
90
- this.isAwaitingAccountCreation = false;
91
- this.isAwaitingLogin = false;
92
- this.isAwaitingFarcaster = false;
93
- this.isAwaitingOAuth = false;
94
80
  this.isWorkerInitialized = false;
95
- /**
96
- * The IDs of the currently active wallets, for each supported wallet type. Any signer integrations will default to the first viable wallet ID in this dictionary.
97
- */
98
- this.currentWalletIds = {};
99
- /**
100
- * Wallets associated with the `ParaCore` instance.
101
- */
102
- this.externalWallets = {};
103
81
  this.onRampPopup = void 0;
104
82
  this.nonPersistedStorageKeys = [];
105
83
  this.localStorageGetItem = (key) => {
@@ -133,7 +111,8 @@ const _ParaCore = class _ParaCore {
133
111
  return this.platformUtils.sessionStorage.removeItem(key);
134
112
  };
135
113
  this.retrieveSessionCookie = () => {
136
- return this.sessionCookie;
114
+ var _a;
115
+ return (_a = __privateGet(this, _sessionManagementService)) == null ? void 0 : _a.sessionCookie;
137
116
  };
138
117
  this.retrieveEnclaveJwt = () => {
139
118
  return this.enclaveJwt;
@@ -160,6 +139,10 @@ const _ParaCore = class _ParaCore {
160
139
  yield this.platformUtils.secureStorage.clear(constants.PARA_PREFIX);
161
140
  }
162
141
  });
142
+ __privateAdd(this, _servicesInitialized, false);
143
+ this.initExternalWalletProvider = (params) => __async(this, null, function* () {
144
+ yield __privateGet(this, _externalWalletService).initExternalWalletProvider(params);
145
+ });
163
146
  this.trackError = (methodName, err) => __async(this, null, function* () {
164
147
  try {
165
148
  yield this.ctx.client.trackError({
@@ -218,7 +201,7 @@ const _ParaCore = class _ParaCore {
218
201
  };
219
202
  authInfo = __privateMethod(this, _ParaCore_instances, toAuthInfo_fn).call(this, authParams);
220
203
  }
221
- __privateSet(this, _authInfo, authInfo);
204
+ __privateGet(this, _authService).authInfo = authInfo;
222
205
  };
223
206
  this.updateEnclaveJwtFromStorage = () => {
224
207
  this.enclaveJwt = this.localStorageGetItem(constants.LOCAL_STORAGE_ENCLAVE_JWT) || this.sessionStorageGetItem(constants.LOCAL_STORAGE_ENCLAVE_JWT) || void 0;
@@ -231,7 +214,7 @@ const _ParaCore = class _ParaCore {
231
214
  }
232
215
  };
233
216
  this.updateUserIdFromStorage = () => {
234
- this.userId = this.localStorageGetItem(constants.LOCAL_STORAGE_USER_ID) || void 0;
217
+ __privateGet(this, _authService).userId = this.localStorageGetItem(constants.LOCAL_STORAGE_USER_ID) || void 0;
235
218
  };
236
219
  this.updateWalletsFromStorage = () => __async(this, null, function* () {
237
220
  var _a;
@@ -272,12 +255,13 @@ const _ParaCore = class _ParaCore {
272
255
  }, {}) : fromJson;
273
256
  })();
274
257
  this.setCurrentWalletIds(currentWalletIds);
275
- if (Object.values(this.wallets).filter((w) => this.isWalletOwned(w)).length > 0 && this.currentWalletIdsArray.length === 0) {
258
+ if (Object.values(this.wallets).filter((w) => __privateGet(this, _walletService).isWalletOwned(w)).length > 0 && this.currentWalletIdsArray.length === 0) {
276
259
  this.findWalletId(void 0, { forbidPregen: true });
277
260
  }
278
261
  };
279
262
  this.updateSessionCookieFromStorage = () => {
280
- this.sessionCookie = this.localStorageGetItem(constants.LOCAL_STORAGE_SESSION_COOKIE) || this.sessionStorageGetItem(constants.LOCAL_STORAGE_SESSION_COOKIE) || void 0;
263
+ __privateGet(this, _sessionManagementService).sessionCookie = this.localStorageGetItem(constants.LOCAL_STORAGE_SESSION_COOKIE) || this.sessionStorageGetItem(constants.LOCAL_STORAGE_SESSION_COOKIE) || void 0;
264
+ __privateGet(this, _sessionManagementService).isImportedSession = this.localStorageGetItem(constants.LOCAL_STORAGE_IS_IMPORTED_SESSION) === "true" || false;
281
265
  };
282
266
  this.updateLoginEncryptionKeyPairFromStorage = () => {
283
267
  const loginEncryptionKey = this.sessionStorageGetItem(constants.SESSION_STORAGE_LOGIN_ENCRYPTION_KEY_PAIR);
@@ -300,6 +284,25 @@ const _ParaCore = class _ParaCore {
300
284
  }
301
285
  }
302
286
  });
287
+ this.setCurrentWalletIds = (...params) => __async(this, null, function* () {
288
+ const [currentWalletIds, { needsWallet = false, sessionLookupId, newDeviceSessionLookupId } = {}] = params;
289
+ return yield __privateGet(this, _walletService).setCurrentWalletIds(currentWalletIds, {
290
+ needsWallet,
291
+ sessionLookupId,
292
+ newDeviceSessionLookupId
293
+ });
294
+ });
295
+ /**
296
+ * Validates that a wallet ID is present on the instance, usable, and matches the desired filters.
297
+ * If no ID is passed, this will instead return the first valid, usable wallet ID that matches the filters.
298
+ * @param {string} [walletId] the wallet ID to validate.
299
+ * @param {WalletFilters} [filter={}] a `WalletFilters` object specifying allowed types, schemes, and whether to forbid unclaimed pregen wallets.
300
+ * @returns {string} the wallet ID originally passed, or the one found.
301
+ */
302
+ this.findWalletId = (...params) => {
303
+ const [walletId, filters = {}] = params;
304
+ return __privateGet(this, _walletService).findWalletId(walletId, filters);
305
+ };
303
306
  /**
304
307
  * Creates several new wallets with the desired types. If no types are provided, this method
305
308
  * will create one for each of the non-optional types specified in the instance's `supportedWalletTypes`
@@ -309,12 +312,8 @@ const _ParaCore = class _ParaCore {
309
312
  * @deprecated alias for `createWalletPerType`
310
313
  **/
311
314
  this.createWalletPerMissingType = this.createWalletPerType;
312
- __privateAdd(this, _isCreateGuestWalletsPending, false);
313
- this.getWalletBalance = (_0) => __async(this, [_0], function* ({
314
- walletId,
315
- rpcUrl
316
- }) {
317
- return (yield this.ctx.client.getWalletBalance({ walletId, rpcUrl })).balance;
315
+ this.addCredential = (params) => __async(this, null, function* () {
316
+ return yield __privateGet(this, _authService).addCredential(params);
318
317
  });
319
318
  let env, apiKey;
320
319
  const actualArgs = Array.from(arguments).filter((arg) => arg !== void 0);
@@ -345,6 +344,7 @@ const _ParaCore = class _ParaCore {
345
344
  apiKey = apiKeyOrOpts;
346
345
  }
347
346
  if (!opts) opts = {};
347
+ __privateSet(this, _debugLogsEnabled, !!opts.enableDebugLogs);
348
348
  let isE2E = false;
349
349
  if (env === "E2E") {
350
350
  isE2E = true;
@@ -379,7 +379,7 @@ const _ParaCore = class _ParaCore {
379
379
  this.localStorageSetItem = this.sessionStorageSetItem;
380
380
  }
381
381
  this.persistSessionCookie = (cookie) => {
382
- this.sessionCookie = cookie;
382
+ __privateGet(this, _sessionManagementService).sessionCookie = cookie;
383
383
  (opts.useSessionStorage ? this.sessionStorageSetItem : this.localStorageSetItem)(
384
384
  constants.LOCAL_STORAGE_SESSION_COOKIE,
385
385
  cookie
@@ -434,6 +434,7 @@ const _ParaCore = class _ParaCore {
434
434
  if (!this.platformUtils.isSyncStorage || opts.useStorageOverrides) {
435
435
  return;
436
436
  }
437
+ this.initializeServices();
437
438
  this.initializeFromStorage();
438
439
  setupListeners.bind(this)();
439
440
  autoBind(this);
@@ -453,71 +454,183 @@ const _ParaCore = class _ParaCore {
453
454
  "signTransaction"
454
455
  ]);
455
456
  }
457
+ __privateGet(this, _stateManager).start();
456
458
  }
457
459
  setModalError(_error) {
458
460
  return;
459
461
  }
462
+ /**
463
+ * The current readiness state.
464
+ */
465
+ get isReady() {
466
+ return __privateGet(this, _stateManager).getSnapshot().isReady;
467
+ }
468
+ /**
469
+ * The current phase of the core flow.
470
+ */
471
+ get corePhase() {
472
+ return __privateGet(this, _stateManager).getSnapshot().phase;
473
+ }
474
+ /**
475
+ * The current phase of the authentication flow.
476
+ */
477
+ get authPhase() {
478
+ return __privateGet(this, _stateManager).getSnapshot().authStatePhase;
479
+ }
480
+ /**
481
+ * The current phase of the wallet flow.
482
+ */
483
+ get walletPhase() {
484
+ return __privateGet(this, _stateManager).getSnapshot().walletStatePhase;
485
+ }
486
+ /**
487
+ * Any error that has occurred in the core flow.
488
+ */
489
+ get error() {
490
+ return __privateGet(this, _stateManager).getSnapshot().error;
491
+ }
492
+ /**
493
+ * Get the current state of the core, auth, and wallet phases.
494
+ * @returns An object containing the current core, auth, and wallet state phases, along with any error.
495
+ */
496
+ getCurrentState() {
497
+ const state = __privateGet(this, _stateManager).getSnapshot();
498
+ return {
499
+ corePhase: state.phase,
500
+ authPhase: state.authStatePhase,
501
+ walletPhase: state.walletStatePhase,
502
+ authStateInfo: state.authStateInfo,
503
+ error: state.error,
504
+ isReady: state.isReady
505
+ };
506
+ }
507
+ /**
508
+ * Subscribe to changes in the core, auth, and wallet state phases.
509
+ *
510
+ * This method immediately calls the callback with the current state, then continues
511
+ * to call it whenever any phase changes. This ensures you never miss the initial state
512
+ * and can react to all subsequent changes.
513
+ *
514
+ * @param callback A function that will be called with the current state phases whenever they change.
515
+ * The callback receives an object containing `corePhase`, `authPhase`, `walletPhase`, and `error`.
516
+ *
517
+ * @returns A function that can be called to unsubscribe from the state changes.
518
+ * Always call this function when your component unmounts or when you no longer need updates
519
+ * to prevent memory leaks.
520
+ *
521
+ * @example
522
+ * ```typescript
523
+ * // React example
524
+ * useEffect(() => {
525
+ * const unsubscribe = paraClient.onStatePhaseChange((snapshot) => {
526
+ * console.log('Core phase:', snapshot.corePhase);
527
+ * console.log('Auth phase:', snapshot.authPhase);
528
+ * console.log('Wallet phase:', snapshot.walletPhase);
529
+ *
530
+ * if (snapshot.error) {
531
+ * console.error('Para error:', snapshot.error.message);
532
+ * }
533
+ * });
534
+ *
535
+ * return unsubscribe; // Cleanup on unmount
536
+ * }, [paraClient]);
537
+ *
538
+ * // Vue example
539
+ * onMounted(() => {
540
+ * const unsubscribe = paraClient.onStatePhaseChange((state) => {
541
+ * phases.value = state;
542
+ * });
543
+ *
544
+ * onUnmounted(unsubscribe);
545
+ * });
546
+ * ```
547
+ */
548
+ onStatePhaseChange(callback) {
549
+ let lastSnapshot = null;
550
+ const fullListener = (state) => {
551
+ const currentSnapshot = {
552
+ corePhase: state.phase,
553
+ authPhase: state.authStatePhase,
554
+ walletPhase: state.walletStatePhase,
555
+ authStateInfo: state.authStateInfo,
556
+ error: state.error,
557
+ isReady: state.isReady
558
+ };
559
+ if (!lastSnapshot || lastSnapshot.corePhase !== currentSnapshot.corePhase || lastSnapshot.authPhase !== currentSnapshot.authPhase || lastSnapshot.walletPhase !== currentSnapshot.walletPhase || lastSnapshot.error !== currentSnapshot.error || lastSnapshot.isReady !== currentSnapshot.isReady) {
560
+ lastSnapshot = currentSnapshot;
561
+ callback(currentSnapshot);
562
+ }
563
+ };
564
+ return __privateGet(this, _stateManager).onStateChange(fullListener);
565
+ }
566
+ /**
567
+ * Subscribe to changes in the readiness state of the ParaCore instance.
568
+ * @param callback A function that will be called with the new readiness state.
569
+ * @returns A function that can be called to unsubscribe from the readiness state changes.
570
+ */
571
+ onReadyStateChange(callback) {
572
+ let lastIsReady = null;
573
+ const unsubscribe = __privateGet(this, _stateManager).onStateChange((state) => {
574
+ if (lastIsReady !== state.isReady) {
575
+ lastIsReady = state.isReady;
576
+ callback(state.isReady);
577
+ }
578
+ });
579
+ return () => unsubscribe();
580
+ }
460
581
  get authInfo() {
461
- return __privateGet(this, _authInfo);
582
+ var _a;
583
+ return (_a = __privateGet(this, _authService)) == null ? void 0 : _a.authInfo;
462
584
  }
463
585
  get email() {
464
586
  var _a;
465
- return isEmail((_a = __privateGet(this, _authInfo)) == null ? void 0 : _a.auth) ? __privateGet(this, _authInfo).auth.email : void 0;
587
+ return (_a = __privateGet(this, _authService)) == null ? void 0 : _a.email;
466
588
  }
467
589
  get phone() {
468
590
  var _a;
469
- return isPhone((_a = __privateGet(this, _authInfo)) == null ? void 0 : _a.auth) ? __privateGet(this, _authInfo).auth.phone : void 0;
591
+ return (_a = __privateGet(this, _authService)) == null ? void 0 : _a.phone;
470
592
  }
471
593
  get farcasterUsername() {
472
594
  var _a;
473
- return isFarcaster((_a = __privateGet(this, _authInfo)) == null ? void 0 : _a.auth) ? __privateGet(this, _authInfo).auth.farcasterUsername : void 0;
595
+ return (_a = __privateGet(this, _authService)) == null ? void 0 : _a.farcasterUsername;
474
596
  }
475
597
  get telegramUserId() {
476
598
  var _a;
477
- return isTelegram((_a = __privateGet(this, _authInfo)) == null ? void 0 : _a.auth) ? __privateGet(this, _authInfo).auth.telegramUserId : void 0;
599
+ return (_a = __privateGet(this, _authService)) == null ? void 0 : _a.telegramUserId;
478
600
  }
479
601
  get externalWalletWithParaAuth() {
480
- const externalWallets = Object.values(this.externalWallets);
481
- return externalWallets.find((w) => w.isExternalWithParaAuth);
602
+ return __privateGet(this, _externalWalletService).externalWalletWithParaAuth;
482
603
  }
483
604
  get externalWalletConnectionType() {
484
- if (this.isExternalWalletAuth) {
485
- return "AUTHENTICATED";
486
- } else if (this.isExternalWalletWithVerification) {
487
- return "VERIFICATION";
488
- } else if (!!Object.keys(this.externalWallets).length) {
489
- const hasEmbeddedWallets = Object.keys(this.wallets).some((id) => !this.wallets[id].isExternal);
490
- if (hasEmbeddedWallets) {
491
- return "NONE";
492
- } else {
493
- return "CONNECTION_ONLY";
494
- }
495
- }
496
- return "NONE";
605
+ return __privateGet(this, _externalWalletService).externalWalletConnectionType;
497
606
  }
498
- get isEmail() {
607
+ get userId() {
499
608
  var _a;
500
- return isEmail((_a = this.authInfo) == null ? void 0 : _a.auth);
609
+ return (_a = __privateGet(this, _authService)) == null ? void 0 : _a.userId;
610
+ }
611
+ get isEnclaveUser() {
612
+ return __privateGet(this, _authService).isEnclaveUser;
613
+ }
614
+ set isEnclaveUser(value) {
615
+ __privateGet(this, _authService).isEnclaveUser = value;
616
+ }
617
+ get isEmail() {
618
+ return __privateGet(this, _authService).isEmail;
501
619
  }
502
620
  get isPhone() {
503
- var _a;
504
- return isPhone((_a = this.authInfo) == null ? void 0 : _a.auth);
621
+ return __privateGet(this, _authService).isPhone;
505
622
  }
506
623
  get isFarcaster() {
507
- var _a;
508
- return isFarcaster((_a = this.authInfo) == null ? void 0 : _a.auth);
624
+ return __privateGet(this, _authService).isFarcaster;
509
625
  }
510
626
  get isTelegram() {
511
- var _a;
512
- return isTelegram((_a = this.authInfo) == null ? void 0 : _a.auth);
627
+ return __privateGet(this, _authService).isTelegram;
513
628
  }
514
629
  get isExternalWalletAuth() {
515
- var _a, _b, _c;
516
- 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);
630
+ return __privateGet(this, _authService).isExternalWalletAuth;
517
631
  }
518
632
  get isExternalWalletWithVerification() {
519
- var _a, _b, _c;
520
- 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);
633
+ return __privateGet(this, _authService).isExternalWalletWithVerification;
521
634
  }
522
635
  get partnerId() {
523
636
  var _a;
@@ -531,45 +644,42 @@ const _ParaCore = class _ParaCore {
531
644
  var _a;
532
645
  return (_a = this.partner) == null ? void 0 : _a.logoUrl;
533
646
  }
647
+ get currentWalletIds() {
648
+ return __privateGet(this, _walletService).currentWalletIds;
649
+ }
534
650
  get currentWalletIdsArray() {
535
- var _a, _b;
536
- return ((_b = (_a = this.partner) == null ? void 0 : _a.supportedWalletTypes) != null ? _b : Object.keys(this.currentWalletIds).map((type) => ({ type }))).reduce(
537
- (acc, { type }) => {
538
- var _a2;
539
- return [
540
- ...acc,
541
- ...((_a2 = this.currentWalletIds[type]) != null ? _a2 : []).map((id) => {
542
- return [id, type];
543
- })
544
- ];
545
- },
546
- []
547
- );
651
+ return __privateGet(this, _walletService).currentWalletIdsArray;
548
652
  }
549
653
  get currentWalletIdsUnique() {
550
- return [...new Set(Object.values(this.currentWalletIds).flat())];
654
+ return __privateGet(this, _walletService).currentWalletIdsUnique;
655
+ }
656
+ /**
657
+ * Wallets associated with the `ParaCore` instance. Retrieve a particular wallet using `para.wallets[walletId]`.
658
+ */
659
+ get wallets() {
660
+ var _a;
661
+ return (_a = __privateGet(this, _walletService)) == null ? void 0 : _a.wallets;
662
+ }
663
+ /**
664
+ * Wallets associated with the `ParaCore` instance.
665
+ */
666
+ get externalWallets() {
667
+ var _a;
668
+ return (_a = __privateGet(this, _externalWalletService)) == null ? void 0 : _a.externalWallets;
551
669
  }
552
670
  /**
553
671
  * A map of pre-generated wallet identifiers that can be claimed in the current instance.
554
672
  */
555
673
  get pregenIds() {
556
- return __spreadValues({}, Object.values(this.wallets).filter((wallet) => !this.userId || this.isPregenWalletClaimable(wallet)).reduce((acc, wallet) => {
557
- var _a, _b;
558
- if (((_a = acc[wallet.pregenIdentifierType]) != null ? _a : []).includes(wallet.pregenIdentifier)) {
559
- return acc;
560
- }
561
- return __spreadProps(__spreadValues({}, acc), {
562
- [wallet.pregenIdentifierType]: [
563
- .../* @__PURE__ */ new Set([...(_b = acc[wallet.pregenIdentifierType]) != null ? _b : [], wallet.pregenIdentifier])
564
- ]
565
- });
566
- }, {}));
674
+ var _a;
675
+ return (_a = __privateGet(this, _pregenWalletService)) == null ? void 0 : _a.pregenIds;
567
676
  }
568
677
  /**
569
678
  * Whether the instance has multiple wallets connected.
570
679
  */
571
680
  get isMultiWallet() {
572
- return this.currentWalletIdsArray.length > 1 || __privateGet(this, _ParaCore_instances, guestWalletIdsArray_get).length > 1;
681
+ var _a;
682
+ return this.currentWalletIdsArray.length > 1 || ((_a = __privateGet(this, _pregenWalletService)) == null ? void 0 : _a.guestWalletIdsArray.length) > 1;
573
683
  }
574
684
  get isNoWalletConfig() {
575
685
  var _a;
@@ -634,60 +744,6 @@ const _ParaCore = class _ParaCore {
634
744
  );
635
745
  }
636
746
  }
637
- isWalletSupported(wallet) {
638
- var _a, _b;
639
- return !((_a = this.partner) == null ? void 0 : _a.supportedWalletTypes) || isWalletSupported((_b = this.partner.supportedWalletTypes.map(({ type }) => type)) != null ? _b : [], wallet);
640
- }
641
- isWalletOwned(wallet) {
642
- 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;
643
- }
644
- isPregenWalletUnclaimed(wallet) {
645
- return this.isWalletSupported(wallet) && (!(wallet == null ? void 0 : wallet.userId) || (wallet == null ? void 0 : wallet.isPregen) && !!(wallet == null ? void 0 : wallet.pregenIdentifier) && !!(wallet == null ? void 0 : wallet.pregenIdentifierType));
646
- }
647
- isPregenWalletClaimable(wallet) {
648
- return this.isWalletSupported(wallet) && this.isPregenWalletUnclaimed(wallet) && (!["EMAIL", "PHONE", "TELEGRAM"].includes(wallet == null ? void 0 : wallet.pregenIdentifierType) || isPregenIdentifierMatch(
649
- (wallet == null ? void 0 : wallet.pregenIdentifierType) === "EMAIL" ? this.email : (wallet == null ? void 0 : wallet.pregenIdentifierType) === "TELEGRAM" ? this.telegramUserId : this.getPhoneNumber(),
650
- wallet == null ? void 0 : wallet.pregenIdentifier,
651
- wallet == null ? void 0 : wallet.pregenIdentifierType
652
- ));
653
- }
654
- isWalletUsable(walletId, { type: types, scheme: schemes, forbidPregen = false } = {}, throwError = false) {
655
- var _a, _b;
656
- let error;
657
- if ((_a = this.externalWallets) == null ? void 0 : _a[walletId]) {
658
- return true;
659
- }
660
- if (!this.wallets[walletId]) {
661
- error = `wallet with id ${walletId} does not exist`;
662
- } else {
663
- const wallet = this.wallets[walletId];
664
- const [isUnclaimed, isOwned] = [this.isPregenWalletUnclaimed(wallet), this.isWalletOwned(wallet)];
665
- if (forbidPregen && isUnclaimed && wallet.pregenIdentifierType !== "GUEST_ID") {
666
- error = `pre-generated wallet with id ${wallet == null ? void 0 : wallet.id} cannot be selected`;
667
- } else if (!isOwned && !isUnclaimed) {
668
- error = `wallet with id ${wallet == null ? void 0 : wallet.id} is not owned by the current user`;
669
- } else if (!this.isWalletSupported(wallet)) {
670
- 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(", ")}`;
671
- } else if (types && (!getEquivalentTypes(types).includes(wallet == null ? void 0 : wallet.type) || isOwned && !types.some((type) => {
672
- var _a2, _b2;
673
- return (_b2 = (_a2 = this.currentWalletIds) == null ? void 0 : _a2[type]) == null ? void 0 : _b2.includes(walletId);
674
- }))) {
675
- error = `wallet with id ${wallet == null ? void 0 : wallet.id} and type ${wallet == null ? void 0 : wallet.type} cannot be selected`;
676
- } else if (schemes && !schemes.includes(wallet == null ? void 0 : wallet.scheme)) {
677
- error = `wallet with id ${wallet == null ? void 0 : wallet.id} and scheme ${wallet == null ? void 0 : wallet.scheme} cannot be selected`;
678
- }
679
- }
680
- if (error) {
681
- if (throwError) {
682
- throw new Error(error);
683
- }
684
- return false;
685
- }
686
- return true;
687
- }
688
- truncateAddress(...args) {
689
- return truncateAddress(args[0], args[1], __spreadValues({ prefix: this.cosmosPrefix }, args[2] || {}));
690
- }
691
747
  /**
692
748
  * Returns the formatted address for the desired wallet ID, depending on your app settings.
693
749
  * @param {string} walletId the ID of the wallet address to display.
@@ -696,32 +752,9 @@ const _ParaCore = class _ParaCore {
696
752
  * @param {TWalletType} options.addressType the type of address to display.
697
753
  * @returns the formatted address
698
754
  */
699
- getDisplayAddress(walletId, options = {}) {
700
- var _a, _b, _c, _d;
701
- if (this.externalWallets[walletId]) {
702
- const wallet2 = this.externalWallets[walletId];
703
- return options.truncate ? truncateAddress(wallet2.address, wallet2.type, {
704
- prefix: (_a = this.partner) == null ? void 0 : _a.cosmosPrefix,
705
- targetLength: options.targetLength
706
- }) : wallet2.address;
707
- }
708
- const wallet = this.findWallet(walletId, options.addressType);
709
- if (!wallet) {
710
- return void 0;
711
- }
712
- let str;
713
- let prefix;
714
- switch (wallet.type) {
715
- case "COSMOS":
716
- prefix = (_d = (_c = options.cosmosPrefix) != null ? _c : (_b = this.partner) == null ? void 0 : _b.cosmosPrefix) != null ? _d : "cosmos";
717
- str = getCosmosAddress(wallet.publicKey, prefix);
718
- break;
719
- default:
720
- prefix = this.cosmosPrefix;
721
- str = wallet.address;
722
- break;
723
- }
724
- return options.truncate ? truncateAddress(str, wallet.type, { prefix, targetLength: options.targetLength }) : str;
755
+ getDisplayAddress(...params) {
756
+ const [walletId, options = {}] = params;
757
+ return __privateGet(this, _walletService).getDisplayAddress(walletId, options);
725
758
  }
726
759
  /**
727
760
  * Returns a unique hash for a wallet suitable for use as an identicon seed.
@@ -729,13 +762,8 @@ const _ParaCore = class _ParaCore {
729
762
  * @param {boolean} options.addressType used to format the hash for another wallet type.
730
763
  * @returns the identicon hash string
731
764
  */
732
- getIdenticonHash(walletId, overrideType) {
733
- if (this.externalWallets[walletId]) {
734
- const wallet2 = this.externalWallets[walletId];
735
- return `${wallet2.id}-${wallet2.address}-${wallet2.type}`;
736
- }
737
- const wallet = this.findWallet(walletId, overrideType);
738
- return wallet ? `${wallet.id}-${wallet.address}-${wallet.type}` : void 0;
765
+ getIdenticonHash(...params) {
766
+ return __privateGet(this, _walletService).getIdenticonHash(...params);
739
767
  }
740
768
  getWallets() {
741
769
  return this.wallets;
@@ -746,192 +774,7 @@ const _ParaCore = class _ParaCore {
746
774
  }
747
775
  constructPortalUrl(_0) {
748
776
  return __async(this, arguments, function* (type, opts = {}) {
749
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
750
- const [
751
- isCreate,
752
- isLogin,
753
- isOnRamp,
754
- isOAuth,
755
- isOAuthCallback,
756
- isTelegramLogin,
757
- isFarcasterLogin,
758
- isAddNewCredential,
759
- isSwitchWallets,
760
- isExportPrivateKey,
761
- isTxReview
762
- ] = [
763
- ["createAuth", "createPassword", "createPIN"].includes(type),
764
- ["loginAuth", "loginPassword", "loginPIN", "loginOTP", "switchWallets", "loginExternalWallet"].includes(type),
765
- type === "onRamp",
766
- type === "oAuth",
767
- type === "oAuthCallback",
768
- ["telegramLogin", "telegramLoginVerify"].includes(type),
769
- type === "loginFarcaster",
770
- type === "addNewCredential",
771
- type === "switchWallets",
772
- type === "exportPrivateKey",
773
- type === "txReview"
774
- ];
775
- if (isOAuth && !opts.oAuthMethod) {
776
- throw new Error("oAuthMethod is required for oAuth portal URLs");
777
- }
778
- if (isCreate || isLogin) {
779
- this.assertIsAuthSet();
780
- }
781
- let sessionId = opts.sessionId;
782
- if ((isLogin || isOnRamp || isTelegramLogin || isFarcasterLogin || isExportPrivateKey || isTxReview) && !sessionId) {
783
- let session = yield this.touchSession(false);
784
- if (!session.sessionId) {
785
- session = yield this.touchSession(true);
786
- }
787
- sessionId = session.sessionId;
788
- }
789
- if (!this.loginEncryptionKeyPair) {
790
- yield this.setLoginEncryptionKeyPair();
791
- }
792
- const shouldUseLegacyPortalUrl = opts.useLegacyUrl || !!opts.addNewCredentialPasskeyId || type === "loginAuth";
793
- const base = type === "onRamp" || isTelegramLogin ? this.ctx.portalUrlOverride || getPortalBaseURL(this.ctx, isTelegramLogin, false, shouldUseLegacyPortalUrl) : yield this.getPortalURL(shouldUseLegacyPortalUrl);
794
- let path;
795
- switch (type) {
796
- case "createPassword": {
797
- path = `/web/users/${this.userId}/passwords/${opts.pathId}`;
798
- break;
799
- }
800
- case "createPIN": {
801
- path = `/web/users/${this.userId}/pin/${opts.pathId}`;
802
- break;
803
- }
804
- case "createAuth": {
805
- path = `/web/users/${this.userId}/biometrics/${opts.pathId}`;
806
- break;
807
- }
808
- case "loginPassword": {
809
- path = "/web/passwords/login";
810
- break;
811
- }
812
- case "loginAuth": {
813
- path = "/web/biometrics/login";
814
- break;
815
- }
816
- case "loginPIN": {
817
- path = "/web/pin/login";
818
- break;
819
- }
820
- case "txReview": {
821
- path = `/web/users/${this.userId}/transaction-review/${opts.pathId}`;
822
- break;
823
- }
824
- case "onRamp": {
825
- path = `/web/users/${this.userId}/on-ramp-transaction/v2/${opts.pathId}`;
826
- break;
827
- }
828
- case "telegramLoginVerify": {
829
- path = `/auth/telegram/verify`;
830
- break;
831
- }
832
- case "telegramLogin": {
833
- path = `/auth/telegram`;
834
- break;
835
- }
836
- case "oAuth": {
837
- path = `/auth/${opts.oAuthMethod.toLowerCase()}`;
838
- break;
839
- }
840
- case "oAuthCallback": {
841
- path = `/auth/${opts.oAuthMethod.toLowerCase()}/callback`;
842
- break;
843
- }
844
- case "loginOTP": {
845
- path = "/auth/otp";
846
- break;
847
- }
848
- case "loginFarcaster": {
849
- path = "/auth/farcaster";
850
- break;
851
- }
852
- case "switchWallets": {
853
- path = `/auth/wallets`;
854
- break;
855
- }
856
- case "addNewCredential": {
857
- path = "/auth/add-new-credential";
858
- break;
859
- }
860
- case "exportPrivateKey": {
861
- path = `/web/users/${this.userId}/private-key/${opts.pathId}`;
862
- break;
863
- }
864
- case "loginExternalWallet": {
865
- path = "/auth/external-wallet";
866
- break;
867
- }
868
- case "connectExternalWallet": {
869
- path = "/auth/connect-external-wallet";
870
- break;
871
- }
872
- default: {
873
- throw new Error(`invalid URL type ${type}`);
874
- }
875
- }
876
- let partner = void 0;
877
- try {
878
- partner = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
879
- } catch (e) {
880
- if (this.isPartnerOptional) {
881
- partner = void 0;
882
- } else {
883
- throw e;
884
- }
885
- }
886
- const thisDevice = (_a = opts.thisDevice) != null ? _a : {
887
- encryptionKey: getPublicKeyHex(this.loginEncryptionKeyPair),
888
- sessionId
889
- };
890
- const params = __spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadValues(__spreadProps(__spreadValues({
891
- apiKey: this.ctx.apiKey,
892
- origin: typeof window !== "undefined" ? window.location.origin : void 0,
893
- partnerId: partner == null ? void 0 : partner.id
894
- }, typeof window !== "undefined" && ((_b = window.location) == null ? void 0 : _b.origin) ? { origin: window.location.origin } : {}), {
895
- portalFont: ((_c = opts.portalTheme) == null ? void 0 : _c.font) || ((_d = this.portalTheme) == null ? void 0 : _d.font) || (partner == null ? void 0 : partner.font),
896
- portalBorderRadius: ((_e = opts.portalTheme) == null ? void 0 : _e.borderRadius) || ((_f = this.portalTheme) == null ? void 0 : _f.borderRadius),
897
- portalThemeMode: ((_g = opts.portalTheme) == null ? void 0 : _g.mode) || ((_h = this.portalTheme) == null ? void 0 : _h.mode) || (partner == null ? void 0 : partner.themeMode),
898
- portalAccentColor: ((_i = opts.portalTheme) == null ? void 0 : _i.accentColor) || ((_j = this.portalTheme) == null ? void 0 : _j.accentColor) || (partner == null ? void 0 : partner.accentColor),
899
- portalForegroundColor: ((_k = opts.portalTheme) == null ? void 0 : _k.foregroundColor) || ((_l = this.portalTheme) == null ? void 0 : _l.foregroundColor) || (partner == null ? void 0 : partner.foregroundColor),
900
- portalBackgroundColor: ((_m = opts.portalTheme) == null ? void 0 : _m.backgroundColor) || ((_n = this.portalTheme) == null ? void 0 : _n.backgroundColor) || (partner == null ? void 0 : partner.backgroundColor) || this.portalBackgroundColor,
901
- portalPrimaryButtonColor: this.portalPrimaryButtonColor,
902
- portalTextColor: this.portalTextColor,
903
- portalPrimaryButtonTextColor: this.portalPrimaryButtonTextColor,
904
- isForNewDevice: opts.isForNewDevice ? opts.isForNewDevice.toString() : void 0
905
- }), this.authInfo && (isCreate || isLogin || isAddNewCredential || isOAuthCallback || isSwitchWallets || isExportPrivateKey || isTxReview) ? __spreadProps(__spreadValues({
906
- authInfo: JSON.stringify(this.authInfo)
907
- }, isPhone(this.authInfo.auth) ? splitPhoneNumber(this.authInfo.auth.phone) : this.authInfo.auth), {
908
- pfpUrl: this.authInfo.pfpUrl,
909
- displayName: this.authInfo.displayName,
910
- userId: this.userId
911
- }) : {}), isOnRamp ? { email: this.email } : {}), isLogin || isOAuth || isOAuthCallback || isTelegramLogin || isFarcasterLogin || isAddNewCredential ? __spreadProps(__spreadValues({
912
- sessionId: thisDevice.sessionId,
913
- encryptionKey: thisDevice.encryptionKey
914
- }, opts.newDevice ? {
915
- newDeviceSessionLookupId: opts.newDevice.sessionId,
916
- newDeviceEncryptionKey: opts.newDevice.encryptionKey
917
- } : {}), {
918
- pregenIds: JSON.stringify(this.pregenIds)
919
- }) : {}), isOAuth || isOAuthCallback || isFarcasterLogin ? {
920
- appScheme: opts.appScheme
921
- } : {}), isTelegramLogin ? { isEmbed: "true" } : {}), isSwitchWallets ? __spreadValues(__spreadValues({}, this.currentWalletIds ? { currentWalletIds: JSON.stringify(this.currentWalletIds) } : {}), this.userId ? { userId: this.userId } : {}) : {}), opts.params || {}), isAddNewCredential ? __spreadProps(__spreadValues({}, opts.addNewCredentialType && { addNewCredentialType: opts.addNewCredentialType.toString() }), {
922
- addNewCredentialPasskeyId: opts.addNewCredentialPasskeyId,
923
- addNewCredentialPasswordId: opts.addNewCredentialPasswordId
924
- }) : {}), isLogin && {
925
- // Prior versions won't have this param which will skip the upgrade prompt
926
- isBasicLoginUpgradeVersion: "true"
927
- }), isExportPrivateKey || isTxReview ? {
928
- sessionId: thisDevice.sessionId
929
- } : {});
930
- const url = constructUrl({ base, path, params });
931
- if (opts.shorten) {
932
- return yield shortenUrl(this.ctx, url, shouldUseLegacyPortalUrl);
933
- }
934
- return url;
777
+ return yield __privateGet(this, _portalUrlService).constructPortalUrl(type, opts);
935
778
  });
936
779
  }
937
780
  static resolveEnvironment(env, apiKey) {
@@ -953,58 +796,239 @@ const _ParaCore = class _ParaCore {
953
796
  }
954
797
  return env;
955
798
  }
956
- touchSession(regenerate = false) {
957
- return __async(this, null, function* () {
958
- var _a, _b, _c, _d, _e;
959
- if (!this.isWorkerInitialized) {
960
- this.initializeWorker();
961
- }
962
- if (!this.isReady) {
963
- yield this.ready();
799
+ initializeServices() {
800
+ if (__privateGet(this, _servicesInitialized)) return;
801
+ __privateSet(this, _authService, new AuthService(this));
802
+ __privateSet(this, _walletService, new WalletService(this));
803
+ __privateSet(this, _externalWalletService, new ExternalWalletService(this));
804
+ __privateSet(this, _pregenWalletService, new PregenWalletService(this));
805
+ __privateSet(this, _pollingService, new PollingService(this));
806
+ __privateSet(this, _portalUrlService, new PortalUrlService(this));
807
+ __privateSet(this, _sessionManagementService, new SessionManagementService(this));
808
+ __privateSet(this, _stateManager, new CoreStateManager(this));
809
+ __privateGet(this, _authService).init({
810
+ stateManager: __privateGet(this, _stateManager),
811
+ portalUrlService: __privateGet(this, _portalUrlService),
812
+ externalWalletService: __privateGet(this, _externalWalletService),
813
+ sessionManagementService: __privateGet(this, _sessionManagementService),
814
+ pregenWalletService: __privateGet(this, _pregenWalletService),
815
+ walletService: __privateGet(this, _walletService)
816
+ });
817
+ __privateGet(this, _walletService).init({
818
+ authService: __privateGet(this, _authService),
819
+ pollingService: __privateGet(this, _pollingService),
820
+ pregenWalletService: __privateGet(this, _pregenWalletService),
821
+ externalWalletService: __privateGet(this, _externalWalletService)
822
+ });
823
+ __privateGet(this, _externalWalletService).init({
824
+ stateManager: __privateGet(this, _stateManager),
825
+ authService: __privateGet(this, _authService),
826
+ walletService: __privateGet(this, _walletService)
827
+ });
828
+ __privateGet(this, _pollingService).init({
829
+ authService: __privateGet(this, _authService),
830
+ pregenWalletService: __privateGet(this, _pregenWalletService),
831
+ walletService: __privateGet(this, _walletService),
832
+ portalUrlService: __privateGet(this, _portalUrlService),
833
+ sessionManagementService: __privateGet(this, _sessionManagementService)
834
+ });
835
+ __privateGet(this, _pregenWalletService).init({
836
+ stateManager: __privateGet(this, _stateManager),
837
+ authService: __privateGet(this, _authService),
838
+ walletService: __privateGet(this, _walletService),
839
+ pollingService: __privateGet(this, _pollingService)
840
+ });
841
+ __privateGet(this, _portalUrlService).init({
842
+ authService: __privateGet(this, _authService),
843
+ walletService: __privateGet(this, _walletService),
844
+ pregenWalletService: __privateGet(this, _pregenWalletService),
845
+ sessionManagementService: __privateGet(this, _sessionManagementService)
846
+ });
847
+ __privateGet(this, _sessionManagementService).init({
848
+ authService: __privateGet(this, _authService),
849
+ portalUrlService: __privateGet(this, _portalUrlService),
850
+ walletService: __privateGet(this, _walletService),
851
+ pregenWalletService: __privateGet(this, _pregenWalletService),
852
+ externalWalletService: __privateGet(this, _externalWalletService)
853
+ });
854
+ __privateSet(this, _servicesInitialized, true);
855
+ }
856
+ // Create a dedicated interface for #authService
857
+ getAuthServiceInterface() {
858
+ const self2 = this;
859
+ return {
860
+ logout: __privateMethod(this, _ParaCore_instances, logout_fn).bind(this),
861
+ setLoginEncryptionKeyPair: this.setLoginEncryptionKeyPair.bind(this),
862
+ localStorageGetItem: this.localStorageGetItem.bind(this),
863
+ localStorageSetItem: this.localStorageSetItem.bind(this),
864
+ localStorageRemoveItem: this.localStorageRemoveItem.bind(this),
865
+ isPasskeySupported: this.isPasskeySupported.bind(this),
866
+ getVerificationEmailProps: this.getVerificationEmailProps.bind(this),
867
+ displayModalError: this.displayModalError.bind(this),
868
+ isPortal: this.isPortal.bind(this),
869
+ assertIsLinkingAccount: __privateMethod(this, _ParaCore_instances, assertIsLinkingAccount_fn).bind(this),
870
+ requireApiKey: this.requireApiKey.bind(this),
871
+ get loginEncryptionKeyPair() {
872
+ return self2.loginEncryptionKeyPair;
873
+ },
874
+ get isNativePasskey() {
875
+ return self2.isNativePasskey;
876
+ },
877
+ ctx: this.ctx,
878
+ get accountLinkInProgress() {
879
+ return self2.accountLinkInProgress;
880
+ },
881
+ partnerId: this.partnerId,
882
+ platformUtils: this.platformUtils,
883
+ externalWalletConnectionOnly: !!this.externalWalletConnectionOnly
884
+ };
885
+ }
886
+ // Create a dedicated interface for WalletService
887
+ getWalletServiceInterface() {
888
+ const self2 = this;
889
+ return {
890
+ assertPartner: __privateMethod(this, _ParaCore_instances, assertPartner_fn).bind(this),
891
+ requireApiKey: this.requireApiKey.bind(this),
892
+ isPortal: this.isPortal.bind(this),
893
+ localStorageSetItem: this.localStorageSetItem.bind(this),
894
+ getBackupKitEmailProps: this.getBackupKitEmailProps.bind(this),
895
+ retrieveSessionCookie: this.retrieveSessionCookie.bind(this),
896
+ isParaConnect: this.isParaConnect.bind(this),
897
+ ctx: this.ctx,
898
+ get partner() {
899
+ return self2.partner;
900
+ },
901
+ platformUtils: this.platformUtils,
902
+ cosmosPrefix: this.cosmosPrefix
903
+ };
904
+ }
905
+ // Create a dedicated interface for PregenWalletService
906
+ getPregenWalletServiceInterface() {
907
+ var _a;
908
+ const self2 = this;
909
+ return {
910
+ fetchPregenWalletsOverride: (_a = this.fetchPregenWalletsOverride) == null ? void 0 : _a.bind(this),
911
+ assertPartner: __privateMethod(this, _ParaCore_instances, assertPartner_fn).bind(this),
912
+ requireApiKey: this.requireApiKey.bind(this),
913
+ getBackupKitEmailProps: this.getBackupKitEmailProps.bind(this),
914
+ isPortal: this.isPortal.bind(this),
915
+ retrieveSessionCookie: this.retrieveSessionCookie.bind(this),
916
+ ctx: this.ctx,
917
+ platformUtils: this.platformUtils,
918
+ get partner() {
919
+ return self2.partner;
964
920
  }
965
- let session;
966
- try {
967
- session = yield this.ctx.client.touchSession(regenerate);
968
- } catch (error) {
969
- this.handleTouchSessionError(error);
970
- throw error;
921
+ };
922
+ }
923
+ // Create a dedicated interface for PortalUrlService
924
+ getPortalUrlServiceInterface() {
925
+ const self2 = this;
926
+ return {
927
+ assertPartner: __privateMethod(this, _ParaCore_instances, assertPartner_fn).bind(this),
928
+ setLoginEncryptionKeyPair: this.setLoginEncryptionKeyPair.bind(this),
929
+ isPortal: this.isPortal.bind(this),
930
+ isPartnerOptional: this.isPartnerOptional,
931
+ ctx: this.ctx,
932
+ get loginEncryptionKeyPair() {
933
+ return self2.loginEncryptionKeyPair;
934
+ },
935
+ get portalTheme() {
936
+ return self2.portalTheme;
937
+ },
938
+ get portalPrimaryButtonColor() {
939
+ return self2.portalPrimaryButtonColor;
940
+ },
941
+ get portalTextColor() {
942
+ return self2.portalTextColor;
943
+ },
944
+ get portalPrimaryButtonTextColor() {
945
+ return self2.portalPrimaryButtonTextColor;
946
+ },
947
+ get portalBackgroundColor() {
948
+ return self2.portalBackgroundColor;
949
+ },
950
+ get accountLinkInProgress() {
951
+ return self2.accountLinkInProgress;
971
952
  }
972
- 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) {
973
- if (!session.partnerId && !this.isPortal()) {
974
- this.displayModalError(
975
- `Invalid API Key. Please ensure you have a valid API key for the current environment: ${(_d = this.ctx.env) == null ? void 0 : _d.toUpperCase()}.`
976
- );
977
- console.error(`
978
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
979
- \u{1F6A8} PARA SDK CONFIGURATION ERROR \u{1F6A8}
980
-
981
- INVALID API KEY FOR CONFIGURED ENVIRONMENT
982
-
983
- Your API key does not match the configured environment. This usually means:
984
-
985
- 1. You're using a production API key with a development environment
986
- 2. You're using a development API key with a production environment
987
- 3. Your API key is invalid or has been regenerated
988
-
989
- SOLUTION:
990
- \u2022 Verify your API key at: https://developer.getpara.com
991
- \u2022 If your API key doesn't contain an environment prefix, ensure your API key is the correct key for your target environment
992
-
993
- Current Environment: ${this.ctx.env}
994
- API Key Prefix: ${((_e = this.ctx.apiKey) == null ? void 0 : _e.split("_")[0].toUpperCase()) || "None"}
995
-
996
- Need help? Visit: https://docs.getpara.com or contact support
997
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
998
- `);
999
- throw new Error("Invalid API Key.");
1000
- } else {
1001
- yield __privateMethod(this, _ParaCore_instances, getPartner_fn).call(this, session.partnerId);
1002
- }
953
+ };
954
+ }
955
+ // Create a dedicated interface for SessionManagementService
956
+ getSessionManagementServiceInterface() {
957
+ const self2 = this;
958
+ return {
959
+ displayModalError: this.displayModalError.bind(this),
960
+ setLoginEncryptionKeyPair: this.setLoginEncryptionKeyPair.bind(this),
961
+ initializeWorker: this.initializeWorker.bind(this),
962
+ isPortal: this.isPortal.bind(this),
963
+ getPartner: this.getPartner.bind(this),
964
+ assertPartner: __privateMethod(this, _ParaCore_instances, assertPartner_fn).bind(this),
965
+ platformUtils: this.platformUtils,
966
+ ctx: this.ctx,
967
+ get loginEncryptionKeyPair() {
968
+ return self2.loginEncryptionKeyPair;
969
+ },
970
+ get partner() {
971
+ return self2.partner;
972
+ },
973
+ get isWorkerInitialized() {
974
+ return self2.isWorkerInitialized;
975
+ },
976
+ get isReady() {
977
+ return self2.isReady;
978
+ },
979
+ isNoWalletConfig: this.isNoWalletConfig,
980
+ get isSwitchingWallets() {
981
+ return self2.isSwitchingWallets;
1003
982
  }
1004
- if (session.currentWalletIds && !currentWalletIdsEq(session.currentWalletIds, this.currentWalletIds)) {
1005
- yield this.setCurrentWalletIds(session.currentWalletIds);
983
+ };
984
+ }
985
+ getStateMachineInterface() {
986
+ const self2 = this;
987
+ return {
988
+ setup: this.setup.bind(this),
989
+ logout: __privateMethod(this, _ParaCore_instances, logout_fn).bind(this),
990
+ isPortal: this.isPortal.bind(this),
991
+ setupAfterLogin: this.setupAfterLogin.bind(this),
992
+ devLog: this.devLog.bind(this),
993
+ authService: __privateGet(this, _authService),
994
+ walletService: __privateGet(this, _walletService),
995
+ pregenWalletService: __privateGet(this, _pregenWalletService),
996
+ pollingService: __privateGet(this, _pollingService),
997
+ externalWalletService: __privateGet(this, _externalWalletService),
998
+ sessionManagementService: __privateGet(this, _sessionManagementService),
999
+ portalUrlService: __privateGet(this, _portalUrlService),
1000
+ get isNoWalletConfig() {
1001
+ return self2.isNoWalletConfig;
1006
1002
  }
1007
- return session;
1003
+ };
1004
+ }
1005
+ // Create a dedicated interface for ExternalWalletService
1006
+ getExternalWalletServiceInterface() {
1007
+ return {
1008
+ assertPartner: __privateMethod(this, _ParaCore_instances, assertPartner_fn).bind(this),
1009
+ localStorageSetItem: this.localStorageSetItem.bind(this),
1010
+ logout: __privateMethod(this, _ParaCore_instances, logout_fn).bind(this)
1011
+ };
1012
+ }
1013
+ // Create a dedicated interface for PollingService
1014
+ getPollingServiceInterface() {
1015
+ const self2 = this;
1016
+ return {
1017
+ isPortal: this.isPortal.bind(this),
1018
+ devLog: this.devLog.bind(this),
1019
+ get popupWindow() {
1020
+ return self2.popupWindow;
1021
+ },
1022
+ set popupWindow(w) {
1023
+ self2.popupWindow = w;
1024
+ },
1025
+ platformUtils: this.platformUtils,
1026
+ ctx: this.ctx
1027
+ };
1028
+ }
1029
+ touchSession(regenerate = false) {
1030
+ return __async(this, null, function* () {
1031
+ return __privateGet(this, _sessionManagementService).touchSession(regenerate);
1008
1032
  });
1009
1033
  }
1010
1034
  getVerificationEmailProps() {
@@ -1037,7 +1061,8 @@ Need help? Visit: https://docs.getpara.com or contact support
1037
1061
  init() {
1038
1062
  return __async(this, null, function* () {
1039
1063
  var _a, _b;
1040
- this.userId = (yield this.localStorageGetItem(constants.LOCAL_STORAGE_USER_ID)) || void 0;
1064
+ this.initializeServices();
1065
+ __privateGet(this, _authService).userId = (yield this.localStorageGetItem(constants.LOCAL_STORAGE_USER_ID)) || void 0;
1041
1066
  const storageAuthInfo = (yield this.localStorageGetItem(constants.LOCAL_STORAGE_AUTH_INFO)) || void 0;
1042
1067
  const stringExternalWallets = yield this.localStorageGetItem(constants.LOCAL_STORAGE_EXTERNAL_WALLETS);
1043
1068
  const _externalWallets = JSON.parse(stringExternalWallets || "{}");
@@ -1055,7 +1080,7 @@ Need help? Visit: https://docs.getpara.com or contact support
1055
1080
  };
1056
1081
  authInfo = __privateMethod(this, _ParaCore_instances, toAuthInfo_fn).call(this, authParams);
1057
1082
  }
1058
- __privateSet(this, _authInfo, authInfo);
1083
+ __privateGet(this, _authService).authInfo = authInfo;
1059
1084
  const stringWallets = this.platformUtils.secureStorage ? yield this.platformUtils.secureStorage.get(constants.LOCAL_STORAGE_WALLETS) : yield this.localStorageGetItem(constants.LOCAL_STORAGE_WALLETS);
1060
1085
  const _wallets = JSON.parse(stringWallets || "{}");
1061
1086
  const stringEd25519Wallets = this.platformUtils.secureStorage ? yield this.platformUtils.secureStorage.get(constants.LOCAL_STORAGE_ED25519_WALLETS) : yield this.localStorageGetItem(constants.LOCAL_STORAGE_ED25519_WALLETS);
@@ -1079,8 +1104,8 @@ Need help? Visit: https://docs.getpara.com or contact support
1079
1104
  }, {}) : fromJson;
1080
1105
  })();
1081
1106
  yield this.setCurrentWalletIds(currentWalletIds);
1082
- this.sessionCookie = (yield this.localStorageGetItem(constants.LOCAL_STORAGE_SESSION_COOKIE)) || (yield this.sessionStorageGetItem(constants.LOCAL_STORAGE_SESSION_COOKIE)) || void 0;
1083
- if (Object.values(this.wallets).filter((w) => this.isWalletOwned(w)).length > 0 && this.currentWalletIdsArray.length === 0) {
1107
+ __privateGet(this, _sessionManagementService).sessionCookie = (yield this.localStorageGetItem(constants.LOCAL_STORAGE_SESSION_COOKIE)) || (yield this.sessionStorageGetItem(constants.LOCAL_STORAGE_SESSION_COOKIE)) || void 0;
1108
+ if (Object.values(this.wallets).filter((w) => __privateGet(this, _walletService).isWalletOwned(w)).length > 0 && this.currentWalletIdsArray.length === 0) {
1084
1109
  this.findWalletId(void 0, { forbidPregen: true });
1085
1110
  }
1086
1111
  const loginEncryptionKey = yield this.sessionStorageGetItem(constants.SESSION_STORAGE_LOGIN_ENCRYPTION_KEY_PAIR);
@@ -1092,17 +1117,14 @@ Need help? Visit: https://docs.getpara.com or contact support
1092
1117
  this.isEnclaveUser = JSON.parse(storedIsEnclaveUser);
1093
1118
  }
1094
1119
  setupListeners.bind(this)();
1120
+ autoBind(this);
1121
+ __privateGet(this, _stateManager).start();
1095
1122
  yield this.touchSession();
1096
1123
  });
1097
1124
  }
1098
1125
  setAuth(_0) {
1099
1126
  return __async(this, arguments, function* (auth, { extras = {}, userId } = {}) {
1100
- const authInfo = __spreadValues(__spreadValues({}, extractAuthInfo(auth, { isRequired: true })), extras || {});
1101
- yield __privateMethod(this, _ParaCore_instances, setAuthInfo_fn).call(this, authInfo);
1102
- if (!!userId) {
1103
- yield this.setUserId(userId);
1104
- }
1105
- return __privateGet(this, _authInfo);
1127
+ return yield __privateGet(this, _authService).setAuth(auth, { extras, userId });
1106
1128
  });
1107
1129
  }
1108
1130
  /**
@@ -1114,40 +1136,11 @@ Need help? Visit: https://docs.getpara.com or contact support
1114
1136
  this.setModalError(error);
1115
1137
  }
1116
1138
  }
1117
- /**
1118
- * Handle specific touchSession errors with user-friendly messages
1119
- * @private
1120
- */
1121
- handleTouchSessionError(error) {
1122
- const errorStr = String(error);
1123
- const errorMessage = error instanceof Error ? error.message : "";
1124
- if (errorStr.includes("blocked by CORS policy") && errorStr.includes("Access-Control-Allow-Origin")) {
1125
- const message = "Request rate limit reached. Please wait a couple of minutes and try again.";
1126
- console.error(`[Para] ${message}`);
1127
- this.displayModalError(message);
1128
- return;
1129
- }
1130
- if (error.status === 403 && errorMessage.includes("origin not authorized")) {
1131
- this.displayModalError(
1132
- "The current origin is not allowed. Update your allowed origins in the Para developer portal to allow the current origin."
1133
- );
1134
- return;
1135
- }
1136
- }
1137
1139
  assertUserId({ allowGuestMode = false } = {}) {
1138
- if (!this.userId || !allowGuestMode && this.isGuestMode) {
1139
- throw new Error("no userId is set");
1140
- }
1141
- return this.userId;
1140
+ return __privateGet(this, _authService).assertUserId({ allowGuestMode });
1142
1141
  }
1143
1142
  assertIsAuthSet(allowed) {
1144
- if (!__privateGet(this, _authInfo)) {
1145
- throw new Error("auth is not set");
1146
- }
1147
- if (allowed && !allowed.includes(__privateGet(this, _authInfo).authType)) {
1148
- throw new Error(`invalid auth type, expected ${allowed.join(", ")}`);
1149
- }
1150
- return __privateGet(this, _authInfo);
1143
+ return __privateGet(this, _authService).assertIsAuthSet(allowed);
1151
1144
  }
1152
1145
  /**
1153
1146
  * Sets the email associated with the `ParaCore` instance.
@@ -1155,7 +1148,7 @@ Need help? Visit: https://docs.getpara.com or contact support
1155
1148
  */
1156
1149
  setEmail(email) {
1157
1150
  return __async(this, null, function* () {
1158
- yield this.setAuth({ email });
1151
+ yield __privateGet(this, _authService).setAuth({ email });
1159
1152
  });
1160
1153
  }
1161
1154
  /**
@@ -1164,7 +1157,7 @@ Need help? Visit: https://docs.getpara.com or contact support
1164
1157
  */
1165
1158
  setTelegramUserId(telegramUserId) {
1166
1159
  return __async(this, null, function* () {
1167
- yield this.setAuth({ telegramUserId });
1160
+ yield __privateGet(this, _authService).setAuth({ telegramUserId });
1168
1161
  });
1169
1162
  }
1170
1163
  /**
@@ -1174,7 +1167,7 @@ Need help? Visit: https://docs.getpara.com or contact support
1174
1167
  */
1175
1168
  setPhoneNumber(phone, countryCode) {
1176
1169
  return __async(this, null, function* () {
1177
- yield this.setAuth({ phone: formatPhoneNumber(phone, countryCode) });
1170
+ yield __privateGet(this, _authService).setAuth({ phone: formatPhoneNumber(phone, countryCode) });
1178
1171
  });
1179
1172
  }
1180
1173
  /**
@@ -1183,7 +1176,7 @@ Need help? Visit: https://docs.getpara.com or contact support
1183
1176
  */
1184
1177
  setFarcasterUsername(farcasterUsername) {
1185
1178
  return __async(this, null, function* () {
1186
- yield this.setAuth({ farcasterUsername });
1179
+ yield __privateGet(this, _authService).setAuth({ farcasterUsername });
1187
1180
  });
1188
1181
  }
1189
1182
  /**
@@ -1193,75 +1186,12 @@ Need help? Visit: https://docs.getpara.com or contact support
1193
1186
  */
1194
1187
  setExternalWallet(externalWallet) {
1195
1188
  return __async(this, null, function* () {
1196
- const { id: partnerId, supportedWalletTypes } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
1197
- this.externalWallets = (Array.isArray(externalWallet) ? externalWallet : [externalWallet]).reduce(
1198
- (acc, {
1199
- partnerId: wPartnerId,
1200
- address,
1201
- type,
1202
- provider,
1203
- providerId,
1204
- addressBech32,
1205
- withFullParaAuth,
1206
- isConnectionOnly,
1207
- withVerification
1208
- }) => {
1209
- if (partnerId === wPartnerId && supportedWalletTypes.some(({ type: supportedType }) => supportedType === type)) {
1210
- return __spreadProps(__spreadValues({}, acc), {
1211
- [address]: {
1212
- id: address,
1213
- partnerId,
1214
- address: addressBech32 != null ? addressBech32 : address,
1215
- type,
1216
- name: provider,
1217
- isExternal: true,
1218
- isExternalWithParaAuth: withFullParaAuth,
1219
- externalProviderId: providerId,
1220
- signer: "",
1221
- isExternalConnectionOnly: isConnectionOnly,
1222
- isExternalWithVerification: withVerification
1223
- }
1224
- });
1225
- }
1226
- return acc;
1227
- },
1228
- {}
1229
- ), this.setExternalWallets(this.externalWallets);
1230
- dispatchEvent(ParaEvent.EXTERNAL_WALLET_CHANGE_EVENT, null);
1189
+ return yield __privateGet(this, _externalWalletService).setExternalWallet({ externalWallet });
1231
1190
  });
1232
1191
  }
1233
1192
  addExternalWallets(externalWallets) {
1234
1193
  return __async(this, null, function* () {
1235
- const { id: partnerId, supportedWalletTypes } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
1236
- this.externalWallets = __spreadValues(__spreadValues({}, Object.entries(this.externalWallets).reduce((acc, [address, wallet]) => {
1237
- if (partnerId === wallet.partnerId && supportedWalletTypes.some(({ type }) => type === wallet.type)) {
1238
- return __spreadProps(__spreadValues({}, acc), {
1239
- [address]: wallet
1240
- });
1241
- }
1242
- return acc;
1243
- }, {})), externalWallets.reduce(
1244
- (acc, { address, type, provider, providerId, addressBech32, withFullParaAuth, isConnectionOnly, withVerification }) => {
1245
- return __spreadProps(__spreadValues({}, acc), {
1246
- [address]: {
1247
- id: address,
1248
- partnerId,
1249
- address: addressBech32 != null ? addressBech32 : address,
1250
- type,
1251
- name: provider,
1252
- isExternal: true,
1253
- isExternalWithParaAuth: withFullParaAuth,
1254
- externalProviderId: providerId,
1255
- signer: "",
1256
- isExternalConnectionOnly: isConnectionOnly,
1257
- isExternalWithVerification: withVerification
1258
- }
1259
- });
1260
- },
1261
- {}
1262
- ));
1263
- this.setExternalWallets(this.externalWallets);
1264
- dispatchEvent(ParaEvent.EXTERNAL_WALLET_CHANGE_EVENT, null);
1194
+ return yield __privateGet(this, _externalWalletService).addExternalWallets({ externalWallets });
1265
1195
  });
1266
1196
  }
1267
1197
  /**
@@ -1270,8 +1200,7 @@ Need help? Visit: https://docs.getpara.com or contact support
1270
1200
  */
1271
1201
  setUserId(userId) {
1272
1202
  return __async(this, null, function* () {
1273
- this.userId = userId;
1274
- yield this.localStorageSetItem(constants.LOCAL_STORAGE_USER_ID, userId);
1203
+ return yield __privateGet(this, _authService).setUserId(userId);
1275
1204
  });
1276
1205
  }
1277
1206
  /**
@@ -1280,12 +1209,7 @@ Need help? Visit: https://docs.getpara.com or contact support
1280
1209
  */
1281
1210
  setWallets(wallets) {
1282
1211
  return __async(this, null, function* () {
1283
- this.wallets = wallets;
1284
- if (this.platformUtils.secureStorage) {
1285
- yield this.platformUtils.secureStorage.set(constants.LOCAL_STORAGE_WALLETS, JSON.stringify(wallets));
1286
- return;
1287
- }
1288
- yield this.localStorageSetItem(constants.LOCAL_STORAGE_WALLETS, JSON.stringify(wallets));
1212
+ return yield __privateGet(this, _walletService).setWallets(wallets);
1289
1213
  });
1290
1214
  }
1291
1215
  /**
@@ -1294,12 +1218,7 @@ Need help? Visit: https://docs.getpara.com or contact support
1294
1218
  */
1295
1219
  setExternalWallets(externalWallets) {
1296
1220
  return __async(this, null, function* () {
1297
- if (typeof externalWallets === "function") {
1298
- this.externalWallets = externalWallets(this.externalWallets);
1299
- } else {
1300
- this.externalWallets = externalWallets;
1301
- }
1302
- yield this.localStorageSetItem(constants.LOCAL_STORAGE_EXTERNAL_WALLETS, JSON.stringify(this.externalWallets));
1221
+ return yield __privateGet(this, _externalWalletService).setExternalWallets({ externalWallets });
1303
1222
  });
1304
1223
  }
1305
1224
  /**
@@ -1326,51 +1245,36 @@ Need help? Visit: https://docs.getpara.com or contact support
1326
1245
  * @returns - userId associated with the `ParaCore` instance.
1327
1246
  */
1328
1247
  getUserId() {
1329
- return this.userId;
1248
+ var _a;
1249
+ return (_a = __privateGet(this, _authService)) == null ? void 0 : _a.userId;
1330
1250
  }
1331
1251
  getAuthInfo() {
1332
- return this.authInfo;
1252
+ var _a;
1253
+ return (_a = __privateGet(this, _authService)) == null ? void 0 : _a.authInfo;
1333
1254
  }
1334
1255
  /**
1335
1256
  * Gets the email associated with the `ParaCore` instance.
1336
1257
  * @returns - email associated with the `ParaCore` instance.
1337
1258
  */
1338
1259
  getEmail() {
1339
- return this.email;
1260
+ var _a;
1261
+ return (_a = __privateGet(this, _authService)) == null ? void 0 : _a.email;
1340
1262
  }
1341
1263
  /**
1342
1264
  * Gets the formatted phone number associated with the `ParaCore` instance.
1343
1265
  * @returns - formatted phone number associated with the `ParaCore` instance.
1344
1266
  */
1345
1267
  getPhoneNumber() {
1346
- return this.phone;
1268
+ var _a;
1269
+ return (_a = __privateGet(this, _authService)) == null ? void 0 : _a.phone;
1347
1270
  }
1348
1271
  /**
1349
1272
  * Gets the farcaster username associated with the `ParaCore` instance.
1350
1273
  * @returns - farcaster username associated with the `ParaCore` instance.
1351
1274
  */
1352
1275
  getFarcasterUsername() {
1353
- return this.farcasterUsername;
1354
- }
1355
- setCurrentWalletIds(_0) {
1356
- return __async(this, arguments, function* (currentWalletIds, {
1357
- needsWallet = false,
1358
- sessionLookupId,
1359
- newDeviceSessionLookupId
1360
- } = {}) {
1361
- this.currentWalletIds = currentWalletIds;
1362
- yield this.localStorageSetItem(constants.LOCAL_STORAGE_CURRENT_WALLET_IDS, JSON.stringify(this.currentWalletIds));
1363
- if (sessionLookupId) {
1364
- yield this.ctx.client.setCurrentWalletIds(
1365
- this.getUserId(),
1366
- this.currentWalletIds,
1367
- needsWallet,
1368
- sessionLookupId,
1369
- newDeviceSessionLookupId
1370
- );
1371
- }
1372
- dispatchEvent(ParaEvent.WALLETS_CHANGE_EVENT, null);
1373
- });
1276
+ var _a;
1277
+ return (_a = __privateGet(this, _authService)) == null ? void 0 : _a.farcasterUsername;
1374
1278
  }
1375
1279
  /**
1376
1280
  * Fetches the most recent OAuth account metadata for the signed-in user.
@@ -1388,29 +1292,6 @@ Need help? Visit: https://docs.getpara.com or contact support
1388
1292
  return accountMetadata;
1389
1293
  });
1390
1294
  }
1391
- /**
1392
- * Validates that a wallet ID is present on the instance, usable, and matches the desired filters.
1393
- * If no ID is passed, this will instead return the first valid, usable wallet ID that matches the filters.
1394
- * @param {string} [walletId] the wallet ID to validate.
1395
- * @param {WalletFilters} [filter={}] a `WalletFilters` object specifying allowed types, schemes, and whether to forbid unclaimed pregen wallets.
1396
- * @returns {string} the wallet ID originally passed, or the one found.
1397
- */
1398
- findWalletId(walletId, filter = {}) {
1399
- if (walletId) {
1400
- this.assertIsValidWalletId(walletId, filter);
1401
- } else {
1402
- for (const id of [...this.currentWalletIdsUnique, ...Object.keys(this.wallets)]) {
1403
- if (this.isWalletUsable(id, filter)) {
1404
- walletId = id;
1405
- break;
1406
- }
1407
- }
1408
- if (!walletId) {
1409
- throw new Error(`no valid wallet id found`);
1410
- }
1411
- }
1412
- return walletId;
1413
- }
1414
1295
  /**
1415
1296
  * Retrieves a wallet with the given address, if present.
1416
1297
  * If no ID is passed, this will instead return the first valid, usable wallet ID that matches the filters.
@@ -1418,78 +1299,15 @@ Need help? Visit: https://docs.getpara.com or contact support
1418
1299
  * @param {WalletFilters} [filter={}] a `WalletFilters` object specifying allowed types, schemes, and whether to forbid unclaimed pregen wallets.
1419
1300
  * @returns {string} the wallet ID originally passed, or the one found.
1420
1301
  */
1421
- findWalletByAddress(address, filter) {
1422
- if (this.externalWallets[address]) {
1423
- return this.externalWallets[address];
1424
- }
1425
- let wallet;
1426
- Object.entries(this.currentWalletIds).forEach(([type, walletIds]) => {
1427
- const pregenWalletIds = Object.keys(this.wallets).filter(
1428
- (id) => this.wallets[id].type === type && this.isPregenWalletClaimable(this.wallets[id])
1429
- );
1430
- [...walletIds, ...pregenWalletIds].forEach((id) => {
1431
- if (address.toLowerCase() === this.getDisplayAddress(id, { addressType: type }).toLowerCase()) {
1432
- wallet = this.wallets[id];
1433
- }
1434
- });
1435
- });
1436
- if (!wallet) {
1437
- throw new Error(`wallet with address ${address} not found`);
1438
- }
1439
- this.assertIsValidWalletId(wallet.id, filter);
1440
- return wallet;
1441
- }
1442
- findWallet(idOrAddress, overrideType, filter = {}) {
1443
- var _a, _c, _d;
1444
- if (!this.isExternalWalletAuth) {
1445
- if (!idOrAddress && Object.keys(this.externalWallets).length > 0) {
1446
- return Object.values(this.externalWallets)[0];
1447
- }
1448
- }
1449
- if ((_a = this.externalWallets) == null ? void 0 : _a[idOrAddress]) {
1450
- return this.externalWallets[idOrAddress];
1451
- }
1452
- try {
1453
- const walletId = this.findWalletId(idOrAddress, filter);
1454
- if (walletId && !!this.wallets[walletId]) {
1455
- const _b = this.wallets[walletId], { signer: _signer } = _b, wallet = __objRest(_b, ["signer"]);
1456
- const type = (_d = overrideType != null ? overrideType : (_c = this.currentWalletIdsArray.find(([id]) => id === walletId)) == null ? void 0 : _c[1]) != null ? _d : wallet.type;
1457
- return __spreadProps(__spreadValues({}, wallet), {
1458
- type
1459
- });
1460
- }
1461
- } catch (e) {
1462
- return void 0;
1463
- }
1302
+ findWalletByAddress(...params) {
1303
+ return __privateGet(this, _walletService).findWalletByAddress(...params);
1304
+ }
1305
+ findWallet(...params) {
1306
+ const [walletId, walletType, filters = {}] = params;
1307
+ return __privateGet(this, _walletService).findWallet(walletId, walletType, filters);
1464
1308
  }
1465
1309
  get availableWallets() {
1466
- var _a;
1467
- return [
1468
- ...[...this.currentWalletIdsArray, ...__privateGet(this, _ParaCore_instances, guestWalletIdsArray_get)].map(([address, type]) => [address, type, false]).map(([id, type]) => {
1469
- const wallet = this.findWallet(id, type);
1470
- if (!wallet) return null;
1471
- const name = wallet.name;
1472
- const address = this.getDisplayAddress(id, { addressType: type });
1473
- const addressShort = this.getDisplayAddress(id, { addressType: type, truncate: true });
1474
- return {
1475
- id: wallet.id,
1476
- partner: wallet.partner,
1477
- type,
1478
- address,
1479
- name,
1480
- addressShort,
1481
- displayName: name != null ? name : addressShort,
1482
- ensName: wallet.ensName,
1483
- ensAvatar: wallet.ensAvatar
1484
- };
1485
- }).filter((obj) => obj !== null),
1486
- ...Object.values((_a = this.externalWallets) != null ? _a : {}).map((wallet) => {
1487
- return __spreadProps(__spreadValues({}, wallet), {
1488
- addressShort: truncateAddress(wallet.address, wallet.type, { prefix: this.cosmosPrefix }),
1489
- displayName: wallet.externalProviderId
1490
- });
1491
- })
1492
- ];
1310
+ return __privateGet(this, _walletService).availableWallets;
1493
1311
  }
1494
1312
  /**
1495
1313
  * Retrieves all usable wallets with the provided type (`'EVM' | 'COSMOS' | 'SOLANA'`)
@@ -1497,52 +1315,16 @@ Need help? Visit: https://docs.getpara.com or contact support
1497
1315
  * @returns {Wallet[]} an array of matching wallets.
1498
1316
  */
1499
1317
  getWalletsByType(type) {
1500
- return Object.values(this.wallets).filter((w) => this.isWalletUsable(w.id, { type: [type] }));
1501
- }
1502
- assertIsValidWalletId(walletId, condition = {}) {
1503
- this.isWalletUsable(walletId, condition, true);
1318
+ return __privateGet(this, _walletService).getWalletsByType(type);
1504
1319
  }
1505
- assertIsValidWalletType(type, walletTypes) {
1320
+ getPartner(partnerId) {
1506
1321
  return __async(this, null, function* () {
1507
- const { supportedWalletTypes } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
1508
- if (!type || !WALLET_TYPES.includes(type) || !(walletTypes != null ? walletTypes : supportedWalletTypes.map(({ type: type2 }) => type2)).includes(type)) {
1509
- throw new Error(`wallet type ${type} is not supported`);
1510
- }
1511
- return type;
1512
- });
1513
- }
1514
- getMissingTypes() {
1515
- return __async(this, null, function* () {
1516
- const { supportedWalletTypes } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
1517
- return supportedWalletTypes.filter(
1518
- ({ type: t, optional }) => !optional && Object.values(this.wallets).every((w) => !this.isWalletOwned(w) || !WalletSchemeTypeMap[w.scheme][t])
1519
- ).map(({ type }) => type);
1520
- });
1521
- }
1522
- getTypesToCreate(types) {
1523
- return __async(this, null, function* () {
1524
- const { supportedWalletTypes } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
1525
- return getSchemes(types != null ? types : yield this.getMissingTypes()).map((scheme) => {
1526
- switch (scheme) {
1527
- case "ED25519":
1528
- return "SOLANA";
1529
- default:
1530
- return supportedWalletTypes.some(({ type, optional }) => type === "COSMOS" && !optional) ? "COSMOS" : "EVM";
1531
- }
1532
- });
1533
- });
1534
- }
1535
- getPartnerURL() {
1536
- return __async(this, null, function* () {
1537
- try {
1538
- const { portalUrl } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
1539
- return portalUrl;
1540
- } catch (e) {
1541
- if (this.isPartnerOptional) {
1542
- return void 0;
1543
- }
1544
- throw e;
1322
+ if (this.isPartnerOptional && !partnerId) {
1323
+ return void 0;
1545
1324
  }
1325
+ const res = yield this.ctx.client.getPartner(partnerId);
1326
+ this.partner = res.data.partner;
1327
+ return this.partner;
1546
1328
  });
1547
1329
  }
1548
1330
  /**
@@ -1552,7 +1334,7 @@ Need help? Visit: https://docs.getpara.com or contact support
1552
1334
  */
1553
1335
  getPortalURL(isLegacy) {
1554
1336
  return __async(this, null, function* () {
1555
- return this.ctx.portalUrlOverride || (yield this.getPartnerURL()) || getPortalBaseURL(this.ctx, false, false, isLegacy);
1337
+ return yield __privateGet(this, _portalUrlService).getPortalURL(isLegacy);
1556
1338
  });
1557
1339
  }
1558
1340
  /**
@@ -1585,33 +1367,12 @@ Need help? Visit: https://docs.getpara.com or contact support
1585
1367
  */
1586
1368
  fetchWallets() {
1587
1369
  return __async(this, null, function* () {
1588
- const res = yield this.isPortal() || this.isParaConnect() ? this.ctx.client.getAllWallets(this.userId) : this.ctx.client.getWallets(this.userId, true);
1589
- return res.data.wallets.filter(
1590
- (wallet) => !!wallet.address && wallet.sharesPersisted && (this.isParaConnect() || !this.isParaConnect() && this.isWalletSupported(entityToWallet(wallet)))
1591
- );
1370
+ return yield __privateGet(this, _walletService).fetchWallets();
1592
1371
  });
1593
1372
  }
1594
1373
  populateWalletAddresses() {
1595
1374
  return __async(this, null, function* () {
1596
- const res = yield (this.isPortal() ? this.ctx.client.getAllWallets : this.ctx.client.getWallets)(this.userId, true);
1597
- const wallets = res.data.wallets;
1598
- wallets.forEach((entity) => {
1599
- if (this.wallets[entity.id]) {
1600
- this.wallets[entity.id] = __spreadValues(__spreadValues({}, entityToWallet(entity)), this.wallets[entity.id]);
1601
- }
1602
- });
1603
- yield this.setWallets(this.wallets);
1604
- });
1605
- }
1606
- populatePregenWalletAddresses() {
1607
- return __async(this, null, function* () {
1608
- const res = yield this.getPregenWallets();
1609
- res.forEach((entity) => {
1610
- if (this.wallets[entity.id]) {
1611
- this.wallets[entity.id] = __spreadValues(__spreadValues({}, entityToWallet(entity)), this.wallets[entity.id]);
1612
- }
1613
- });
1614
- yield this.setWallets(this.wallets);
1375
+ return yield __privateGet(this, _walletService).populateWalletAddresses();
1615
1376
  });
1616
1377
  }
1617
1378
  /**
@@ -1621,86 +1382,34 @@ Need help? Visit: https://docs.getpara.com or contact support
1621
1382
  * @param {TWalletType} opts.type type of external wallet to use for identification.
1622
1383
  * @param {string} opts.provider the name of the provider for the external wallet.
1623
1384
  */
1624
- loginExternalWallet(_a) {
1385
+ loginExternalWallet(params) {
1625
1386
  return __async(this, null, function* () {
1626
- var _b = _a, {
1627
- externalWallet,
1628
- chainId,
1629
- uri
1630
- } = _b, urlOptions = __objRest(_b, [
1631
- "externalWallet",
1632
- "chainId",
1633
- "uri"
1634
- ]);
1635
- const externalWallets = Array.isArray(externalWallet) ? externalWallet : [externalWallet];
1636
- try {
1637
- yield this.ctx.client.trackExternalWalletConnections({
1638
- wallets: externalWallets.map((wallet) => ({
1639
- address: wallet.address,
1640
- type: wallet.type,
1641
- provider: wallet.provider
1642
- }))
1643
- });
1644
- } catch (err) {
1645
- console.error("Error tracking external wallet connections:", err);
1646
- }
1647
- if (this.externalWalletConnectionOnly || externalWallets.every((wallet) => wallet.isConnectionOnly)) {
1648
- yield this.addExternalWallets(
1649
- externalWallets.map((wallet) => __spreadProps(__spreadValues({}, wallet), {
1650
- withFullParaAuth: false
1651
- }))
1652
- );
1653
- return Promise.resolve({
1654
- userId: constants.EXTERNAL_WALLET_CONNECTION_ONLY_USER_ID
1655
- });
1656
- }
1657
- if (Array.isArray(externalWallet)) {
1658
- throw new Error(
1659
- "Cannot authenticate multiple external wallets at once. To connect multiple wallets at once, use CONNECTION_ONLY mode."
1660
- );
1661
- }
1662
- this.requireApiKey();
1663
- const serverAuthState = yield this.ctx.client.loginExternalWallet({ externalWallet, chainId, uri });
1664
- if (!externalWallet.withFullParaAuth && externalWallet.withVerification) {
1665
- yield this.touchSession(true);
1666
- }
1667
- if (externalWallet.withFullParaAuth) {
1668
- yield this.ctx.client.sessionAddPortalVerification();
1669
- }
1670
- return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
1387
+ return yield __privateGet(this, _authService).loginExternalWallet(params);
1388
+ });
1389
+ }
1390
+ /**
1391
+ * Connects to an external wallet & logs in to Para (if applicable).
1392
+ * @param {Object} params the params object
1393
+ * @param {Function} params.connect the function called to connect to the external wallet.
1394
+ */
1395
+ connectExternalWallet(params) {
1396
+ return __async(this, null, function* () {
1397
+ return yield __privateGet(this, _authService).connectExternalWallet(params);
1671
1398
  });
1672
1399
  }
1673
1400
  verifyExternalWallet(params) {
1674
1401
  return __async(this, null, function* () {
1675
- var _c;
1676
- let serverAuthState;
1677
- let urlOptions;
1678
- if ("serverAuthState" in params && params.serverAuthState !== void 0) {
1679
- const _a = params, { serverAuthState: optsServerAuthState } = _a, rest = __objRest(_a, ["serverAuthState"]);
1680
- serverAuthState = optsServerAuthState;
1681
- urlOptions = rest;
1682
- } else if ("externalWallet" in params) {
1683
- const _b = params, { externalWallet, signedMessage, cosmosPublicKeyHex, cosmosSigner } = _b, rest = __objRest(_b, ["externalWallet", "signedMessage", "cosmosPublicKeyHex", "cosmosSigner"]);
1684
- const _serverAuthState = yield this.ctx.client.verifyExternalWallet(this.userId, {
1685
- externalWallet,
1686
- signedMessage,
1687
- cosmosPublicKeyHex,
1688
- cosmosSigner
1689
- });
1690
- serverAuthState = _serverAuthState;
1691
- urlOptions = rest;
1692
- }
1693
- if (serverAuthState.stage === "login" && ((_c = serverAuthState.loginAuthMethods) == null ? void 0 : _c.includes(AuthMethod.PIN))) {
1694
- const { sessionLookupId } = yield this.touchSession();
1695
- return yield __privateMethod(this, _ParaCore_instances, prepareLoginState_fn).call(this, serverAuthState, __spreadProps(__spreadValues({}, urlOptions), { sessionLookupId }));
1696
- }
1697
- let state;
1698
- try {
1699
- state = yield __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
1700
- } catch (err) {
1701
- console.error("Error prepping state:", err);
1702
- }
1703
- return state;
1402
+ return yield __privateGet(this, _authService).verifyExternalWallet(params);
1403
+ });
1404
+ }
1405
+ retryVerifyExternalWallet() {
1406
+ return __async(this, null, function* () {
1407
+ return yield __privateGet(this, _authService).retryVerifyExternalWallet();
1408
+ });
1409
+ }
1410
+ signExternalWalletVerification(params) {
1411
+ return __async(this, null, function* () {
1412
+ return yield __privateGet(this, _authService).signExternalWalletVerification(params);
1704
1413
  });
1705
1414
  }
1706
1415
  verifyExternalWalletLink(opts) {
@@ -1723,13 +1432,13 @@ Need help? Visit: https://docs.getpara.com or contact support
1723
1432
  * @param authResponse - the response JSON object received from the Telegram widget.
1724
1433
  * @returns `{ isValid: boolean; telegramUserId?: string; userId?: string; isNewUser?: boolean; supportedAuthMethods?: AuthMethod[]; biometricHints?: BiometricLocationHint[] }`
1725
1434
  */
1726
- verifyTelegramProcess(_c) {
1435
+ verifyTelegramProcess(_a) {
1727
1436
  return __async(this, null, function* () {
1728
- var _d = _c, {
1437
+ var _b = _a, {
1729
1438
  serverAuthState: optsServerAuthState,
1730
1439
  telegramAuthResponse,
1731
1440
  isLinkAccount
1732
- } = _d, urlOptions = __objRest(_d, [
1441
+ } = _b, urlOptions = __objRest(_b, [
1733
1442
  "serverAuthState",
1734
1443
  "telegramAuthResponse",
1735
1444
  "isLinkAccount"
@@ -1737,12 +1446,10 @@ Need help? Visit: https://docs.getpara.com or contact support
1737
1446
  try {
1738
1447
  switch (isLinkAccount) {
1739
1448
  case false: {
1740
- if (!optsServerAuthState && !telegramAuthResponse) {
1741
- throw new Error("one of serverAuthState or telegramAuthResponse are required for verifying telegram");
1742
- }
1743
- const serverAuthState = optsServerAuthState != null ? optsServerAuthState : yield this.ctx.client.verifyTelegram({ authObject: telegramAuthResponse });
1744
- const { sessionLookupId } = yield this.touchSession();
1745
- return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, __spreadProps(__spreadValues({}, urlOptions), { sessionLookupId }));
1449
+ return yield __privateGet(this, _authService).verifyTelegram(__spreadValues({
1450
+ serverAuthState: optsServerAuthState,
1451
+ telegramAuthResponse
1452
+ }, urlOptions));
1746
1453
  }
1747
1454
  case true: {
1748
1455
  if (!telegramAuthResponse) {
@@ -1762,9 +1469,9 @@ Need help? Visit: https://docs.getpara.com or contact support
1762
1469
  }
1763
1470
  });
1764
1471
  }
1765
- verifyTelegram(opts) {
1472
+ verifyTelegram(params) {
1766
1473
  return __async(this, null, function* () {
1767
- return yield this.verifyTelegramProcess(__spreadProps(__spreadValues({}, opts), { isLinkAccount: false }));
1474
+ return yield this.verifyTelegramProcess(__spreadProps(__spreadValues({}, params), { isLinkAccount: false }));
1768
1475
  });
1769
1476
  }
1770
1477
  verifyTelegramLink(opts) {
@@ -1816,35 +1523,8 @@ Need help? Visit: https://docs.getpara.com or contact support
1816
1523
  * Resend a verification email for the current user.
1817
1524
  */
1818
1525
  resendVerificationCode(_0) {
1819
- return __async(this, arguments, function* ({
1820
- type: reason = "SIGNUP"
1821
- }) {
1822
- let type, linkedAccountId;
1823
- switch (reason) {
1824
- case "SIGNUP":
1825
- case "LOGIN":
1826
- {
1827
- const authInfo = this.assertIsAuthSet(["email", "phone"]);
1828
- type = authInfo.authType.toUpperCase();
1829
- }
1830
- break;
1831
- case "LINK_ACCOUNT":
1832
- {
1833
- const accountLinkInProgress = __privateMethod(this, _ParaCore_instances, assertIsLinkingAccount_fn).call(this, ["EMAIL", "PHONE"]);
1834
- linkedAccountId = accountLinkInProgress.id;
1835
- type = accountLinkInProgress.type;
1836
- }
1837
- break;
1838
- }
1839
- const userId = this.assertUserId({ allowGuestMode: true });
1840
- if (type !== "EMAIL" && type !== "PHONE") {
1841
- throw new Error("invalid auth type for verification code");
1842
- }
1843
- yield this.ctx.client.resendVerificationCode(__spreadValues({
1844
- userId,
1845
- type,
1846
- linkedAccountId
1847
- }, this.getVerificationEmailProps()));
1526
+ return __async(this, arguments, function* ({ type: reason = "SIGNUP" }) {
1527
+ return yield __privateGet(this, _authService).resendVerificationCode({ type: reason });
1848
1528
  });
1849
1529
  }
1850
1530
  /**
@@ -1853,18 +1533,7 @@ Need help? Visit: https://docs.getpara.com or contact support
1853
1533
  */
1854
1534
  isSessionActive() {
1855
1535
  return __async(this, null, function* () {
1856
- if (this.externalWalletConnectionType === "CONNECTION_ONLY") {
1857
- return true;
1858
- }
1859
- const { isAuthenticated, verifiedExternalWalletAddresses } = yield this.touchSession();
1860
- if (this.externalWalletConnectionType === "VERIFICATION") {
1861
- if (!verifiedExternalWalletAddresses) {
1862
- return false;
1863
- }
1864
- const externalAddresses = Object.values(this.externalWallets).map((w) => w.id);
1865
- return externalAddresses.every((address) => verifiedExternalWalletAddresses.includes(address));
1866
- }
1867
- return !!isAuthenticated;
1536
+ return yield __privateGet(this, _sessionManagementService).isSessionActive();
1868
1537
  });
1869
1538
  }
1870
1539
  /**
@@ -1873,58 +1542,15 @@ Need help? Visit: https://docs.getpara.com or contact support
1873
1542
  **/
1874
1543
  isFullyLoggedIn() {
1875
1544
  return __async(this, null, function* () {
1876
- if (this.externalWalletConnectionType === "CONNECTION_ONLY") {
1877
- if (!this.isReady) {
1878
- yield this.ready();
1879
- }
1880
- return true;
1881
- }
1882
- if (this.isGuestMode) {
1883
- return true;
1884
- }
1885
- const isSessionActive = yield this.isSessionActive();
1886
- if (this.externalWalletConnectionType === "VERIFICATION") {
1887
- return isSessionActive;
1888
- }
1889
- if (this.isSwitchingWallets) {
1890
- return isSessionActive;
1891
- }
1892
- if (!isSessionActive) {
1893
- return false;
1894
- }
1895
- if (this.isNoWalletConfig) {
1896
- return true;
1897
- }
1898
- const { supportedWalletTypes } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
1899
- const requiredWalletTypes = supportedWalletTypes.filter(({ optional }) => !optional);
1900
- for (const { type } of requiredWalletTypes) {
1901
- const hasWalletForType = this.currentWalletIdsArray.some(([walletId, walletType]) => {
1902
- try {
1903
- const wallet = this.wallets[walletId];
1904
- return wallet && walletType === type && typeof wallet.address === "string";
1905
- } catch (e) {
1906
- return false;
1907
- }
1908
- });
1909
- if (!hasWalletForType) {
1910
- return false;
1911
- }
1912
- }
1913
- const allWalletsLoaded = this.currentWalletIdsArray.every(([walletId]) => {
1914
- const wallet = this.wallets[walletId];
1915
- return wallet && typeof wallet.address === "string";
1916
- });
1917
- if (!allWalletsLoaded) {
1918
- return false;
1919
- }
1920
- return true;
1545
+ return yield __privateGet(this, _sessionManagementService).isFullyLoggedIn();
1921
1546
  });
1922
1547
  }
1923
1548
  get isGuestMode() {
1924
- return __privateGet(this, _ParaCore_instances, guestWalletIdsArray_get).length > 0 && Object.values(this.wallets).every(
1549
+ var _a;
1550
+ return ((_a = __privateGet(this, _pregenWalletService)) == null ? void 0 : _a.guestWalletIdsArray.length) > 0 && Object.values(this.wallets).every(
1925
1551
  ({ userId, partnerId }) => {
1926
- var _a;
1927
- return partnerId === ((_a = this.partner) == null ? void 0 : _a.id) && (!userId || userId !== this.userId);
1552
+ var _a2;
1553
+ return partnerId === ((_a2 = this.partner) == null ? void 0 : _a2.id) && (!userId || userId !== this.userId);
1928
1554
  }
1929
1555
  );
1930
1556
  }
@@ -1954,30 +1580,7 @@ Need help? Visit: https://docs.getpara.com or contact support
1954
1580
  */
1955
1581
  supportedUserAuthMethods() {
1956
1582
  return __async(this, null, function* () {
1957
- this.assertIsAuthSet();
1958
- const { supportedAuthMethods, hasPasswordWithoutPIN } = yield this.ctx.client.getSupportedAuthMethodsV2(
1959
- this.authInfo.auth
1960
- );
1961
- const authMethods = /* @__PURE__ */ new Set();
1962
- for (const type of supportedAuthMethods) {
1963
- switch (type) {
1964
- case "PASSWORD":
1965
- if (hasPasswordWithoutPIN) {
1966
- authMethods.add(AuthMethod.PASSWORD);
1967
- }
1968
- break;
1969
- case "PASSKEY":
1970
- authMethods.add(AuthMethod.PASSKEY);
1971
- break;
1972
- case "PIN":
1973
- authMethods.add(AuthMethod.PIN);
1974
- break;
1975
- case "BASIC_LOGIN":
1976
- authMethods.add(AuthMethod.BASIC_LOGIN);
1977
- break;
1978
- }
1979
- }
1980
- return authMethods;
1583
+ return yield __privateGet(this, _authService).supportedUserAuthMethods();
1981
1584
  });
1982
1585
  }
1983
1586
  /**
@@ -1994,94 +1597,14 @@ Need help? Visit: https://docs.getpara.com or contact support
1994
1597
  /**
1995
1598
  * Waits for the session to be active.
1996
1599
  **/
1997
- waitForSignup(_0) {
1998
- return __async(this, arguments, function* ({
1999
- isCanceled = () => false,
2000
- onCancel,
2001
- onPoll
2002
- }) {
2003
- const startedAt = Date.now();
2004
- return new Promise((resolve, reject) => {
2005
- (() => __async(this, null, function* () {
2006
- yield this.touchSession();
2007
- if (!this.isExternalWalletAuth) {
2008
- this.externalWallets = {};
2009
- }
2010
- while (true) {
2011
- try {
2012
- if (isCanceled() || Date.now() - startedAt > constants.POLLING_TIMEOUT_MS) {
2013
- onCancel == null ? void 0 : onCancel();
2014
- dispatchEvent(ParaEvent.ACCOUNT_CREATION_EVENT, false, "failed to sign up user");
2015
- return reject("canceled");
2016
- }
2017
- yield new Promise((_resolve) => setTimeout(_resolve, constants.POLLING_INTERVAL_MS));
2018
- if (yield this.isSessionActive()) {
2019
- dispatchEvent(ParaEvent.ACCOUNT_CREATION_EVENT, true);
2020
- return resolve(true);
2021
- }
2022
- onPoll == null ? void 0 : onPoll();
2023
- } catch (err) {
2024
- console.error(err);
2025
- onPoll == null ? void 0 : onPoll();
2026
- }
2027
- }
2028
- }))();
2029
- });
1600
+ waitForSignup(params) {
1601
+ return __async(this, null, function* () {
1602
+ return yield __privateGet(this, _authService).waitForSignup(params);
2030
1603
  });
2031
1604
  }
2032
- waitForWalletCreation() {
2033
- return __async(this, arguments, function* ({
2034
- isCanceled = () => false,
2035
- onCancel
2036
- } = {}) {
2037
- yield this.waitForSignup({ isCanceled, onCancel });
2038
- const { supportedWalletTypes } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
2039
- const pregenWallets = yield this.getPregenWallets();
2040
- let recoverySecret, walletIds = {};
2041
- if (pregenWallets.length > 0) {
2042
- let shares = [];
2043
- try {
2044
- shares = yield this.ctx.enclaveClient.getPregenShares({
2045
- userId: this.userId,
2046
- walletIds: pregenWallets.map((w) => w.id),
2047
- partnerId: pregenWallets[0].partnerId
2048
- });
2049
- for (const share of shares) {
2050
- const wallet = pregenWallets.find((w) => w.id === share.walletId);
2051
- if (wallet) {
2052
- this.wallets[wallet.id] = {
2053
- id: wallet.id,
2054
- address: wallet.address,
2055
- scheme: wallet.scheme,
2056
- type: wallet.type,
2057
- partnerId: wallet.partnerId,
2058
- isPregen: wallet.isPregen,
2059
- pregenIdentifier: wallet.pregenIdentifier,
2060
- pregenIdentifierType: wallet.pregenIdentifierType,
2061
- signer: share.signer,
2062
- createdAt: String(wallet.createdAt)
2063
- };
2064
- }
2065
- }
2066
- } catch (err) {
2067
- console.warn("[waitForWalletCreation] Failed to fetch pregen shares:", err);
2068
- }
2069
- if (shares.length > 0) {
2070
- recoverySecret = yield this.claimPregenWallets();
2071
- walletIds = supportedWalletTypes.reduce((acc, { type }) => {
2072
- var _a;
2073
- return __spreadProps(__spreadValues({}, acc), {
2074
- [type]: [(_a = pregenWallets.find((w) => !!WalletSchemeTypeMap[w.scheme][type])) == null ? void 0 : _a.id]
2075
- });
2076
- }, {});
2077
- }
2078
- }
2079
- const created = yield this.createWalletPerType();
2080
- recoverySecret = recoverySecret != null ? recoverySecret : created.recoverySecret;
2081
- walletIds = __spreadValues(__spreadValues({}, walletIds), created.walletIds);
2082
- const resp = { walletIds, recoverySecret };
2083
- dispatchEvent(ParaEvent.ACCOUNT_SETUP_EVENT, resp);
2084
- return resp;
1605
+ waitForWalletCreation(params) {
1606
+ return __async(this, null, function* () {
1607
+ return yield __privateGet(this, _authService).waitForWalletCreation(params);
2085
1608
  });
2086
1609
  }
2087
1610
  /**
@@ -2101,35 +1624,34 @@ Need help? Visit: https://docs.getpara.com or contact support
2101
1624
  * If successful, this returns the user's Farcaster username and profile picture and indicates whether the user already exists.
2102
1625
  * @return {Object} `{userExists: boolean; username: string; pfpUrl?: string | null }` - the user's information and whether the user already exists.
2103
1626
  */
2104
- verifyFarcasterProcess(_e) {
1627
+ verifyFarcasterProcess(_c) {
2105
1628
  return __async(this, null, function* () {
2106
- var _f = _e, {
1629
+ var _d = _c, {
2107
1630
  isCanceled = () => false,
2108
1631
  onConnectUri,
2109
1632
  onCancel,
2110
- onPoll,
2111
1633
  isLinkAccount,
2112
1634
  serverAuthState: optsServerAuthState
2113
- } = _f, urlOptions = __objRest(_f, [
1635
+ } = _d, urlOptions = __objRest(_d, [
2114
1636
  "isCanceled",
2115
1637
  "onConnectUri",
2116
1638
  "onCancel",
2117
- "onPoll",
2118
1639
  "isLinkAccount",
2119
1640
  "serverAuthState"
2120
1641
  ]);
2121
- if (optsServerAuthState) {
2122
- const authState = yield __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, optsServerAuthState, urlOptions);
2123
- return authState;
1642
+ if (onConnectUri) {
1643
+ const connectUri = yield this.getFarcasterConnectUri();
1644
+ onConnectUri(connectUri);
1645
+ }
1646
+ if (!isLinkAccount) {
1647
+ return yield __privateGet(this, _authService).verifyFarcaster(__spreadValues({
1648
+ serverAuthState: optsServerAuthState
1649
+ }, urlOptions));
2124
1650
  }
2125
1651
  let accountLinkInProgress;
2126
1652
  if (isLinkAccount) {
2127
1653
  accountLinkInProgress = yield __privateMethod(this, _ParaCore_instances, assertIsLinkingAccountOrStart_fn).call(this, "FARCASTER");
2128
1654
  }
2129
- if (onConnectUri) {
2130
- const connectUri = yield this.getFarcasterConnectUri();
2131
- onConnectUri(connectUri);
2132
- }
2133
1655
  return new Promise((resolve, reject) => {
2134
1656
  (() => __async(this, null, function* () {
2135
1657
  const startedAt = Date.now();
@@ -2140,27 +1662,13 @@ Need help? Visit: https://docs.getpara.com or contact support
2140
1662
  return reject("CANCELED");
2141
1663
  }
2142
1664
  yield new Promise((_resolve) => setTimeout(_resolve, constants.POLLING_INTERVAL_MS));
2143
- switch (isLinkAccount) {
2144
- case false:
2145
- {
2146
- const serverAuthState = yield this.ctx.client.getFarcasterAuthStatus();
2147
- if (isServerAuthState(serverAuthState)) {
2148
- const authState = yield __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
2149
- return resolve(authState);
2150
- }
2151
- }
2152
- break;
2153
- case true: {
2154
- const result = yield this.verifyLink({
2155
- accountLinkInProgress
2156
- });
2157
- if ("isConflict" in result) {
2158
- throw new Error(AccountLinkError.Conflict);
2159
- }
2160
- return resolve(result);
2161
- }
1665
+ const result = yield this.verifyLink({
1666
+ accountLinkInProgress
1667
+ });
1668
+ if ("isConflict" in result) {
1669
+ throw new Error(AccountLinkError.Conflict);
2162
1670
  }
2163
- onPoll == null ? void 0 : onPoll();
1671
+ return resolve(result);
2164
1672
  } catch (e) {
2165
1673
  if (!isLinkAccount || e.message === AccountLinkError.Conflict) {
2166
1674
  return reject(e.message);
@@ -2171,9 +1679,9 @@ Need help? Visit: https://docs.getpara.com or contact support
2171
1679
  });
2172
1680
  });
2173
1681
  }
2174
- verifyFarcaster(opts) {
1682
+ verifyFarcaster(params) {
2175
1683
  return __async(this, null, function* () {
2176
- return yield this.verifyFarcasterProcess(__spreadProps(__spreadValues({}, opts), { isLinkAccount: false }));
1684
+ return yield this.verifyFarcasterProcess(__spreadProps(__spreadValues({}, params), { isLinkAccount: false }));
2177
1685
  });
2178
1686
  }
2179
1687
  verifyFarcasterLink(opts) {
@@ -2181,11 +1689,17 @@ Need help? Visit: https://docs.getpara.com or contact support
2181
1689
  return yield this.verifyFarcasterProcess(__spreadProps(__spreadValues({}, opts), { isLinkAccount: true }));
2182
1690
  });
2183
1691
  }
2184
- getOAuthUrl(opts) {
1692
+ /**
1693
+ * Generates a URL for the user to log in with OAuth using a desire method.
1694
+ *
1695
+ * @param {Object} opts the options object
1696
+ * @param {TOAuthMethod} opts.method the third-party service to use for OAuth.
1697
+ * @param {string} [opts.appScheme] the app scheme to redirect to after the OAuth flow. This is for mobile only.
1698
+ * @returns {string} the URL for the user to log in with OAuth.
1699
+ */
1700
+ getOAuthUrl(params) {
2185
1701
  return __async(this, null, function* () {
2186
- var _a;
2187
- const sessionLookupId = (_a = opts.sessionLookupId) != null ? _a : yield this.prepareLogin();
2188
- return __privateMethod(this, _ParaCore_instances, getOAuthUrl_fn).call(this, __spreadProps(__spreadValues({}, opts), { sessionLookupId }));
1702
+ return yield __privateGet(this, _portalUrlService).getOAuthUrl(params);
2189
1703
  });
2190
1704
  }
2191
1705
  /**
@@ -2196,27 +1710,12 @@ Need help? Visit: https://docs.getpara.com or contact support
2196
1710
  * @param {Window} [opts.popupWindow] the popup window being used for login.
2197
1711
  * @return {Object} `{ email?: string; isError?: boolean; userExists: boolean; }` the result data
2198
1712
  */
2199
- verifyOAuthProcess(_g) {
1713
+ verifyOAuthProcess(params) {
2200
1714
  return __async(this, null, function* () {
2201
- var _h = _g, {
2202
- method,
2203
- appScheme,
2204
- isCanceled = () => false,
2205
- onCancel,
2206
- onPoll,
2207
- onOAuthUrl,
2208
- onOAuthPopup,
2209
- isLinkAccount
2210
- } = _h, urlOptions = __objRest(_h, [
2211
- "method",
2212
- "appScheme",
2213
- "isCanceled",
2214
- "onCancel",
2215
- "onPoll",
2216
- "onOAuthUrl",
2217
- "onOAuthPopup",
2218
- "isLinkAccount"
2219
- ]);
1715
+ if (!params.isLinkAccount) {
1716
+ return yield __privateGet(this, _authService).verifyOAuthProcess(params);
1717
+ }
1718
+ const { method, appScheme, isCanceled = () => false, onCancel, onPoll, onOAuthUrl, onOAuthPopup } = params;
2220
1719
  if (onOAuthPopup) {
2221
1720
  try {
2222
1721
  this.popupWindow = yield this.platformUtils.openPopup("about:blank", { type: PopupType.OAUTH });
@@ -2226,13 +1725,14 @@ Need help? Visit: https://docs.getpara.com or contact support
2226
1725
  }
2227
1726
  let sessionLookupId, accountLinkInProgress;
2228
1727
  if (onOAuthUrl || onOAuthPopup) {
2229
- if (isLinkAccount) {
2230
- accountLinkInProgress = yield __privateMethod(this, _ParaCore_instances, assertIsLinkingAccountOrStart_fn).call(this, method);
2231
- sessionLookupId = (yield this.touchSession()).sessionLookupId;
2232
- } else {
2233
- sessionLookupId = yield this.prepareLogin();
2234
- }
2235
- const oAuthUrl = yield __privateMethod(this, _ParaCore_instances, getOAuthUrl_fn).call(this, { method, appScheme, sessionLookupId, accountLinkInProgress });
1728
+ accountLinkInProgress = yield __privateMethod(this, _ParaCore_instances, assertIsLinkingAccountOrStart_fn).call(this, method);
1729
+ sessionLookupId = (yield this.touchSession()).sessionLookupId;
1730
+ const oAuthUrl = yield __privateGet(this, _portalUrlService).getOAuthUrl({
1731
+ method,
1732
+ appScheme,
1733
+ sessionLookupId,
1734
+ accountLinkInProgress
1735
+ });
2236
1736
  switch (true) {
2237
1737
  case !!onOAuthUrl: {
2238
1738
  onOAuthUrl(oAuthUrl);
@@ -2257,24 +1757,10 @@ Need help? Visit: https://docs.getpara.com or contact support
2257
1757
  return reject(AccountLinkError.Canceled);
2258
1758
  }
2259
1759
  yield new Promise((_resolve) => setTimeout(_resolve, constants.POLLING_INTERVAL_MS));
2260
- switch (isLinkAccount) {
2261
- case false:
2262
- {
2263
- const serverAuthState = yield this.ctx.client.verifyOAuth();
2264
- if (isServerAuthState(serverAuthState)) {
2265
- const authState = yield __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, __spreadProps(__spreadValues({}, urlOptions), { sessionLookupId }));
2266
- return resolve(authState);
2267
- }
2268
- }
2269
- break;
2270
- case true: {
2271
- const accounts = yield this.verifyLink({ accountLinkInProgress });
2272
- return resolve(accounts);
2273
- }
2274
- }
2275
- onPoll == null ? void 0 : onPoll();
1760
+ const accounts = yield this.verifyLink({ accountLinkInProgress });
1761
+ return resolve(accounts);
2276
1762
  } catch (err) {
2277
- if (isLinkAccount && err.message === AccountLinkError.Conflict) {
1763
+ if (err.message === AccountLinkError.Conflict) {
2278
1764
  return reject(err.message);
2279
1765
  }
2280
1766
  onPoll == null ? void 0 : onPoll();
@@ -2284,9 +1770,9 @@ Need help? Visit: https://docs.getpara.com or contact support
2284
1770
  });
2285
1771
  });
2286
1772
  }
2287
- verifyOAuth(opts) {
1773
+ verifyOAuth(params) {
2288
1774
  return __async(this, null, function* () {
2289
- return yield this.verifyOAuthProcess(__spreadProps(__spreadValues({}, opts), { isLinkAccount: false }));
1775
+ return yield this.verifyOAuthProcess(__spreadProps(__spreadValues({}, params), { isLinkAccount: false }));
2290
1776
  });
2291
1777
  }
2292
1778
  verifyOAuthLink(opts) {
@@ -2302,9 +1788,9 @@ Need help? Visit: https://docs.getpara.com or contact support
2302
1788
  * @param {boolean} [opts.skipSessionRefresh] whether to skip refreshing the session.
2303
1789
  * @returns {Object} `{ isComplete: boolean; isError: boolean; needsWallet: boolean; partnerId: string; }` the result data
2304
1790
  **/
2305
- waitForLogin(args) {
1791
+ waitForLogin(params) {
2306
1792
  return __async(this, null, function* () {
2307
- return yield __privateMethod(this, _ParaCore_instances, waitForLoginProcess_fn).call(this, args);
1793
+ return yield __privateGet(this, _authService).waitForLogin(params);
2308
1794
  });
2309
1795
  }
2310
1796
  waitForWalletSwitching(args) {
@@ -2336,32 +1822,20 @@ Need help? Visit: https://docs.getpara.com or contact support
2336
1822
  * @returns a URL for the user to reauthenticate.
2337
1823
  **/
2338
1824
  refreshSession() {
2339
- return __async(this, arguments, function* ({
2340
- shouldOpenPopup = false
2341
- } = {}) {
2342
- const { sessionId } = yield this.touchSession(true);
2343
- if (!this.loginEncryptionKeyPair) {
2344
- yield this.setLoginEncryptionKeyPair();
2345
- }
2346
- const link = yield this.getLoginUrl({
2347
- sessionId
2348
- });
2349
- if (shouldOpenPopup) {
2350
- yield this.platformUtils.openPopup(link);
2351
- }
2352
- return link;
1825
+ return __async(this, arguments, function* (params = {}) {
1826
+ return yield __privateGet(this, _sessionManagementService).refreshSession(params);
2353
1827
  });
2354
1828
  }
2355
1829
  /**
2356
1830
  * Call this method after login to ensure that the user ID is set
2357
1831
  * internally.
2358
1832
  **/
2359
- userSetupAfterLogin() {
1833
+ userSetupAfterLogin(existingSession) {
2360
1834
  return __async(this, null, function* () {
2361
- const session = yield this.touchSession();
2362
- yield this.setUserId(session.userId);
2363
- if (session.currentWalletIds && session.currentWalletIds !== this.currentWalletIds)
2364
- yield this.setCurrentWalletIds(session.currentWalletIds, {
1835
+ const session = existingSession != null ? existingSession : yield this.touchSession();
1836
+ yield __privateGet(this, _authService).setUserId(session.userId);
1837
+ if (session.currentWalletIds && session.currentWalletIds !== __privateGet(this, _walletService).currentWalletIds)
1838
+ yield __privateGet(this, _walletService).setCurrentWalletIds(session.currentWalletIds, {
2365
1839
  sessionLookupId: this.isPortal() ? session.sessionLookupId : void 0
2366
1840
  });
2367
1841
  return session;
@@ -2374,9 +1848,12 @@ Need help? Visit: https://docs.getpara.com or contact support
2374
1848
  * @returns - transmission keyshares.
2375
1849
  **/
2376
1850
  getTransmissionKeyShares() {
2377
- return __async(this, arguments, function* ({ isForNewDevice = false } = {}) {
2378
- const session = yield this.touchSession();
2379
- const sessionLookupId = isForNewDevice ? `${session.sessionLookupId}-new-device` : session.sessionLookupId;
1851
+ return __async(this, arguments, function* ({
1852
+ isForNewDevice = false,
1853
+ sessionLookupId: existingSessionLookupId
1854
+ } = {}) {
1855
+ const baseSessionLookupId = existingSessionLookupId != null ? existingSessionLookupId : (yield this.touchSession()).sessionLookupId;
1856
+ const sessionLookupId = isForNewDevice ? `${baseSessionLookupId}-new-device` : baseSessionLookupId;
2380
1857
  return this.ctx.client.getTransmissionKeyshares(this.userId, sessionLookupId);
2381
1858
  });
2382
1859
  }
@@ -2395,106 +1872,29 @@ Need help? Visit: https://docs.getpara.com or contact support
2395
1872
  temporaryShares = (yield this.getTransmissionKeyShares()).data.temporaryShares;
2396
1873
  }
2397
1874
  temporaryShares.forEach((share) => {
2398
- const signer = decryptWithPrivateKey(this.loginEncryptionKeyPair.privateKey, share.encryptedShare, share.encryptedKey);
2399
- this.wallets[share.walletId] = {
2400
- id: share.walletId,
2401
- signer
2402
- };
2403
- });
2404
- yield this.deleteLoginEncryptionKeyPair();
2405
- yield this.populateWalletAddresses();
2406
- yield this.touchSession(!skipSessionRefresh);
2407
- });
2408
- }
2409
- /**
2410
- * Distributes a new wallet recovery share.
2411
- * @param {Object} opts the options object.
2412
- * @param {string} opts.walletId the wallet to distribute the recovery share for.
2413
- * @param {string} opts.userShare optional user share generate the recovery share from. Defaults to the signer from the passed in walletId
2414
- * @param {boolean} opts.skipBiometricShareCreation whether or not to skip biometric share creation. Used when regenerating recovery shares.
2415
- * @param {boolean} opts.forceRefreshRecovery whether or not to force recovery secret regeneration. Used when regenerating recovery shares.
2416
- * @returns {string} the recovery share.
2417
- **/
2418
- distributeNewWalletShare(_0) {
2419
- return __async(this, arguments, function* ({
2420
- walletId,
2421
- userShare,
2422
- skipBiometricShareCreation = false,
2423
- forceRefresh = false
2424
- }) {
2425
- let userSigner = userShare;
2426
- if (!userSigner) {
2427
- userSigner = this.wallets[walletId].signer;
2428
- }
2429
- const recoveryShare = skipBiometricShareCreation ? yield sendRecoveryForShare({
2430
- ctx: this.ctx,
2431
- userId: this.userId,
2432
- walletId,
2433
- userSigner,
2434
- emailProps: this.getBackupKitEmailProps(),
2435
- forceRefresh
2436
- }) : yield distributeNewShare({
2437
- ctx: this.ctx,
2438
- userId: this.userId,
2439
- walletId,
2440
- userShare: userSigner,
2441
- emailProps: this.getBackupKitEmailProps(),
2442
- isEnclaveUser: this.isEnclaveUser,
2443
- walletScheme: this.wallets[walletId].scheme
2444
- });
2445
- return recoveryShare;
2446
- });
2447
- }
2448
- waitForWalletAddress(walletId) {
2449
- return __async(this, null, function* () {
2450
- let maxPolls = 0;
2451
- while (true) {
2452
- try {
2453
- if (maxPolls === 10) {
2454
- break;
2455
- }
2456
- ++maxPolls;
2457
- const res = yield (this.isPortal() ? this.ctx.client.getAllWallets : this.ctx.client.getWallets)(this.userId);
2458
- const wallet = res.data.wallets.find((w) => w.id === walletId);
2459
- if (wallet && wallet.address) {
2460
- return;
2461
- }
2462
- yield new Promise((resolve) => setTimeout(resolve, constants.SHORT_POLLING_INTERVAL_MS));
2463
- } catch (err) {
2464
- console.error(err);
2465
- }
2466
- }
2467
- throw new Error("timed out waiting for wallet address");
1875
+ const signer = decryptWithPrivateKey(this.loginEncryptionKeyPair.privateKey, share.encryptedShare, share.encryptedKey);
1876
+ this.wallets[share.walletId] = {
1877
+ id: share.walletId,
1878
+ signer
1879
+ };
1880
+ });
1881
+ yield this.deleteLoginEncryptionKeyPair();
1882
+ yield __privateGet(this, _walletService).populateWalletAddresses();
1883
+ yield this.touchSession(!skipSessionRefresh);
2468
1884
  });
2469
1885
  }
2470
1886
  /**
2471
- * Waits for a pregen wallet address to be created.
2472
- *
2473
- * @param pregenIdentifier - the identifier of the user the pregen wallet is associated with.
2474
- * @param walletId - the wallet id
2475
- * @param pregenIdentifierType - the identifier type of the user the pregen wallet is associated with.
2476
- * @returns - recovery share.
1887
+ * Distributes a new wallet recovery share.
1888
+ * @param {Object} opts the options object.
1889
+ * @param {string} opts.walletId the wallet to distribute the recovery share for.
1890
+ * @param {string} opts.userShare optional user share generate the recovery share from. Defaults to the signer from the passed in walletId
1891
+ * @param {boolean} opts.skipBiometricShareCreation whether or not to skip biometric share creation. Used when regenerating recovery shares.
1892
+ * @param {boolean} opts.forceRefreshRecovery whether or not to force recovery secret regeneration. Used when regenerating recovery shares.
1893
+ * @returns {string} the recovery share.
2477
1894
  **/
2478
- waitForPregenWalletAddress(walletId) {
1895
+ distributeNewWalletShare(params) {
2479
1896
  return __async(this, null, function* () {
2480
- let maxPolls = 0;
2481
- while (true) {
2482
- try {
2483
- if (maxPolls === 10) {
2484
- break;
2485
- }
2486
- ++maxPolls;
2487
- const res = yield this.getPregenWallets();
2488
- const wallet = res.find((w) => w.id === walletId);
2489
- if (wallet && wallet.address) {
2490
- return;
2491
- }
2492
- yield new Promise((resolve) => setTimeout(resolve, constants.SHORT_POLLING_INTERVAL_MS));
2493
- } catch (err) {
2494
- console.error(err);
2495
- }
2496
- }
2497
- throw new Error("timed out waiting for wallet address");
1897
+ return yield __privateGet(this, _walletService).distributeNewWalletShare(params);
2498
1898
  });
2499
1899
  }
2500
1900
  /**
@@ -2509,24 +1909,8 @@ Need help? Visit: https://docs.getpara.com or contact support
2509
1909
  * @returns {Object} the wallets created, their ids, and the recovery secret.
2510
1910
  **/
2511
1911
  createWalletPerType() {
2512
- return __async(this, arguments, function* ({
2513
- skipDistribute = false,
2514
- types
2515
- } = {}) {
2516
- const wallets = [];
2517
- const walletIds = {};
2518
- let recoverySecret;
2519
- for (const type of yield this.getTypesToCreate(types)) {
2520
- const [wallet, recoveryShare] = yield this.createWallet({ type, skipDistribute });
2521
- wallets.push(wallet);
2522
- getEquivalentTypes(type).filter((t) => !!this.isWalletTypeEnabled[t]).forEach((t) => {
2523
- walletIds[t] = [wallet.id];
2524
- });
2525
- if (recoveryShare) {
2526
- recoverySecret = recoveryShare;
2527
- }
2528
- }
2529
- return { wallets, walletIds, recoverySecret };
1912
+ return __async(this, arguments, function* (params = {}) {
1913
+ return yield __privateGet(this, _walletService).createWalletPerType(params);
2530
1914
  });
2531
1915
  }
2532
1916
  /**
@@ -2541,38 +1925,9 @@ Need help? Visit: https://docs.getpara.com or contact support
2541
1925
  * @param {boolean} [opts.redistributeBackupEncryptedShares] whether or not to redistribute backup encrypted shares.
2542
1926
  * @returns {Object} the new user share and recovery secret.
2543
1927
  **/
2544
- refreshShare(_0) {
2545
- return __async(this, arguments, function* ({
2546
- walletId,
2547
- share,
2548
- oldPartnerId,
2549
- newPartnerId,
2550
- keyShareProtocolId,
2551
- redistributeBackupEncryptedShares
2552
- }) {
2553
- const { signer, protocolId } = yield this.platformUtils.refresh(
2554
- this.ctx,
2555
- this.retrieveSessionCookie(),
2556
- this.userId,
2557
- walletId,
2558
- share,
2559
- oldPartnerId,
2560
- newPartnerId,
2561
- keyShareProtocolId
2562
- );
2563
- const recoverySecret = yield distributeNewShare({
2564
- ctx: this.ctx,
2565
- userId: this.userId,
2566
- walletId,
2567
- userShare: signer,
2568
- ignoreRedistributingBackupEncryptedShare: !redistributeBackupEncryptedShares,
2569
- emailProps: this.getBackupKitEmailProps(),
2570
- partnerId: newPartnerId,
2571
- protocolId,
2572
- isEnclaveUser: this.isEnclaveUser,
2573
- walletScheme: this.wallets[walletId].scheme
2574
- });
2575
- return { signer, recoverySecret, protocolId };
1928
+ refreshShare(params) {
1929
+ return __async(this, null, function* () {
1930
+ return yield __privateGet(this, _walletService).refreshShare(params);
2576
1931
  });
2577
1932
  }
2578
1933
  /**
@@ -2583,80 +1938,22 @@ Need help? Visit: https://docs.getpara.com or contact support
2583
1938
  * @returns {[Wallet, string | null]} `[wallet, recoveryShare]` - the wallet object and the new recovery share.
2584
1939
  **/
2585
1940
  createWallet() {
2586
- return __async(this, arguments, function* ({
2587
- type: _type,
2588
- skipDistribute = false
2589
- } = {}) {
2590
- var _a, _b;
2591
- this.requireApiKey();
2592
- const { supportedWalletTypes } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
2593
- const walletType = yield this.assertIsValidWalletType(
2594
- _type != null ? _type : (_a = supportedWalletTypes.find(({ optional }) => !optional)) == null ? void 0 : _a.type
2595
- );
2596
- let signer;
2597
- let wallet;
2598
- let keygenRes;
2599
- switch (walletType) {
2600
- case "SOLANA": {
2601
- keygenRes = yield this.platformUtils.ed25519Keygen(
2602
- this.ctx,
2603
- this.userId,
2604
- this.retrieveSessionCookie(),
2605
- this.getBackupKitEmailProps()
2606
- );
2607
- break;
2608
- }
2609
- default: {
2610
- keygenRes = yield this.platformUtils.keygen(
2611
- this.ctx,
2612
- this.userId,
2613
- walletType,
2614
- null,
2615
- this.retrieveSessionCookie(),
2616
- this.getBackupKitEmailProps()
2617
- );
2618
- break;
2619
- }
2620
- }
2621
- const walletId = keygenRes.walletId;
2622
- const walletScheme = walletType === "SOLANA" ? "ED25519" : "DKLS";
2623
- signer = keygenRes.signer;
2624
- yield this.waitForWalletAddress(walletId);
2625
- let recoveryShare = null;
2626
- if (!skipDistribute) {
2627
- recoveryShare = yield distributeNewShare({
2628
- ctx: this.ctx,
2629
- userId: this.userId,
2630
- walletId,
2631
- userShare: signer,
2632
- emailProps: this.getBackupKitEmailProps(),
2633
- isEnclaveUser: this.isEnclaveUser,
2634
- walletScheme
2635
- });
2636
- }
2637
- this.wallets[walletId] = {
2638
- id: walletId,
2639
- signer,
2640
- scheme: walletScheme,
2641
- type: walletType
2642
- };
2643
- wallet = this.wallets[walletId];
2644
- yield this.populateWalletAddresses();
2645
- yield this.setCurrentWalletIds(__spreadProps(__spreadValues({}, this.currentWalletIds), {
2646
- [walletType]: [.../* @__PURE__ */ new Set([...(_b = this.currentWalletIds[walletType]) != null ? _b : [], walletId])]
2647
- }));
2648
- const walletNoSigner = __spreadValues({}, wallet);
2649
- delete walletNoSigner.signer;
2650
- dispatchEvent(ParaEvent.WALLET_CREATED, {
2651
- wallet: walletNoSigner,
2652
- recoverySecret: recoveryShare
2653
- });
2654
- return [wallet, recoveryShare];
1941
+ return __async(this, arguments, function* (params = {}) {
1942
+ return yield __privateGet(this, _walletService).createWallet(params);
2655
1943
  });
2656
1944
  }
2657
- createPregenWallet(opts) {
1945
+ /**
1946
+ * Creates a new pregenerated wallet.
1947
+ *
1948
+ * @param {Object} opts the options object.
1949
+ * @param {string} opts.pregenIdentifier the identifier associated with the new wallet.
1950
+ * @param {TPregenIdentifierType} [opts.pregenIdentifierType] the identifier type. Defaults to `EMAIL`.
1951
+ * @param {TWalletType} [opts.type] the type of wallet to create. Defaults to the first non-optional type in the instance's `supportedWalletTypes` array.
1952
+ * @returns {Wallet} the created wallet.
1953
+ **/
1954
+ createPregenWallet(params) {
2658
1955
  return __async(this, null, function* () {
2659
- return yield __privateMethod(this, _ParaCore_instances, createPregenWallet_fn).call(this, opts);
1956
+ return yield __privateGet(this, _pregenWalletService).createPregenWallet(params);
2660
1957
  });
2661
1958
  }
2662
1959
  /**
@@ -2669,17 +1966,9 @@ Need help? Visit: https://docs.getpara.com or contact support
2669
1966
  * @param {TWalletType[]} [opts.types] the wallet types to create. Defaults to any types the instance supports that are not already present.
2670
1967
  * @returns {Wallet[]} an array containing the created wallets.
2671
1968
  **/
2672
- createPregenWalletPerType(_0) {
2673
- return __async(this, arguments, function* ({
2674
- types,
2675
- pregenId
2676
- }) {
2677
- const wallets = [];
2678
- for (const type of yield this.getTypesToCreate(types)) {
2679
- const wallet = yield this.createPregenWallet({ type, pregenId });
2680
- wallets.push(wallet);
2681
- }
2682
- return wallets;
1969
+ createPregenWalletPerType(params) {
1970
+ return __async(this, null, function* () {
1971
+ return yield __privateGet(this, _pregenWalletService).createPregenWalletPerType(params);
2683
1972
  });
2684
1973
  }
2685
1974
  /**
@@ -2690,70 +1979,8 @@ Need help? Visit: https://docs.getpara.com or contact support
2690
1979
  * @returns {[Wallet, string | null]} `[wallet, recoveryShare]` - the wallet object and the new recovery share.
2691
1980
  **/
2692
1981
  claimPregenWallets() {
2693
- return __async(this, arguments, function* ({
2694
- pregenId
2695
- } = {}) {
2696
- var _a;
2697
- this.requireApiKey();
2698
- const pregenWallets = pregenId ? yield this.getPregenWallets({ pregenId }) : yield this.getPregenWallets();
2699
- if (pregenWallets.length === 0) {
2700
- return void 0;
2701
- }
2702
- const missingWallets = pregenWallets.filter((wallet) => !this.wallets[wallet.id]);
2703
- if (missingWallets.length > 0) {
2704
- throw new Error(
2705
- `Cannot claim pregen wallets because wallet data is missing. Please call setUserShare first to load the wallet data for the following wallet IDs: ${missingWallets.map((w) => w.id).join(", ")}`
2706
- );
2707
- }
2708
- let newRecoverySecret;
2709
- const { walletIds } = yield this.ctx.client.claimPregenWallets({
2710
- userId: this.userId,
2711
- walletIds: pregenWallets.map((w) => w.id)
2712
- });
2713
- for (const walletId of walletIds) {
2714
- const wallet = this.wallets[walletId];
2715
- let refreshedShare;
2716
- if (wallet.scheme === "ED25519") {
2717
- const distributeRes = yield distributeNewShare({
2718
- ctx: this.ctx,
2719
- userId: this.userId,
2720
- walletId: wallet.id,
2721
- userShare: this.wallets[wallet.id].signer,
2722
- emailProps: this.getBackupKitEmailProps(),
2723
- partnerId: wallet.partnerId,
2724
- isEnclaveUser: this.isEnclaveUser,
2725
- walletScheme: wallet.scheme
2726
- });
2727
- if (distributeRes.length > 0) {
2728
- newRecoverySecret = distributeRes;
2729
- }
2730
- } else {
2731
- refreshedShare = yield this.refreshShare({
2732
- walletId: wallet.id,
2733
- share: this.wallets[wallet.id].signer,
2734
- oldPartnerId: wallet.partnerId,
2735
- newPartnerId: wallet.partnerId,
2736
- redistributeBackupEncryptedShares: true
2737
- });
2738
- if (refreshedShare.recoverySecret) {
2739
- newRecoverySecret = refreshedShare.recoverySecret;
2740
- }
2741
- }
2742
- this.wallets[wallet.id] = __spreadProps(__spreadValues({}, this.wallets[wallet.id]), {
2743
- signer: (_a = refreshedShare == null ? void 0 : refreshedShare.signer) != null ? _a : wallet.signer,
2744
- userId: this.userId,
2745
- pregenIdentifier: void 0,
2746
- pregenIdentifierType: void 0
2747
- });
2748
- const walletNoSigner = __spreadValues({}, this.wallets[wallet.id]);
2749
- delete walletNoSigner.signer;
2750
- dispatchEvent(ParaEvent.PREGEN_WALLET_CLAIMED, {
2751
- wallet: walletNoSigner,
2752
- recoverySecret: newRecoverySecret
2753
- });
2754
- }
2755
- yield this.setWallets(this.wallets);
2756
- return newRecoverySecret;
1982
+ return __async(this, arguments, function* (params = {}) {
1983
+ return yield __privateGet(this, _pregenWalletService).claimPregenWallets(params);
2757
1984
  });
2758
1985
  }
2759
1986
  /**
@@ -2763,24 +1990,9 @@ Need help? Visit: https://docs.getpara.com or contact support
2763
1990
  * @param {string} opts.newPregenIdentifier the new identtifier
2764
1991
  * @param {TPregenIdentifierType} opts.newPregenIdentifierType: the new identifier type
2765
1992
  **/
2766
- updatePregenWalletIdentifier(_0) {
2767
- return __async(this, arguments, function* ({
2768
- walletId,
2769
- newPregenId
2770
- }) {
2771
- this.requireApiKey();
2772
- const [newPregenIdentifierType, newPregenIdentifier] = toPregenTypeAndId(newPregenId);
2773
- yield this.ctx.client.updatePregenWallet(walletId, {
2774
- pregenIdentifier: newPregenIdentifier,
2775
- pregenIdentifierType: newPregenIdentifierType
2776
- });
2777
- if (!!this.wallets[walletId]) {
2778
- this.wallets[walletId] = __spreadProps(__spreadValues({}, this.wallets[walletId]), {
2779
- pregenIdentifier: newPregenIdentifier,
2780
- pregenIdentifierType: newPregenIdentifierType
2781
- });
2782
- yield this.setWallets(this.wallets);
2783
- }
1993
+ updatePregenWalletIdentifier(params) {
1994
+ return __async(this, null, function* () {
1995
+ return yield __privateGet(this, _pregenWalletService).updatePregenWalletIdentifier(params);
2784
1996
  });
2785
1997
  }
2786
1998
  /**
@@ -2790,18 +2002,9 @@ Need help? Visit: https://docs.getpara.com or contact support
2790
2002
  * @param {TPregenIdentifierType} opts.pregenIdentifierType type of the string of the identifier of the user claiming the wallet
2791
2003
  * @returns {boolean} whether the pregen wallet exists
2792
2004
  **/
2793
- hasPregenWallet(_0) {
2794
- return __async(this, arguments, function* ({ pregenId }) {
2795
- this.requireApiKey();
2796
- const [pregenIdentifierType, pregenIdentifier] = toPregenTypeAndId(pregenId);
2797
- const wallets = yield this.getPregenWallets({ pregenId });
2798
- const wallet = wallets.find(
2799
- (w) => w.pregenIdentifier === pregenIdentifier && w.pregenIdentifierType === pregenIdentifierType
2800
- );
2801
- if (!wallet) {
2802
- return false;
2803
- }
2804
- return true;
2005
+ hasPregenWallet(params) {
2006
+ return __async(this, null, function* () {
2007
+ return yield __privateGet(this, _pregenWalletService).hasPregenWallet(params);
2805
2008
  });
2806
2009
  }
2807
2010
  /**
@@ -2812,64 +2015,21 @@ Need help? Visit: https://docs.getpara.com or contact support
2812
2015
  * @returns {Promise<WalletEntity[]>} the array of found wallets
2813
2016
  **/
2814
2017
  getPregenWallets() {
2815
- return __async(this, arguments, function* ({ pregenId } = {}) {
2816
- this.requireApiKey();
2817
- const res = yield this.ctx.client.getPregenWallets(
2818
- pregenId ? toPregenIds(pregenId) : this.pregenIds,
2819
- this.isPortal(),
2820
- this.userId
2821
- );
2822
- return res.wallets.filter((w) => this.isWalletSupported(entityToWallet(w)));
2018
+ return __async(this, arguments, function* (params = {}) {
2019
+ return yield __privateGet(this, _pregenWalletService).getPregenWallets(params);
2823
2020
  });
2824
2021
  }
2825
2022
  createGuestWallets() {
2826
2023
  return __async(this, null, function* () {
2827
- let error;
2828
- if (__privateGet(this, _isCreateGuestWalletsPending)) {
2829
- error = new Error("Guest wallets creation already in progress");
2830
- dispatchEvent(ParaEvent.GUEST_WALLETS_CREATED, null, error.message);
2831
- throw error;
2832
- }
2833
- if (this.isGuestMode) {
2834
- error = new Error("Guest wallets already created");
2835
- dispatchEvent(ParaEvent.GUEST_WALLETS_CREATED, null, error.message);
2836
- throw error;
2837
- }
2838
- try {
2839
- __privateSet(this, _isCreateGuestWalletsPending, true);
2840
- const { supportedWalletTypes } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
2841
- const wallets = [];
2842
- const guestId = newUuid();
2843
- for (const type of yield this.getTypesToCreate(
2844
- supportedWalletTypes.filter(({ optional }) => !optional).map(({ type: type2 }) => type2)
2845
- )) {
2846
- const wallet = yield __privateMethod(this, _ParaCore_instances, createPregenWallet_fn).call(this, { type, pregenId: { guestId } });
2847
- wallets.push(wallet);
2848
- }
2849
- dispatchEvent(ParaEvent.GUEST_WALLETS_CREATED, wallets);
2850
- __privateSet(this, _isCreateGuestWalletsPending, false);
2851
- return wallets;
2852
- } catch (error2) {
2853
- dispatchEvent(ParaEvent.GUEST_WALLETS_CREATED, null, error2 == null ? void 0 : error2.message);
2854
- __privateSet(this, _isCreateGuestWalletsPending, false);
2855
- throw error2;
2856
- }
2024
+ return yield __privateGet(this, _pregenWalletService).createGuestWallets();
2857
2025
  });
2858
2026
  }
2859
- encodeWalletBase64(wallet) {
2860
- const walletJson = JSON.stringify(wallet);
2861
- const base64Wallet = Buffer.from(walletJson).toString("base64");
2862
- return base64Wallet;
2863
- }
2864
2027
  /**
2865
2028
  * Encodes the current wallets encoded in Base 64.
2866
2029
  * @returns {string} the encoded wallet string
2867
2030
  **/
2868
2031
  getUserShare() {
2869
- if (Object.values(this.wallets).length === 0) {
2870
- return null;
2871
- }
2872
- return Object.values(this.wallets).map((wallet) => this.encodeWalletBase64(wallet)).join("-");
2032
+ return __privateGet(this, _walletService).getUserShare();
2873
2033
  }
2874
2034
  /**
2875
2035
  * Sets the current wallets from a Base 64 string.
@@ -2877,16 +2037,7 @@ Need help? Visit: https://docs.getpara.com or contact support
2877
2037
  **/
2878
2038
  setUserShare(base64Wallets) {
2879
2039
  return __async(this, null, function* () {
2880
- if (!base64Wallets) {
2881
- return;
2882
- }
2883
- const base64WalletsSplit = base64Wallets.split("-");
2884
- for (const base64Wallet of base64WalletsSplit) {
2885
- const walletJson = Buffer.from(base64Wallet, "base64").toString();
2886
- const wallet = migrateWallet(JSON.parse(walletJson));
2887
- this.wallets[wallet.id] = wallet;
2888
- yield this.setWallets(this.wallets);
2889
- }
2040
+ return yield __privateGet(this, _walletService).setUserShare(base64Wallets);
2890
2041
  });
2891
2042
  }
2892
2043
  getTransactionReviewUrl(transactionId, timeoutMs) {
@@ -2910,6 +2061,11 @@ Need help? Visit: https://docs.getpara.com or contact support
2910
2061
  });
2911
2062
  });
2912
2063
  }
2064
+ getWalletBalance(params) {
2065
+ return __async(this, null, function* () {
2066
+ return yield __privateGet(this, _walletService).getWalletBalance(params);
2067
+ });
2068
+ }
2913
2069
  /**
2914
2070
  * Signs a message using one of the current wallets.
2915
2071
  *
@@ -2932,7 +2088,7 @@ Need help? Visit: https://docs.getpara.com or contact support
2932
2088
  onPoll
2933
2089
  }) {
2934
2090
  var _a;
2935
- this.assertIsValidWalletId(walletId);
2091
+ __privateGet(this, _walletService).assertIsValidWalletId(walletId);
2936
2092
  const wallet = this.wallets[walletId];
2937
2093
  let signerId = this.userId;
2938
2094
  if (wallet.partnerId && !wallet.userId) {
@@ -3037,7 +2193,7 @@ Need help? Visit: https://docs.getpara.com or contact support
3037
2193
  onPoll
3038
2194
  }) {
3039
2195
  var _a;
3040
- this.assertIsValidWalletId(walletId);
2196
+ __privateGet(this, _walletService).assertIsValidWalletId(walletId);
3041
2197
  const wallet = this.wallets[walletId];
3042
2198
  let signerId = this.userId;
3043
2199
  if (wallet.partnerId && !wallet.userId) {
@@ -3121,6 +2277,12 @@ Need help? Visit: https://docs.getpara.com or contact support
3121
2277
  return __async(this, null, function* () {
3122
2278
  var _b;
3123
2279
  const _a = options, { params, shouldOpenPopup } = _a, walletParams = __objRest(_a, ["params", "shouldOpenPopup"]);
2280
+ const allowedProviders = Object.values(OnRampProvider);
2281
+ if (!params.provider || !allowedProviders.includes(params.provider)) {
2282
+ throw new Error(
2283
+ `Invalid onramp provider: ${JSON.stringify(params.provider)}. Must be one of: ${allowedProviders.join(", ")}`
2284
+ );
2285
+ }
3124
2286
  const onRampPurchase = yield this.ctx.client.createOnRampPurchase(__spreadValues({
3125
2287
  userId: this.userId,
3126
2288
  params: __spreadProps(__spreadValues({}, params), {
@@ -3143,12 +2305,7 @@ Need help? Visit: https://docs.getpara.com or contact support
3143
2305
  **/
3144
2306
  keepSessionAlive() {
3145
2307
  return __async(this, null, function* () {
3146
- try {
3147
- yield this.ctx.client.keepSessionAlive(this.userId);
3148
- return true;
3149
- } catch (e) {
3150
- return false;
3151
- }
2308
+ return yield __privateGet(this, _sessionManagementService).keepSessionAlive();
3152
2309
  });
3153
2310
  }
3154
2311
  /**
@@ -3158,10 +2315,10 @@ Need help? Visit: https://docs.getpara.com or contact support
3158
2315
  */
3159
2316
  exportSession({ excludeSigners = false } = {}) {
3160
2317
  const sessionInfo = {
3161
- authInfo: __privateGet(this, _authInfo),
2318
+ authInfo: __privateGet(this, _authService).authInfo,
3162
2319
  userId: this.userId,
3163
2320
  wallets: structuredClone(this.wallets),
3164
- currentWalletIds: this.currentWalletIds,
2321
+ currentWalletIds: __privateGet(this, _walletService).currentWalletIds,
3165
2322
  sessionCookie: this.retrieveSessionCookie(),
3166
2323
  externalWallets: this.externalWallets
3167
2324
  };
@@ -3179,10 +2336,25 @@ Need help? Visit: https://docs.getpara.com or contact support
3179
2336
  importSession(serializedInstanceBase64) {
3180
2337
  return __async(this, null, function* () {
3181
2338
  var _a, _b;
2339
+ yield waitForAuthStateChange({
2340
+ stateManager: __privateGet(this, _stateManager),
2341
+ resolvePhases: [{ phase: "unauthenticated", onPhase: () => void 0 }],
2342
+ rejectPhases: [
2343
+ {
2344
+ phase: "authenticated",
2345
+ onPhase: () => new Error("Cannot import a session into a Para instance that already has an active session.")
2346
+ },
2347
+ {
2348
+ phase: "guest_mode",
2349
+ onPhase: () => new Error("Cannot import a session into a Para instance that is in guest mode.")
2350
+ }
2351
+ ],
2352
+ waitForCoreAuthenticated: false
2353
+ });
3182
2354
  const serializedInstance = Buffer.from(serializedInstanceBase64, "base64").toString("utf8");
3183
2355
  const sessionInfo = jsonParse(serializedInstance);
3184
2356
  const authInfo = (_a = sessionInfo.authInfo) != null ? _a : __privateMethod(this, _ParaCore_instances, toAuthInfo_fn).call(this, sessionInfo);
3185
- yield __privateMethod(this, _ParaCore_instances, setAuthInfo_fn).call(this, authInfo);
2357
+ yield __privateGet(this, _authService).setAuthInfo(authInfo);
3186
2358
  yield this.setUserId(sessionInfo.userId);
3187
2359
  yield this.setWallets(sessionInfo.wallets);
3188
2360
  yield this.setExternalWallets(sessionInfo.externalWallets || {});
@@ -3203,7 +2375,10 @@ Need help? Visit: https://docs.getpara.com or contact support
3203
2375
  }
3204
2376
  yield this.setCurrentWalletIds(currentWalletIds);
3205
2377
  }
2378
+ __privateGet(this, _sessionManagementService).isImportedSession = true;
2379
+ yield this.localStorageSetItem(constants.LOCAL_STORAGE_IS_IMPORTED_SESSION, JSON.stringify(true));
3206
2380
  this.persistSessionCookie(sessionInfo.sessionCookie);
2381
+ __privateGet(this, _stateManager).send({ type: "SESSION_IMPORTED" });
3207
2382
  });
3208
2383
  }
3209
2384
  /**
@@ -3212,22 +2387,12 @@ Need help? Visit: https://docs.getpara.com or contact support
3212
2387
  **/
3213
2388
  getVerificationToken() {
3214
2389
  return __async(this, null, function* () {
3215
- const { sessionLookupId } = yield this.touchSession();
3216
- return sessionLookupId;
2390
+ return yield __privateGet(this, _sessionManagementService).getVerificationToken();
3217
2391
  });
3218
2392
  }
3219
2393
  issueJwt() {
3220
- return __async(this, arguments, function* ({ keyIndex = 0 } = {}) {
3221
- try {
3222
- return yield this.ctx.client.issueJwt({ keyIndex });
3223
- } catch (error) {
3224
- if (error.status === 403 || error.status === 401) {
3225
- const errorMessage = "The user needs to be logged in to issue a JWT. Please log in and try again.";
3226
- this.displayModalError(errorMessage);
3227
- console.warn(errorMessage);
3228
- }
3229
- throw error;
3230
- }
2394
+ return __async(this, arguments, function* (params = {}) {
2395
+ return yield __privateGet(this, _sessionManagementService).issueJwt(params);
3231
2396
  });
3232
2397
  }
3233
2398
  /**
@@ -3237,30 +2402,39 @@ Need help? Visit: https://docs.getpara.com or contact support
3237
2402
  **/
3238
2403
  logout() {
3239
2404
  return __async(this, arguments, function* ({ clearPregenWallets = false } = {}) {
3240
- const shouldDispatchLogoutEvent = yield this.isSessionActive();
3241
- yield this.ctx.client.logout();
3242
- yield this.clearStorage();
3243
- if (!clearPregenWallets) {
3244
- Object.entries(this.wallets).forEach(([id, wallet]) => {
3245
- if (!wallet.pregenIdentifier) {
3246
- delete this.wallets[id];
3247
- }
2405
+ yield __privateMethod(this, _ParaCore_instances, logout_fn).call(this, { clearPregenWallets });
2406
+ __privateGet(this, _pollingService).cancelAllPolling();
2407
+ yield __privateGet(this, _externalWalletService).disconnectAllExternalWallets();
2408
+ try {
2409
+ yield waitForAuthStateChange({
2410
+ stateManager: __privateGet(this, _stateManager),
2411
+ resolvePhases: [{ phase: "unauthenticated", onPhase: () => void 0 }],
2412
+ rejectInErrorPhaseOnly: true,
2413
+ timeoutMs: 5e3
3248
2414
  });
3249
- yield this.setWallets(this.wallets);
3250
- } else {
3251
- this.wallets = {};
2415
+ } catch (e) {
3252
2416
  }
3253
- this.currentWalletIds = {};
3254
- this.externalWallets = {};
3255
- this.loginEncryptionKeyPair = void 0;
3256
- __privateSet(this, _authInfo, void 0);
3257
- this.accountLinkInProgress = void 0;
3258
- this.userId = void 0;
3259
- this.sessionCookie = void 0;
3260
- this.isEnclaveUser = false;
3261
- if (shouldDispatchLogoutEvent) {
3262
- dispatchEvent(ParaEvent.LOGOUT_EVENT, null);
2417
+ });
2418
+ }
2419
+ /**
2420
+ * Cancels any in-progress authentication flow, returning the auth state machine
2421
+ * to its initial unauthenticated state. Does not affect existing sessions or stored data.
2422
+ *
2423
+ * Resolves once the auth state machine has settled back to `unauthenticated`.
2424
+ */
2425
+ cancelAuthFlow() {
2426
+ return __async(this, null, function* () {
2427
+ if (this.authPhase === "unauthenticated" || this.authPhase === "error") {
2428
+ return;
3263
2429
  }
2430
+ const settled = waitForAuthStateChange({
2431
+ stateManager: __privateGet(this, _stateManager),
2432
+ resolvePhases: [{ phase: "unauthenticated", onPhase: () => true }],
2433
+ rejectInErrorPhaseOnly: true,
2434
+ timeoutMs: 5e3
2435
+ });
2436
+ __privateGet(this, _stateManager).send({ type: "CANCEL" });
2437
+ yield settled;
3264
2438
  });
3265
2439
  }
3266
2440
  get toStringAdditions() {
@@ -3293,16 +2467,16 @@ Need help? Visit: https://docs.getpara.com or contact support
3293
2467
  partnerId: (_a = this.partner) == null ? void 0 : _a.id,
3294
2468
  supportedWalletTypes: (_b = this.partner) == null ? void 0 : _b.supportedWalletTypes,
3295
2469
  cosmosPrefix: (_c = this.partner) == null ? void 0 : _c.cosmosPrefix,
3296
- authInfo: __privateGet(this, _authInfo),
2470
+ authInfo: __privateGet(this, _authService).authInfo,
3297
2471
  isGuestMode: this.isGuestMode,
3298
2472
  userId: this.userId,
3299
2473
  pregenIds: this.pregenIds,
3300
- currentWalletIds: this.currentWalletIds,
3301
- guestWalletIds: __privateGet(this, _ParaCore_instances, guestWalletIds_get),
2474
+ currentWalletIds: __privateGet(this, _walletService).currentWalletIds,
2475
+ guestWalletIds: __privateGet(this, _pregenWalletService).guestWalletIds,
3302
2476
  wallets: redactedWallets,
3303
2477
  externalWallets: redactedExternalWallets,
3304
2478
  loginEncryptionKeyPair: this.loginEncryptionKeyPair ? "[REDACTED]" : void 0,
3305
- isReady: this.isReady
2479
+ isSetup: this.isSetup
3306
2480
  }, this.toStringAdditions), {
3307
2481
  ctx: {
3308
2482
  apiKey: this.ctx.apiKey,
@@ -3318,90 +2492,13 @@ Need help? Visit: https://docs.getpara.com or contact support
3318
2492
  return `Para ${JSON.stringify(obj, null, 2)}`;
3319
2493
  }
3320
2494
  devLog(...s) {
3321
- if (this.ctx.env === Environment.DEV || this.ctx.env === Environment.SANDBOX) {
2495
+ if (this.ctx.env === Environment.DEV || this.ctx.env === Environment.SANDBOX || !!__privateGet(this, _debugLogsEnabled)) {
3322
2496
  console.log(...s);
3323
2497
  }
3324
2498
  }
3325
2499
  getNewCredentialAndUrl() {
3326
- return __async(this, arguments, function* ({
3327
- authMethod: optsAuthMethod,
3328
- isForNewDevice = false,
3329
- portalTheme,
3330
- shorten = false
3331
- } = {}) {
3332
- const userAuthMethods = yield this.supportedUserAuthMethods();
3333
- const isEnclaveUser = userAuthMethods.has(AuthMethod.BASIC_LOGIN);
3334
- const isAddingBasicLogin = optsAuthMethod === "BASIC_LOGIN";
3335
- if (isEnclaveUser && isAddingBasicLogin) {
3336
- throw new Error("That user is already using basic login");
3337
- }
3338
- if (isEnclaveUser || isAddingBasicLogin) {
3339
- isForNewDevice = true;
3340
- }
3341
- const authMethods = optsAuthMethod ? [optsAuthMethod] : isForNewDevice ? ["PASSKEY", "PIN", "PASSWORD"] : ["PASSKEY"];
3342
- this.assertIsAuthSet();
3343
- let passkeyId, passwordId, urlType, credentialId;
3344
- if (!isAddingBasicLogin) {
3345
- const canAddPasswordOrPIN = !userAuthMethods.has(AuthMethod.PASSWORD) && !userAuthMethods.has(AuthMethod.PIN);
3346
- if (authMethods.includes("PASSKEY") && (yield this.isPasskeySupported())) {
3347
- ({
3348
- data: { id: passkeyId }
3349
- } = yield this.ctx.client.addSessionPublicKey(this.userId, {
3350
- status: AuthMethodStatus.PENDING,
3351
- type: PublicKeyType.WEB
3352
- }));
3353
- urlType = "createAuth";
3354
- }
3355
- if (authMethods.includes("PASSWORD")) {
3356
- if (!canAddPasswordOrPIN) {
3357
- if (optsAuthMethod === "PASSWORD") throw new Error("A user cannot have more than one password or PIN.");
3358
- } else {
3359
- ({
3360
- data: { id: passwordId }
3361
- } = yield this.ctx.client.addSessionPasswordPublicKey(this.userId, {
3362
- status: AuthMethodStatus.PENDING
3363
- }));
3364
- urlType = "createPassword";
3365
- }
3366
- }
3367
- if (authMethods.includes("PIN")) {
3368
- if (!canAddPasswordOrPIN) {
3369
- if (optsAuthMethod === "PIN") throw new Error("A user cannot have more than one password or PIN.");
3370
- } else {
3371
- ({
3372
- data: { id: passwordId }
3373
- } = yield this.ctx.client.addSessionPasswordPublicKey(this.userId, {
3374
- status: AuthMethodStatus.PENDING
3375
- }));
3376
- urlType = "createPIN";
3377
- }
3378
- }
3379
- credentialId = passkeyId != null ? passkeyId : passwordId;
3380
- if (this.isNativePasskey && authMethods.includes("PASSKEY")) {
3381
- return { credentialId };
3382
- }
3383
- }
3384
- const { sessionId } = yield this.touchSession();
3385
- const url = (isForNewDevice || urlType) && (yield this.constructPortalUrl(isForNewDevice ? "addNewCredential" : urlType, {
3386
- isForNewDevice,
3387
- pathId: credentialId,
3388
- portalTheme,
3389
- shorten,
3390
- sessionId: isForNewDevice ? sessionId : void 0,
3391
- addNewCredentialType: optsAuthMethod,
3392
- addNewCredentialPasskeyId: passkeyId,
3393
- addNewCredentialPasswordId: passwordId
3394
- }));
3395
- return __spreadValues({ credentialId }, url ? { url } : {});
3396
- });
3397
- }
3398
- addCredential(_0) {
3399
- return __async(this, arguments, function* ({ authMethod }) {
3400
- if (authMethod === "PASSKEY" && !(yield this.isPasskeySupported())) {
3401
- throw new Error("Passkeys are not supported.");
3402
- }
3403
- const { url } = yield this.getNewCredentialAndUrl({ isForNewDevice: true, authMethod });
3404
- return url;
2500
+ return __async(this, arguments, function* (params = {}) {
2501
+ return yield __privateGet(this, _authService).getNewCredentialAndUrl(params);
3405
2502
  });
3406
2503
  }
3407
2504
  /**
@@ -3412,92 +2509,34 @@ Need help? Visit: https://docs.getpara.com or contact support
3412
2509
  * @param {Theme} opts.portalTheme the Para Portal theme to apply to the password creation URL, if other than the default theme
3413
2510
  * @returns {SignUpOrLogInResponse} an object in the form of either: `{ stage: 'verify' }` or `{ stage: 'login'; passkeyUrl?: string; passwordUrl?: string; biometricHints?: BiometricLocationHint[] }`
3414
2511
  */
3415
- getLoginUrl(_0) {
3416
- return __async(this, arguments, function* ({
3417
- authMethod = "PASSKEY",
3418
- shorten = false,
3419
- portalTheme,
3420
- sessionId
3421
- }) {
3422
- if (!sessionId) {
3423
- sessionId = (yield this.touchSession()).sessionLookupId;
3424
- }
3425
- this.assertIsAuthSet();
3426
- let urlType;
3427
- switch (authMethod) {
3428
- case "PASSKEY":
3429
- urlType = "loginAuth";
3430
- break;
3431
- case "PASSWORD":
3432
- urlType = "loginPassword";
3433
- break;
3434
- case "PIN":
3435
- urlType = "loginPIN";
3436
- break;
3437
- case "BASIC_LOGIN":
3438
- urlType = this.authInfo.authType === "externalWallet" ? "loginExternalWallet" : "loginOTP";
3439
- break;
3440
- default:
3441
- throw new Error(`invalid authentication method: '${authMethod}'`);
3442
- }
3443
- return this.constructPortalUrl(urlType, {
3444
- sessionId,
3445
- shorten,
3446
- portalTheme
3447
- });
2512
+ getLoginUrl(params) {
2513
+ return __async(this, null, function* () {
2514
+ return yield __privateGet(this, _portalUrlService).getLoginUrl(params);
3448
2515
  });
3449
2516
  }
3450
2517
  prepareLogin() {
3451
2518
  return __async(this, null, function* () {
3452
- yield this.logout();
3453
- const { sessionLookupId } = yield this.touchSession(true);
3454
- if (!this.loginEncryptionKeyPair) {
3455
- yield this.setLoginEncryptionKeyPair();
3456
- }
3457
- return sessionLookupId;
2519
+ return __privateGet(this, _authService).prepareLogin();
3458
2520
  });
3459
2521
  }
3460
- signUpOrLogIn(_i) {
2522
+ signUpOrLogIn(params) {
3461
2523
  return __async(this, null, function* () {
3462
- var _j = _i, { auth } = _j, urlOptions = __objRest(_j, ["auth"]);
3463
- let serverAuthState;
3464
- try {
3465
- serverAuthState = yield this.ctx.client.signUpOrLogIn(__spreadValues(__spreadValues({}, auth), this.getVerificationEmailProps()));
3466
- } catch (error) {
3467
- if (error.message.includes("max beta users reached")) {
3468
- this.displayModalError(
3469
- `50 user limit reached. [Go to Production.](https://docs.getpara.com/v2/general/checklist#go-live-checklist)`
3470
- );
3471
- }
3472
- throw error;
3473
- }
3474
- const authInfo = serverAuthState.auth;
3475
- if (this.fetchPregenWalletsOverride && isPregenAuth(authInfo)) {
3476
- const { userShare } = yield this.fetchPregenWalletsOverride({ pregenId: authInfo });
3477
- if (userShare) {
3478
- yield this.setUserShare(userShare);
3479
- }
3480
- }
3481
- return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, __spreadValues({}, urlOptions));
2524
+ return yield __privateGet(this, _authService).signUpOrLogIn(params);
3482
2525
  });
3483
2526
  }
3484
- verifyNewAccount(_k) {
2527
+ authenticateWithEmailOrPhone(params) {
3485
2528
  return __async(this, null, function* () {
3486
- var _l = _k, {
3487
- verificationCode
3488
- } = _l, urlOptions = __objRest(_l, [
3489
- "verificationCode"
3490
- ]);
3491
- this.assertIsAuthSet(["email", "phone"]);
3492
- const userId = this.assertUserId({ allowGuestMode: true });
3493
- const serverAuthState = yield this.ctx.client.verifyAccount(userId, {
3494
- verificationCode
3495
- });
3496
- if (serverAuthState.stage === "login" || serverAuthState.stage === "done") {
3497
- throw new Error("Account already exists.");
3498
- }
3499
- yield this.touchSession(true);
3500
- return __privateMethod(this, _ParaCore_instances, prepareAuthState_fn).call(this, serverAuthState, urlOptions);
2529
+ return yield __privateGet(this, _authService).authenticateWithEmailOrPhone(params);
2530
+ });
2531
+ }
2532
+ authenticateWithOAuth(params) {
2533
+ return __async(this, null, function* () {
2534
+ return yield __privateGet(this, _authService).authenticateWithOAuth(params);
2535
+ });
2536
+ }
2537
+ verifyNewAccount(params) {
2538
+ return __async(this, null, function* () {
2539
+ return yield __privateGet(this, _authService).verifyNewAccount(params);
3501
2540
  });
3502
2541
  }
3503
2542
  getLinkedAccounts() {
@@ -3583,10 +2622,10 @@ Need help? Visit: https://docs.getpara.com or contact support
3583
2622
  });
3584
2623
  }
3585
2624
  verifyLink() {
3586
- return __async(this, arguments, function* (_m = {}) {
3587
- var _n = _m, {
2625
+ return __async(this, arguments, function* (_e = {}) {
2626
+ var _f = _e, {
3588
2627
  accountLinkInProgress = __privateMethod(this, _ParaCore_instances, assertIsLinkingAccount_fn).call(this)
3589
- } = _n, opts = __objRest(_n, [
2628
+ } = _f, opts = __objRest(_f, [
3590
2629
  "accountLinkInProgress"
3591
2630
  ]);
3592
2631
  try {
@@ -3668,7 +2707,15 @@ Need help? Visit: https://docs.getpara.com or contact support
3668
2707
  });
3669
2708
  }
3670
2709
  };
3671
- _authInfo = new WeakMap();
2710
+ _stateManager = new WeakMap();
2711
+ _authService = new WeakMap();
2712
+ _walletService = new WeakMap();
2713
+ _externalWalletService = new WeakMap();
2714
+ _pregenWalletService = new WeakMap();
2715
+ _pollingService = new WeakMap();
2716
+ _portalUrlService = new WeakMap();
2717
+ _sessionManagementService = new WeakMap();
2718
+ _debugLogsEnabled = new WeakMap();
3672
2719
  _ParaCore_instances = new WeakSet();
3673
2720
  assertPartner_fn = function() {
3674
2721
  return __async(this, null, function* () {
@@ -3682,27 +2729,6 @@ assertPartner_fn = function() {
3682
2729
  return this.partner;
3683
2730
  });
3684
2731
  };
3685
- guestWalletIds_get = function() {
3686
- var _a, _b, _c;
3687
- if (!((_a = this.partner) == null ? void 0 : _a.supportedWalletTypes)) {
3688
- return {};
3689
- }
3690
- const guestId = (_c = (_b = this.pregenIds) == null ? void 0 : _b.GUEST_ID) == null ? void 0 : _c[0];
3691
- return !!guestId ? Object.entries(this.wallets).reduce((acc, [id, wallet]) => {
3692
- if (wallet.isPregen && !wallet.userId && wallet.pregenIdentifierType === "GUEST_ID" && wallet.pregenIdentifier === guestId) {
3693
- return __spreadValues(__spreadValues({}, acc), getEquivalentTypes(wallet.type).filter((type) => this.partner.supportedWalletTypes.some((entry) => entry.type === type)).reduce((acc2, eqType) => {
3694
- var _a2;
3695
- return __spreadProps(__spreadValues({}, acc2), { [eqType]: [.../* @__PURE__ */ new Set([...(_a2 = acc2[eqType]) != null ? _a2 : [], id])] });
3696
- }, {}));
3697
- }
3698
- return acc;
3699
- }, {}) : {};
3700
- };
3701
- guestWalletIdsArray_get = function() {
3702
- return Object.entries(__privateGet(this, _ParaCore_instances, guestWalletIds_get)).reduce((acc, [type, ids]) => {
3703
- return [...acc, ...ids.map((id) => [id, type])];
3704
- }, []);
3705
- };
3706
2732
  toAuthInfo_fn = function({
3707
2733
  email,
3708
2734
  phone,
@@ -3734,27 +2760,7 @@ toAuthInfo_fn = function({
3734
2760
  }
3735
2761
  return extractAuthInfo(auth);
3736
2762
  };
3737
- setAuthInfo_fn = function(authInfo) {
3738
- return __async(this, null, function* () {
3739
- __privateSet(this, _authInfo, authInfo);
3740
- yield this.localStorageSetItem(constants.LOCAL_STORAGE_AUTH_INFO, JSON.stringify(authInfo));
3741
- yield this.localStorageRemoveItem(constants.LOCAL_STORAGE_EMAIL);
3742
- yield this.localStorageRemoveItem(constants.LOCAL_STORAGE_PHONE);
3743
- yield this.localStorageRemoveItem(constants.LOCAL_STORAGE_COUNTRY_CODE);
3744
- yield this.localStorageRemoveItem(constants.LOCAL_STORAGE_FARCASTER_USERNAME);
3745
- yield this.localStorageRemoveItem(constants.LOCAL_STORAGE_TELEGRAM_USER_ID);
3746
- });
3747
- };
3748
- getPartner_fn = function(partnerId) {
3749
- return __async(this, null, function* () {
3750
- if (this.isPartnerOptional && !partnerId) {
3751
- return void 0;
3752
- }
3753
- const res = yield this.ctx.client.getPartner(partnerId);
3754
- this.partner = res.data.partner;
3755
- return this.partner;
3756
- });
3757
- };
2763
+ _servicesInitialized = new WeakMap();
3758
2764
  assertIsLinkingAccount_fn = function(types) {
3759
2765
  if (!this.accountLinkInProgress || this.accountLinkInProgress.isComplete) {
3760
2766
  throw new Error("no account linking in progress");
@@ -3774,49 +2780,6 @@ assertIsLinkingAccountOrStart_fn = function(type) {
3774
2780
  return yield this.linkAccount({ type });
3775
2781
  });
3776
2782
  };
3777
- getOAuthUrl_fn = function(_0) {
3778
- return __async(this, arguments, function* ({
3779
- method,
3780
- appScheme,
3781
- accountLinkInProgress,
3782
- sessionLookupId,
3783
- encryptionKey,
3784
- portalCallbackParams
3785
- }) {
3786
- if (!accountLinkInProgress && !this.isPortal()) {
3787
- return yield this.constructPortalUrl("oAuth", { sessionId: sessionLookupId, oAuthMethod: method, appScheme });
3788
- }
3789
- const [portalSessionLookupId, callback] = yield Promise.all([
3790
- this.isPortal() ? this.touchSession(true).then((s) => s.sessionLookupId) : Promise.resolve(void 0),
3791
- !accountLinkInProgress ? this.constructPortalUrl("oAuthCallback", __spreadValues({
3792
- sessionId: sessionLookupId,
3793
- oAuthMethod: method,
3794
- appScheme,
3795
- thisDevice: {
3796
- sessionId: sessionLookupId,
3797
- encryptionKey
3798
- }
3799
- }, this.isPortal() && {
3800
- params: portalCallbackParams,
3801
- // Build callback for legacy portal if needed
3802
- useLegacyUrl: typeof window !== "undefined" ? window.location.host.includes("usecapsule") : false
3803
- })) : Promise.resolve(false)
3804
- ]);
3805
- return constructUrl({
3806
- base: getBaseOAuthUrl(this.ctx.env),
3807
- path: `/auth/${method.toLowerCase()}`,
3808
- params: __spreadValues(__spreadValues({
3809
- apiKey: this.ctx.apiKey,
3810
- origin: typeof window !== "undefined" ? window.location.origin : void 0,
3811
- sessionLookupId,
3812
- portalSessionLookupId,
3813
- appScheme
3814
- }, accountLinkInProgress ? {
3815
- linkedAccountId: this.accountLinkInProgress.id
3816
- } : {}), callback && { callback })
3817
- });
3818
- });
3819
- };
3820
2783
  waitForLoginProcess_fn = function() {
3821
2784
  return __async(this, arguments, function* ({
3822
2785
  isCanceled = () => false,
@@ -3844,7 +2807,7 @@ waitForLoginProcess_fn = function() {
3844
2807
  var _a;
3845
2808
  if (!this.isExternalWalletAuth && !isSwitchingWallets) {
3846
2809
  this.devLog("[waitForLoginProcess] Clearing external wallets");
3847
- this.externalWallets = {};
2810
+ __privateGet(this, _externalWalletService).externalWallets = {};
3848
2811
  }
3849
2812
  let pollCount = 0;
3850
2813
  while (true) {
@@ -3889,7 +2852,7 @@ waitForLoginProcess_fn = function() {
3889
2852
  continue;
3890
2853
  }
3891
2854
  this.devLog("[waitForLoginProcess] Authentication check passed, setting up user");
3892
- session = yield this.userSetupAfterLogin();
2855
+ session = yield this.userSetupAfterLogin(session);
3893
2856
  const needsWallet = (_a = session.needsWallet) != null ? _a : false;
3894
2857
  this.devLog("[waitForLoginProcess] User setup complete", { needsWallet });
3895
2858
  if (isSwitchingWallets) {
@@ -3914,7 +2877,9 @@ waitForLoginProcess_fn = function() {
3914
2877
  }
3915
2878
  }
3916
2879
  this.devLog("[waitForLoginProcess] Getting transmission key shares");
3917
- const tempSharesRes = yield this.getTransmissionKeyShares();
2880
+ const tempSharesRes = yield this.getTransmissionKeyShares({
2881
+ sessionLookupId: session.sessionLookupId
2882
+ });
3918
2883
  this.devLog("[waitForLoginProcess] Transmission shares received", {
3919
2884
  shareCount: tempSharesRes.data.temporaryShares.length,
3920
2885
  shares: tempSharesRes.data.temporaryShares.map((s) => ({
@@ -3981,224 +2946,41 @@ waitForLoginProcess_fn = function() {
3981
2946
  });
3982
2947
  });
3983
2948
  };
3984
- createPregenWallet_fn = function(opts) {
3985
- return __async(this, null, function* () {
3986
- var _a, _b;
3987
- const { supportedWalletTypes } = yield __privateMethod(this, _ParaCore_instances, assertPartner_fn).call(this);
3988
- const { type: _type = (_a = supportedWalletTypes.find(({ optional }) => !optional)) == null ? void 0 : _a.type, pregenId } = opts;
3989
- this.requireApiKey();
3990
- const walletType = yield this.assertIsValidWalletType(
3991
- _type != null ? _type : (_b = supportedWalletTypes.find(({ optional }) => !optional)) == null ? void 0 : _b.type
3992
- );
3993
- const [pregenIdentifierType, pregenIdentifier] = toPregenTypeAndId(pregenId);
3994
- let keygenRes;
3995
- switch (walletType) {
3996
- case "SOLANA":
3997
- keygenRes = yield this.platformUtils.ed25519PreKeygen(
3998
- this.ctx,
3999
- pregenIdentifier,
4000
- pregenIdentifierType,
4001
- this.retrieveSessionCookie()
4002
- );
4003
- break;
4004
- default:
4005
- keygenRes = yield this.platformUtils.preKeygen(
4006
- this.ctx,
4007
- void 0,
4008
- pregenIdentifier,
4009
- pregenIdentifierType,
4010
- walletType,
4011
- null,
4012
- this.retrieveSessionCookie()
4013
- );
4014
- break;
4015
- }
4016
- const { signer, walletId } = keygenRes;
4017
- this.wallets[walletId] = {
4018
- id: walletId,
4019
- signer,
4020
- scheme: walletType === "SOLANA" ? "ED25519" : "DKLS",
4021
- type: walletType,
4022
- isPregen: true,
4023
- pregenIdentifier,
4024
- pregenIdentifierType
4025
- };
4026
- yield this.waitForPregenWalletAddress(walletId);
4027
- yield this.populatePregenWalletAddresses();
4028
- return this.wallets[walletId];
4029
- });
4030
- };
4031
- _isCreateGuestWalletsPending = new WeakMap();
4032
- prepareAuthState_fn = function(_0) {
4033
- return __async(this, arguments, function* (serverAuthState, opts = {}) {
4034
- var _a, _b;
4035
- 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))))) {
4036
- opts.sessionLookupId = yield this.prepareLogin();
4037
- }
4038
- const { auth, externalWallet, userId, displayName, pfpUrl, username } = serverAuthState;
4039
- const authInfo = __spreadValues(__spreadValues({}, extractAuthInfo(auth, { isRequired: true })), Object.fromEntries(
4040
- Object.entries({
4041
- displayName,
4042
- pfpUrl,
4043
- username,
4044
- externalWallet
4045
- }).filter(([_, v]) => !!v)
4046
- ));
4047
- yield __privateMethod(this, _ParaCore_instances, setAuthInfo_fn).call(this, authInfo);
4048
- this.assertIsAuthSet();
4049
- if (!!externalWallet) {
4050
- yield this.setExternalWallet([externalWallet]);
4051
- }
4052
- if (!!userId) {
4053
- yield this.setUserId(userId);
2949
+ logout_fn = function() {
2950
+ return __async(this, arguments, function* ({
2951
+ clearPregenWallets = false,
2952
+ skipStateReset = false
2953
+ } = {}) {
2954
+ const isSessionActive = yield this.isSessionActive();
2955
+ if (!isSessionActive && !skipStateReset) {
2956
+ __privateGet(this, _stateManager).send({ type: "LOGOUT" });
4054
2957
  }
4055
- let authState;
4056
- switch (serverAuthState.stage) {
4057
- case "done": {
4058
- authState = yield __privateMethod(this, _ParaCore_instances, prepareDoneState_fn).call(this, serverAuthState);
4059
- break;
4060
- }
4061
- case "verify":
4062
- authState = yield __privateMethod(this, _ParaCore_instances, prepareVerificationState_fn).call(this, serverAuthState, __spreadProps(__spreadValues({}, opts), {
4063
- sessionLookupId: opts.sessionLookupId
4064
- }));
4065
- break;
4066
- case "login":
4067
- if (externalWallet && !(externalWallet == null ? void 0 : externalWallet.withFullParaAuth)) {
4068
- authState = serverAuthState;
4069
- break;
4070
- }
4071
- authState = yield __privateMethod(this, _ParaCore_instances, prepareLoginState_fn).call(this, serverAuthState, __spreadProps(__spreadValues({}, opts), { sessionLookupId: opts.sessionLookupId }));
4072
- break;
4073
- case "signup":
4074
- if (externalWallet && !(externalWallet == null ? void 0 : externalWallet.withFullParaAuth)) {
4075
- authState = serverAuthState;
4076
- break;
2958
+ yield this.ctx.client.logout();
2959
+ yield this.clearStorage();
2960
+ if (!clearPregenWallets) {
2961
+ Object.entries(this.wallets).forEach(([id, wallet]) => {
2962
+ if (!wallet.pregenIdentifier) {
2963
+ delete this.wallets[id];
4077
2964
  }
4078
- authState = yield __privateMethod(this, _ParaCore_instances, prepareSignUpState_fn).call(this, serverAuthState, opts);
4079
- break;
4080
- }
4081
- return authState;
4082
- });
4083
- };
4084
- prepareDoneState_fn = function(doneState) {
4085
- return __async(this, null, function* () {
4086
- let isSLOPossible = doneState.authMethods.includes(AuthMethod.BASIC_LOGIN);
4087
- this.isEnclaveUser = isSLOPossible;
4088
- yield this.localStorageSetItem(constants.LOCAL_STORAGE_IS_ENCLAVE_USER, JSON.stringify(isSLOPossible));
4089
- return doneState;
4090
- });
4091
- };
4092
- prepareVerificationState_fn = function(_0, _1) {
4093
- return __async(this, arguments, function* (verifyState, {
4094
- useShortUrls: shorten = false,
4095
- portalTheme,
4096
- sessionLookupId
4097
- }) {
4098
- var _a;
4099
- let isSLOPossible = false;
4100
- if (verifyState.nextStage === "login") {
4101
- isSLOPossible = verifyState.loginAuthMethods.includes(AuthMethod.BASIC_LOGIN);
4102
- } else if (verifyState.nextStage === "signup") {
4103
- isSLOPossible = verifyState.signupAuthMethods.includes(AuthMethod.BASIC_LOGIN);
4104
- }
4105
- this.isEnclaveUser = isSLOPossible;
4106
- yield this.localStorageSetItem(constants.LOCAL_STORAGE_IS_ENCLAVE_USER, JSON.stringify(isSLOPossible));
4107
- const isExternalWalletFullAuth = (_a = verifyState.externalWallet) == null ? void 0 : _a.withFullParaAuth;
4108
- return __spreadValues(__spreadValues({}, verifyState), isSLOPossible || isExternalWalletFullAuth ? {
4109
- loginUrl: yield this.getLoginUrl({
4110
- authMethod: AuthMethod.BASIC_LOGIN,
4111
- sessionId: sessionLookupId,
4112
- shorten,
4113
- portalTheme
4114
- })
4115
- } : {});
4116
- });
4117
- };
4118
- prepareLoginState_fn = function(_0, _1) {
4119
- return __async(this, arguments, function* (loginState, {
4120
- useShortUrls: shorten = false,
4121
- portalTheme,
4122
- sessionLookupId
4123
- }) {
4124
- const _a = loginState, { loginAuthMethods = [], hasPasswordWithoutPIN } = _a, authState = __objRest(_a, ["loginAuthMethods", "hasPasswordWithoutPIN"]);
4125
- const isPasskeySupported = yield this.isPasskeySupported(), isPasskeyPossible = loginAuthMethods.includes(AuthMethod.PASSKEY) && !this.isNativePasskey, isPasswordPossible = loginAuthMethods.includes(AuthMethod.PASSWORD) && hasPasswordWithoutPIN, isPINPossible = loginAuthMethods.includes(AuthMethod.PIN);
4126
- return __spreadValues(__spreadValues(__spreadValues(__spreadProps(__spreadValues({}, authState), {
4127
- isPasskeySupported,
4128
- loginAuthMethods
4129
- }), isPasskeyPossible ? {
4130
- passkeyUrl: yield this.getLoginUrl({ sessionId: sessionLookupId, shorten, portalTheme }),
4131
- passkeyKnownDeviceUrl: yield this.constructPortalUrl("loginAuth", {
4132
- sessionId: sessionLookupId,
4133
- newDevice: {
4134
- sessionId: sessionLookupId,
4135
- encryptionKey: getPublicKeyHex(this.loginEncryptionKeyPair)
4136
- },
4137
- shorten,
4138
- portalTheme
4139
- })
4140
- } : {}), isPasswordPossible ? {
4141
- passwordUrl: yield this.constructPortalUrl("loginPassword", {
4142
- sessionId: sessionLookupId,
4143
- shorten,
4144
- portalTheme,
4145
- params: { isEmbedded: `${!loginState.isWalletSelectionNeeded}` }
4146
- })
4147
- } : {}), isPINPossible ? {
4148
- pinUrl: yield this.constructPortalUrl("loginPIN", {
4149
- sessionId: sessionLookupId,
4150
- shorten,
4151
- portalTheme,
4152
- params: { isEmbedded: `${!loginState.isWalletSelectionNeeded}` }
4153
- })
4154
- } : {});
4155
- });
4156
- };
4157
- prepareSignUpState_fn = function(_0, _1) {
4158
- return __async(this, arguments, function* (serverSignupState, { useShortUrls: shorten = false, portalTheme }) {
4159
- const _a = serverSignupState, { signupAuthMethods = [] } = _a, authState = __objRest(_a, ["signupAuthMethods"]);
4160
- const isPasskeySupported = yield this.isPasskeySupported();
4161
- const [isPasskey, isPassword, isPIN] = [
4162
- signupAuthMethods.includes(AuthMethod.PASSKEY),
4163
- signupAuthMethods.includes(AuthMethod.PASSWORD) || !isPasskeySupported,
4164
- signupAuthMethods.includes(AuthMethod.PIN)
4165
- ];
4166
- if (!isPasskey && !isPassword && !isPIN) {
4167
- throw new Error(
4168
- "No supported authentication methods found. Please ensure you have enabled either WebAuth passkeys, passwords or PINs in your Developer Portal settings."
4169
- );
4170
- }
4171
- const signupState = __spreadProps(__spreadValues({}, authState), {
4172
- isPasskeySupported,
4173
- signupAuthMethods
4174
- });
4175
- if (isPasskey) {
4176
- const { url: passkeyUrl, credentialId: passkeyId } = yield this.getNewCredentialAndUrl({
4177
- authMethod: "PASSKEY",
4178
- shorten
4179
2965
  });
4180
- if (passkeyUrl) signupState.passkeyUrl = passkeyUrl;
4181
- signupState.passkeyId = passkeyId;
4182
- }
4183
- if (isPassword) {
4184
- const { url: passwordUrl, credentialId: passwordId } = yield this.getNewCredentialAndUrl({
4185
- authMethod: "PASSWORD",
4186
- portalTheme,
4187
- shorten
4188
- });
4189
- signupState.passwordUrl = passwordUrl;
4190
- signupState.passwordId = passwordId;
2966
+ yield this.setWallets(this.wallets);
2967
+ } else {
2968
+ __privateGet(this, _walletService).wallets = {};
4191
2969
  }
4192
- if (isPIN) {
4193
- const { url: pinUrl, credentialId: pinId } = yield this.getNewCredentialAndUrl({
4194
- authMethod: "PIN",
4195
- portalTheme,
4196
- shorten
4197
- });
4198
- signupState.pinUrl = pinUrl;
4199
- signupState.pinId = pinId;
2970
+ __privateGet(this, _walletService).currentWalletIds = {};
2971
+ __privateGet(this, _externalWalletService).externalWallets = {};
2972
+ this.loginEncryptionKeyPair = void 0;
2973
+ __privateGet(this, _authService).authInfo = void 0;
2974
+ this.accountLinkInProgress = void 0;
2975
+ __privateGet(this, _authService).userId = void 0;
2976
+ __privateGet(this, _sessionManagementService).sessionCookie = void 0;
2977
+ this.isEnclaveUser = false;
2978
+ if (isSessionActive) {
2979
+ dispatchEvent(ParaEvent.LOGOUT_EVENT, null);
2980
+ if (!skipStateReset) {
2981
+ __privateGet(this, _stateManager).send({ type: "LOGOUT" });
2982
+ }
4200
2983
  }
4201
- return signupState;
4202
2984
  });
4203
2985
  };
4204
2986
  _ParaCore.version = constants.PARA_CORE_VERSION;